前一阵给公安局做项目,用到了RSA加密技术。Java原生的RSA加密算法一次最多加密128字节数据(多于128字节需要拆分成多段分别加密再连接起来),经过加密后得到一个长度为128字节的加密数据。但这对于需要进行收发双方身份确认的公钥体系来说会带来不少麻烦。在我的系统中,我需要通过以下步骤实现对用户会话密钥的网上加密传递:
所以自己对RSA进行了改装,使其自动分段进行加密
1.base64工具类
package com.bjfulei.robo.machine.test;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Base64Util {
/**
* Base64加密
*/
public static String encryptBASE64(byte[] key) throws Exception {
return (new BASE64Encoder()).encodeBuffer(key);
}
/**
* Base64解密
*/
public static byte[] decryptBASE64(String key) throws Exception {
return (new BASE64Decoder()).decodeBuffer(key);
}
}
2.RSA调用工具类
package com.bjfulei.robo.machine.test;
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;
import org.apache.commons.lang.ArrayUtils;
public class RSAUtil {
public static final String ENCRYPTION_ALGORITHM = "RSA";
public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
/**
* 生成密钥
*/
public static Map<String, Object> initKey() throws Exception {
/* 初始化密钥生成器 */
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ENCRYPTION_ALGORITHM);
keyPairGenerator.initialize(512);
/* 生成密钥 */
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
Map<String, Object> keyMap = new HashMap<String, Object>(2);
keyMap.put("PublicKey", publicKey);
keyMap.put("PrivateKey", privateKey);
return keyMap;
}
/**
* 取得公钥
*/
public static String getPublicKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get("PublicKey");
return Base64Util.encryptBASE64(key.getEncoded());
}
/**
* 取得私钥
*/
public static String getPrivateKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get("PrivateKey");
return Base64Util.encryptBASE64(key.getEncoded());
}
/**
* 加密
*/
public static byte[] encrypt(byte[] data, String keyString, boolean isPublic) throws Exception {
Map<String, Object> keyAndFactoryMap = RSAUtil.generateKeyAndFactory(keyString, isPublic);
KeyFactory keyFactory = RSAUtil.getKeyFactory(keyAndFactoryMap);
Key key = RSAUtil.getKey(keyAndFactoryMap);
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] enBytes = null;
for (int i = 0; i < data.length; i += 50) {
// 注意要使用2的倍数,否则会出现加密后的内容再解密时为乱码
byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(data, i,i + 50));
enBytes = ArrayUtils.addAll(enBytes, doFinal);
}
return enBytes;
}
/**
* 解密
*/
public static byte[] decrypt(byte[] data, String keyString, boolean isPublic) throws Exception {
Map<String, Object> keyAndFactoryMap = RSAUtil.generateKeyAndFactory(keyString, isPublic);
KeyFactory keyFactory = RSAUtil.getKeyFactory(keyAndFactoryMap);
Key key = RSAUtil.getKey(keyAndFactoryMap);
// 对数据解密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] enBytes = null;
for (int i = 0; i < data.length; i += 64) {
// 注意要使用2的倍数,否则会出现加密后的内容再解密时为乱码
byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(data, i,i + 64));
enBytes = ArrayUtils.addAll(enBytes, doFinal);
}
return enBytes;
}
/**
* 生成钥匙
*/
public static Map<String, Object> generateKeyAndFactory(String keyString, boolean isPublic) throws Exception {
byte[] keyBytes = Base64Util.decryptBASE64(keyString);
KeyFactory keyFactory = KeyFactory.getInstance(ENCRYPTION_ALGORITHM);
Key key = null;
if (isPublic) {
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
key = keyFactory.generatePublic(x509KeySpec);
} else {
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
key = keyFactory.generatePrivate(pkcs8KeySpec);
}
Map<String, Object> keyAndFactoryMap = new HashMap<String, Object>(2);
keyAndFactoryMap.put("key", key);
keyAndFactoryMap.put("keyFactory", keyFactory);
return keyAndFactoryMap;
}
/**
* 从指定对象中获取钥匙
*/
public static Key getKey(Map<String, Object> map) {
if (map.get("key") == null) {
return null;
}
return (Key)map.get("key");
}
/**
* 从指定对象中获取钥匙工厂
*/
public static KeyFactory getKeyFactory(Map<String, Object> map) {
if (map.get("keyFactory") == null) {
return null;
}
return (KeyFactory)map.get("keyFactory");
}
/**
* 对信息生成数字签名(用私钥)
*/
public static String sign(byte[] data, String keyString) throws Exception {
Map<String, Object> keyAndFactoryMap = RSAUtil.generateKeyAndFactory(keyString, false);
Key key = RSAUtil.getKey(keyAndFactoryMap);
PrivateKey privateKey = (PrivateKey)key;
// 用私钥对信息生成数字签名
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(privateKey);
signature.update(data);
return Base64Util.encryptBASE64(signature.sign());
}
/**
* 校验数字签名(用公钥)
*/
public static boolean verify(byte[] data, String keyString, String sign)
throws Exception {
Map<String, Object> keyAndFactoryMap = RSAUtil.generateKeyAndFactory(keyString, true);
Key key = RSAUtil.getKey(keyAndFactoryMap);
PublicKey publicKey = (PublicKey)key;
// 取公钥匙对象
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(publicKey);
signature.update(data);
// 验证签名是否正常
return signature.verify(Base64Util.decryptBASE64(sign));
}
}
package com.bjfulei.robo.machine.test;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import java.util.Map;
public class HowToUse {
private String publicKey = null;
private String privateKey = null;
@Before
public void setUp() throws Exception {
Map<String, Object> keyMap = RSAUtil.initKey();
publicKey = RSAUtil.getPublicKey(keyMap);
privateKey = RSAUtil.getPrivateKey(keyMap);
System.out.println("公钥 -> " + publicKey);
System.out.println("私钥 -> " + privateKey);
}
@Test
public void test() throws Exception {
System.out.println("公钥加密,私钥解密");
String sourceString = "hi, RSA";
byte[] encodedData = RSAUtil.encrypt(sourceString.getBytes(), publicKey, true);
byte[] decodedData = RSAUtil.decrypt(encodedData, privateKey, false);
String targetString = new String(decodedData);
System.out.println("加密前: " + sourceString + ",解密后: " + targetString);
assertEquals(sourceString, targetString);
}
@Test
public void test2() throws Exception {
System.out.println("私钥签名,公钥验证签名");
String sourceString = "hello, RSA sign";
byte[] data = sourceString.getBytes();
// 产生签名
String sign = RSAUtil.sign(data, privateKey);
System.out.println("签名 -> " + sign);
// 验证签名
boolean status = RSAUtil.verify(data, publicKey, sign);
System.out.println("状态 -> " + status);
assertTrue(status);
}
@Test
public void test3() throws Exception {
System.out.println("私钥加密,公钥解密");
String sourceString="MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAlFU2d5JVaqGA7xbRYPsKiFemT6k9"
+"NEcGVQ5FjT60ukGCU7S9M16DIF9psda+uVwxWLuEr3ABLhPOWBoGTlX1QwIDAQABAkA9jBH6kTxh"
+"7ztpeUVNgTzAj+XRHf7oRyQofLB9R+yDb3M10B3ndHHJKSg+FlLFqKVv0z5e/n97vgPmLDfN6/Xp"
+"AiEAzI+tNbWny+7tLq1ewPkRGM2vNmjnIGVnJWTwuAPsCk0CIQC5oesx+gPwGwp95ygyqLdeFzpz"
+"x4dzt9/2FBm5vi6lzwIgRVfPF43ku7TaoiATJsdHjGjtJDybXNgDByIYl8h8k2ECIHTrVTYPIPfU"
+"MFGIjLsLpSLwQnK2E8yA3eEiW+mvrbXlAiEApCY+t9XfEJKl7k66NL4AkErLZEV5cEFLVtzMOWBM"
+"ga8=";
byte[] data = sourceString.getBytes("UTF-8");
byte[] encodedData = RSAUtil.encrypt(data, privateKey, false);
byte[] decodedData = RSAUtil.decrypt(encodedData, publicKey, true);
String targetString = new String(decodedData);
System.out.println("原文长度: "+sourceString.length()+"---加密长度" +encodedData.length+"---解密长度" + decodedData.length);
System.out.println("加密前: "+ sourceString);
System.out.println("解密后: " + targetString);
assertEquals(sourceString, targetString);
}
public static void main(String[] args) {
try {
//RSA加密算法
HowToUse aaa=new HowToUse();
aaa.setUp();
System.out.println("publicKey"+aaa.publicKey);
System.out.println("publicKey length:"+aaa.publicKey.length());
System.out.println("privateKey length:"+aaa.privateKey.length());
long start=System.currentTimeMillis()/1000;
for(int i=0;i<1000;i++){
aaa.test3();
}
long end=System.currentTimeMillis()/1000;
System.out.println("加密耗时"+(end-start)+"秒");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}