前言
http和https的区别,几乎被面试官问烂了。下面的一个测试用例简单展示了https的原理,你也可以用这套方案作为自己的加密方式运用到实际项目中。如果阅读代码困难,请直接复制代码到IDE debug,掌握https只需3分钟。
1.用例实现
public class HttpsDemo {
/**
* RSA 秘钥算法
*/
public static final String KEY_ALGORITHM_RSA = "RSA";
/**
* AES秘钥算法
*/
public static final String KEY_ALGORITHM_AES = "AES";
/**
* 默认字符集:UTF-8
*/
public static final String DEFAULT_CHARSET = "UTF-8";
/**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
/**
* AES加解密算法
*/
private static final String CIPHER_ALGORITHM_AES = "AES/ECB/PKCS5Padding";
public static void main(String[] args) throws Exception {
String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpnDaXs4kZr57XvusSXjDc+jdSdmkxO+RrRTvr\n"
+ "1PDjxu/8PiiBqK6O4ahYOyXZWZsSjyRD4Z7BUuhLw9GtqJoNojNmu/Tg1asdoaWeF5h+R/UN+Lu5\n"
+ "XCwGrUsXaOLXYTUJCA7jvrwruRTQ1wP+OkIr1mi990PY3vfwq0W1NuaoCwIDAQAB";
String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKmcNpeziRmvnte+6xJeMNz6N1J2\n"
+ "aTE75GtFO+vU8OPG7/w+KIGoro7hqFg7JdlZmxKPJEPhnsFS6EvD0a2omg2iM2a79ODVqx2hpZ4X\n"
+ "mH5H9Q34u7lcLAatSxdo4tdhNQkIDuO+vCu5FNDXA/46QivWaL33Q9je9/CrRbU25qgLAgMBAAEC\n"
+ "gYAr/FscFG9lvenPwa9s4AiEBk/6jsLRBdtDBn13t42RRLJQFD6lAX3jiBoEZ7J1H4vb0EtzXzuw\n"
+ "nzOnEm16P9NTcC/5oxDeE7ER5K1+kddwukSSXchL750Dvg2Ep4PNeDF3v7icbZp23WuzBcZSuKdz\n"
+ "B3lNJolQpFUiDw9BapiJQQJBAPbI0q1FLsHcTgEB770mSCRkXYieWwK9pxiM6n3c6CSM2Oh+HgV+\n"
+ "51/1ARnhlYq6Dcps1UCSzm5QMDb5FwBnUxMCQQCv8aFTolz/J7cjz8uGKC+6DH4Ir7+2vkYcC1Bz\n"
+ "Hq6mSlH3MWUrq3TKWsn+Lv5cWtCFn2qsl7+V3NsU55KOjX4pAkB6+O1KXCwFfBL+m4lsFrRiNgUJ\n"
+ "u+ccAYdPS4DZwQeIlwrLJ3UsReVjwoGO9QMAgt+2W+8T41OsUpcD/bGBiPszAkEApU6qW9D1/UnM\n"
+ "WVpYB8FkLjKki/bMcp9NcfXzbWYLg/PaFR2Ux7X9Mk6g8DApDo7I0nMYn/anq99o+7gjy8oHGQJB\n"
+ "AMbkvILpBoP5YDJxalmdh9OaKS0HXgTMhgFVurRPgwuHxfkm01vt4Py33lpd8bVDzS+A9Txn1Kvx\n" + "fHuVj1RJDdI=";
String content = "{\n" + " \"resp_data\":{\n" + " \"loan_amt\":\"101900\",\n"
+ " \"loan_list\":[\n" + " {\n" + " \"cost_list\":[\n"
+ " {\n" + " \"actual_payamt\":\"98000\",\n"
+ " \"actual_paydate\":\"\",\n"
+ " \"deductionamt\":\"0\",\n"
+ " \"fee_code\":\"F010\",\n"
+ " \"fee_name\":\"F010-车款\",\n"
+ " \"loan_serial_no\":\"I41O90P0007591A8C00000D91268E9\",\n"
+ " \"original_payamt\":\"98000\",\n"
+ " \"pay_status\":\"5 \"\n" + " },\n"
+ " {\n" + " \"actual_payamt\":\"1000\",\n"
+ " \"actual_paydate\":\"\",\n"
+ " \"deductionamt\":\"0\",\n"
+ " \"fee_code\":\"0012\",\n"
+ " \"fee_name\":\"F0012-GPS加价\",\n"
+ " \"loan_serial_no\":\"I41O98R0027591A8C000000D7C2C28\",\n"
+ " \"original_payamt\":\"1000\",\n"
+ " \"pay_status\":\"5 \"\n" + " },\n"
+ " {\n" + " \"actual_payamt\":\"2450\",\n"
+ " \"actual_paydate\":\"\",\n"
+ " \"deductionamt\":\"0\",\n"
+ " \"fee_code\":\"F011\",\n"
+ " \"fee_name\":\"F011-账户管理费\",\n"
+ " \"loan_serial_no\":\"I41O94N0017591A8C00000BFE2002E\",\n"
+ " \"original_payamt\":\"2450\",\n"
+ " \"pay_status\":\"5 \"\n" + " }\n" + " ],\n"
+ " \"loan_batch\":\"PAY20180714001114\"\n" + " }\n" + " ],\n"
+ " \"loan_status\":\"5\",\n" + " \"order_no\":\"1000136848\"\n" + " },\n"
+ " \"resp_msg\":\"查询成功。\",\n" + " \"resp_code\":\"0000\"\n" + "}";
System.out.println("请求明文:" + content);
// 1.获取AES随机秘钥
String randomKey = getAESRandomKey();
System.out.println("AES随机秘钥:" + randomKey);
/* 请求加密 */
// 2. AES加密请求内容(传到后端)
String encryptAES = encryptAES(content, randomKey);
System.out.println("AES 加密结果:" + encryptAES);
// 3. 加密AES秘钥(传到后端)
String encryptKey = encryptRSA(randomKey, publicKey);
System.out.println("AES的秘钥加密结果:" + encryptKey);
// 4. 对密文生成签名(传到后端)
String signature = doSign(encryptAES);
System.out.println("生成的签名:" + signature);
/* 响应解密 */
// 1. 验签
System.out.println("验签结果:" + doCheck(encryptAES, signature));
// 2. 通过RSA私钥解密,得到通过AES秘钥
String decryptKey = decryptRSA(encryptKey, privateKey);
System.out.println("AES的秘钥解密结果:" + decryptKey);
// 3. AES解密请求内容
String decryptAES = decryptAES(encryptAES, decryptKey);
System.out.println("AES 解密结果:" + decryptAES);
}
/**
* RSA加密
*
* @param content 待加密数据
* @param publicKey 公钥
* @return 密文
* @throws Exception RSA加密异常
*/
public static String encryptRSA(String content, String publicKey) throws Exception {
return encryptRSA(content, publicKey, DEFAULT_CHARSET);
}
/**
* RSA加密
*
* @param content 待加密数据
* @param publicKey 公钥
* @param charset 字符集
* @return 密文
* @throws Exception RSA加密异常
*/
public static String encryptRSA(String content, String publicKey, String charset) throws Exception {
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
// 取公钥
X509EncodedKeySpec pkcs8EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
PublicKey key = keyFactory.generatePublic(pkcs8EncodedKeySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] data = content.getBytes(charset);
// 对数据分段加密
doFinal(data, cipher, out, MAX_ENCRYPT_BLOCK);
byte[] encryptedData = out.toByteArray();
return new String(Base64.encodeBase64(encryptedData), charset);
}
}
/**
* 用私钥解密
*
* @param content 加密的数据
* @param privateKey 私钥
* @return 明文
* @throws Exception 私钥解密异常
*/
public static String decryptRSA(String content, String privateKey) throws Exception {
return decryptRSA(content, privateKey, DEFAULT_CHARSET);
}
/**
* 用私钥解密
*
* @param content 加密的数据
* @param privateKey 私钥
* @param charset 字符集
* @return 明文
* @throws Exception 私钥解密异常
*/
public static String decryptRSA(String content, String privateKey, String charset) throws Exception {
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
// 取私钥
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
PrivateKey key = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
// 对数据解密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] data = Base64.decodeBase64(content);
// 对数据分段加密
doFinal(data, cipher, out, MAX_DECRYPT_BLOCK);
byte[] decryptedData = out.toByteArray();
return new String(decryptedData, charset);
}
}
/**
* 生成签名
*
* @param content 请求内容
* @return 签名
*/
public static String doSign(String content) {
if (StringUtils.isBlank(content)) {
return null;
}
return DigestUtils.md5Hex(content);
}
/**
* 校验签名
*
* @param content 请求内容
* @param sign 签名
* @return 校验结果
*/
public static boolean doCheck(String content, String sign) {
String signature = doSign(content);
return StringUtils.equals(sign, signature);
}
/**
* AES加密
*
* @param content 明文
* @param key 秘钥
* @return 密文
* @throws Exception AES加密异常
*/
public static String encryptAES(String content, String key) throws Exception {
return encryptAES(content, key, DEFAULT_CHARSET);
}
/**
* AES加密
*
* @param content 明文
* @param key 秘钥
* @param charset 字符集
* @return 密文
* @throws Exception AES加密异常
*/
public static String encryptAES(String content, String key, String charset) throws Exception {
Key k = new SecretKeySpec(key.getBytes(charset), KEY_ALGORITHM_AES);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_AES);
cipher.init(Cipher.ENCRYPT_MODE, k);
return Base64.encodeBase64String(cipher.doFinal(content.getBytes(charset)));
}
/**
* AES解密
*
* @param content 密文
* @param key 秘钥
* @return 明文
* @throws Exception AES解密异常
*/
public static String decryptAES(String content, String key) throws Exception {
return decryptAES(content, key, DEFAULT_CHARSET);
}
/**
* AES解密
*
* @param content 密文
* @param key 秘钥
* @param charset 字符集
* @return 明文
* @throws Exception AES解密异常
*/
public static String decryptAES(String content, String key, String charset) throws Exception {
Key k = new SecretKeySpec(key.getBytes(charset), KEY_ALGORITHM_AES);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_AES);
cipher.init(Cipher.DECRYPT_MODE, k);
return new String(cipher.doFinal(Base64.decodeBase64(content)), charset);
}
/**
* 获取AES随机秘钥
*
* @return AES秘钥
* @throws Exception 获取AES随机秘钥异常
*/
public static String getAESRandomKey() throws Exception {
// 实例化
KeyGenerator kgen = KeyGenerator.getInstance(KEY_ALGORITHM_AES);
// 设置密钥长度
kgen.init(128);
// 生成密钥
SecretKey skey = kgen.generateKey();
// 对密钥的二进制编码,做base64转换
return Base64.encodeBase64String(skey.getEncoded());
}
/**
* 对数据分段解密
*
* @param data 数据
* @param cipher 处理器
* @param out 输出流
* @param maxBlock 最大长度限制
* @throws Exception 对数据分段解密异常
*/
public static void doFinal(byte[] data, Cipher cipher, ByteArrayOutputStream out, int maxBlock) throws Exception {
int offSet = 0;
byte[] cache;
int i = 0;
int inputLen = data.length;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > maxBlock) {
cache = cipher.doFinal(data, offSet, maxBlock);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * maxBlock;
}
}
}
2.可能会遇到问题
加密解密时报错:java.security.InvalidKeyException: Illegal key size
请下载 US_export_policy.jar 和 local_policy.jar 放入JAVA_HOME/lib/security/目录。
Thx!
网友评论