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类:
- <span style="font-family:Comic Sans MS;font-size:18px;">package org.md5.util;
- import java.security.MessageDigest;
- public class MD5Util {
- public final static String getMD5String(String s) {
- char hexDigits[] = { '0', '1', '2', '3', '4',
- '5', '6', '7', '8', '9',
- 'A', 'B', 'C', 'D', 'E', 'F' };
- try {
- byte[] btInput = s.getBytes();
- //获得MD5摘要算法的 MessageDigest 对象
- MessageDigest mdInst = MessageDigest.getInstance("MD5");
- //使用指定的字节更新摘要
- mdInst.update(btInput);
- //获得密文
- byte[] md = mdInst.digest();
- //把密文转换成十六进制的字符串形式
- int j = md.length;
- char str[] = new char[j * 2];
- int k = 0;
- for (int i = 0; i < j; i++) {
- byte byte0 = md[i];
- str[k++] = hexDigits[byte0 >>> 4 & 0xf];
- str[k++] = hexDigits[byte0 & 0xf];
- }
- return new String(str);
- }
- catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- }</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类:
- <span style="font-family:Comic Sans MS;font-size:18px;">package org.rsa.util;
- import javax.crypto.Cipher;
- import java.security.*;
- import java.security.spec.RSAPublicKeySpec;
- import java.security.spec.RSAPrivateKeySpec;
- import java.security.spec.InvalidKeySpecException;
- import java.security.interfaces.RSAPrivateKey;
- import java.security.interfaces.RSAPublicKey;
- import java.io.*;
- import java.math.BigInteger;
- /**
- * RSA 工具类。提供加密,解密,生成密钥对等方法。
- * 需要到http://www.bouncycastle.org下载bcprov-jdk14-123.jar。
- * RSA加密原理概述
- * RSA的安全性依赖于大数的分解,公钥和私钥都是两个大素数(大于100的十进制位)的函数。
- * 据猜测,从一个密钥和密文推断出明文的难度等同于分解两个大素数的积
- * ===================================================================
- * (该算法的安全性未得到理论的证明)
- * ===================================================================
- * 密钥的产生:
- * 1.选择两个大素数 p,q ,计算 n=p*q;
- * 2.随机选择加密密钥 e ,要求 e 和 (p-1)*(q-1)互质
- * 3.利用 Euclid 算法计算解密密钥 d , 使其满足 e*d = 1(mod(p-1)*(q-1)) (其中 n,d 也要互质)
- * 4:至此得出公钥为 (n,e) 私钥为 (n,d)
- * ===================================================================
- * 加解密方法:
- * 1.首先将要加密的信息 m(二进制表示) 分成等长的数据块 m1,m2,...,mi 块长 s(尽可能大) ,其中 2^s<n
- * 2:对应的密文是: ci = mi^e(mod n)
- * 3:解密时作如下计算: mi = ci^d(mod n)
- * ===================================================================
- * RSA速度
- * 由于进行的都是大数计算,使得RSA最快的情况也比DES慢上100倍,无论 是软件还是硬件实现。
- * 速度一直是RSA的缺陷。一般来说只用于少量数据 加密。
- *文件名:RSAUtil.java<br>
- *@author hellio<br>
- *版本:<br>
- *描述:<br>
- *创建时间:2015-9-23 下午09:58:16<br>
- *文件描述:<br>
- *修改者:<br>
- *修改日期:<br>
- *修改描述:<br>
- */
- public class RSAUtil {
- //密钥对
- private KeyPair keyPair = null;
- /**
- * 初始化密钥对
- */
- public RSAUtil(){
- try {
- this.keyPair = this.generateKeyPair();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 生成密钥对
- * @return KeyPair
- * @throws Exception
- */
- private KeyPair generateKeyPair() throws Exception {
- try {
- KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",new org.bouncycastle.jce.provider.BouncyCastleProvider());
- //这个值关系到块加密的大小,可以更改,但是不要太大,否则效率会低
- final int KEY_SIZE = 1024;
- keyPairGen.initialize(KEY_SIZE, new SecureRandom());
- KeyPair keyPair = keyPairGen.genKeyPair();
- return keyPair;
- } catch (Exception e) {
- throw new Exception(e.getMessage());
- }
- }
- /**
- * 生成公钥
- * @param modulus
- * @param publicExponent
- * @return RSAPublicKey
- * @throws Exception
- */
- private RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent) throws Exception {
- KeyFactory keyFac = null;
- try {
- keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
- } catch (NoSuchAlgorithmException ex) {
- throw new Exception(ex.getMessage());
- }
- RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent));
- try {
- return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);
- } catch (InvalidKeySpecException ex) {
- throw new Exception(ex.getMessage());
- }
- }
- /**
- * 生成私钥
- * @param modulus
- * @param privateExponent
- * @return RSAPrivateKey
- * @throws Exception
- */
- private RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent) throws Exception {
- KeyFactory keyFac = null;
- try {
- keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
- } catch (NoSuchAlgorithmException ex) {
- throw new Exception(ex.getMessage());
- }
- RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(modulus), new BigInteger(privateExponent));
- try {
- return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);
- } catch (InvalidKeySpecException ex) {
- throw new Exception(ex.getMessage());
- }
- }
- /**
- * 加密
- * @param key 加密的密钥
- * @param data 待加密的明文数据
- * @return 加密后的数据
- * @throws Exception
- */
- public byte[] encrypt(Key key, byte[] data) throws Exception {
- try {
- Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
- cipher.init(Cipher.ENCRYPT_MODE, key);
- //获得加密块大小,如:加密前数据为128个byte,而key_size=1024 加密块大小为127 byte,加密后为128个byte;
- //因此共有2个加密块,第一个127 byte第二个为1个byte
- int blockSize = cipher.getBlockSize();
- int outputSize = cipher.getOutputSize(data.length);//获得加密块加密后块大小
- int leavedSize = data.length % blockSize;
- int blocksSize = leavedSize != 0 ? data.length / blockSize + 1 : data.length / blockSize;
- byte[] raw = new byte[outputSize * blocksSize];
- int i = 0;
- while (data.length - i * blockSize > 0) {
- if (data.length - i * blockSize > blockSize)
- cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize);
- else
- cipher.doFinal(data, i * blockSize, data.length - i * blockSize, raw, i * outputSize);
- //这里面doUpdate方法不可用,查看源代码后发现每次doUpdate后并没有什么实际动作除了把byte[]放到ByteArrayOutputStream中
- //,而最后doFinal的时候才将所有的byte[]进行加密,可是到了此时加密块大小很可能已经超出了OutputSize所以只好用dofinal方法。
- i++;
- }
- return raw;
- } catch (Exception e) {
- throw new Exception(e.getMessage());
- }
- }
- /**
- * 解密
- * @param key 解密的密钥
- * @param raw 已经加密的数据
- * @return 解密后的明文
- * @throws Exception
- */
- public byte[] decrypt(Key key, byte[] raw) throws Exception {
- try {
- Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
- cipher.init(cipher.DECRYPT_MODE, key);
- int blockSize = cipher.getBlockSize();
- ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
- int j = 0;
- while (raw.length - j * blockSize > 0) {
- bout.write(cipher.doFinal(raw, j * blockSize, blockSize));
- j++;
- }
- return bout.toByteArray();
- } catch (Exception e) {
- throw new Exception(e.getMessage());
- }
- }
- /**
- * 返回公钥
- * @return
- * @throws Exception
- */
- public RSAPublicKey getRSAPublicKey() throws Exception{
- //获取公钥
- RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();
- //获取公钥系数(字节数组形式)
- byte[] pubModBytes = pubKey.getModulus().toByteArray();
- //返回公钥公用指数(字节数组形式)
- byte[] pubPubExpBytes = pubKey.getPublicExponent().toByteArray();
- //生成公钥
- RSAPublicKey recoveryPubKey = this.generateRSAPublicKey(pubModBytes,pubPubExpBytes);
- return recoveryPubKey;
- }
- /**
- * 获取私钥
- * @return
- * @throws Exception
- */
- public RSAPrivateKey getRSAPrivateKey() throws Exception{
- //获取私钥
- RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();
- //返回私钥系数(字节数组形式)
- byte[] priModBytes = priKey.getModulus().toByteArray();
- //返回私钥专用指数(字节数组形式)
- byte[] priPriExpBytes = priKey.getPrivateExponent().toByteArray();
- //生成私钥
- RSAPrivateKey recoveryPriKey = this.generateRSAPrivateKey(priModBytes,priPriExpBytes);
- return recoveryPriKey;
- }
- }
- </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加密对明文的长度是有限制的,如果加密数据过大会抛出如下异常:
- Exception in thread "main" javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes
- at com.sun.crypto.provider.RSACipher.a(DashoA13*..)
- at com.sun.crypto.provider.RSACipher.engineDoFinal(DashoA13*..)
- at javax.crypto.Cipher.doFinal(DashoA13*..)
RSAUtils.java
- package security;
- import java.io.ByteArrayOutputStream;
- import java.security.Key;
- import java.security.KeyFactory;
- import java.security.KeyPair;
- import java.security.KeyPairGenerator;
- import java.security.PrivateKey;
- import java.security.PublicKey;
- import java.security.Signature;
- import java.security.interfaces.RSAPrivateKey;
- import java.security.interfaces.RSAPublicKey;
- import java.security.spec.PKCS8EncodedKeySpec;
- import java.security.spec.X509EncodedKeySpec;
- import java.util.HashMap;
- import java.util.Map;
- import javax.crypto.Cipher;
- /** *//**
- * <p>
- * RSA公钥/私钥/签名工具包
- * </p>
- * <p>
- * 罗纳德·李维斯特(Ron [R]ivest)、阿迪·萨莫尔(Adi [S]hamir)和伦纳德·阿德曼(Leonard [A]dleman)
- * </p>
- * <p>
- * 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/>
- * 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,<br/>
- * 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全
- * </p>
- *
- * @author IceWee
- * @date 2012-4-26
- * @version 1.0
- */
- public class RSAUtils {
- /** *//**
- * 加密算法RSA
- */
- public static final String KEY_ALGORITHM = "RSA";
- /** *//**
- * 签名算法
- */
- public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
- /** *//**
- * 获取公钥的key
- */
- private static final String PUBLIC_KEY = "RSAPublicKey";
- /** *//**
- * 获取私钥的key
- */
- private static final String PRIVATE_KEY = "RSAPrivateKey";
- /** *//**
- * RSA最大加密明文大小
- */
- private static final int MAX_ENCRYPT_BLOCK = 117;
- /** *//**
- * RSA最大解密密文大小
- */
- private static final int MAX_DECRYPT_BLOCK = 128;
- /** *//**
- * <p>
- * 生成密钥对(公钥和私钥)
- * </p>
- *
- * @return
- * @throws Exception
- */
- public static Map<String, Object> genKeyPair() throws Exception {
- KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
- keyPairGen.initialize(1024);
- KeyPair keyPair = keyPairGen.generateKeyPair();
- RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
- RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
- Map<String, Object> keyMap = new HashMap<String, Object>(2);
- keyMap.put(PUBLIC_KEY, publicKey);
- keyMap.put(PRIVATE_KEY, privateKey);
- return keyMap;
- }
- /** *//**
- * <p>
- * 用私钥对信息生成数字签名
- * </p>
- *
- * @param data 已加密数据
- * @param privateKey 私钥(BASE64编码)
- *
- * @return
- * @throws Exception
- */
- public static String sign(byte[] data, String privateKey) throws Exception {
- byte[] keyBytes = Base64Utils.decode(privateKey);
- PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
- KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
- PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
- Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
- signature.initSign(privateK);
- signature.update(data);
- return Base64Utils.encode(signature.sign());
- }
- /** *//**
- * <p>
- * 校验数字签名
- * </p>
- *
- * @param data 已加密数据
- * @param publicKey 公钥(BASE64编码)
- * @param sign 数字签名
- *
- * @return
- * @throws Exception
- *
- */
- public static boolean verify(byte[] data, String publicKey, String sign)
- throws Exception {
- byte[] keyBytes = Base64Utils.decode(publicKey);
- X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
- KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
- PublicKey publicK = keyFactory.generatePublic(keySpec);
- Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
- signature.initVerify(publicK);
- signature.update(data);
- return signature.verify(Base64Utils.decode(sign));
- }
- /** *//**
- * <P>
- * 私钥解密
- * </p>
- *
- * @param encryptedData 已加密数据
- * @param privateKey 私钥(BASE64编码)
- * @return
- * @throws Exception
- */
- public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)
- throws Exception {
- byte[] keyBytes = Base64Utils.decode(privateKey);
- PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
- KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
- Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
- Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
- cipher.init(Cipher.DECRYPT_MODE, privateK);
- int inputLen = encryptedData.length;
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- int offSet = 0;
- byte[] cache;
- int i = 0;
- // 对数据分段解密
- while (inputLen - offSet > 0) {
- if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
- cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
- } else {
- cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
- }
- out.write(cache, 0, cache.length);
- i++;
- offSet = i * MAX_DECRYPT_BLOCK;
- }
- byte[] decryptedData = out.toByteArray();
- out.close();
- return decryptedData;
- }
- /** *//**
- * <p>
- * 公钥解密
- * </p>
- *
- * @param encryptedData 已加密数据
- * @param publicKey 公钥(BASE64编码)
- * @return
- * @throws Exception
- */
- public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey)
- throws Exception {
- byte[] keyBytes = Base64Utils.decode(publicKey);
- X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
- KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
- Key publicK = keyFactory.generatePublic(x509KeySpec);
- Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
- cipher.init(Cipher.DECRYPT_MODE, publicK);
- int inputLen = encryptedData.length;
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- int offSet = 0;
- byte[] cache;
- int i = 0;
- // 对数据分段解密
- while (inputLen - offSet > 0) {
- if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
- cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
- } else {
- cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
- }
- out.write(cache, 0, cache.length);
- i++;
- offSet = i * MAX_DECRYPT_BLOCK;
- }
- byte[] decryptedData = out.toByteArray();
- out.close();
- return decryptedData;
- }
- /** *//**
- * <p>
- * 公钥加密
- * </p>
- *
- * @param data 源数据
- * @param publicKey 公钥(BASE64编码)
- * @return
- * @throws Exception
- */
- public static byte[] encryptByPublicKey(byte[] data, String publicKey)
- throws Exception {
- byte[] keyBytes = Base64Utils.decode(publicKey);
- X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
- KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
- Key publicK = keyFactory.generatePublic(x509KeySpec);
- // 对数据加密
- Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
- cipher.init(Cipher.ENCRYPT_MODE, publicK);
- int inputLen = data.length;
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- int offSet = 0;
- byte[] cache;
- int i = 0;
- // 对数据分段加密
- while (inputLen - offSet > 0) {
- if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
- cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
- } else {
- cache = cipher.doFinal(data, offSet, inputLen - offSet);
- }
- out.write(cache, 0, cache.length);
- i++;
- offSet = i * MAX_ENCRYPT_BLOCK;
- }
- byte[] encryptedData = out.toByteArray();
- out.close();
- return encryptedData;
- }
- /** *//**
- * <p>
- * 私钥加密
- * </p>
- *
- * @param data 源数据
- * @param privateKey 私钥(BASE64编码)
- * @return
- * @throws Exception
- */
- public static byte[] encryptByPrivateKey(byte[] data, String privateKey)
- throws Exception {
- byte[] keyBytes = Base64Utils.decode(privateKey);
- PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
- KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
- Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
- Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
- cipher.init(Cipher.ENCRYPT_MODE, privateK);
- int inputLen = data.length;
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- int offSet = 0;
- byte[] cache;
- int i = 0;
- // 对数据分段加密
- while (inputLen - offSet > 0) {
- if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
- cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
- } else {
- cache = cipher.doFinal(data, offSet, inputLen - offSet);
- }
- out.write(cache, 0, cache.length);
- i++;
- offSet = i * MAX_ENCRYPT_BLOCK;
- }
- byte[] encryptedData = out.toByteArray();
- out.close();
- return encryptedData;
- }
- /** *//**
- * <p>
- * 获取私钥
- * </p>
- *
- * @param keyMap 密钥对
- * @return
- * @throws Exception
- */
- public static String getPrivateKey(Map<String, Object> keyMap)
- throws Exception {
- Key key = (Key) keyMap.get(PRIVATE_KEY);
- return Base64Utils.encode(key.getEncoded());
- }
- /** *//**
- * <p>
- * 获取公钥
- * </p>
- *
- * @param keyMap 密钥对
- * @return
- * @throws Exception
- */
- public static String getPublicKey(Map<String, Object> keyMap)
- throws Exception {
- Key key = (Key) keyMap.get(PUBLIC_KEY);
- return Base64Utils.encode(key.getEncoded());
- }
- }
Base64Utils.java
- package security;
- import java.io.ByteArrayInputStream;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.InputStream;
- import java.io.OutputStream;
- import it.sauronsoftware.base64.Base64;
- /** *//**
- * <p>
- * BASE64编码解码工具包
- * </p>
- * <p>
- * 依赖javabase64-1.3.1.jar
- * </p>
- *
- * @author IceWee
- * @date 2012-5-19
- * @version 1.0
- */
- public class Base64Utils {
- /** *//**
- * 文件读取缓冲区大小
- */
- private static final int CACHE_SIZE = 1024;
- /** *//**
- * <p>
- * BASE64字符串解码为二进制数据
- * </p>
- *
- * @param base64
- * @return
- * @throws Exception
- */
- public static byte[] decode(String base64) throws Exception {
- return Base64.decode(base64.getBytes());
- }
- /** *//**
- * <p>
- * 二进制数据编码为BASE64字符串
- * </p>
- *
- * @param bytes
- * @return
- * @throws Exception
- */
- public static String encode(byte[] bytes) throws Exception {
- return new String(Base64.encode(bytes));
- }
- /** *//**
- * <p>
- * 将文件编码为BASE64字符串
- * </p>
- * <p>
- * 大文件慎用,可能会导致内存溢出
- * </p>
- *
- * @param filePath 文件绝对路径
- * @return
- * @throws Exception
- */
- public static String encodeFile(String filePath) throws Exception {
- byte[] bytes = fileToByte(filePath);
- return encode(bytes);
- }
- /** *//**
- * <p>
- * BASE64字符串转回文件
- * </p>
- *
- * @param filePath 文件绝对路径
- * @param base64 编码字符串
- * @throws Exception
- */
- public static void decodeToFile(String filePath, String base64) throws Exception {
- byte[] bytes = decode(base64);
- byteArrayToFile(bytes, filePath);
- }
- /** *//**
- * <p>
- * 文件转换为二进制数组
- * </p>
- *
- * @param filePath 文件路径
- * @return
- * @throws Exception
- */
- public static byte[] fileToByte(String filePath) throws Exception {
- byte[] data = new byte[0];
- File file = new File(filePath);
- if (file.exists()) {
- FileInputStream in = new FileInputStream(file);
- ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
- byte[] cache = new byte[CACHE_SIZE];
- int nRead = 0;
- while ((nRead = in.read(cache)) != -1) {
- out.write(cache, 0, nRead);
- out.flush();
- }
- out.close();
- in.close();
- data = out.toByteArray();
- }
- return data;
- }
- /** *//**
- * <p>
- * 二进制数据写文件
- * </p>
- *
- * @param bytes 二进制数据
- * @param filePath 文件生成目录
- */
- public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
- InputStream in = new ByteArrayInputStream(bytes);
- File destFile = new File(filePath);
- if (!destFile.getParentFile().exists()) {
- destFile.getParentFile().mkdirs();
- }
- destFile.createNewFile();
- OutputStream out = new FileOutputStream(destFile);
- byte[] cache = new byte[CACHE_SIZE];
- int nRead = 0;
- while ((nRead = in.read(cache)) != -1) {
- out.write(cache, 0, nRead);
- out.flush();
- }
- out.close();
- in.close();
- }
- }
RSATester.java
- package security;
- import java.util.Map;
- public class RSATester {
- static String publicKey;
- static String privateKey;
- static {
- try {
- Map<String, Object> keyMap = RSAUtils.genKeyPair();
- publicKey = RSAUtils.getPublicKey(keyMap);
- privateKey = RSAUtils.getPrivateKey(keyMap);
- System.err.println("公钥: \n\r" + publicKey);
- System.err.println("私钥: \n\r" + privateKey);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public static void main(String[] args) throws Exception {
- test();
- testSign();
- }
- static void test() throws Exception {
- System.err.println("公钥加密——私钥解密");
- String source = "这是一行没有任何意义的文字,你看完了等于没看,不是吗?";
- System.out.println("\r加密前文字:\r\n" + source);
- byte[] data = source.getBytes();
- byte[] encodedData = RSAUtils.encryptByPublicKey(data, publicKey);
- System.out.println("加密后文字:\r\n" + new String(encodedData));
- byte[] decodedData = RSAUtils.decryptByPrivateKey(encodedData, privateKey);
- String target = new String(decodedData);
- System.out.println("解密后文字: \r\n" + target);
- }
- static void testSign() throws Exception {
- System.err.println("私钥加密——公钥解密");
- String source = "这是一行测试RSA数字签名的无意义文字";
- System.out.println("原文字:\r\n" + source);
- byte[] data = source.getBytes();
- byte[] encodedData = RSAUtils.encryptByPrivateKey(data, privateKey);
- System.out.println("加密后:\r\n" + new String(encodedData));
- byte[] decodedData = RSAUtils.decryptByPublicKey(encodedData, publicKey);
- String target = new String(decodedData);
- System.out.println("解密后: \r\n" + target);
- System.err.println("私钥签名——公钥验证签名");
- String sign = RSAUtils.sign(encodedData, privateKey);
- System.err.println("签名:\r" + sign);
- boolean status = RSAUtils.verify(encodedData, publicKey, sign);
- System.err.println("验证结果:\r" + status);
- }
- }