1 . 生成密钥
public static Map<String, Object> initKey() throws Exception{
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
Map<String, Object> map = new HashMap<>();
map.put(PUBLIC_KEY, rsaPublicKey);
map.put(PRIVATE_KEY, rsaPrivateKey);
return map;
}
2 . 利用公钥进行加密
public static byte[] encryptRSA(byte[] data, RSAPublicKey key) throws Exception{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] resultBytes = cipher.doFinal(data);
return resultBytes;
}
3 . 利用私钥解密
public static byte[] decryptRSA(byte[] src, RSAPrivateKey key) throws Exception{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] plainBytes = cipher.doFinal(src);
return plainBytes;
}
4 . 测试
public class Client {
public static final String DATA = "helloworld";
public static void main(String[] args) throws Exception {
Map<String, Object> map = RSAUtil.initKey();
RSAPrivateKey rsaPrivateKey = RSAUtil.getPrivateKey(map);
RSAPublicKey rsaPublicKey = RSAUtil.getPublicKey(map);
byte[] resultBytes = RSAUtil.encryptRSA(DATA.getBytes(), rsaPublicKey);
System.out.println("RSA Encrypt : " + Helper.fromByteToHex(resultBytes));
byte[] plainBytes = RSAUtil.decryptRSA(resultBytes, rsaPrivateKey);
System.out.println("RES Plain : " + new String(plainBytes));
}
}
5 . 结果
RSA Encrypt : 50005af95cc6d79f22c4baf9c289926ef2afb48c0c1760eecbe2bacc22e989349af66cea1f12be343629f8889a6d06679924df445e4c59012753529c7dffb563c783a2e45a20a8ca8ec0ee0fa74625cfce0a4f77cf4fea96c0d1c944ce2f4433aecc941fdd213f1186e8e71668e842acbc4c630a7befdbf20a901af2da1718e4
RSA Plain : helloworld