java中RSA加解密的实现

来源:互联网 发布:盐城大数据产业园招聘 编辑:程序博客网 时间:2024/05/04 14:05

转自:http://blog.csdn.net/centralperk/article/details/8558678


关于加密数据长度和解密数据长度大家可以看一下我前一篇文章内的介绍:

关于RSA算法密钥长度/密文长度/明文长度的介绍

 

[java] view plain copy
  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.     }  


RSAUtils.java

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

0 0
原创粉丝点击