之前寫過一篇在python中實(shí)現(xiàn)RSA和AES混合加密的文章塞蹭,這次用java來實(shí)現(xiàn)
什么是RSA加密?
這是一種非對(duì)稱加密算法患朱,密鑰分為公鑰和私鑰牢酵。通常私鑰長(zhǎng)度有512bit,1024bit谊却,2048bit柔昼,4096bit,長(zhǎng)度越長(zhǎng)炎辨,越安全岳锁,但是生成密鑰越慢,加解密也越耗時(shí)蹦魔。一般公鑰用來加密數(shù)據(jù)激率,私鑰用來解密數(shù)據(jù),并且為防止有人冒充發(fā)送密文勿决,私鑰又可以負(fù)責(zé)簽名乒躺,公鑰負(fù)責(zé)驗(yàn)證。公鑰可以分發(fā)給其他系統(tǒng)低缩,但是私鑰一般保存在唯一的系統(tǒng)中嘉冒。
什么是AES加密?
這是一種對(duì)稱加密算法咆繁,加密和解密公用同一密鑰讳推。密鑰最長(zhǎng)只有256個(gè)bit,執(zhí)行速度快玩般,易于硬件實(shí)現(xiàn)银觅。通常發(fā)送方使用密鑰加密數(shù)據(jù)后會(huì)使用口令對(duì)密鑰進(jìn)行加密,然后把密文和加密后的密鑰一同發(fā)送給接收方坏为,接收方接收到數(shù)據(jù)后首先使用口令對(duì)密鑰進(jìn)行解密究驴,在使用密鑰對(duì)密文進(jìn)行解密镊绪。
以上兩種加密方式都有各自的特點(diǎn),在互聯(lián)網(wǎng)領(lǐng)域有著廣泛的應(yīng)用洒忧,我們需要根據(jù)不同的場(chǎng)景使用不同的加密解密方案蝴韭。
一般需要加密傳輸?shù)臅r(shí)候存在以下兩種場(chǎng)景:
客戶端發(fā)送加密數(shù)據(jù),服務(wù)端解密后返回明文:
例如用戶在客戶端提交個(gè)人信息時(shí)熙侍,客戶端把個(gè)人信息加密后發(fā)送給服務(wù)端榄鉴,服務(wù)端再返回code或者提交成功的提示
客戶端發(fā)送加密數(shù)據(jù),服務(wù)端解密后同樣返回密文
例如用戶登錄時(shí)蛉抓,客戶端發(fā)送加密后的賬號(hào)密碼庆尘,服務(wù)端解密后生成對(duì)應(yīng)的token,并且對(duì)token進(jìn)行加密芝雪,客戶端收到返回的token再對(duì)其進(jìn)行解密
如何生成RSA公鑰和私鑰可以參考我的另一篇文章
RSA公鑰和私鑰的生成以及PKCS#1與PKCE#8格式的轉(zhuǎn)換
下面直接貼代碼
java實(shí)現(xiàn)RSA加密
Config類
**
* @author Taoyimin
* @create 2019 05 07 20:39
*/
public class Config {
public static final String AES_ALGORITHM = "AES/CBC/PKCS5Padding";
public static final String RSA_ALGORITHM = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";
//必須是PKCS8格式
public static final String CLIENT_PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAO/8ucCgOTJ7DCPC" +
"rCCL1VKDnUX61QnxwbAvpGp1/lletEIcjUouM7F0VvMHzViNLvpw7N7NBHPa+5gO" +
"js68t9hKMUh+a6RTE34SWIqSDRPCzDKVWugsFb04o3vRl3rZ1z6B+QDdW7xwOhEr" +
"PPoEqmjjIOjQPcU6xs0SPzSimOa1AgMBAAECgYAO5m0OBaSnerZNPhf7yVLMVbmd" +
"D67MeEMjUkHuDjdlixi8BhPLqESzXtrLKg/Y0KM7D2nVh3sgSldWoIjDUzpCx8Z2" +
"yHLU1K2wakMdBgEF3xeJPxxZRpP+earl0SyLTA4hMxl48uAjn/mkPgzoMgQkqyQz" +
"5HOWjjsCLJFyEvqmoQJBAP5cBk0KXpHnCMgOupbi/pXDyaF1o+dCE97GaEdrV/0P" +
"uwDfYDYfY3wzd1QM7C4b4MmE+SNVpC0W9PyaMONJlN0CQQDxiPiGdwX9actMNJea" +
"JZ+k3BjCN+mM6Px7j/mtYcXWNZkyCXSXUBI62drZ0htenrh2qwichMlMgNJClvG6" +
"Gu+5AkEA30R7q2gstrkrNh/nnMZHXcJr3DPc2QNhWayin/4TT+hc51krpJZMxxqN" +
"5dMqBRcnavwzi9aCs6lxBcF6pCdUaQJANhd7uPls4PzRZ6abkQz9/LjB3rUQ29rN" +
"uIpc2yR7XuawAVG2x7BJ9N4XMhLoyD75hrH1AsCGKFjtPbZ6OjiQGQJAF2DbIodC" +
"uYb6eMZ8ux1Ab0wBEWWc5+iGgEVBNh22uZ/klE1/C0+KKzZhqgzaA/vPapq6dhuJ" +
"sNXlJia10PwYrQ==";
public static final String CLIENT_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDv/LnAoDkyewwjwqwgi9VSg51F" +
"+tUJ8cGwL6Rqdf5ZXrRCHI1KLjOxdFbzB81YjS76cOzezQRz2vuYDo7OvLfYSjFI" +
"fmukUxN+EliKkg0TwswylVroLBW9OKN70Zd62dc+gfkA3Vu8cDoRKzz6BKpo4yDo" +
"0D3FOsbNEj80opjmtQIDAQAB";
public static final String SERVER_PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAPGkxlAJPKR3BRxT\n" +
"PIeB3pDv117j8XbpuEik5UIOlY3GUtAV1sad5NNDUAnP/DB80yAQ8ycm9Xdkutuo" +
"f25Xlb7w0bRQNpfJlijx9eF8PsB6t63r8KAfWJlqbNHgN8AMK9P5XzVyN4YiEnUl" +
"Jh/EYiwLiYzflNnmnnfRrI4nUo8fAgMBAAECgYEAvwTxm81heeV4Tcbi33/jUBG4" +
"4BMzCzyA6DQp4wkiYju3tTS+Xq3seLEKcWdPxYi3YO7lODsM6j/fksrlSXXFMe1i" +
"ZAF3FNuDVZPz2zdFYS8vh6kdlDHMJAUnU/POMMWJ880MQDtkwTuzH8Tao8OKcAP4" +
"kc0QuG00wOrmuE+5gZECQQD9bqZkJsN+tj3+pxs57azy6B6gOqgm54/ujB+u63XU" +
"rO9Sf57asgF4OfUFltaVhjlUMSrWcgp6f4HSy7hBSKJpAkEA9BeML5iDIHOgTIws" +
"+ID55ELbzO7A/YtcYnUU09mkKCdonMXbXke+EhLApf5vX9ZmreoEfJCdsTnMEcQi" +
"fkjkRwJBALpf2TXl2/cfhs/zjG45f+rTEVK8UFTsDklb+yDkQC87TnTZLbWfGr2T" +
"wcFugDhOEXL9BYfXLiWQB6VB9Crug6ECQGEmTiFTbj0oSBCvaeauTsdO5PS3whAn" +
"u2lkeBmpcfCZXsWm6hyoKTpARHTMw789Mjjd/1Mkq96xxkr76U6h7FkCQHRc2elg" +
"Dh84wqHIptwa+moosVvd7aSzktuOB4CQRO10qKkSHVFuI+sl47A4KGzH/nX9ydUm" +
"tpsTnQAlXwBczd4=";
public static final String SERVER_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDxpMZQCTykdwUcUzyHgd6Q79de" +
"4/F26bhIpOVCDpWNxlLQFdbGneTTQ1AJz/wwfNMgEPMnJvV3ZLrbqH9uV5W+8NG0" +
"UDaXyZYo8fXhfD7Aeret6/CgH1iZamzR4DfADCvT+V81cjeGIhJ1JSYfxGIsC4mM" +
"35TZ5p530ayOJ1KPHwIDAQAB";
}
RSACipher類
import javax.crypto.Cipher;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
import java.security.*;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* @author Taoyimin
* @create 2019 05 07 20:25
*/
public class RSACipher {
/**
* 加密方法
*
* @param publicKey 公鑰
* @param raw 待加密明文
* @return 加密后的密文
* @throws Exception
*/
public static byte[] encrypt(String publicKey, byte[] raw) throws Exception {
Key key = getPublicKey(publicKey);
Cipher cipher = Cipher.getInstance(Config.RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key, new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT));
byte[] b1 = cipher.doFinal(raw);
return Base64.encodeBase64(b1);
}
/**
* 解密方法
*
* @param privateKey 私鑰
* @param enc 待解密密文
* @return 解密后的明文
* @throws Exception
*/
public static byte[] decrypt(String privateKey, byte[] enc) throws Exception {
Key key = getPrivateKey(privateKey);
Cipher cipher = Cipher.getInstance(Config.RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key, new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT));
return cipher.doFinal(Base64.decodeBase64(enc));
}
/**
* 獲取公鑰
*
* @param key 密鑰字符串(經(jīng)過base64編碼)
* @return 公鑰
* @throws Exception
*/
public static PublicKey getPublicKey(String key) throws Exception {
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(key.getBytes()));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
/**
* 獲取私鑰
*
* @param key 密鑰字符串(經(jīng)過base64編碼)
* @return 私鑰
* @throws Exception
*/
public static PrivateKey getPrivateKey(String key) throws Exception {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(key.getBytes()));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
/**
* 簽名
*
* @param privateKey 私鑰
* @param content 要進(jìn)行簽名的內(nèi)容
* @return 簽名
*/
public static String sign(String privateKey, byte[] content) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey.getBytes()));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
Signature signature = Signature.getInstance("SHA256WithRSA");
signature.initSign(priKey);
signature.update(content);
byte[] signed = signature.sign();
return new String(Base64.encodeBase64(signed));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 驗(yàn)簽
*
* @param publicKey 公鑰
* @param content 要驗(yàn)簽的內(nèi)容
* @param sign 簽名
* @return 驗(yàn)簽結(jié)果
*/
public static boolean checkSign(String publicKey, byte[] content, String sign) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = Base64.decode2(publicKey);
PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
java.security.Signature signature = java.security.Signature.getInstance("SHA256WithRSA");
signature.initVerify(pubKey);
signature.update(content);
return signature.verify(Base64.decode2(sign));
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static void main(String[] args) throws Exception {
//客戶端代碼
String text = "hello";
//使用服務(wù)端公鑰加密
byte[] encryptText = RSACipher.encrypt(Config.SERVER_PUBLIC_KEY, text.getBytes());
System.out.println("加密后:\n" + new String(encryptText));
//使用客戶端私鑰簽名
String signature = RSACipher.sign(Config.CLIENT_PRIVATE_KEY, encryptText);
System.out.println("簽名:\n" + signature);
//服務(wù)端代碼
//使用客戶端公鑰驗(yàn)簽
boolean result = RSACipher.checkSign(Config.CLIENT_PUBLIC_KEY, encryptText, signature);
System.out.println("驗(yàn)簽:\n" + result);
//使用服務(wù)端私鑰解密
byte[] decryptText = RSACipher.decrypt(Config.SERVER_PRIVATE_KEY, encryptText);
System.out.println("解密后:\n" + new String(decryptText));
}
}
運(yùn)行結(jié)果:
加密后:
y5u+c89sm1UZ2VrFwpcRKceQkdL1+N8QmqOiRR/lRvQpYx7a2DQqi962IAgG4wUO4EppetGPCZt+gzNakKnLPE3qCCf3gYd0iT81+Q/9QMSF6MBGEV/eB30VFlgYllpy/VRuwCZBWzZNEjTo/2vi/ntXEuSz02Qp34TpHAbUdww=
簽名:
kJviixPG3l7hmpPoKg7WXveks2A7hFe1NbcQT0UrdA8cmElzKxqBw6PjnBy3KxSpwx9ilh1W4+aGtiar08WnlRAYBSkGEx7VsoeTNaVDIT09pJcV3qokeO7WQEw29s6HrH1ebPLbfIKkn0jX1XTr7cHIMXxVuOBGOnDf0FhmK7M=
驗(yàn)簽:
true
解密后:
hello
java實(shí)現(xiàn)AES加密
AESCipher類
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
/**
* @author Taoyimin
* @create 2019 05 07 12:31
*/
public class AESCipher {
/**
* 加密方法,使用key充當(dāng)向量iv综苔,增加加密算法的強(qiáng)度
*
* @param key 密鑰
* @param raw 需要加密的內(nèi)容
* @return
*/
public static String encrypt(byte[] key, String raw) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec seckey = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance(Config.AES_ALGORITHM);
IvParameterSpec iv = new IvParameterSpec(key);
cipher.init(Cipher.ENCRYPT_MODE, seckey, iv);
byte[] result = cipher.doFinal(raw.getBytes());
Base64.Encoder encoder = Base64.getEncoder();
return encoder.encodeToString(result);
}
/**
* 解密方法惩系,使用key充當(dāng)向量iv,增加加密算法的強(qiáng)度
*
* @param key 密鑰
* @param enc 待解密內(nèi)容
* @return
*/
public static String decrypt(byte[] key, String enc) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec seckey = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance(Config.AES_ALGORITHM);
IvParameterSpec iv = new IvParameterSpec(key);
cipher.init(Cipher.DECRYPT_MODE, seckey, iv);
Base64.Decoder decoder = Base64.getDecoder();
byte[] result = cipher.doFinal(decoder.decode(enc));
return new String(result);
}
public static void main(String[] args) throws Exception {
//客戶端代碼
String text = "hello";
//隨機(jī)生成16位aes密鑰
byte[] aesKey = SecureRandomUtil.getRandom(16).getBytes();
String encryptText = AESCipher.encrypt(aesKey, text);
System.out.println("加密后:\n" + encryptText);
String decryptText = AESCipher.decrypt(aesKey, encryptText);
System.out.println("解密后:\n" + decryptText);
}
}
運(yùn)行結(jié)果:
加密后:
J85vumF+sEJjMDtxgQ41rA==
解密后:
hello
RSA+AES混合加密:
public class Main {
public static void main(String[] args) throws Exception {
//客戶端代碼
String text = "hello server!";
//隨機(jī)生成16位aes密鑰
byte[] aesKey = SecureRandomUtil.getRandom(16).getBytes();
System.out.println("生成的aes密鑰:\n" + new String(aesKey));
//使用aes密鑰對(duì)數(shù)據(jù)進(jìn)行加密
String encryptText = AESCipher.encrypt(aesKey, text);
System.out.println("經(jīng)過aes加密后的數(shù)據(jù):\n" + encryptText);
//使用客戶端私鑰對(duì)aes密鑰簽名
String signature = RSACipher.sign(Config.CLIENT_PRIVATE_KEY, aesKey);
System.out.println("簽名:\n" + signature);
//使用服務(wù)端公鑰加密aes密鑰
byte[] encryptKey = RSACipher.encrypt(Config.SERVER_PUBLIC_KEY, aesKey);
System.out.println("加密后的aes密鑰:\n" + new String(encryptKey));
//客戶端發(fā)送密文如筛、簽名和加密后的aes密鑰
System.out.println("\n************************分割線************************\n");
//接收到客戶端發(fā)送過來的signature encrypt_key encrypt_text
//服務(wù)端代碼
//使用服務(wù)端私鑰對(duì)加密后的aes密鑰解密
byte[] aesKey1 = RSACipher.decrypt(Config.SERVER_PRIVATE_KEY, encryptKey);
System.out.println("解密后的aes密鑰:\n" + new String(aesKey1));
//使用客戶端公鑰驗(yàn)簽
Boolean result = RSACipher.checkSign(Config.CLIENT_PUBLIC_KEY, aesKey1, signature);
System.out.println("驗(yàn)簽結(jié)果:\n" + result);
//使用aes私鑰解密密文
String decryptText = AESCipher.decrypt(aesKey1, encryptText);
System.out.println("經(jīng)過aes解密后的數(shù)據(jù):\n" + decryptText);
}
}
運(yùn)行結(jié)果:
生成的aes密鑰:
95Gnm1leO485A7iZ
經(jīng)過aes加密后的數(shù)據(jù):
Mesvxp102Fv1khfBebqXxQ==
簽名:
EzLFRvY3cFFiRocio+vx0g4l3eZO6wWaoZ+lnI949ETn6xlQ+nDLZ7njSHbjvWCnWai9hFAM99AWHDRvw92jNv9R8T3JHnJ/wFAKvHYryFh0BMuHSeB3yefdqwzRQpbwp+Z/6HL6OA9s9bLw8CKhq3rQCsVKAKiDxTUDqwZ6P3E=
加密后的aes密鑰:
PtGl6PaJE5ZQIRx62WUn+Ak6iLMBVGbVq+a5ANDHnu6V3EGpT40BF7PBEDsBrebd92kAI1T2Pihts+77N4Zz6LQ8gpQnL1sAao0mz84/ZGvEUgjdK8x75+NLY61VFAEx3eKtjWjLPyqdgahMxJtByRhEw/PGJ5VgEJgNODhts+8=
************************分割線************************
解密后的aes密鑰:
95Gnm1leO485A7iZ
驗(yàn)簽結(jié)果:
true
經(jīng)過aes解密后的數(shù)據(jù):
hello server!
最后附上python版本文章和相關(guān)源碼源碼:
python實(shí)現(xiàn)RSA與AES混合加密
python堡牡,java跨語言RSA+AES混合加密解密以及踩過的那些坑
https://github.com/taoyimin/rsa-aes-python
https://github.com/taoyimin/rsa-aes-java