一、簡介
對於機密資訊,我們需要加密,這裡介紹加密演算法在java中的使用。
二、知識點
目前常用的加密演算法有對稱加密演算法與非對稱加密演算法。
2.1 對稱加密演算法
在對稱加密中,加密方與解密方都共用同一個金鑰,也就是加密與解密的金鑰是一樣的。 特點:
通常它的演算法公開,加解密速度快。現在常用的AES演算法,即advanced encrytion standard,
金鑰長度,目前可用的是128位。
加密的原文長度不限。
2.2 非對稱加密
非對稱加密,又稱公開金鑰加密,它有兩個金鑰,公鑰(public key)和私鑰(private key),它們是不同的。公鑰與私鑰是配對使用的,使用公鑰加密時,只有對應的私鑰才能解開;用私鑰加密時,只有對應的公鑰才能解開。 特點:
通常是接收方先生成一對金鑰,即公鑰和私鑰,然後公鑰公開,傳送方用公開的公鑰加密,密方傳給接收方,然後接收方用私鑰解密。
非對稱加密沒有對稱加密速度快,常用的是RSA演算法。
RSA通常加密原文較小的串,串越大,keyGen.initialize(n)的n值就相應增大,加密解密速度越慢;
三、例項
3.1 新增base64的maven依賴
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
3.2 對稱加密AES程式碼例項
public class AESMain {
public static void main(String[] args) throws Exception {
String source = "study hard and make progress everyday";
System.out.println("message source : "+source);
/********** 金鑰生成方式一: 自動生成金鑰 **************/
String keyStr = genKeyAES(); //生成金鑰串
System.out.println("AES keyStr : "+keyStr);
SecretKey key = loadKeyAES(keyStr); //根據金鑰串獲取金鑰
// /********** 金鑰生成方式二: 指定種子(或者可以說是密碼)生成金鑰 ***********/
// String password = "123456";
// SecretKey key = genRawKeyAES(password); //根據password獲取金鑰
// String keyStr = Base64.encodeBase64String(key.getEncoded()); //生成金鑰串
// System.out.println("AES keyStr : "+keyStr);
//
String encryptStr = encryptAES(source,key); //AES加密
System.out.println("AES encrypt result : " + encryptStr);
String deencryptStr = deencryptAES(encryptStr,key); //AES解密
System.out.println("AES deencrypt result : " +deencryptStr);
}
//生成金鑰串
static String genKeyAES() throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
SecretKey key = keyGen.generateKey();
String keyStr = Base64.encodeBase64String(key.getEncoded());
return keyStr;
}
//根據password生成金鑰串
static String genKeyAES(String password) throws Exception {
SecretKey key = genRawKeyAES(password);
String keyStr = Base64.encodeBase64String(key.getEncoded());
return keyStr;
}
//根據password生成原始金鑰串
static SecretKey genRawKeyAES(String password) throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128,new SecureRandom(password.getBytes("utf8")));
SecretKey key = keyGen.generateKey();
return key;
}
//根據金鑰串獲取金鑰
static SecretKey loadKeyAES(String keyStr) throws Exception {
SecretKey key = new SecretKeySpec(Base64.decodeBase64(keyStr), "AES");
return key;
}
//AES加密
static String encryptAES(String source, SecretKey key) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(source.getBytes("utf8"));
return Base64.encodeBase64String(result);
}
//AES解密
static String deencryptAES(String source, SecretKey key) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] resultByte = cipher.doFinal(Base64.decodeBase64(source));
String result = new String(resultByte,"utf-8");
return result;
}
}
執行結果:
message source : study hard and make progress everyday
AES keyStr : evD5UdP8LK8UrfrmxGQheA==
AES encrypt result : 1z8zSWmRRFPNb6qoURgFp1c778SzaDqbErrVroDthM5eBXrQTFevAzYmRStK7EPZ
AES deencrypt result : study hard and make progress everyday
3.3 非對稱加密演算法RSA程式碼例項
public class RSAMain {
public static void main(String[] args) throws Exception {
String source = "study hard and make progress everyday";
System.out.println("message source : "+source);
KeyPair keyPair = getKeyPair(); //生成金鑰對
String pubKeyStr = getPubKey(keyPair); //獲取公鑰串
System.out.println("pubKeyStr : "+pubKeyStr);
String priKeyStr = getPriKey(keyPair); //獲取私鑰串
System.out.println("priKeyStr : "+priKeyStr);
PublicKey pubKey = loadPubKey(pubKeyStr);//載入公鑰
PrivateKey priKey = loadPriKey(priKeyStr);//載入私鑰
/**************** 公鑰加密 私鑰解密********************/
System.out.println("\n/**************** 公鑰加密 私鑰解密********************/");
String encryptStr = pubEncrypt(source,pubKey); //RSA加密
System.out.println("RSA pubKey encrypt result : " + encryptStr);
String decryptStr = priDecrypt(encryptStr,priKey); //RSA解密
System.out.println("RSA priKey decryptStr result : " +decryptStr);
/**************** 私鑰加密 公鑰解密********************/
System.out.println("\n/**************** 私鑰加密 公鑰解密********************/");
encryptStr = priEncrypt(source,priKey); //RSA加密
System.out.println("RSA priKey encrypt result : " + encryptStr);
decryptStr = pubDecrypt(encryptStr,pubKey); //RSA解密
System.out.println("RSA pubKey decryptStr result : " +decryptStr);
}
//生成金鑰對
static KeyPair getKeyPair() throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(512); //可以理解為:加密後的密文長度,實際原文要小些 越大 加密解密越慢
KeyPair keyPair = keyGen.generateKeyPair();
return keyPair;
}
//獲取公鑰Base64字串
static String getPubKey(KeyPair keyPair){
PublicKey key = keyPair.getPublic();
return Base64.encodeBase64String(key.getEncoded());
}
//獲取私鑰Base64字串
static String getPriKey(KeyPair keyPair){
PrivateKey key = keyPair.getPrivate();
return Base64.encodeBase64String(key.getEncoded());
}
//根據公鑰串獲取公鑰
static PublicKey loadPubKey(String keyStr) throws Exception {
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(keyStr));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey key = keyFactory.generatePublic(keySpec);
return key;
}
//根據私鑰串獲取私鑰
static PrivateKey loadPriKey(String keyStr) throws Exception {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(keyStr));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey key = keyFactory.generatePrivate(keySpec);
return key;
}
/**************** 公鑰加密 私鑰解密********************/
//使用公鑰加密
static String pubEncrypt(String source,PublicKey key) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE,key);
return Base64.encodeBase64String(cipher.doFinal(source.getBytes("utf8")));
}
//使用私鑰解密
static String priDecrypt(String source,PrivateKey key) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE,key);
return new String(cipher.doFinal(Base64.decodeBase64(source)),"utf8");
}
/**************** 私鑰加密 公鑰解密********************/
//使用私鑰加密
static String priEncrypt(String source,PrivateKey key) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE,key);
return Base64.encodeBase64String(cipher.doFinal(source.getBytes("utf8")));
}
//使用公鑰解密
static String pubDecrypt(String source,PublicKey key) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE,key);
return new String(cipher.doFinal(Base64.decodeBase64(source)),"utf8");
}
}
執行結果:
message source : study hard and make progress everyday
pubKeyStr : M2wwDQYJKoZIhvcNAQEBBQADSwAwSAJBAItWYa39aUhRTIXEIBCSfSCp9CvXj/k9STtMv7y5OVD9ILArIf8ZwU+qepahkO40EUJ37IBS3ciiTw7CcS7U7UsCAwEAAQ==
priKeyStr : M2IBUwIBADANBgkqhkiG9w0BAQEFAASCAT0wggE5AgEAAkEAi1Zhrf1pSFFMhcQgEJJ9IKn0K9eP+T1JO0y/vLk5UP0gsCsh/xnBT6p6lqGQ7jQRQnfsgFLdyKJPDsJxLtTtSwIDAQABAkBeSJNMIl9tWeXH1hBEZntY8OeSCwkXA8tb3vEXCNap37p06hj5d2gqaK/ZkgBqVfY6keCcRqbkOROyxdfCQTjBAiEA49WvON+HhlApKXHhHglz9bmpu+LLp6NGDicTLszfGLECIQCckAMKaWcn8u1V+svGbIBHxiKI+QUBXbbo6sUZt/UkuwIgEDpcLLTfNlXnWKhf3H/X3pzG1jclQl+C0ec+morFKUECIE5CMjLnIvg2FuqOdYOWwrydzq93Akh/hqmAiMtlR7V3AiBVblFmuDimgKb8OWg+2BaWTuKZA/BG9Z8nsT2tqaNuSA==
/**************** 公鑰加密 私鑰解密********************/
RSA pubKey encrypt result : do1DUKBnm9J49+IhFDqPEI53tGX69kPfPbqYsPPEabm9NYTvNiEEUzjT5w1j1yQtxlz7T2n6QyHKHv0BjZOoqg==
RSA priKey decryptStr result : study hard and make progress everyday
/**************** 私鑰加密 公鑰解密********************/
RSA priKey encrypt result : S6bEfnsciTRNmdqe3mh9LBUsyYS5Qff6nj2xRxaiyhi2/Frw17snIZfB0rOTSnu7JjamjLZozaJ/WlwdEFcloA==
RSA pubKey decryptStr result : study hard and make progress everyday