RSA算法是一种非对称密码算法,所谓非对称,就是指该算法需要一对密钥,使用其中一个加密,则需要用另一个才能解密。
由于RSA进行的都是大数计算,使得RSA最快的情况也比DES慢上好几倍,无论是软件还是硬件实现。速度一直是RSA的缺陷。一般来说只用于少量数据加密。RSA的速度是对应同样安全级别的对称密码算法的1/1000左右(摘自百度),所以要考虑性能速度就不要使用RSA了,考虑更高级别的安全可以使用RSA,现在主流的支付平台都是用了RSA算法加密解密。
以下是示例代码:
public class RSAUtil {
public static final String CHARSET = "UTF-8";
public static final String RSA_ALGORITHM = "RSA";
public static Map generateKeys(int keySize){
try {
KeyPairGenerator keyPairGenerator= KeyPairGenerator.getInstance(RSA_ALGORITHM);
keyPairGenerator.initialize(keySize);
KeyPair keyPair= keyPairGenerator.generateKeyPair();
Key publicKey= keyPair.getPublic();
Key privateKey= keyPair.getPrivate();
Map keyPairMap = new HashMap<>();
keyPairMap.put("publicKey",encodeBase64(publicKey.getEncoded()));
keyPairMap.put("privateKey",encodeBase64(privateKey.getEncoded()));
return keyPairMap;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
throw new RuntimeException("generate rsa keys error.");
}
/**
* 公钥加密
* @param data
* @param publicKeyStr
* @return
*/
public static String publicEncrypt(String data, String publicKeyStr){
try{
RSAPublicKey publicKey= getPublicKey(publicKeyStr);
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return encodeBase64(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength()));
}catch(Exception e){
throw new RuntimeException("加密字符串:" + data + "异常", e);
}
}
/**
* 私钥解密
* @param data
* @param privateKeyStr
* @return
*/
public static String privateDecrypt(String data, String privateKeyStr){
try{
RSAPrivateKey privateKey= getPrivateKey(privateKeyStr);
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.getDecoder().decode(data), privateKey.getModulus().bitLength()), CHARSET);
}catch(Exception e){
throw new RuntimeException("解密字符串:" + data + "异常", e);
}
}
/**
* 私钥加密
* @param data
* @param privateKeyStr
* @return
*/
public static String privateEncrypt(String data, String privateKeyStr){
try{
RSAPrivateKey privateKey= getPrivateKey(privateKeyStr);
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return encodeBase64(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength()));
}catch(Exception e){
throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
}
}
/**
* 公钥解密
* @param data
* @param publicKeyStr
* @return
*/
public static String publicDecrypt(String data, String publicKeyStr){
try{
RSAPublicKey publicKey= getPublicKey(publicKeyStr);
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.getDecoder().decode(data), publicKey.getModulus().bitLength()), CHARSET);
}catch(Exception e){
throw new RuntimeException("解密字符串:" + data + "异常", e);
}
}
private static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
return key;
}
private static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
return key;
}
private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize){
int maxBlock = 0;
if(opmode == Cipher.DECRYPT_MODE){
maxBlock = keySize / 8;
}else{
maxBlock = keySize / 8 - 11;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] buff;
int i = 0;
try{
while(datas.length > offSet){
if(datas.length-offSet > maxBlock){
buff = cipher.doFinal(datas, offSet, maxBlock);
}else{
buff = cipher.doFinal(datas, offSet, datas.length-offSet);
}
out.write(buff, 0, buff.length);
i++;
offSet = i * maxBlock;
}
}catch(Exception e){
throw new RuntimeException("加解密阀值为["+maxBlock+"]的数据时发生异常", e);
}
byte[] resultDatas = out.toByteArray();
IOUtils.closeQuietly(out);
return resultDatas;
}
private static String encodeBase64(byte[] bytes){
return new String(Base64.getEncoder().encode(bytes));
}
private static String decodeBase64(byte[] bytes){
return new String(Base64.getDecoder().decode(bytes));
}
public static void main(String[] args) {
Map keyMap = RSAUtil.generateKeys(1024);
String publicKey = keyMap.get("publicKey");
String privateKey = keyMap.get("privateKey");
System.out.println("公钥: " + publicKey);
System.out.println("私钥:" + privateKey);
String content= "莫言自己在《红高粱家族》开篇便写道:“我终于悟到:高密东北乡无疑是世界上最美丽最丑陋,最超脱最世俗,最圣洁最龌龊," +
"最英雄好汉最王八蛋,最能喝酒最能爱的地方。”与那些一味赞扬自己家乡的人来说,莫言的这段话或许才是对自己家乡最真实的看法," +
"而且这里的“丑陋,世俗,龌龊,王八蛋”等词汇并不是刻意贬低或丑化自己的家乡,而是真实地正直客观地写出其真实状况。" +
"毫无疑问,但凡看过这部小说的人都会发现里面充满了暴力、血腥和情色的东西,但莫言在描写这些东西的时候并不是带着鄙视批评的态度去描写的," +
"甚至在有的部分,我们会发现莫言在情感上是认同的。在轿夫们合力杀死打劫人,余占鳌杀死单家父子,余占鳌与戴凤莲在高粱地野合," +
"甚至于余占鳌带领队伍与胶高大队的八路军和冷支队三种不同势力之间的斗争等,莫言都是从第三者视角去叙述的," +
"他并没有对其中的故事过程进行批判是对是错,只是尽力写出这个故事的种种,仿佛是亲身经历过的样子,写尽其中的美与丑。\n";
System.out.println("明文:\r\n"+content);
String encode= RSAUtil.privateEncrypt(content, privateKey);
System.out.println("私钥加密:\r\n"+encode);
String decode= RSAUtil.publicDecrypt(encode,publicKey);
System.out.println("公钥解密:\r\n"+decode);
System.out.println("-----------------------------------------------------------------");
encode= RSAUtil.publicEncrypt(content,publicKey);
System.out.println("公钥加密:\r\n"+encode);
decode= RSAUtil.privateDecrypt(encode,privateKey);
System.out.println("私钥解密:\r\n"+decode);
}
}
运行结果:
公钥: MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCdZIcDNwaiBMmT6YET3Y1UbiTCIueEfv9Eixwv2rbfggVRa6VvZNpA/y+1Im6NtYVEx60RUNB7BZ1oXLv9VhYKE8wjKvfXicPchnOl6r9rG7jXmuTXSX9HGkuY6F9+W56zoIhKp/aofKfCf9vDQfxAmsqw0Q6bfbVY8AgHawI7CwIDAQAB
私钥:MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAJ1khwM3BqIEyZPpgRPdjVRuJMIi54R+/0SLHC/att+CBVFrpW9k2kD/L7Uibo21hUTHrRFQ0HsFnWhcu/1WFgoTzCMq99eJw9yGc6Xqv2sbuNea5NdJf0caS5joX35bnrOgiEqn9qh8p8J/28NB/ECayrDRDpt9tVjwCAdrAjsLAgMBAAECgYEAlrnTld+XSYc+J5kBVK3iD43fQ887WaZo/RIfLzDL2mVghGWLK48wd/gpjtRnfOvtsT1rXt6+mGF7KZtNKEHNndk+CedtQipAp8PlMswQn/Sz44qgxoJ68mKrRfVOMot7pWpJLuXxbunenfMqguZi5U1NNEERsoTRK1fV1NaTZ6ECQQDsuQw6sVES9PZ+H4shN+u/Q/0xs9er1zZE53NGtmOMOGLx1Smth7rymt5vywB8PcfhxTCzvcppf5ro1VUBfpnbAkEAqjWv0gZ0WwCrh53tUWK83uHNJehV0dY8cor9ChG5AH5Kr8YtRZEHVE7Mrtl+oTBtSuyOKEOKlpZSysWCJvoikQJBAMPLcqABFWu2jUJYWL1LAYSbeYpok9QgF1T6ktBD/yZ1ZPFdPDG5eBk9mwmgQHCCsRa+AMBKFGcaEkjOWpb33c0CQQCDnlxFNoSHUm9RwYegJZATcdxncc/bIaVAlcWyIZ5DiWVLox2i69EVGpIgq0LGdmItS9tpu0DRzZBcCHrqlQZhAkBrKidHuqii4SPj5JPqJuqfxpXdYBR2q0vqn5/ZWTRnVuIhEXQrOumxmnr2fUnPSd38YuTpcooQ3M5hdNUqhUy9
明文:
莫言自己在《红高粱家族》开篇便写道:“我终于悟到:高密东北乡无疑是世界上最美丽最丑陋,最超脱最世俗,最圣洁最龌龊,最英雄好汉最王八蛋,最能喝酒最能爱的地方。”与那些一味赞扬自己家乡的人来说,莫言的这段话或许才是对自己家乡最真实的看法,而且这里的“丑陋,世俗,龌龊,王八蛋”等词汇并不是刻意贬低或丑化自己的家乡,而是真实地正直客观地写出其真实状况。毫无疑问,但凡看过这部小说的人都会发现里面充满了暴力、血腥和情色的东西,但莫言在描写这些东西的时候并不是带着鄙视批评的态度去描写的,甚至在有的部分,我们会发现莫言在情感上是认同的。在轿夫们合力杀死打劫人,余占鳌杀死单家父子,余占鳌与戴凤莲在高粱地野合,甚至于余占鳌带领队伍与胶高大队的八路军和冷支队三种不同势力之间的斗争等,莫言都是从第三者视角去叙述的,他并没有对其中的故事过程进行批判是对是错,只是尽力写出这个故事的种种,仿佛是亲身经历过的样子,写尽其中的美与丑。
私钥加密:
aLL79np/Ef6zWz2ekH6t2bTyWRp570ValsINnzzDMaNkY3B/wOp2xPSop4htTNWT0198ftamv9b/M4s1qI7mMuilye/x8Hz/nGTOLkH16dy0Vn37PLCh1yb6mU/Wi5B4167dXsu5Qs2SJ1IeVvYpPtpN3ZQ8fCgBRkBvPTvwaMVx14CFd/AyXv51a12kett9inkCaup8rHPAoWXGAzGolQTgAyGoV/aZJRW3uSx6+O7f07D7LfNn8bTNPb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G/+Jk8vilT34pH1nl9uCuHNVrhbECkx6cdGQzh2Tce0hO/onGJcoY0sv5DQ/bIrIgtMO+PjA65jj8Vea3p9zC7IV+5+0DB14xNDH2wIMjK1b+E8KDnQIZda9FsZ+I10R7OMEy1HCoFW+ePJoYVBVK7m3uSNn0WkHEP0ZtjiwmjrE7JGn5p3ikLDBiaTwBtUfVlP1P/gOHrJqNqBH3HHcf2d4rybHNzA6LohaB6RmfGD7AbvDKHPewebtBheoLkXSZqYrahFf1yFJ4TPD2f6I2f0akCvzQqrJeViUj9gx7F5R0GImQZdaEbUY3x+FAxny5JrCfvjXEPwZMFMJyQSvv5I/28mcVpqBWZfwnTPK8fXO4tT6LR9IvZg8aELXCELO5DkpMqpU9/1V+pEwAlVi+4R6ZXU4Sun935taKP8lfNFBC7MlpiQP0Fx+XzebY3aS8uibK5qd8bcQF3rmp7AHAmJPgJThP3HuRhg8+BQduCbicA4CP8YJrBAa4kXF/+bFeGjV/wI1JZ7kYJEQLTSmhLadBiFlodAuM56IXR1w3F8YOdQb65IUMA==
公钥解密:
莫言自己在《红高粱家族》开篇便写道:“我终于悟到:高密东北乡无疑是世界上最美丽最丑陋,最超脱最世俗,最圣洁最龌龊,最英雄好汉最王八蛋,最能喝酒最能爱的地方。”与那些一味赞扬自己家乡的人来说,莫言的这段话或许才是对自己家乡最真实的看法,而且这里的“丑陋,世俗,龌龊,王八蛋”等词汇并不是刻意贬低或丑化自己的家乡,而是真实地正直客观地写出其真实状况。毫无疑问,但凡看过这部小说的人都会发现里面充满了暴力、血腥和情色的东西,但莫言在描写这些东西的时候并不是带着鄙视批评的态度去描写的,甚至在有的部分,我们会发现莫言在情感上是认同的。在轿夫们合力杀死打劫人,余占鳌杀死单家父子,余占鳌与戴凤莲在高粱地野合,甚至于余占鳌带领队伍与胶高大队的八路军和冷支队三种不同势力之间的斗争等,莫言都是从第三者视角去叙述的,他并没有对其中的故事过程进行批判是对是错,只是尽力写出这个故事的种种,仿佛是亲身经历过的样子,写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s+REgPq/uAEG/ZRP3mq2FQOX0MLk9s9OuIkNwgIPWWc7YTRxg/I6AJvJVN/eVVWNd5bk3hBApL6eJ38dbAuTUSbZi/FA1xGAhLKqKEHWOShd3d3b09bCrw1UhJ9yvfacv1gCYOlgOLca7etT/U4R61KqUg6Ma23dgOZ6Ok9ag2otkoLntLyjZ29pgCWZDx1YAPL+UGbunR6TFnmn31StkTwhskAWNF3fCbWTxSdvCbQ2OhhAVk6r0J9OlFYw18qMPxnbAN2dSLc9EIgqbyIaykqHm+tDoL+H4JxUTWDa44CzVvD/aggbz+mArdhrk4jkXx1hEi0Y+YPqGxbAaGpmiVxmC2crdf4psZ4JJZPXHMme1GdNYpNL+zOMuJG9hdDGsoL4miwvantl5pZsBBhdqZgNC2Zc6TOlx32XiVBauIZ/BuKxBn2vj8Xfb9FjG2nUfZMNBshz5SgrQtT2CqPPErMAtkmCoXhyDz/DEkL5pWEi3bgVItqtZPyRt4uyGFxYHbCaZ1RGRHROgaaE0URKk1OUkTaviG7cpBl0m/pIKtqlJIpE8CU4/1uB6PbjsXnAaC7eu7KkCbQH4Zfnq26Qk4z9kdP9hY5vwQ4rtS9XYQU7Yn7aXoK7sXg95wgVfsD5HsnZTxsGyXQxD3AzHsv0vq2boH22T4fdBByP9pwQegfmzB3TeGJk8Ng4j8xKXHVo2uTFqzheO2fptCDVdxjW3OBK61uuAur4Zm68mg33Rr1cvfQZp34a4issOaz01PxkQZX6tiCyZOEo7fBin7WlxhkFfmTw/ZI0KhXN27tkUMQhfnA==
私钥解密:
莫言自己在《红高粱家族》开篇便写道:“我终于悟到:高密东北乡无疑是世界上最美丽最丑陋,最超脱最世俗,最圣洁最龌龊,最英雄好汉最王八蛋,最能喝酒最能爱的地方。”与那些一味赞扬自己家乡的人来说,莫言的这段话或许才是对自己家乡最真实的看法,而且这里的“丑陋,世俗,龌龊,王八蛋”等词汇并不是刻意贬低或丑化自己的家乡,而是真实地正直客观地写出其真实状况。毫无疑问,但凡看过这部小说的人都会发现里面充满了暴力、血腥和情色的东西,但莫言在描写这些东西的时候并不是带着鄙视批评的态度去描写的,甚至在有的部分,我们会发现莫言在情感上是认同的。在轿夫们合力杀死打劫人,余占鳌杀死单家父子,余占鳌与戴凤莲在高粱地野合,甚至于余占鳌带领队伍与胶高大队的八路军和冷支队三种不同势力之间的斗争等,莫言都是从第三者视角去叙述的,他并没有对其中的故事过程进行批判是对是错,只是尽力写出这个故事的种种,仿佛是亲身经历过的样子,写尽其中的美与丑。