本文共 1909 字,大约阅读时间需要 6 分钟。
[Java] 纯文本查看 复制代码package com.example.AESTest;
import java.security.SecureRandom;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class MyClass {
private static final String ALGORITHM = "AES";
/**
* 生成一个密钥
* @param password用于当做密钥生成种子
* [url=home.php?mod=space&uid=155549]@Return[/url] secretKey生成的密钥
* @throws Exception
*/
private static SecretKey geneKey(String password) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
SecureRandom random = new SecureRandom();
random.setSeed(password.getBytes());
keyGenerator.init(256);
keyGenerator.init(random);
SecretKey secretKey = keyGenerator.generateKey();
return secretKey;
}
/**
* 加密
* @param password秘钥
* @param data明文
* @return result密文
* @throws Exception
*/
public static byte[] testEncrypt(byte[] data,String password) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
SecretKey secretKey = geneKey(password);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
cipher.update(data);
byte[] result = cipher.doFinal();
return result;
}
/**
* 解密
* @param password秘钥
* @param data密文
* @return result明文
* @throws Exception
*/
public static byte[] testDecrpyt(byte[] data,String password) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
SecretKey secretKey = geneKey(password);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] encodedBytes = data;
byte[] result = cipher.doFinal(encodedBytes);
return result;
}
public static void main(String[] args) throws Exception {
byte[] input= {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
System.out.println("Source Data: "+Arrays.toString(input));
String password="123456";
byte[] temp;
temp=testEncrypt(input,password);
System.out.println("Encrypt Data: "+Arrays.toString(temp));
byte[] output=testDecrpyt(temp,password);
System.out.println("Decrypt Data: "+Arrays.toString(output));
}
}
转载地址:https://blog.csdn.net/weixin_31649177/article/details/114116241 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!