⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 rsautil.java

📁 简单的sso实现
💻 JAVA
字号:
/**
 * 
 */
package org.yqing.util;

import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;

import javax.crypto.Cipher;

import org.bouncycastle.util.encoders.Hex;

/**
 * @author cabby
 * 
 */
public class RSAUtil {

	/**
	 * 生成密钥对
	 * 
	 * @return KeyPair
	 * @throws EncryptException
	 */
	public static KeyPair generateKeyPair() {
		try {
			KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",
					new org.bouncycastle.jce.provider.BouncyCastleProvider());
			final int KEY_SIZE = 64;// 这个值关系到块加密的大小,可以更改,但是不要太大,否则效率会�?
			keyPairGen.initialize(KEY_SIZE, new SecureRandom());
			
			KeyPair keyPair = keyPairGen.genKeyPair();
			
			return keyPair;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	/**
	 * 生成公钥
	 * 
	 * @param modulus
	 * @param publicExponent
	 * @return RSAPublicKey
	 * @throws EncryptException
	 */
	public static RSAPublicKey generateRSAPublicKey(byte[] modulus,
			byte[] publicExponent)  {
		KeyFactory keyFac = null;
		try {
			keyFac = KeyFactory.getInstance("RSA",
					new org.bouncycastle.jce.provider.BouncyCastleProvider());
		} catch (NoSuchAlgorithmException ex) {
			throw new RuntimeException(ex.getMessage());
		}

		RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(
				modulus), new BigInteger(publicExponent));
		try {
			return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);
		} catch (InvalidKeySpecException ex) {
			throw new RuntimeException(ex.getMessage());
		}
	}

	/**
	 * 生成私钥
	 * 
	 * @param modulus
	 * @param privateExponent
	 * @return RSAPrivateKey
	 * @throws EncryptException
	 */
	public static RSAPrivateKey generateRSAPrivateKey(byte[] modulus,
			byte[] privateExponent) throws RuntimeException {
		KeyFactory keyFac = null;
		try {
			keyFac = KeyFactory.getInstance("RSA",
					new org.bouncycastle.jce.provider.BouncyCastleProvider());
		} catch (NoSuchAlgorithmException ex) {
			throw new RuntimeException(ex.getMessage());
		}

		RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(
				modulus), new BigInteger(privateExponent));
		try {
			return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);
		} catch (InvalidKeySpecException ex) {
			throw new RuntimeException(ex.getMessage());
		}
	}

	/**
	 * 加密
	 * 
	 * @param key
	 *            加密的密
	 * @param data
	 *            待加密的明文数据
	 * @return 加密后的数据
	 * @throws EncryptException
	 */
	public static byte[] encrypt(Key key, byte[] data) {
		try {
			Cipher cipher = Cipher.getInstance("RSA",
					new org.bouncycastle.jce.provider.BouncyCastleProvider());
			cipher.init(Cipher.ENCRYPT_MODE, key);
			int blockSize = cipher.getBlockSize();// 获得加密块大小,如:加密前数据为128个byte,�?key_size=1024
													// 加密块大小为127
													// byte,加密后为128个byte;因此共有2个加密块,第�?��127
													// byte第二个为1个byte
			int outputSize = cipher.getOutputSize(data.length);// 获得加密块加密后块大�?
			int leavedSize = data.length % blockSize;
			int blocksSize = leavedSize != 0 ? data.length / blockSize + 1
					: data.length / blockSize;
			byte[] raw = new byte[outputSize * blocksSize];
			int i = 0;
			while (data.length - i * blockSize > 0) {
				if (data.length - i * blockSize > blockSize)
					cipher.doFinal(data, i * blockSize, blockSize, raw, i
							* outputSize);
				else
					cipher.doFinal(data, i * blockSize, data.length - i
							* blockSize, raw, i * outputSize);
				// 这里面doUpdate方法不可用,查看源代码后发现每次doUpdate后并没有�?��实际动作除了把byte[]放到ByteArrayOutputStream中,而最后doFinal的时候才将所有的byte[]进行加密,可是到了此时加密块大小很可能已经超出了OutputSize�?��只好用dofinal方法�?

				i++;
			}
			return raw;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}
	
	public static String encrypt(String modulus,String priExponent,String str){
		byte[] modBytes = new BigInteger(modulus).toByteArray();
		byte[] priPriExpBytes = new BigInteger(priExponent).toByteArray();
		RSAPrivateKey priKey = generateRSAPrivateKey(modBytes, priPriExpBytes);
		byte[] raw = RSAUtil.encrypt(priKey,str.getBytes());
		String result=new String(Hex.encode(raw));
		return result;
	}

	/**
	 * 解密
	 * 
	 * @param key
	 *            解密的密�?
	 * @param raw
	 *            已经加密的数�?
	 * @return 解密后的明文
	 * @throws EncryptException
	 */
	public static byte[] decrypt(Key key, byte[] raw) {
		try {
			Cipher cipher = Cipher.getInstance("RSA",
					new org.bouncycastle.jce.provider.BouncyCastleProvider());
			cipher.init(cipher.DECRYPT_MODE, key);
			int blockSize = cipher.getBlockSize();
			ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
			int j = 0;

			while (raw.length - j * blockSize > 0) {
				bout.write(cipher.doFinal(raw, j * blockSize, blockSize));
				j++;
			}
			return bout.toByteArray();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}
	
	
	public void demo(){
		/*
		 * modulus: 893f99c3f84b74dce9346da0d6c19d8b
		 * public exponent: 10001
		 * private exponent: 59fe15f8e569b4a9d5cd610b94a410c1
		 */
		String modulus ="188653760425766735526814242366660004217";
		String pubExponent="65537";
		String priExponent="152927654246903025620843468798881510073";
		byte[] modBytes = new BigInteger(modulus).toByteArray();
		byte[] pubPubExpBytes = new BigInteger(pubExponent).toByteArray();
		byte[] priPriExpBytes = new BigInteger(priExponent).toByteArray();
		RSAPublicKey pubKey = generateRSAPublicKey(modBytes,pubPubExpBytes);
		RSAPrivateKey priKey = generateRSAPrivateKey(modBytes, priPriExpBytes);
		byte[] raw = RSAUtil.encrypt(priKey,"aaaaa".getBytes());
		byte[] data = RSAUtil.decrypt(pubKey, raw);
        String des = new String(data);
        System.out.println("decode:"+des);
		
	}
	
	

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		
        KeyPair keyPair = RSAUtil.generateKeyPair();
        RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();

		byte[] pubModBytes = pubKey.getModulus().toByteArray();
		byte[] pubPubExpBytes = pubKey.getPublicExponent().toByteArray();
        byte[] priModBytes = priKey.getModulus().toByteArray();
        byte[] priPriExpBytes = priKey.getPrivateExponent().toByteArray();
        //RSAPublicKey recoveryPubKey = RSAUtil.generateRSAPublicKey(pubModBytes,pubPubExpBytes);
        //RSAPrivateKey recoveryPriKey = RSAUtil.generateRSAPrivateKey(priModBytes,priPriExpBytes);

        System.out.println(priKey.toString());
        System.out.println("--------------------------");
        System.out.println(pubKey.toString());
        System.out.println();
        System.out.println("--------------------------");
        System.out.println(new BigInteger(pubModBytes));
        System.out.println(new BigInteger(priModBytes));
        System.out.println(new BigInteger(pubPubExpBytes));
        System.out.println(new BigInteger(priPriExpBytes));
        System.out.println("--------------------------");
        byte[] raw = RSAUtil.encrypt(priKey,"-1".getBytes());
        
        String s = new String(raw);
        System.out.println(s);
        for(int i=0;i<10;i++){
        	System.out.println("##:"+i+"##"+URLEncoder.encode(new String(RSAUtil.encrypt(priKey,"cabby".getBytes())),"utf-8"));
        }
        String sen = URLEncoder.encode(new String(raw),"utf-8");
        System.out.println(sen);
        byte[] data = RSAUtil.decrypt(pubKey, raw);
        String des = new String(data);
        System.out.println("decode:"+des);
        
		RSAUtil rsa = new RSAUtil();
		rsa.demo();
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -