java中加密算法AES和RSA
文章目錄
一、簡介
對於機密信息,我們需要加密,這裏介紹加密算法在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