提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
ASE加密工具
一、使用步骤
1.生成随机的key
代码如下(示例):
/**
* 生成32位的密钥
**/
public static String KeyValue32() {
//定义一个字符串(A-Z,a-z,0-9)即62位;
String str = "zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
//由Random生成随机数
Random random = new Random();
StringBuffer sb = new StringBuffer();
//长度为几就循环几次
for (int i = 0; i < 32; ++i) {
//产生0-61的数字
int number = random.nextInt(62);
//将产生的数字通过length次承载到sb中
sb.append(str.charAt(number));
}
//将承载的字符转换成字符串
return sb.toString();
}
2.加密解密
代码如下(示例):
public static byte[] encrypt(String plainText, String key) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(plainText.getBytes());
}
public static String decrypt(byte[] cipherText, String key) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(cipherText);
return new String(decryptedBytes);
}
3.调用
public static void main(String[] args) throws Exception {
String plainText = "Hello, this is a secret message!";
String key = "qmpjWL86mKuHDEHartCVCjkTBm2U3arZ"; // 16, 24, or 32 bytes
// 加密
byte[] encryptedBytes = encrypt(plainText, key);
String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
System.out.println("Encrypted Text: " + encryptedText);
// 解密
String decryptedText = decrypt(encryptedBytes, key);
System.out.println("Decrypted Text: " + decryptedText);
}```