首先RSA是一个非对称的加密算法,所以在使用该算法加密解密之前,必须先行生成密钥对,包括公钥和私钥
JDK中提供了生成密钥对的类KeyPairGenerator,实例如下:
public static Map<String, Object> genKeyPair() throws Exception {
// 获取公钥私钥密钥对的生成器
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
// 初始化确定密钥大小的密钥生成器
kpg.initialize(1024);
// 生成密钥对
KeyPair kp = kpg.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) kp.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) kp.getPrivate();
Map<String, Object> keyMap = new HashMap<String, Object>();
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}
以上这段代码返回的是一个Map类型的数据,其中存储了公钥和私钥
当你完成了密钥对的生成之后,你就可以将公钥公开出去了,让相关的加密程序通过该公钥对实施RSA加密
public static byte[] encryptByPublicKey(byte[] data, String publicKey)
throws Exception {
//data即是待加密的数据String.getBytes即可
byte[] keyBytes = Base64Utils.decode(publicKey);
//根据指定的编码密钥创建一个新的X509EncodedKeySpec
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ENCRYPT_ALGORITHM);
//根据提供的密钥规范生成公钥对象
Key publicK = keyFactory.generatePublic(x509KeySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
//用密钥初始化加密模式的cipher,所有后面的doFinal方法做的是加密
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;
}
加密完成之后通过自己的私钥对密文进行解密
public static byte[] decryptByPrivateKey(byte[] data, String privateKey)
throws Exception {
byte[] keyBytes = Base64Utils.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ENCRYPT_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateK);
int inputLen = data.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(data, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
}
生成密钥对:
try {
Map<String, Object> keyMap = RSAUtils.genKeyPair();
publicKey = RSAUtils.getPublicKey(keyMap);
privateKey = RSAUtils.getPrivateKey(keyMap);
System.out.println("公钥-->" + publicKey);
System.out.println("私钥-->" + privateKey);
} catch (Exception e) {
e.printStackTrace();
}
运行结果展示: