MD5 和 RSA 加密算法理解

MD5和RSA是网络传输中最常用的两个算法,了解这两个算法原理后就能大致知道加密是怎么一回事了。但这两种算法使用环境有差异,刚好互补。

一、MD5算法

首先MD5是不可逆的,只能加密而不能解密。比如明文是hellolio,得到MD5加密后的字符串是:C6BBAFDE337BFB9775C5A9CAFB927EA2  但不能由后面一大串倒推出yanzi1225627.因此可以用来存储用户输入的密码在服务器上。现在下载文件校验文件是否中途被篡改也是用的它,原理参见:http://blog.csdn.net/forgotaboutgirl/article/details/7258109 无论在Android上还是pc上用java实现MD5都比较容易,因为java已经把它做到了java.security.MessageDigest里。下面是一个MD5Util.java类:

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-family:Comic Sans MS;font-size:18px;">package org.md5.util;  
  2.   
  3. import java.security.MessageDigest;  
  4. public class MD5Util {  
  5.     public final static String getMD5String(String s) {  
  6.         char hexDigits[] = { '0''1''2''3''4',  
  7.                 '5''6''7''8''9',  
  8.                 'A''B''C''D''E''F' };  
  9.         try {  
  10.             byte[] btInput = s.getBytes();  
  11.             //获得MD5摘要算法的 MessageDigest 对象  
  12.             MessageDigest mdInst = MessageDigest.getInstance("MD5");  
  13.             //使用指定的字节更新摘要  
  14.             mdInst.update(btInput);  
  15.             //获得密文  
  16.             byte[] md = mdInst.digest();  
  17.             //把密文转换成十六进制的字符串形式  
  18.             int j = md.length;  
  19.             char str[] = new char[j * 2];  
  20.             int k = 0;  
  21.             for (int i = 0; i < j; i++) {  
  22.                 byte byte0 = md[i];  
  23.                 str[k++] = hexDigits[byte0 >>> 4 & 0xf];  
  24.                 str[k++] = hexDigits[byte0 & 0xf];  
  25.             }  
  26.             return new String(str);  
  27.         }  
  28.         catch (Exception e) {  
  29.             e.printStackTrace();  
  30.             return null;  
  31.         }  
  32.     }  
  33. }</span>  

通过下面两行代码调用:

/************************************MD5加密测试*****************************/
String srcString = "hellolio";
System.out.println("MD5加密后 = " + MD5Util.getMD5String(srcString));

二、RSA加密

RSA是可逆的,一个字符串可以经rsa加密后,经加密后的字符串传到对端如服务器上,再进行解密即可。前提是服务器知道解密的私钥,当然这个私钥最好不要再网络传输。RSA算法描述中需要以下几个变量:

1、p和q 是不相等的,足够大的两个质数。 p和q是保密的

2、n = p*q n是公开的

3、f(n) = (p-1)*(q-1)

4、e 是和f(n)互质的质数

5、计算参数d 

6、经过上面5步计算得到公钥KU=(e,n) 私钥KR=(d,n)

下面两篇文章对此有清晰的描述:

http://wenku.baidu.com/view/e53fbe36a32d7375a417801b.html

http://bank.hexun.com/2009-06-24/118958531.html

下面是java实现RSAUtil.java类:

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

/****************************RSA加密解密测试********************************/
try {
RSAUtil rsa = new RSAUtil();
String str = "hellolio";
RSAPublicKey pubKey = rsa.getRSAPublicKey();
RSAPrivateKey priKey = rsa.getRSAPrivateKey();
byte[] enRsaBytes = rsa.encrypt(pubKey,str.getBytes());
String enRsaStr = new String(enRsaBytes, "UTF-8");
System.out.println("加密后==" + enRsaStr);
System.out.println("解密后==" + new String(rsa.decrypt(priKey, rsa.encrypt(pubKey,str.getBytes()))));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

下面是执行结果:

加密后==Wi��=�=�x��iw�xb�m����'�[��?�(�Ⴀ-s�o��@’�0I�;����y���J*��֊��jf%_��y���:��6� s�QM0M2&_��ǚ��X�b}�5��a���@�.�
解密后==hellolio




我已经做了完整的java测试包 下载链接见下:

http://download.csdn.net/detail/yanzi1225627/7382263




Java中RSA非对称密钥加解密使用示例

一、简介:

  RSA加密算法是最常用的非对称加密算法,CFCA在证书服务中离不了它。RSA是第一个比较完善的公开密钥算法,它既能用于加密,也能用于数字签名。这个算法经受住了多年深入的密码分析,虽然密码分析者既不能证明也不能否定RSA的安全性,但这恰恰说明该算法有一定的可信性,目前它已经成为最流行的公开密钥算法。

  二、RSA的公钥、私钥的组成,以及加密、解密的公式可见于下表

  三、使用方式:

  ① 假设A、B机器进行通信,已A机器为主;

  ② A首先需要用自己的私钥为发送请求数据签名,并将公钥一同发送给B;

  ③ B收到数据后,需要用A发送的公钥进行验证,已确保收到的数据是未经篡改的;

  ④ B验签通过后,处理逻辑,并把处理结果返回,返回数据需要用A发送的公钥进行加密(公钥加密后,只能用配对的私钥解密);

  ⑤ A收到B返回的数据,使用私钥解密,至此,一次数据交互完成。

该工具类中用到了BASE64,需要借助第三方类库:javabase64-1.3.1.jar

下载地址:http://download.csdn.net/detail/centralperk/5025595

注意:
RSA加密明文最大长度117字节,解密要求密文最大长度为128字节,所以在加密和解密的过程中需要分块进行。
RSA加密对明文的长度是有限制的,如果加密数据过大会抛出如下
异常:

[java]  view plain copy
  1. Exception in thread "main" javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes  
  2.     at com.sun.crypto.provider.RSACipher.a(DashoA13*..)  
  3.     at com.sun.crypto.provider.RSACipher.engineDoFinal(DashoA13*..)  
  4.     at javax.crypto.Cipher.doFinal(DashoA13*..)  

RSAUtils.java
[java]  view plain copy
  1. package security;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.security.Key;  
  5. import java.security.KeyFactory;  
  6. import java.security.KeyPair;  
  7. import java.security.KeyPairGenerator;  
  8. import java.security.PrivateKey;  
  9. import java.security.PublicKey;  
  10. import java.security.Signature;  
  11. import java.security.interfaces.RSAPrivateKey;  
  12. import java.security.interfaces.RSAPublicKey;  
  13. import java.security.spec.PKCS8EncodedKeySpec;  
  14. import java.security.spec.X509EncodedKeySpec;  
  15. import java.util.HashMap;  
  16. import java.util.Map;  
  17.   
  18. import javax.crypto.Cipher;  
  19.   
  20. /** *//** 
  21.  * <p> 
  22.  * RSA公钥/私钥/签名工具包 
  23.  * </p> 
  24.  * <p> 
  25.  * 罗纳德·李维斯特(Ron [R]ivest)、阿迪·萨莫尔(Adi [S]hamir)和伦纳德·阿德曼(Leonard [A]dleman) 
  26.  * </p> 
  27.  * <p> 
  28.  * 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/> 
  29.  * 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,<br/> 
  30.  * 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全 
  31.  * </p> 
  32.  *  
  33.  * @author IceWee 
  34.  * @date 2012-4-26 
  35.  * @version 1.0 
  36.  */  
  37. public class RSAUtils {  
  38.   
  39.     /** *//** 
  40.      * 加密算法RSA 
  41.      */  
  42.     public static final String KEY_ALGORITHM = "RSA";  
  43.       
  44.     /** *//** 
  45.      * 签名算法 
  46.      */  
  47.     public static final String SIGNATURE_ALGORITHM = "MD5withRSA";  
  48.   
  49.     /** *//** 
  50.      * 获取公钥的key 
  51.      */  
  52.     private static final String PUBLIC_KEY = "RSAPublicKey";  
  53.       
  54.     /** *//** 
  55.      * 获取私钥的key 
  56.      */  
  57.     private static final String PRIVATE_KEY = "RSAPrivateKey";  
  58.       
  59.     /** *//** 
  60.      * RSA最大加密明文大小 
  61.      */  
  62.     private static final int MAX_ENCRYPT_BLOCK = 117;  
  63.       
  64.     /** *//** 
  65.      * RSA最大解密密文大小 
  66.      */  
  67.     private static final int MAX_DECRYPT_BLOCK = 128;  
  68.   
  69.     /** *//** 
  70.      * <p> 
  71.      * 生成密钥对(公钥和私钥) 
  72.      * </p> 
  73.      *  
  74.      * @return 
  75.      * @throws Exception 
  76.      */  
  77.     public static Map<String, Object> genKeyPair() throws Exception {  
  78.         KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);  
  79.         keyPairGen.initialize(1024);  
  80.         KeyPair keyPair = keyPairGen.generateKeyPair();  
  81.         RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  
  82.         RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();  
  83.         Map<String, Object> keyMap = new HashMap<String, Object>(2);  
  84.         keyMap.put(PUBLIC_KEY, publicKey);  
  85.         keyMap.put(PRIVATE_KEY, privateKey);  
  86.         return keyMap;  
  87.     }  
  88.       
  89.     /** *//** 
  90.      * <p> 
  91.      * 用私钥对信息生成数字签名 
  92.      * </p> 
  93.      *  
  94.      * @param data 已加密数据 
  95.      * @param privateKey 私钥(BASE64编码) 
  96.      *  
  97.      * @return 
  98.      * @throws Exception 
  99.      */  
  100.     public static String sign(byte[] data, String privateKey) throws Exception {  
  101.         byte[] keyBytes = Base64Utils.decode(privateKey);  
  102.         PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);  
  103.         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
  104.         PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);  
  105.         Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);  
  106.         signature.initSign(privateK);  
  107.         signature.update(data);  
  108.         return Base64Utils.encode(signature.sign());  
  109.     }  
  110.   
  111.     /** *//** 
  112.      * <p> 
  113.      * 校验数字签名 
  114.      * </p> 
  115.      *  
  116.      * @param data 已加密数据 
  117.      * @param publicKey 公钥(BASE64编码) 
  118.      * @param sign 数字签名 
  119.      *  
  120.      * @return 
  121.      * @throws Exception 
  122.      *  
  123.      */  
  124.     public static boolean verify(byte[] data, String publicKey, String sign)  
  125.             throws Exception {  
  126.         byte[] keyBytes = Base64Utils.decode(publicKey);  
  127.         X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);  
  128.         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
  129.         PublicKey publicK = keyFactory.generatePublic(keySpec);  
  130.         Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);  
  131.         signature.initVerify(publicK);  
  132.         signature.update(data);  
  133.         return signature.verify(Base64Utils.decode(sign));  
  134.     }  
  135.   
  136.     /** *//** 
  137.      * <P> 
  138.      * 私钥解密 
  139.      * </p> 
  140.      *  
  141.      * @param encryptedData 已加密数据 
  142.      * @param privateKey 私钥(BASE64编码) 
  143.      * @return 
  144.      * @throws Exception 
  145.      */  
  146.     public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)  
  147.             throws Exception {  
  148.         byte[] keyBytes = Base64Utils.decode(privateKey);  
  149.         PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);  
  150.         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
  151.         Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);  
  152.         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());  
  153.         cipher.init(Cipher.DECRYPT_MODE, privateK);  
  154.         int inputLen = encryptedData.length;  
  155.         ByteArrayOutputStream out = new ByteArrayOutputStream();  
  156.         int offSet = 0;  
  157.         byte[] cache;  
  158.         int i = 0;  
  159.         // 对数据分段解密  
  160.         while (inputLen - offSet > 0) {  
  161.             if (inputLen - offSet > MAX_DECRYPT_BLOCK) {  
  162.                 cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);  
  163.             } else {  
  164.                 cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);  
  165.             }  
  166.             out.write(cache, 0, cache.length);  
  167.             i++;  
  168.             offSet = i * MAX_DECRYPT_BLOCK;  
  169.         }  
  170.         byte[] decryptedData = out.toByteArray();  
  171.         out.close();  
  172.         return decryptedData;  
  173.     }  
  174.   
  175.     /** *//** 
  176.      * <p> 
  177.      * 公钥解密 
  178.      * </p> 
  179.      *  
  180.      * @param encryptedData 已加密数据 
  181.      * @param publicKey 公钥(BASE64编码) 
  182.      * @return 
  183.      * @throws Exception 
  184.      */  
  185.     public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey)  
  186.             throws Exception {  
  187.         byte[] keyBytes = Base64Utils.decode(publicKey);  
  188.         X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);  
  189.         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
  190.         Key publicK = keyFactory.generatePublic(x509KeySpec);  
  191.         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());  
  192.         cipher.init(Cipher.DECRYPT_MODE, publicK);  
  193.         int inputLen = encryptedData.length;  
  194.         ByteArrayOutputStream out = new ByteArrayOutputStream();  
  195.         int offSet = 0;  
  196.         byte[] cache;  
  197.         int i = 0;  
  198.         // 对数据分段解密  
  199.         while (inputLen - offSet > 0) {  
  200.             if (inputLen - offSet > MAX_DECRYPT_BLOCK) {  
  201.                 cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);  
  202.             } else {  
  203.                 cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);  
  204.             }  
  205.             out.write(cache, 0, cache.length);  
  206.             i++;  
  207.             offSet = i * MAX_DECRYPT_BLOCK;  
  208.         }  
  209.         byte[] decryptedData = out.toByteArray();  
  210.         out.close();  
  211.         return decryptedData;  
  212.     }  
  213.   
  214.     /** *//** 
  215.      * <p> 
  216.      * 公钥加密 
  217.      * </p> 
  218.      *  
  219.      * @param data 源数据 
  220.      * @param publicKey 公钥(BASE64编码) 
  221.      * @return 
  222.      * @throws Exception 
  223.      */  
  224.     public static byte[] encryptByPublicKey(byte[] data, String publicKey)  
  225.             throws Exception {  
  226.         byte[] keyBytes = Base64Utils.decode(publicKey);  
  227.         X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);  
  228.         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
  229.         Key publicK = keyFactory.generatePublic(x509KeySpec);  
  230.         // 对数据加密  
  231.         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());  
  232.         cipher.init(Cipher.ENCRYPT_MODE, publicK);  
  233.         int inputLen = data.length;  
  234.         ByteArrayOutputStream out = new ByteArrayOutputStream();  
  235.         int offSet = 0;  
  236.         byte[] cache;  
  237.         int i = 0;  
  238.         // 对数据分段加密  
  239.         while (inputLen - offSet > 0) {  
  240.             if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {  
  241.                 cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);  
  242.             } else {  
  243.                 cache = cipher.doFinal(data, offSet, inputLen - offSet);  
  244.             }  
  245.             out.write(cache, 0, cache.length);  
  246.             i++;  
  247.             offSet = i * MAX_ENCRYPT_BLOCK;  
  248.         }  
  249.         byte[] encryptedData = out.toByteArray();  
  250.         out.close();  
  251.         return encryptedData;  
  252.     }  
  253.   
  254.     /** *//** 
  255.      * <p> 
  256.      * 私钥加密 
  257.      * </p> 
  258.      *  
  259.      * @param data 源数据 
  260.      * @param privateKey 私钥(BASE64编码) 
  261.      * @return 
  262.      * @throws Exception 
  263.      */  
  264.     public static byte[] encryptByPrivateKey(byte[] data, String privateKey)  
  265.             throws Exception {  
  266.         byte[] keyBytes = Base64Utils.decode(privateKey);  
  267.         PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);  
  268.         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
  269.         Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);  
  270.         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());  
  271.         cipher.init(Cipher.ENCRYPT_MODE, privateK);  
  272.         int inputLen = data.length;  
  273.         ByteArrayOutputStream out = new ByteArrayOutputStream();  
  274.         int offSet = 0;  
  275.         byte[] cache;  
  276.         int i = 0;  
  277.         // 对数据分段加密  
  278.         while (inputLen - offSet > 0) {  
  279.             if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {  
  280.                 cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);  
  281.             } else {  
  282.                 cache = cipher.doFinal(data, offSet, inputLen - offSet);  
  283.             }  
  284.             out.write(cache, 0, cache.length);  
  285.             i++;  
  286.             offSet = i * MAX_ENCRYPT_BLOCK;  
  287.         }  
  288.         byte[] encryptedData = out.toByteArray();  
  289.         out.close();  
  290.         return encryptedData;  
  291.     }  
  292.   
  293.     /** *//** 
  294.      * <p> 
  295.      * 获取私钥 
  296.      * </p> 
  297.      *  
  298.      * @param keyMap 密钥对 
  299.      * @return 
  300.      * @throws Exception 
  301.      */  
  302.     public static String getPrivateKey(Map<String, Object> keyMap)  
  303.             throws Exception {  
  304.         Key key = (Key) keyMap.get(PRIVATE_KEY);  
  305.         return Base64Utils.encode(key.getEncoded());  
  306.     }  
  307.   
  308.     /** *//** 
  309.      * <p> 
  310.      * 获取公钥 
  311.      * </p> 
  312.      *  
  313.      * @param keyMap 密钥对 
  314.      * @return 
  315.      * @throws Exception 
  316.      */  
  317.     public static String getPublicKey(Map<String, Object> keyMap)  
  318.             throws Exception {  
  319.         Key key = (Key) keyMap.get(PUBLIC_KEY);  
  320.         return Base64Utils.encode(key.getEncoded());  
  321.     }  
  322.   
  323. }  

Base64Utils.java
[java]  view plain copy
  1. package security;  
  2.   
  3. import java.io.ByteArrayInputStream;  
  4. import java.io.ByteArrayOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.FileOutputStream;  
  8. import java.io.InputStream;  
  9. import java.io.OutputStream;  
  10.   
  11. import it.sauronsoftware.base64.Base64;  
  12.   
  13. /** *//** 
  14.  * <p> 
  15.  * BASE64编码解码工具包 
  16.  * </p> 
  17.  * <p> 
  18.  * 依赖javabase64-1.3.1.jar 
  19.  * </p> 
  20.  *  
  21.  * @author IceWee 
  22.  * @date 2012-5-19 
  23.  * @version 1.0 
  24.  */  
  25. public class Base64Utils {  
  26.   
  27.     /** *//** 
  28.      * 文件读取缓冲区大小 
  29.      */  
  30.     private static final int CACHE_SIZE = 1024;  
  31.       
  32.     /** *//** 
  33.      * <p> 
  34.      * BASE64字符串解码为二进制数据 
  35.      * </p> 
  36.      *  
  37.      * @param base64 
  38.      * @return 
  39.      * @throws Exception 
  40.      */  
  41.     public static byte[] decode(String base64) throws Exception {  
  42.         return Base64.decode(base64.getBytes());  
  43.     }  
  44.       
  45.     /** *//** 
  46.      * <p> 
  47.      * 二进制数据编码为BASE64字符串 
  48.      * </p> 
  49.      *  
  50.      * @param bytes 
  51.      * @return 
  52.      * @throws Exception 
  53.      */  
  54.     public static String encode(byte[] bytes) throws Exception {  
  55.         return new String(Base64.encode(bytes));  
  56.     }  
  57.       
  58.     /** *//** 
  59.      * <p> 
  60.      * 将文件编码为BASE64字符串 
  61.      * </p> 
  62.      * <p> 
  63.      * 大文件慎用,可能会导致内存溢出 
  64.      * </p> 
  65.      *  
  66.      * @param filePath 文件绝对路径 
  67.      * @return 
  68.      * @throws Exception 
  69.      */  
  70.     public static String encodeFile(String filePath) throws Exception {  
  71.         byte[] bytes = fileToByte(filePath);  
  72.         return encode(bytes);  
  73.     }  
  74.       
  75.     /** *//** 
  76.      * <p> 
  77.      * BASE64字符串转回文件 
  78.      * </p> 
  79.      *  
  80.      * @param filePath 文件绝对路径 
  81.      * @param base64 编码字符串 
  82.      * @throws Exception 
  83.      */  
  84.     public static void decodeToFile(String filePath, String base64) throws Exception {  
  85.         byte[] bytes = decode(base64);  
  86.         byteArrayToFile(bytes, filePath);  
  87.     }  
  88.       
  89.     /** *//** 
  90.      * <p> 
  91.      * 文件转换为二进制数组 
  92.      * </p> 
  93.      *  
  94.      * @param filePath 文件路径 
  95.      * @return 
  96.      * @throws Exception 
  97.      */  
  98.     public static byte[] fileToByte(String filePath) throws Exception {  
  99.         byte[] data = new byte[0];  
  100.         File file = new File(filePath);  
  101.         if (file.exists()) {  
  102.             FileInputStream in = new FileInputStream(file);  
  103.             ByteArrayOutputStream out = new ByteArrayOutputStream(2048);  
  104.             byte[] cache = new byte[CACHE_SIZE];  
  105.             int nRead = 0;  
  106.             while ((nRead = in.read(cache)) != -1) {  
  107.                 out.write(cache, 0, nRead);  
  108.                 out.flush();  
  109.             }  
  110.             out.close();  
  111.             in.close();  
  112.             data = out.toByteArray();  
  113.          }  
  114.         return data;  
  115.     }  
  116.       
  117.     /** *//** 
  118.      * <p> 
  119.      * 二进制数据写文件 
  120.      * </p> 
  121.      *  
  122.      * @param bytes 二进制数据 
  123.      * @param filePath 文件生成目录 
  124.      */  
  125.     public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {  
  126.         InputStream in = new ByteArrayInputStream(bytes);     
  127.         File destFile = new File(filePath);  
  128.         if (!destFile.getParentFile().exists()) {  
  129.             destFile.getParentFile().mkdirs();  
  130.         }  
  131.         destFile.createNewFile();  
  132.         OutputStream out = new FileOutputStream(destFile);  
  133.         byte[] cache = new byte[CACHE_SIZE];  
  134.         int nRead = 0;  
  135.         while ((nRead = in.read(cache)) != -1) {     
  136.             out.write(cache, 0, nRead);  
  137.             out.flush();  
  138.         }  
  139.         out.close();  
  140.         in.close();  
  141.     }  
  142.       
  143.       
  144. }  

 

RSATester.java

[java]  view plain copy
  1. package security;  
  2.   
  3. import java.util.Map;  
  4.   
  5. public class RSATester {  
  6.   
  7.     static String publicKey;  
  8.     static String privateKey;  
  9.   
  10.     static {  
  11.         try {  
  12.             Map<String, Object> keyMap = RSAUtils.genKeyPair();  
  13.             publicKey = RSAUtils.getPublicKey(keyMap);  
  14.             privateKey = RSAUtils.getPrivateKey(keyMap);  
  15.             System.err.println("公钥: \n\r" + publicKey);  
  16.             System.err.println("私钥: \n\r" + privateKey);  
  17.         } catch (Exception e) {  
  18.             e.printStackTrace();  
  19.         }  
  20.     }  
  21.       
  22.     public static void main(String[] args) throws Exception {  
  23.         test();  
  24.         testSign();  
  25.     }  
  26.   
  27.     static void test() throws Exception {  
  28.         System.err.println("公钥加密——私钥解密");  
  29.         String source = "这是一行没有任何意义的文字,你看完了等于没看,不是吗?";  
  30.         System.out.println("\r加密前文字:\r\n" + source);  
  31.         byte[] data = source.getBytes();  
  32.         byte[] encodedData = RSAUtils.encryptByPublicKey(data, publicKey);  
  33.         System.out.println("加密后文字:\r\n" + new String(encodedData));  
  34.         byte[] decodedData = RSAUtils.decryptByPrivateKey(encodedData, privateKey);  
  35.         String target = new String(decodedData);  
  36.         System.out.println("解密后文字: \r\n" + target);  
  37.     }  
  38.   
  39.     static void testSign() throws Exception {  
  40.         System.err.println("私钥加密——公钥解密");  
  41.         String source = "这是一行测试RSA数字签名的无意义文字";  
  42.         System.out.println("原文字:\r\n" + source);  
  43.         byte[] data = source.getBytes();  
  44.         byte[] encodedData = RSAUtils.encryptByPrivateKey(data, privateKey);  
  45.         System.out.println("加密后:\r\n" + new String(encodedData));  
  46.         byte[] decodedData = RSAUtils.decryptByPublicKey(encodedData, publicKey);  
  47.         String target = new String(decodedData);  
  48.         System.out.println("解密后: \r\n" + target);  
  49.         System.err.println("私钥签名——公钥验证签名");  
  50.         String sign = RSAUtils.sign(encodedData, privateKey);  
  51.         System.err.println("签名:\r" + sign);  
  52.         boolean status = RSAUtils.verify(encodedData, publicKey, sign);  
  53.         System.err.println("验证结果:\r" + status);  
  54.     }  
  55.       
  56. }  


我已经做了完整的java测试包 下载链接见下:

http://download.csdn.net/detail/yanzi1225627/7382263


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值