java中RSA加解密的实现

今天在做RSA加密的时候遇到了一个这样的错误:ArrayIndexOutOfBoundsException: too much data for RSA block

查询相关资料后得知该错误是加密数据过长导致的。

加密数据长度 <= 模长-11

解决办法:将要加密的数据截取后分段加密

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

1.密钥长度
rsa算法初始化的时候一般要填入密钥长度,在96-1024bits间
(1)为啥下限是96bits(12bytes)?因为加密1byte的明文,需要至少1+11=12bytes的密钥(不懂?看下面的明文长度),低于下限96bits时,一个byte都加密不了,当然没意义啦
(2)为啥上限是1024(128bytes)?这是算法本身决定的...当然如果某天网上出现了支持2048bits长的密钥的rsa算法时,你当我废话吧

2.明文长度
明文长度(bytes) <= 密钥长度(bytes)-11.这样的话,对于上限密钥长度1024bits能加密的明文上限就是117bytes了.
这个规定很狗血,所以就出现了分片加密,网上很流行这个版本.很简单,如果明文长度大于那个最大明文长度了,我就分片吧,保证每片都别超过那个值就是了.
片数=(明文长度(bytes)/(密钥长度(bytes)-11))的整数部分+1,就是不满一片的按一片算

3.密文长度
对,就是这个充满了谣言,都说密文长度为密钥长度的一半,经俺验证,密文长度等于密钥长度.当然这是不分片情况下的.
分片后,密文长度=密钥长度*片数

例如96bits的密钥,明文4bytes
每片明文长度=96/8-11=1byte,片数=4,密文长度=96/8*4=48bytes

又例如128bits的密钥,明文8bytes
每片明文长度=128/8-11=5bytes,片数=8/5取整+1=2,密文长度=128/8*2=32

注意,对于指定长度的明文,其密文长度与密钥长度非正比关系.如4bytes的明文,在最短密钥96bites是,密文长度48bytes,128bits米密钥时,密文长度为16bytes,1024bits密钥时,密文长度128bytes.
因为分片越多,密文长度显然会变大,所以有人说,那就一直用1024bits的密钥吧...拜托,现在的机器算1024bits的密钥还是要点时间滴,别以为你的cpu很牛逼...那么选个什么值比较合适呢?个人认为是600bits,因为我们对于一个字符串的加密,一般不是直接加密,而是将字符串hash 后,对hash值加密.现在的hash值一般都是4bytes,很少有8bytes,几十年内应该也不会超过64bytes.那就用64bytes算吧, 密钥长度就是(64+11)*8=600bits了.

用开源rsa算法的时候,还要注意,那个年代的人把long当4bytes用,如今放在64位的机器上,就会死循环啊多悲催....因为有个循环里让一个4bytes做递减....64位机上long是8bytes,这个循环进去后个把小时都出不来....所以要注意下哦....同理对于所有年代久远的开源库都得注意下...


  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

  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. }  
  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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值