Java实现AES对称加密算法 - NapoleonKo
Java实现AES加密算法" title="对称加密算法">对称加密算法
Java代码实现
import java.security.SecureRandom;import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class AesEntriptor {
private Cipher encryptCipher; // 负责加密工作
private Cipher decryptCipher; // 负责解密工作
public AesEntriptor(String rules) throws Exception {
// 1.实例化AES算法密钥生成器
KeyGenerator keygen = KeyGenerator.getInstance("AES");
// 2.根据传入的字节数组,生成一个128位的随机源
keygen.init(128, new SecureRandom(rules.getBytes()));
// 3.生成密钥
SecretKey secretKey = keygen.generateKey();
// 4.生成Cipher对象,指定其支持AES算法
encryptCipher = Cipher.getInstance("AES");
decryptCipher = Cipher.getInstance("AES");
// 5.初始化加密对象及解密对象
encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey);
decryptCipher.init(Cipher.DECRYPT_MODE, secretKey);
}
public byte[] encrypt(byte[] source) throws Exception {
return encryptCipher.doFinal(source);
}
public byte[] decrypt(byte[] source) throws Exception {
return decryptCipher.doFinal(source);
}
public static void main(String[] args) throws Exception {
AesEntriptor aesEntriptor = new AesEntriptor("123456");
byte[] encrypt = aesEntriptor.encrypt("Napolean".getBytes());
byte[] decrypt = aesEntriptor.decrypt(encrypt);
System.out.println(new String(decrypt));
}
}
发表于
2019-12-16 15:15
NapoleonKo
阅读(1045)
评论(0)
编辑
收藏
举报
以上是 Java实现AES对称加密算法 - NapoleonKo 的全部内容, 来源链接: utcz.com/z/390051.html