代码:
RSAUtils.java
package com.util;
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;
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>
*/
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编码)
*/
public static String sign(byte[] data, String privateKey) throws Exception {
byte[] keyBytes = Base64.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 Base64.encode(signature.sign());
}
/*
* <p>
* 校验数字签名
* </p>
*
* @param data 已加密数据
* @param publicKey 公钥(BASE64编码)
* @param sign 数字签名
*
*/
public static boolean verify(byte[] data, String publicKey, String sign)
throws Exception {
byte[] keyBytes = Base64.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(Base64.decode(sign));
}
/*
* <P>
* 私钥解密
* </p>
*
* @param encryptedData 已加密数据
* @param privateKey 私钥(BASE64编码)
*/
public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)
throws Exception {
byte[] keyBytes = Base64.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编码)
*/
public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey)
throws Exception {
byte[] keyBytes = Base64.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编码)
*/
public static byte[] encryptByPublicKey(byte[] data, String publicKey)
throws Exception {
byte[] keyBytes = Base64.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编码)
*/
public static byte[] encryptByPrivateKey(byte[] data, String privateKey)
throws Exception {
byte[] keyBytes = Base64.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 密钥对
*/
public static String getPrivateKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PRIVATE_KEY);
return Base64.encode(key.getEncoded());
}
/*
* <p>
* 获取公钥
* </p>
*
* @param keyMap 密钥对
*/
public static String getPublicKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PUBLIC_KEY);
return Base64.encode(key.getEncoded());
}
}
Base64.java(Base64编码)
package com.util;
public class Base64
{
private static char[] Base64Code = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', '+', '/' };
private static byte[] Base64Decode = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 62, -1, 63, -1, 63, 52, 53,
54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
-1, 0, -1, -1, -1, 0, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, -1, -1, -1, -1, -1 };
public static String encode(byte[] b)
{
int code = 0;
if (b == null)
return null;
StringBuffer sb = new StringBuffer((b.length - 1) / 3 << 6);
for (int i = 0; i < b.length; i++)
{
code |= b[i] << 16 - i % 3 * 8 & 255 << 16 - i % 3 * 8;
if ((i % 3 != 2) && (i != b.length - 1))
continue;
sb.append(Base64Code[((code & 0xFC0000) >>> 18)]);
sb.append(Base64Code[((code & 0x3F000) >>> 12)]);
sb.append(Base64Code[((code & 0xFC0) >>> 6)]);
sb.append(Base64Code[(code & 0x3F)]);
code = 0;
}
if (b.length % 3 > 0)
sb.setCharAt(sb.length() - 1, '=');
if (b.length % 3 == 1)
sb.setCharAt(sb.length() - 2, '=');
return sb.toString();
}
public static byte[] decode(String code)
{
if (code == null)
return null;
int len = code.length();
if (len % 4 != 0)
throw new IllegalArgumentException("Base64 string length must be 4*n");
if (code.length() == 0)
return new byte[0];
int pad = 0;
if (code.charAt(len - 1) == '=')
pad++;
if (code.charAt(len - 2) == '=')
pad++;
int retLen = len / 4 * 3 - pad;
byte[] ret = new byte[retLen];
for (int i = 0; i < len; i += 4)
{
int j = i / 4 * 3;
char ch1 = code.charAt(i);
char ch2 = code.charAt(i + 1);
char ch3 = code.charAt(i + 2);
char ch4 = code.charAt(i + 3);
int tmp = Base64Decode[ch1] << 18 | Base64Decode[ch2] << 12 | Base64Decode[ch3] << 6 | Base64Decode[ch4];
ret[j] = (byte)((tmp & 0xFF0000) >> 16);
if (i < len - 4)
{
ret[(j + 1)] = (byte)((tmp & 0xFF00) >> 8);
ret[(j + 2)] = (byte)(tmp & 0xFF);
}
else {
if (j + 1 < retLen)
ret[(j + 1)] = (byte)((tmp & 0xFF00) >> 8);
if (j + 2 < retLen)
ret[(j + 2)] = (byte)(tmp & 0xFF);
}
}
return ret;
}
}
RSATester.java (数字签名测试类)
package com.util;
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 = "my Test -----200---测试RSA数字签名的原始数据";
String source = "海马汽车2017年5月20日";
System.out.println("原文字:\r\n" + source);
byte[] data = source.getBytes("UTF-8");
//私钥加密
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);
}
}
测试结果: