public class RSAUtils {
//加密算法RSA
public static final String KEY_ALGORITHM = "RSA";
//获取公钥的key
private static final String PUBLIC_KEY = "RSAPublicKey";
//获取私钥的key
private static final String PRIVATE_KEY = "RSAPrivateKey";
//RSA最大加密明文大小
private static final int MAX_ENCRYPT_BLOCK = 117;
//RSA最大解密密文大小
private static final int MAX_DECRYPT_BLOCK = 128;
private static final String RSA = "RSA/ECB/NoPadding";
//"RSA/None/PKCS1Padding"; "RSA/ECB/PKCS1Padding"; "RSA"; "RSA/None/NoPadding";
/**
* 随机生成RSA密钥对
*
*@return
*/
public static Map genKeyPair() {
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
Map keyMap = new HashMap(2);
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取私钥
*/
public static String getPrivateKey(Map keyMap) {
Key key = (Key) keyMap.get(PRIVATE_KEY);
return Base64Util.encode(key.getEncoded());
}
/**
* 获取公钥
*/
public static String getPublicKey(Map keyMap) {
Key key = (Key) keyMap.get(PUBLIC_KEY);
return Base64Util.encode(key.getEncoded());
}
/**
* 用公钥加密
* 每次加密的字节数,不能超过密钥的长度值减去11
*
*@param data 需加密数据的byte数据
*@param publicKey 公钥
*@return 加密后的byte型数据
*/
public static byte[] encryptData(byte[] data, PublicKey publicKey) {
try {
Cipher cipher = Cipher.getInstance(RSA);
// 编码前设定编码方式及密钥
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
// 传入编码数据并返回编码结果
return cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 用私钥解密
*
*@param encryptedData 经过encryptedData()加密返回的byte数据
*@param privateKey 私钥
*@return
*/
public static byte[] decryptData(byte[] encryptedData, PrivateKey privateKey) {
try {
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(encryptedData);
} catch (Exception e) {
return null;
}
}
/**
* 公钥加密
*
*@param data 明文
*@param publicKey 公钥字节
*@return
*@throws Exception
*/
public static byte[] encryptByPublicKey(byte[] data, String publicKey) {
try {
PublicKey publicK = getPublicKey(publicKey);
// 对数据加密
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.ENCRYPT_MODE, publicK);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet >= MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) {
try {
PrivateKey privateK = getPrivateKey(privateKey);
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.DECRYPT_MODE, privateK);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 通过公钥byte[](publicKey.getEncoded())将公钥还原,适用于RSA算法
* 从字符串中加载公钥
*
*@param publicKey
*@return
*@throws NoSuchAlgorithmException
*@throws InvalidKeySpecException
*/
public static PublicKey getPublicKey(String publicKey) {
try {
byte[] keyBytes = Base64Util.decode(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey pubKey = keyFactory.generatePublic(keySpec);
return pubKey;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 通过私钥byte[]将私钥还原,适用于RSA算法
* 从字符串中加载私钥
*
*@param privateKey
*@return
*@throws NoSuchAlgorithmException
*@throws InvalidKeySpecException
*/
public static PrivateKey getPrivateKey(String privateKey) {
try {
byte[] keyBytes = Base64Util.decode(privateKey);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey priKey = keyFactory.generatePrivate(keySpec);
return priKey;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 使用N、e值还原公钥
*
*@param modulus
*@param publicExponent
*@return
*/
public static PublicKey getPublicKey(String modulus, String publicExponent) {
try {
BigInteger bigIntModulus = new BigInteger(modulus);
BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static PublicKey getPublicKey(byte[] modulus, String publicExponent) {
try {
BigInteger bigIntModulus = new BigInteger(1, modulus);
BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 使用N、d值还原私钥
*
*@param modulus
*@param privateExponent
*@return
*/
public static PrivateKey getPrivateKey(String modulus, String privateExponent) {
try {
BigInteger bigIntModulus = new BigInteger(modulus);
BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(bigIntModulus, bigIntPrivateExponent);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 打印公钥信息
*
*@param publicKey
*/
public static String public_encode = "";
public static String printPublicKeyInfo(PublicKey publicKey) {
RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
System.out.println("----------RSAPublicKey----------");
System.out.println("Modulus.length=" + rsaPublicKey.getModulus().bitLength());
System.out.println("Modulus=" + rsaPublicKey.getModulus().toString());
byte[] byteArray = rsaPublicKey.getModulus().toByteArray();
System.out.println(Util.bytes2Hex(byteArray));
String pk = "30819F300D06092A864886F70D010101050003818D00308189028181" + Util.bytes2Hex(byteArray) + "0203010001";
public_encode = Base64Util.encode(Util.hexToBytes(pk));
System.out.println("公钥=" + public_encode);
System.out.println("byteArray=" + byteArray.length);
System.out.println("PublicExponent.length=" + rsaPublicKey.getPublicExponent().bitLength());
System.out.println("PublicExponent=" + rsaPublicKey.getPublicExponent().toString());
return rsaPublicKey.getModulus().toString();
}
public static String printPrivateKeyInfo(PrivateKey privateKey) {
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
System.out.println("----------RSAPrivateKey ----------");
System.out.println("Modulus.length=" + rsaPrivateKey.getModulus().bitLength());
System.out.println("Modulus=" + rsaPrivateKey.getModulus().toString());
System.out.println("PrivateExponent.length=" + rsaPrivateKey.getPrivateExponent().bitLength());
System.out.println("PrivatecExponent=" + rsaPrivateKey.getPrivateExponent().toString());
return rsaPrivateKey.getPrivateExponent().toString();
}
}