一、应用情景
总结:公钥加密(对方公钥)、私钥解密(自己私钥);私钥签名、公钥验签。
代码实例
// AES.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
/**
* AES加解密工具
*
* @author Created by zqc on 2018/11/02.
*/
public class AES {
private final static Logger log = LoggerFactory.getLogger(AES.class);
// 加密。sSrc等待加密的数据;sKey用来加密数据的明文密码
public static byte[] Encrypt(String sSrc, String sKey) throws Exception {
if (sKey == null) {
log.error("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
log.error("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);//先把明文密码用AES算法加密一下成为AES密码
byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));//再用加密后的明文密码(AES密码)来加密数据
return encrypted;
}
// 解密
public static byte[] Decrypt(byte[] sSrc, String sKey) throws Exception {
try {
// 判断Key是否正确
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 = sSrc;//先用base64解密
try {
byte[] original = cipher.doFinal(encrypted1);
return original;
} catch (Exception e) {
log.error(e.toString());
return null;
}
} catch (Exception ex) {
log.error(ex.toString());
return null;
}
}
}
//BaseUtils.java
import java.io.*;
import java.util.Base64;
/**
* BASE64编码解码工具包
*
* @author Created by zqc on 2018/11/02.
*/
public class BaseUtils {
/**
* 文件读取缓冲区大小
*/
private static final int CACHE_SIZE = 1024;
/**
* BASE64字符串解码为二进制数据
*
* @param base64
* @return
* @throws Exception
*/
public static byte[] decode(String base64) throws Exception {
return Base64.getDecoder().decode(base64);
// return Base64.decode(base64.getBytes());
}
/**
* 二进制数据编码为BASE64字符串
*
* @param bytes
* @return
* @throws Exception
*/
public static String encode(byte[] bytes) throws Exception {
// return new String(Base64.encode(bytes));
return Base64.getEncoder().encodeToString(bytes);
}
/**
* 将文件编码为BASE64字符串 大文件慎用,可能会导致内存溢出
*
* @param filePath 文件绝对路径
* @return
* @throws Exception
*/
public static String encodeFile(String filePath) throws Exception {
byte[] bytes = fileToByte(filePath);
return encode(bytes);
}
/**
* <p>
* BASE64字符串转回文件
*
* @param filePath 文件绝对路径
* @param base64 编码字符串
* @throws Exception
*/
public static void decodeToFile(String filePath, String base64) throws Exception {
byte[] bytes = decode(base64);
byteArrayToFile(bytes, filePath);
}
/**
* 文件转换为二进制数组
*
* @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;
}
/**
* 二进制数据写文件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();
}
}
// RSAUtils.java
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.*;
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;
/**
* <p>
* RSA公钥/私钥/签名工具包
* </p>
* <p>
* 罗纳德・李维斯特(Ron [R]ivest)、阿迪・萨莫尔(Adi [S]hamir)和伦纳德・阿德曼(Leonard [A]dleman)
* </p>
* <p>
* 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/>
* 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,<br/>
* 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全
* </p>
*
* @author Created by zqc on 2018/11/02.
*/
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;
/**
* 生成密钥对(公钥和私钥)
*
* @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;
}
/**
* 用私钥对信息生成数字签名
*
* @param data 已加密数据
* @param privateKey 私钥(BASE64编码)
* @return
* @throws Exception
*/
public static String sign(byte[] data, String privateKey) throws Exception {
byte[] keyBytes = BaseUtils.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 BaseUtils.encode(signature.sign());
}
/**
* 校验数字签名
*
* @param data 已加密数据
* @param publicKey 公钥(BASE64编码)
* @param sign 数字签名
* @return
* @throws Exception
*/
public static boolean verify(byte[] data, String publicKey, String sign)
throws Exception {
byte[] keyBytes = BaseUtils.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(BaseUtils.decode(sign));
}
/**
* 私钥解密
*
* @param encryptedData 已加密数据
* @param privateKey 私钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)
throws Exception {
byte[] keyBytes = BaseUtils.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);
return getByteArray(encryptedData, cipher, MAX_DECRYPT_BLOCK);
}
private static byte[] getByteArray(byte[] data, Cipher cipher, int maxBlockSize) throws IllegalBlockSizeException, BadPaddingException, IOException {
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > maxBlockSize) {
cache = cipher.doFinal(data, offSet, maxBlockSize);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * maxBlockSize;
}
byte[] endeData = out.toByteArray();
out.close();
return endeData;
}
/**
* 公钥解密
*
* @param encryptedData 已加密数据
* @param publicKey 公钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey)
throws Exception {
byte[] keyBytes = BaseUtils.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);
return getByteArray(encryptedData, cipher, MAX_DECRYPT_BLOCK);
}
/**
* 公钥加密
*
* @param data 源数据
* @param publicKey 公钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] encryptByPublicKey(byte[] data, String publicKey)
throws Exception {
byte[] keyBytes = BaseUtils.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);
return getByteArray(data, cipher, MAX_ENCRYPT_BLOCK);
}
/**
* 私钥加密
*
* @param data 源数据
* @param privateKey 私钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] encryptByPrivateKey(byte[] data, String privateKey)
throws Exception {
byte[] keyBytes = BaseUtils.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);
return getByteArray(data, cipher, MAX_ENCRYPT_BLOCK);
}
/**
* 获取私钥
*
* @param keyMap 密钥对
* @return
* @throws Exception
*/
public static String getPrivateKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PRIVATE_KEY);
return BaseUtils.encode(key.getEncoded());
}
/**
* 获取公钥
*
* @param keyMap 密钥对
* @return
* @throws Exception
*/
public static String getPublicKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PUBLIC_KEY);
return BaseUtils.encode(key.getEncoded());
}
}
// ZASignUtil.java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Random;
/**
* 类ZASignUtil的实现描述:加签加密验签解密工具类
*
* @author Created by zqc on 2018/11/02.
*/
public class ZASignUtil {
private final static Logger log = LoggerFactory.getLogger(ZASignUtil.class);
/**
* 签名参数生成
*
* @param privatekey 我方私钥
* @param publickey 对方公钥
* @param param 参数
* @return 签名之后的JSON格式参数
* @throws Exception
*/
public static String paramSign(String privatekey, String publickey, String param) throws Exception {
//1. 生成AES 16位明文密码
String encodeRules = getRandomString(16);
/*私钥加签、公钥验签(我方用我方自己的私钥加签,对方用我方公钥验签)
我方用自己的私钥对消息加签,形成签名,将加签的消息传递给对方
对方收到消息后,再获取我方的公钥进行验签,如果验签出来的内容与消息本身一致,证明消息是我方回复的。
*/
//2.1 用生成的AES密码加密数据内容
byte[] enContent = AES.Encrypt(param, encodeRules);
//2.2 使用我方私钥生成签名(签名=我方私钥+AES密码)
String sign = RSAUtils.sign(enContent, privatekey);
/*公钥加密、私钥解密(我方用对方的公钥加密,对方用对方自己的私钥解密)
对方传递自己的公钥给我方,我方用对方的公钥对消息进行加密。
对方接收到我方加密的信息,利用他们自己的私钥对信息进行解密。
*/
//3. 使用对方公钥对16位明文密码进行RSA加密
byte[] enKey = RSAUtils.encryptByPublicKey(encodeRules.getBytes(), publickey);
//4. 组装成json格式输出
JSONObject object = new JSONObject();
object.put("content", BaseUtils.encode(enContent));//AES密码加密数据内容
object.put("sign", sign); //(签名=我方私钥+AES密码)
object.put("encodeRules", BaseUtils.encode(enKey)); //RSA算法加密后的16位明文密码
object.put("timestamp", System.currentTimeMillis()); //当前时间
String json = object.toJSONString();
log.info(">>>加签加密后:" + json);
return json;
}
/**
* 签名校验
*
* @param byte_content 接收到的数据
* @param sign 签名
* @param publickey 对方公钥
* @param timestamp 时间戳
* @return 验签结果
* @throws Exception 验签失败
*/
public static boolean checkSign(byte[] byte_content, String sign, String publickey, long timestamp) throws Exception {
long now = System.currentTimeMillis();
//5分钟之内请求
if ((now - timestamp) > 300000) {
//throw new RuntimeException("非法请求");
}
boolean verify = RSAUtils.verify(byte_content, publickey, sign);
return verify;
}
/**
* 验签 + 解密
*
* @param data 原始数据
* @param c_private_key 我方私钥
* @param s_public_key 对方公钥
* @return 解密后的内容
*/
public static String checkSignDecrypt(String data, String c_private_key, String s_public_key) throws Exception {
JSONObject parse = JSON.parseObject(data);
//1. 验证签名
byte[] byte_content = BaseUtils.decode(parse.getString("content"));
String sign = parse.getString("sign");
Long timestamp = parse.getLong("timestamp");
boolean signd = ZASignUtil.checkSign(byte_content, sign, s_public_key, timestamp);
if (!signd) {
throw new RuntimeException("验签失败");
}
log.info(">>> 验签" + (signd ? "成功" : "失败"));
//2.解密数据
byte[] encodeRules = BaseUtils.decode(parse.getString("encodeRules"));
return decryptData(byte_content, encodeRules, c_private_key);
}
/**
* 解密数据
*
* @param data 加密内容
* @param encodeRules RSA加密后的AES密码
* @param privateKey RSA私钥
* @return 解密后的数据
* @throws Exception
*/
public static String decryptData(byte[] data, byte[] encodeRules, String privateKey) throws Exception {
//解密RSA算法加密过的AES密码
byte[] bytesKey = RSAUtils.decryptByPrivateKey(encodeRules, privateKey);
//用得到的AES密码解密数据内容
byte[] deContent = AES.Decrypt(data, new String(bytesKey));
String str_de_content = new String(deContent, "utf-8");
log.info(">>> 解密后:" + str_de_content);
return str_de_content;
}
static String getRandomString(int length) { //length表示生成字符串的长度
String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
}
public static void main( String[] args ) throws Exception {
//发送方
//发送方私钥
String privatekey = "";
//接收方公钥
String publickey = "";
//发送方传递的信息
String param = "success";
//得到加密的数据
String paramSign = ZASignUtil.paramSign(privatekey, publickey, param);
//接收方
//接收方私钥
String c_private_key = "";
//发送方公钥
String s_public_key = "";
//得到解密数据
String checkSignDecrypt = ZASignUtil.checkSignDecrypt(paramSign, c_private_key, s_public_key);
}
三、公私钥生成工具