RSA加密解密算法java实现

论坛 期权论坛 脚本     
匿名网站用户   2020-12-21 09:33   669   0

转载自:http://blog.csdn.net/markcooper/article/details/53814747


pom.xml:

[html] view plain copy
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>com.dzh</groupId>
  5. <artifactId>encrypt-util</artifactId>
  6. <version>0.0.1-SNAPSHOT</version>
  7. <packaging>jar</packaging>
  8. <name>encrypt-util</name>
  9. <url>http://maven.apache.org</url>
  10. <properties>
  11. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  12. </properties>
  13. <dependencies>
  14. <dependency>
  15. <groupId>commons-codec</groupId>
  16. <artifactId>commons-codec</artifactId>
  17. <version>1.9</version>
  18. </dependency>
  19. <dependency>
  20. <groupId>org.bouncycastle</groupId>
  21. <artifactId>bcprov-jdk15on</artifactId>
  22. <version>1.55</version>
  23. <!-- <scope>provided</scope> -->
  24. </dependency>
  25. </dependencies>
  26. </project>

关于下面的代码的注意点:

此工具类能使用指定的字符串,每次生成相同的公钥和私钥且在linux和windows密钥也相同;相同的原文和密钥生成的密文相同。

如果需要每次生成不同的密钥或者生成不同的密文,代码要做修改。

下面的代码用到了我写的BASE64加密,参考《加密解密算法java实现(1)—BASE64》

java代码如下:

[java] view plain copy
  1. package com.dzh.rsa;
  2. import java.security.Key;
  3. import java.security.KeyFactory;
  4. import java.security.KeyPair;
  5. import java.security.KeyPairGenerator;
  6. import java.security.SecureRandom;
  7. import java.security.interfaces.RSAPrivateKey;
  8. import java.security.interfaces.RSAPublicKey;
  9. import java.security.spec.PKCS8EncodedKeySpec;
  10. import java.security.spec.X509EncodedKeySpec;
  11. import java.util.HashMap;
  12. import java.util.Map;
  13. import javax.crypto.Cipher;
  14. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  15. import com.dzh.base64.BASE64Util;
  16. /**
  17. * RSA加密解密
  18. * 此工具类能使用指定的字符串,每次生成相同的公钥和私钥且在linux和windows密钥也相同;相同的原文和密钥生成的密文相同
  19. */
  20. public class RSAUtil {
  21. private static final String ALGORITHM_RSA = "RSA";
  22. private static final String ALGORITHM_SHA1PRNG = "SHA1PRNG";
  23. private static final int KEY_SIZE = 1024;
  24. private static final String PUBLIC_KEY = "RSAPublicKey";
  25. private static final String PRIVATE_KEY = "RSAPrivateKey";
  26. private static final String TRANSFORMATION = "RSA/None/NoPadding";
  27. /**
  28. * 解密
  29. * 用私钥解密,解密字符串,返回字符串
  30. * @param data
  31. * @param key
  32. * @return
  33. * @throws Exception
  34. */
  35. public static String decryptByPrivateKey(String data, String key) throws Exception {
  36. return new String(decryptByPrivateKey(BASE64Util.decodeToByte(data), key));
  37. }
  38. /**
  39. * 加密
  40. * 用公钥加密,加密字符串,返回用base64加密后的字符串
  41. * @param data
  42. * @param key
  43. * @return
  44. * @throws Exception
  45. */
  46. public static String encryptByPublicKey(String data, String key) throws Exception {
  47. return encryptByBytePublicKey(data.getBytes(), key);
  48. }
  49. /**
  50. * 加密
  51. * 用公钥加密,加密byte数组,返回用base64加密后的字符串
  52. * @param data
  53. * @param key
  54. * @return
  55. * @throws Exception
  56. */
  57. public static String encryptByBytePublicKey(byte[] data, String key) throws Exception {
  58. return BASE64Util.encodeByte(encryptByPublicKey(data, key));
  59. }
  60. /**
  61. * 解密
  62. * 用私钥解密
  63. * @param data
  64. * @param key
  65. * @return
  66. * @throws Exception
  67. */
  68. public static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception {
  69. byte[] keyBytes = BASE64Util.decodeToByte(key);//对私钥解密
  70. /*取得私钥*/
  71. PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
  72. KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
  73. Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
  74. /*对数据解密*/
  75. Cipher cipher = Cipher.getInstance(TRANSFORMATION, new BouncyCastleProvider());//相同的原文、公钥能生成相同的密文。如果使用Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());//相同的原文、公钥生成的密文不同
  76. cipher.init(Cipher.DECRYPT_MODE, privateKey);
  77. return cipher.doFinal(data);
  78. }
  79. /**
  80. * 加密
  81. * 用公钥加密
  82. * @param data
  83. * @param key
  84. * @return
  85. * @throws Exception
  86. */
  87. public static byte[] encryptByPublicKey(byte[] data, String key) throws Exception {
  88. byte[] keyBytes = BASE64Util.decodeToByte(key);//对公钥解密
  89. /*取得公钥*/
  90. X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
  91. KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
  92. Key publicKey = keyFactory.generatePublic(x509KeySpec);
  93. /*对数据加密*/
  94. Cipher cipher = Cipher.getInstance(TRANSFORMATION, new BouncyCastleProvider());//相同的原文、公钥能生成相同的密文。如果使用Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());//相同的原文、公钥生成的密文不同
  95. cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  96. return cipher.doFinal(data);
  97. }
  98. /**
  99. * 取得私钥
  100. * @param keyMap
  101. * @return
  102. */
  103. public static String getPrivateKey(Map<String, Object> keyMap) {
  104. Key key = (Key) keyMap.get(PRIVATE_KEY);
  105. return BASE64Util.encodeByte(key.getEncoded());
  106. }
  107. /**
  108. * 取得公钥
  109. * @param keyMap
  110. * @return
  111. */
  112. public static String getPublicKey(Map<String, Object> keyMap) {
  113. Key key = (Key) keyMap.get(PUBLIC_KEY);
  114. return BASE64Util.encodeByte(key.getEncoded());
  115. }
  116. /**
  117. * 初始化公钥和私钥
  118. * @param seed
  119. * @return
  120. * @throws Exception
  121. */
  122. public static Map<String, Object> initKey(String seed) throws Exception {
  123. KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM_RSA);
  124. SecureRandom random = SecureRandom.getInstance(ALGORITHM_SHA1PRNG);//如果使用SecureRandom random = new SecureRandom();//windows和linux默认不同,导致两个平台生成的公钥和私钥不同
  125. random.setSeed(seed.getBytes());//使用种子则生成相同的公钥和私钥
  126. keyPairGen.initialize(KEY_SIZE, random);
  127. KeyPair keyPair = keyPairGen.generateKeyPair();
  128. RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();//公钥
  129. RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();//私钥
  130. Map<String, Object> keyMap = new HashMap<String, Object>(2);
  131. keyMap.put(PUBLIC_KEY, publicKey);
  132. keyMap.put(PRIVATE_KEY, privateKey);
  133. return keyMap;
  134. }
  135. /**
  136. * 使用示例
  137. * @param args
  138. * @throws Exception
  139. */
  140. public static void main(String[] args) throws Exception {
  141. String source = "12dfefDKLJKLKL464d中文f465as43f1a3 f46e353D1F34&*^$E65F46EF43456abcd54as56f00ef";//原文
  142. String seed = "abc123";//种子
  143. System.out.println("原文:\n" + source);
  144. Map<String, Object> keyMap = RSAUtil.initKey(seed);//初始化密钥
  145. String publicKey = RSAUtil.getPublicKey(keyMap);//公钥
  146. String privateKey = RSAUtil.getPrivateKey(keyMap);//私钥
  147. System.out.println("公钥:\n" + publicKey);
  148. System.out.println("私钥:\n" + privateKey);
  149. String encodedStr = RSAUtil.encryptByPublicKey(source, publicKey);//加密
  150. System.out.println("密文:\n" + encodedStr);
  151. String decodedStr = RSAUtil.decryptByPrivateKey(encodedStr, privateKey);//解密
  152. System.out.println("解密后的结果:\n" + decodedStr);
  153. }
  154. }
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1136255
帖子:227251
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP