RSA 加密解密

小灰灰 2023-06-19 09:42 79阅读 0赞

RSA 加密解密实现代码如下:

  1. package com.barcodecheck;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.serializer.SerializerFeature;
  4. import javax.crypto.Cipher;
  5. import java.security.*;
  6. import java.security.interfaces.RSAPrivateKey;
  7. import java.security.interfaces.RSAPublicKey;
  8. import java.security.spec.PKCS8EncodedKeySpec;
  9. import java.security.spec.X509EncodedKeySpec;
  10. import java.util.Arrays;
  11. import java.util.Base64;
  12. import java.util.HashMap;
  13. import java.util.Map;
  14. /**
  15. * @author :zoboy
  16. * @Description:
  17. * @ Date: Created in 2019-12-05 09:28
  18. */
  19. public class RSADemo {
  20. static String publicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAM/bj9+o9pQobuHKRCIuFm2fky8cAvmE1aiAsG/fGLm0zqVGt7M9DAHEVcLd3WVPPVSFLGvp9ysRm565vGrU4HkCAwEAAQ==";
  21. static String privateKey = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAz9uP36j2lChu4cpEIi4WbZ+TLxwC+YTVqICwb98YubTOpUa3sz0MAcRVwt3dZU89VIUsa+n3KxGbnrm8atTgeQIDAQABAkEAm62pw21sSSlDaw8wGp2EJNTYyvbi73ljARJpk1B311XPlsrfJJzDEGpHmqoenXnKTtrFK+OOLGWEEwPsJWY+gQIhAO6WrONtzxmc9CF3TgpD8c05XpKdQKHlvHNXcnCzn5bRAiEA3wbFJiQFFOXzeelDOVw+xwdKO4o4eyPx67AX4ElKaSkCIBdw+GWT+WAT2qybEzDRAiXeuBsBlkMR1lUix1ypWUmxAiEAonSSAxhVw0VFN1Zcq1mwONXskrY6Miiave2FVtDMLRECIDWX4aXKHKDpu7HwUYwsa7o/bbG7POMsCoeMkKhUxAN9";
  22. public static void main(String[] args) {
  23. initKey();
  24. Map map = new HashMap();
  25. map.put("requestId", "1231");
  26. map.put("companyCode", "10");
  27. map.put("busNum", "陕A07157D");
  28. map.put("svrReqTime", "1575422395");
  29. map.put("classesMD5Code", "");
  30. map.put("lineNum", "123569");
  31. String result11 = encrypt(map);
  32. decrypt(result11);
  33. }
  34. public static void rsaPrivateKeyInfo(RSAPrivateKey rsaPrivateKey){
  35. System.out.println("Private Key : " + privateKey);
  36. System.out.println("Private Key Mod: " + rsaPrivateKey.getModulus());
  37. System.out.println("Private Key Mod length: " + rsaPrivateKey.getModulus().bitLength());
  38. System.out.println("Private Key Exp: " + rsaPrivateKey.getPrivateExponent());
  39. System.out.println("Private format:" + rsaPrivateKey.getFormat());
  40. System.out.println("Private Key Algorithm: " + rsaPrivateKey.getAlgorithm());
  41. }
  42. public static void rsaPublicKeyInfo(RSAPublicKey rsaPublicKey){
  43. System.out.println("Public Key : " + publicKey);
  44. System.out.println("Public Key Mod: " + rsaPublicKey.getModulus());
  45. System.out.println("Public Key Mod length: " + rsaPublicKey.getModulus().bitLength());
  46. System.out.println("Public Key Exp: " + rsaPublicKey.getPublicExponent());
  47. System.out.println("Public Key Algorithm: " + rsaPublicKey.getAlgorithm());
  48. System.out.println("Public format:" + rsaPublicKey.getFormat());
  49. }
  50. public static void initKey() {
  51. // 1、初始化密钥
  52. KeyPairGenerator keyPairGenerator;
  53. try {
  54. keyPairGenerator = KeyPairGenerator.getInstance("RSA");
  55. keyPairGenerator.initialize(512);// 64的整倍数
  56. KeyPair keyPair = keyPairGenerator.generateKeyPair();
  57. RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
  58. RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
  59. publicKey = Base64.getEncoder().encodeToString(rsaPublicKey.getEncoded());
  60. privateKey = Base64.getEncoder().encodeToString(rsaPrivateKey.getEncoded());
  61. rsaPublicKeyInfo(rsaPublicKey);
  62. rsaPrivateKeyInfo(rsaPrivateKey);
  63. } catch (NoSuchAlgorithmException e) {
  64. e.printStackTrace();
  65. }
  66. }
  67. public static String encrypt(Object obj) {
  68. //2 私钥加密,公钥解密 --加密
  69. try {
  70. String encryptStr = JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect);
  71. byte[] result1 = encryptStr.getBytes("utf-8");
  72. byte[] buffer = Base64.getDecoder().decode(privateKey);
  73. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
  74. KeyFactory instance = KeyFactory.getInstance("RSA");
  75. RSAPrivateKey key = (RSAPrivateKey) instance.generatePrivate(keySpec);
  76. rsaPrivateKeyInfo(key);
  77. Cipher cipher = Cipher.getInstance("RSA");
  78. cipher.init(Cipher.ENCRYPT_MODE, key);
  79. int inputLength = result1.length;
  80. System.out.println("加密字节数:" + inputLength);
  81. int MAX_ENCRYPT_BLOCK = key.getModulus().bitLength()/8-11;
  82. // 标识
  83. int offSet = 0;
  84. byte[] resultBytes = {};
  85. byte[] cache = {};
  86. while (inputLength - offSet > 0) {
  87. if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
  88. cache = cipher.doFinal(result1, offSet, MAX_ENCRYPT_BLOCK);
  89. offSet += MAX_ENCRYPT_BLOCK;
  90. } else {
  91. cache = cipher.doFinal(result1, offSet, inputLength - offSet);
  92. offSet = inputLength;
  93. }
  94. resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
  95. System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
  96. }
  97. String result11 = Base64.getEncoder().encodeToString(resultBytes);
  98. System.out.println("私钥加密,公钥解密 --加密: " + result11);
  99. return result11;
  100. } catch (Exception e) {
  101. e.printStackTrace();
  102. }
  103. return null;
  104. }
  105. public static void decrypt(String ss) {
  106. //3 私钥加密,公钥解密 --解密
  107. try {
  108. byte[] buffer = Base64.getDecoder().decode(publicKey);
  109. byte[] result1 = Base64.getDecoder().decode(ss);
  110. X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(buffer);
  111. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  112. RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(x509EncodedKeySpec);
  113. rsaPublicKeyInfo(publicKey);
  114. Cipher cipher = Cipher.getInstance("RSA");
  115. cipher.init(Cipher.DECRYPT_MODE, publicKey);
  116. int inputLength = result1.length;
  117. int MAX_ENCRYPT_BLOCK = publicKey.getModulus().bitLength()/8;
  118. // 标识
  119. int offSet = 0;
  120. byte[] resultBytes = {};
  121. byte[] cache = {};
  122. while (inputLength - offSet > 0) {
  123. if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
  124. cache = cipher.doFinal(result1, offSet, MAX_ENCRYPT_BLOCK);
  125. offSet += MAX_ENCRYPT_BLOCK;
  126. } else {
  127. cache = cipher.doFinal(result1, offSet, inputLength - offSet);
  128. offSet = inputLength;
  129. }
  130. resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
  131. System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
  132. }
  133. System.out.println("私钥加密,公钥解密 --解密: " + javax.xml.bind.DatatypeConverter.printHexBinary(resultBytes));
  134. System.out.println("私钥加密,公钥解密 --解密: " + new String(resultBytes, "utf-8"));
  135. } catch (Exception e) {
  136. e.printStackTrace();
  137. }
  138. }
  139. }

发表评论

表情:
评论列表 (有 0 条评论,79人围观)

还没有评论,来说两句吧...

相关阅读

    相关 RSA加密解密

    RSA加密与解密 RSA算法的密钥由公钥和私钥组成,公钥用于加密,私钥用于解密。顾名思义,公钥就是可以进行公开的密钥,一般可以公开给你的合作伙伴;私钥就是私有的,也就是只

    相关 JS-RSA加密解密

      在上一篇文章《Java使用RSA加密解密签名及校验》中,用java实现加密解密,但是在实际应用中,如前端页面用户输入的密码传输给后台服务前,需加密,也就是公钥加密,私钥解密