RSA算法Java实现

Java代码   收藏代码
  1. package com.hexun.blog.dongliwei.utils;  
  2. import javax.crypto.Cipher;  
  3. import java.security.*;  
  4. import java.security.spec.RSAPublicKeySpec;  
  5. import java.security.spec.RSAPrivateKeySpec;  
  6. import java.security.spec.InvalidKeySpecException;  
  7. import java.security.interfaces.RSAPrivateKey;  
  8. import java.security.interfaces.RSAPublicKey;  
  9. import java.io.*;  
  10. import java.math.BigInteger;  
  11.   
  12. /** 
  13.  * RSA 工具类。提供加密,解密,生成密钥对等方法。 
  14.  * 需要到http://www.bouncycastle.org下载bcprov-jdk14-123.jar。 
  15.  * RSA加密原理概述   
  16.  * RSA的安全性依赖于大数的分解,公钥和私钥都是两个大素数(大于100的十进制位)的函数。   
  17.  * 据猜测,从一个密钥和密文推断出明文的难度等同于分解两个大素数的积   
  18.  * ===================================================================   
  19.  * (该算法的安全性未得到理论的证明)   
  20.  * ===================================================================   
  21.  * 密钥的产生:   
  22.  * 1.选择两个大素数 p,q ,计算 n=p*q;   
  23.  * 2.随机选择加密密钥 e ,要求 e 和 (p-1)*(q-1)互质   
  24.  * 3.利用 Euclid 算法计算解密密钥 d , 使其满足 e*d = 1(mod(p-1)*(q-1)) (其中 n,d 也要互质)   
  25.  * 4:至此得出公钥为 (n,e) 私钥为 (n,d)   
  26.  * ===================================================================   
  27.  * 加解密方法:   
  28.  * 1.首先将要加密的信息 m(二进制表示) 分成等长的数据块 m1,m2,...,mi 块长 s(尽可能大) ,其中 2^s<n   
  29.  * 2:对应的密文是: ci = mi^e(mod n)   
  30.  * 3:解密时作如下计算: mi = ci^d(mod n)   
  31.  * ===================================================================   
  32.  * RSA速度   
  33.  * 由于进行的都是大数计算,使得RSA最快的情况也比DES慢上100倍,无论 是软件还是硬件实现。   
  34.  * 速度一直是RSA的缺陷。一般来说只用于少量数据 加密。  
  35.  *文件名:RSAUtil.java<br> 
  36.  *@author 董利伟<br> 
  37.  *版本:<br> 
  38.  *描述:<br> 
  39.  *创建时间:2008-9-23 下午09:58:16<br> 
  40.  *文件描述:<br> 
  41.  *修改者:<br> 
  42.  *修改日期:<br> 
  43.  *修改描述:<br> 
  44.  */  
  45. public class RSAUtil {  
  46.   
  47.     //密钥对  
  48.     private KeyPair keyPair = null;  
  49.       
  50.     /** 
  51.      * 初始化密钥对 
  52.      */  
  53.     public RSAUtil(){  
  54.         try {  
  55.             this.keyPair = this.generateKeyPair();  
  56.         } catch (Exception e) {  
  57.             e.printStackTrace();  
  58.         }  
  59.     }  
  60.       
  61.     /** 
  62.     * 生成密钥对 
  63.     * @return KeyPair 
  64.     * @throws Exception 
  65.     */  
  66.     private KeyPair generateKeyPair() throws Exception {  
  67.         try {  
  68.             KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",new org.bouncycastle.jce.provider.BouncyCastleProvider());  
  69.             //这个值关系到块加密的大小,可以更改,但是不要太大,否则效率会低  
  70.             final int KEY_SIZE = 1024;  
  71.             keyPairGen.initialize(KEY_SIZE, new SecureRandom());  
  72.             KeyPair keyPair = keyPairGen.genKeyPair();  
  73.             return keyPair;  
  74.         } catch (Exception e) {  
  75.             throw new Exception(e.getMessage());  
  76.         }  
  77.       
  78.     }  
  79.   
  80.     /** 
  81.     * 生成公钥 
  82.     * @param modulus 
  83.     * @param publicExponent 
  84.     * @return RSAPublicKey 
  85.     * @throws Exception 
  86.     */  
  87.     private RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent) throws Exception {  
  88.       
  89.         KeyFactory keyFac = null;  
  90.         try {  
  91.             keyFac = KeyFactory.getInstance("RSA"new org.bouncycastle.jce.provider.BouncyCastleProvider());  
  92.         } catch (NoSuchAlgorithmException ex) {  
  93.         throw new Exception(ex.getMessage());  
  94.         }  
  95.         RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent));  
  96.         try {  
  97.             return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);  
  98.         } catch (InvalidKeySpecException ex) {  
  99.             throw new Exception(ex.getMessage());  
  100.         }  
  101.       
  102.     }  
  103.   
  104.     /** 
  105.     * 生成私钥 
  106.     * @param modulus 
  107.     * @param privateExponent 
  108.     * @return RSAPrivateKey 
  109.     * @throws Exception 
  110.     */  
  111.     private RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent) throws Exception {  
  112.         KeyFactory keyFac = null;  
  113.         try {  
  114.             keyFac = KeyFactory.getInstance("RSA"new org.bouncycastle.jce.provider.BouncyCastleProvider());  
  115.         } catch (NoSuchAlgorithmException ex) {  
  116.             throw new Exception(ex.getMessage());  
  117.         }  
  118.         RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(modulus), new BigInteger(privateExponent));  
  119.         try {  
  120.             return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);  
  121.         } catch (InvalidKeySpecException ex) {  
  122.             throw new Exception(ex.getMessage());  
  123.         }  
  124.     }  
  125.   
  126.     /** 
  127.     * 加密 
  128.     * @param key 加密的密钥 
  129.     * @param data 待加密的明文数据 
  130.     * @return 加密后的数据 
  131.     * @throws Exception 
  132.     */  
  133.     public byte[] encrypt(Key key, byte[] data) throws Exception {  
  134.         try {  
  135.             Cipher cipher = Cipher.getInstance("RSA"new org.bouncycastle.jce.provider.BouncyCastleProvider());  
  136.             cipher.init(Cipher.ENCRYPT_MODE, key);  
  137.             //获得加密块大小,如:加密前数据为128个byte,而key_size=1024 加密块大小为127 byte,加密后为128个byte;  
  138.             //因此共有2个加密块,第一个127 byte第二个为1个byte  
  139.             int blockSize = cipher.getBlockSize();  
  140.             int outputSize = cipher.getOutputSize(data.length);//获得加密块加密后块大小  
  141.             int leavedSize = data.length % blockSize;  
  142.             int blocksSize = leavedSize != 0 ? data.length / blockSize + 1 : data.length / blockSize;  
  143.             byte[] raw = new byte[outputSize * blocksSize];  
  144.             int i = 0;  
  145.             while (data.length - i * blockSize > 0) {  
  146.                 if (data.length - i * blockSize > blockSize)  
  147.                 cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize);  
  148.                 else  
  149.                 cipher.doFinal(data, i * blockSize, data.length - i * blockSize, raw, i * outputSize);  
  150.                 //这里面doUpdate方法不可用,查看源代码后发现每次doUpdate后并没有什么实际动作除了把byte[]放到ByteArrayOutputStream中  
  151.                 //,而最后doFinal的时候才将所有的byte[]进行加密,可是到了此时加密块大小很可能已经超出了OutputSize所以只好用dofinal方法。  
  152.                 i++;  
  153.             }  
  154.             return raw;  
  155.         } catch (Exception e) {  
  156.         throw new Exception(e.getMessage());  
  157.         }  
  158.     }  
  159.   
  160.     /** 
  161.     * 解密 
  162.     * @param key 解密的密钥 
  163.     * @param raw 已经加密的数据 
  164.     * @return 解密后的明文 
  165.     * @throws Exception 
  166.     */  
  167.     public byte[] decrypt(Key key, byte[] raw) throws Exception {  
  168.         try {  
  169.             Cipher cipher = Cipher.getInstance("RSA"new org.bouncycastle.jce.provider.BouncyCastleProvider());  
  170.             cipher.init(cipher.DECRYPT_MODE, key);  
  171.             int blockSize = cipher.getBlockSize();  
  172.             ByteArrayOutputStream bout = new ByteArrayOutputStream(64);  
  173.             int j = 0;  
  174.             while (raw.length - j * blockSize > 0) {  
  175.                 bout.write(cipher.doFinal(raw, j * blockSize, blockSize));  
  176.                 j++;  
  177.             }  
  178.             return bout.toByteArray();  
  179.         } catch (Exception e) {  
  180.             throw new Exception(e.getMessage());  
  181.         }  
  182.     }  
  183.       
  184.     /** 
  185.      * 返回公钥 
  186.      * @return 
  187.      * @throws Exception  
  188.      */  
  189.     public RSAPublicKey getRSAPublicKey() throws Exception{  
  190.           
  191.         //获取公钥  
  192.         RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();  
  193.         //获取公钥系数(字节数组形式)  
  194.         byte[] pubModBytes = pubKey.getModulus().toByteArray();  
  195.         //返回公钥公用指数(字节数组形式)  
  196.         byte[] pubPubExpBytes = pubKey.getPublicExponent().toByteArray();  
  197.         //生成公钥  
  198.         RSAPublicKey recoveryPubKey = this.generateRSAPublicKey(pubModBytes,pubPubExpBytes);  
  199.         return recoveryPubKey;  
  200.     }  
  201.       
  202.     /** 
  203.      * 获取私钥 
  204.      * @return 
  205.      * @throws Exception  
  206.      */  
  207.     public RSAPrivateKey getRSAPrivateKey() throws Exception{  
  208.           
  209.         //获取私钥  
  210.         RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();  
  211.         //返回私钥系数(字节数组形式)  
  212.         byte[] priModBytes = priKey.getModulus().toByteArray();  
  213.         //返回私钥专用指数(字节数组形式)  
  214.         byte[] priPriExpBytes = priKey.getPrivateExponent().toByteArray();  
  215.         //生成私钥  
  216.         RSAPrivateKey recoveryPriKey = this.generateRSAPrivateKey(priModBytes,priPriExpBytes);  
  217.         return recoveryPriKey;  
  218.     }  
  219.       
  220.       
  221.     /** 
  222.     * 测试 
  223.     * @param args 
  224.     * @throws Exception 
  225.     */  
  226.     public static void main(String[] args) throws Exception {  
  227.           
  228.         RSAUtil rsa = new RSAUtil();  
  229.         String str = "董利伟";  
  230.         RSAPublicKey pubKey = rsa.getRSAPublicKey();  
  231.         RSAPrivateKey priKey = rsa.getRSAPrivateKey();  
  232.         System.out.println("加密后==" + new String(rsa.encrypt(pubKey,str.getBytes())));  
  233.         System.out.println("解密后==" + new String(rsa.decrypt(priKey, rsa.encrypt(pubKey,str.getBytes()))));  
  234.     }  
  235. }  
7 
1 
分享到:   
参考知识库
算法与数据结构知识库 18251  关注 | 2320  收录
评论
8 楼  wx_hello 2014-12-06  
sinosoft_yj 写道
denglei9018 写道
为什么得到的加密数据是乱码啊,请楼主大人讲解下



确实乱码,楼主讲解下呢!
7 楼  sinosoft_yj 2014-09-15  
denglei9018 写道
为什么得到的加密数据是乱码啊,请楼主大人讲解下

6 楼  denglei9018 2014-06-23  
为什么得到的加密数据是乱码啊,请楼主大人讲解下
5 楼  zhglhy 2011-11-08  
写得很好,收藏学习了
4 楼  nextw3 2011-02-11  
你好,有个疑问?

在RSAPublicKey、RSAPrivateKey方法中,为什么使用密钥对对象生成密钥后,还要再重新生成一遍?(是否是为了教程演示的需要?)
Java代码   收藏代码
  1. RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();    
  2.         //返回私钥系数(字节数组形式)    
  3.         byte[] priModBytes = priKey.getModulus().toByteArray();    
  4.         //返回私钥专用指数(字节数组形式)    
  5.         byte[] priPriExpBytes = priKey.getPrivateExponent().toByteArray();    
  6.         //生成私钥    
  7.         RSAPrivateKey recoveryPriKey = this.generateRSAPrivateKey(priModBytes,priPriExpBytes);    
3 楼  zyy2010 2010-10-20  
如果不引入bcprov-jdk15-140.jar,在运行时改为: 
Java代码   收藏代码
  1. Cipher cipher = Cipher.getInstance("RSA");     

这时
Java代码   收藏代码
  1. int blockSize = cipher.getBlockSize();     
blockSize 的值为0,楼主能否讲解一下
2 楼  763691 2010-08-11  
注释很好  谢谢了 最近正在做有关加密的项目 





80791834  J2EE高级技术群  欢迎来讨论
1 楼  wh8766 2009-03-12  
收藏了~ 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值