Java使用AES 128位加密算法对字符串进行加密/解密
在 web 开发时,有时候会碰到一些比较敏感的信息传到了客户端,比如需要对url、字符串,这时可以对其进行加密。下面是用 java 实现 AES 128位加/解密的代码。
实现
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
/**
* 使用 AES 128位算法 加密/解密字符串
*/
public class EncryptDecryptString {
private static final String encryptionKey = "ABCDEFGHIJKLMNOP";
private static final String characterEncoding = "UTF-8";
private static final String cipherTransformation = "AES/CBC/PKCS5PADDING";
private static final String aesEncryptionAlgorithem = "AES";
/**
* 加密文本
*
* @param plainText
* @return encryptedText
*/
public static String encrypt(String plainText) {
String encryptedText = "";
try {
Cipher cipher = Cipher.getInstance(cipherTransformation);
byte[] key = encryptionKey.getBytes(characterEncoding);
SecretKeySpec secretKey = new SecretKeySpec(key, aesEncryptionAlgorithem);
IvParameterSpec ivparameterspec = new IvParameterSpec(key);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivparameterspec);
byte[] cipherText = cipher.doFinal(plainText.getBytes("UTF8"));
Base64.Encoder encoder = Base64.getEncoder();
encryptedText = encoder.encodeToString(cipherText);
} catch (Exception E) {
System.err.println("Encrypt Exception : " + E.getMessage());
}
return encryptedText;
}
/**
* 解密文本
*
* @param encryptedText
* @return decryptedText
*/
public static String decrypt(String encryptedText) {
String decryptedText = "";
try {
Cipher cipher = Cipher.getInstance(cipherTransformation);
byte[] key = encryptionKey.getBytes(characterEncoding);
SecretKeySpec secretKey = new SecretKeySpec(key, aesEncryptionAlgorithem);
IvParameterSpec ivparameterspec = new IvParameterSpec(key);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivparameterspec);
Base64.Decoder decoder = Base64.getDecoder();
byte[] cipherText = decoder.decode(encryptedText.getBytes("UTF8"));
decryptedText = new String(cipher.doFinal(cipherText), "UTF-8");
} catch (Exception E) {
System.err.println("decrypt Exception : " + E.getMessage());
}
return decryptedText;
}
}
调用
下面是使用AES 128位加密算法对字符串进行加密,并使用相同的方法对加密后的字符串进行解密。
public class Test {
public static void main(String[] args) {
String plainString = "{\"hello\": \"world\"}";
String encyptStr = EncryptDecryptString.encrypt(plainString);
String decryptStr = EncryptDecryptString.decrypt(encyptStr);
System.out.println("Plain String : " + plainString);
System.out.println("Encrypt String : " + encyptStr);
System.out.println("Decrypt String : " + decryptStr);
}
}
输出
Plain String : {"hello": "world"}
Encrypt String : YbhOplwpB8rq6J7euPmb6cZX+NMCWzKEvZ0tpF1K8NQ=
Decrypt String : {"hello": "world"}
非特殊说明,本网站所有文章均为原创。如若转载,请注明出处:https://mip.cpming.top/p/encrypt-decrypt-string-using-aes-128-bits