[Java] java实现RSA加密和解密 →→→→→进入此内容的聊天室

来自 , 2021-03-09, 写在 Java, 查看 125 次.
URL http://www.code666.cn/view/a0e2a2c5
  1. public static void main(String[] args) throws Exception {
  2.         // TODO Auto-generated method stub
  3.         HashMap<String, Object> map = RSAUtils.getKeys();
  4.         //生成公钥和私钥
  5.         RSAPublicKey publicKey = (RSAPublicKey) map.get("public");
  6.         RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");
  7.  
  8.         //模
  9.         String modulus = publicKey.getModulus().toString();
  10.         //公钥指数
  11.         String public_exponent = publicKey.getPublicExponent().toString();
  12.         //私钥指数
  13.         String private_exponent = privateKey.getPrivateExponent().toString();
  14.         //明文
  15.         String ming = "123456789";
  16.         //使用模和指数生成公钥和私钥
  17.         RSAPublicKey pubKey = RSAUtils.getPublicKey(modulus, public_exponent);
  18.         RSAPrivateKey priKey = RSAUtils.getPrivateKey(modulus, private_exponent);
  19.         //加密后的密文
  20.         String mi = RSAUtils.encryptByPublicKey(ming, pubKey);
  21.         System.err.println(mi);
  22.         //解密后的明文
  23.         ming = RSAUtils.decryptByPrivateKey(mi, priKey);
  24.         System.err.println(ming);
  25.     }
  26.  
  27. //源代码片段来自云代码http://yuncode.net
  28.                        
  29.  
  30.  
  31.  
  32.  
  33.  
  34. package yyy.test.rsa;
  35.  
  36. import java.math.BigInteger;
  37. import java.security.KeyFactory;
  38. import java.security.KeyPair;
  39. import java.security.KeyPairGenerator;
  40. import java.security.NoSuchAlgorithmException;
  41. import java.security.interfaces.RSAPrivateKey;
  42. import java.security.interfaces.RSAPublicKey;
  43. import java.security.spec.RSAPrivateKeySpec;
  44. import java.security.spec.RSAPublicKeySpec;
  45. import java.util.HashMap;
  46.  
  47. import javax.crypto.Cipher;
  48.  
  49. public class RSAUtils {
  50.  
  51.     /**
  52.      * 生成公钥和私钥
  53.      * @throws NoSuchAlgorithmException
  54.      *
  55.      */
  56.     public static HashMap<String, Object> getKeys() throws NoSuchAlgorithmException{
  57.         HashMap<String, Object> map = new HashMap<String, Object>();
  58.         KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
  59.         keyPairGen.initialize(1024);
  60.         KeyPair keyPair = keyPairGen.generateKeyPair();
  61.         RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
  62.         RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
  63.         map.put("public", publicKey);
  64.         map.put("private", privateKey);
  65.         return map;
  66.     }
  67.     /**
  68.      * 使用模和指数生成RSA公钥
  69.      * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA
  70.      * /None/NoPadding】
  71.      *
  72.      * @param modulus
  73.      *            模
  74.      * @param exponent
  75.      *            指数
  76.      * @return
  77.      */
  78.     public static RSAPublicKey getPublicKey(String modulus, String exponent) {
  79.         try {
  80.             BigInteger b1 = new BigInteger(modulus);
  81.             BigInteger b2 = new BigInteger(exponent);
  82.             KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  83.             RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
  84.             return (RSAPublicKey) keyFactory.generatePublic(keySpec);
  85.         } catch (Exception e) {
  86.             e.printStackTrace();
  87.             return null;
  88.         }
  89.     }
  90.  
  91.     /**
  92.      * 使用模和指数生成RSA私钥
  93.      * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA
  94.      * /None/NoPadding】
  95.      *
  96.      * @param modulus
  97.      *            模
  98.      * @param exponent
  99.      *            指数
  100.      * @return
  101.      */
  102.     public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {
  103.         try {
  104.             BigInteger b1 = new BigInteger(modulus);
  105.             BigInteger b2 = new BigInteger(exponent);
  106.             KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  107.             RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
  108.             return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
  109.         } catch (Exception e) {
  110.             e.printStackTrace();
  111.             return null;
  112.         }
  113.     }
  114.  
  115.     /**
  116.      * 公钥加密
  117.      *
  118.      * @param data
  119.      * @param publicKey
  120.      * @return
  121.      * @throws Exception
  122.      */
  123.     public static String encryptByPublicKey(String data, RSAPublicKey publicKey)
  124.             throws Exception {
  125.         Cipher cipher = Cipher.getInstance("RSA");
  126.         cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  127.         // 模长
  128.         int key_len = publicKey.getModulus().bitLength() / 8;
  129.         // 加密数据长度 <= 模长-11
  130.         String[] datas = splitString(data, key_len - 11);
  131.         String mi = "";
  132.         //如果明文长度大于模长-11则要分组加密
  133.         for (String s : datas) {
  134.             mi += bcd2Str(cipher.doFinal(s.getBytes()));
  135.         }
  136.         return mi;
  137.     }
  138.  
  139.     /**
  140.      * 私钥解密
  141.      *
  142.      * @param data
  143.      * @param privateKey
  144.      * @return
  145.      * @throws Exception
  146.      */
  147.     public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey)
  148.             throws Exception {
  149.         Cipher cipher = Cipher.getInstance("RSA");
  150.         cipher.init(Cipher.DECRYPT_MODE, privateKey);
  151.         //模长
  152.         int key_len = privateKey.getModulus().bitLength() / 8;
  153.         byte[] bytes = data.getBytes();
  154.         byte[] bcd = ASCII_To_BCD(bytes, bytes.length);
  155.         System.err.println(bcd.length);
  156.         //如果密文长度大于模长则要分组解密
  157.         String ming = "";
  158.         byte[][] arrays = splitArray(bcd, key_len);
  159.         for(byte[] arr : arrays){
  160.             ming += new String(cipher.doFinal(arr));
  161.         }
  162.         return ming;
  163.     }
  164.     /**
  165.      * ASCII码转BCD码
  166.      *
  167.      */
  168.     public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) {
  169.         byte[] bcd = new byte[asc_len / 2];
  170.         int j = 0;
  171.         for (int i = 0; i < (asc_len + 1) / 2; i++) {
  172.             bcd[i] = asc_to_bcd(ascii[j++]);
  173.             bcd[i] = (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4));
  174.         }
  175.         return bcd;
  176.     }
  177.     public static byte asc_to_bcd(byte asc) {
  178.         byte bcd;
  179.  
  180.         if ((asc >= '0') && (asc <= '9'))
  181.             bcd = (byte) (asc - '0');
  182.         else if ((asc >= 'A') && (asc <= 'F'))
  183.             bcd = (byte) (asc - 'A' + 10);
  184.         else if ((asc >= 'a') && (asc <= 'f'))
  185.             bcd = (byte) (asc - 'a' + 10);
  186.         else
  187.             bcd = (byte) (asc - 48);
  188.         return bcd;
  189.     }
  190.     /**
  191.      * BCD转字符串
  192.      */
  193.     public static String bcd2Str(byte[] bytes) {
  194.         char temp[] = new char[bytes.length * 2], val;
  195.  
  196.         for (int i = 0; i < bytes.length; i++) {
  197.             val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);
  198.             temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
  199.  
  200.             val = (char) (bytes[i] & 0x0f);
  201.             temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
  202.         }
  203.         return new String(temp);
  204.     }
  205.     /**
  206.      * 拆分字符串
  207.      */
  208.     public static String[] splitString(String string, int len) {
  209.         int x = string.length() / len;
  210.         int y = string.length() % len;
  211.         int z = 0;
  212.         if (y != 0) {
  213.             z = 1;
  214.         }
  215.         String[] strings = new String[x + z];
  216.         String str = "";
  217.         for (int i=0; i<x+z; i++) {
  218.             if (i==x+z-1 && y!=0) {
  219.                 str = string.substring(i*len, i*len+y);
  220.             }else{
  221.                 str = string.substring(i*len, i*len+len);
  222.             }
  223.             strings[i] = str;
  224.         }
  225.         return strings;
  226.     }
  227.     /**
  228.      *拆分数组
  229.      */
  230.     public static byte[][] splitArray(byte[] data,int len){
  231.         int x = data.length / len;
  232.         int y = data.length % len;
  233.         int z = 0;
  234.         if(y!=0){
  235.             z = 1;
  236.         }
  237.         byte[][] arrays = new byte[x+z][];
  238.         byte[] arr;
  239.         for(int i=0; i<x+z; i++){
  240.             arr = new byte[len];
  241.             if(i==x+z-1 && y!=0){
  242.                 System.arraycopy(data, i*len, arr, 0, y);
  243.             }else{
  244.                 System.arraycopy(data, i*len, arr, 0, len);
  245.             }
  246.             arrays[i] = arr;
  247.         }
  248.         return arrays;
  249.     }
  250. }
  251.  
  252. //源代码片段来自云代码http://yuncode.net
  253.                        

回复 " java实现RSA加密和解密"

这儿你可以回复上面这条便签

captcha