Java使用非对称数据加密RSA
非对称加密算法需要两个密钥:公开密钥(publicKey)和私有密钥(privateKey);公钥加密,私钥解密;
实现一下RSA加密的工具类吧
注意:RSA加密明文最大长度是117字节,解密要求密文最大长度为128字节,所以再加密和解密的时候要分段进行,就是每117字节就加密,然后再把这一节节拼起来。
public class AES_RSAUtil { public static void main(String[] args) throws Exception{ /*模拟客户端*/ String msg = "hello 冬竹"; byte[] key = AESUtil.getKeys();//获取密钥的编码 byte[] bytes = AESUtil.encrypt(msg,key); String seKey = Base64.encodeBase64URLSafeString(key);//转成字符串之后进行再加密 RSAUtil.init(); //RSA公钥 加密后的 AES密钥 String encryptKey = RSAUtil.encryptByPublicKey(seKey,RSAUtil.getPublicKey(RSAUtil.keyMap.get("PUBLIC_KEY"))); /*模拟服务端*/ //解码AES密钥 String aesKey = RSAUtil.decryptByPrivateKey(encryptKey,RSAUtil.getPrivateKey(RSAUtil.keyMap.get("PRIVATE_KEY"))); //还原aesKey byte[] secretKey = Base64.decodeBase64(aesKey); String ming = new String(AESUtil.decrypt(bytes,secretKey)); System.out.println(ming); } }
加密字符串的过程:
1. msg.getBytes() 获得字符数组, 然后用rsaSplitCode() 方法加密,再用encodeBase64URLSafeString编码成字符串(密文)
解密字符串的过程:
1. decodeBase64() 把密文解码成字符数组,再用new String()方法转为字符串