Java AES256加密解密示例代码加密解密示例代码
主要介绍了Java AES256加密解密示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有
一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
Java支持许多安全的加密算法,但是其中一些功能较弱,无法在安全性要求很高的应用程序中使用。例如,数据加密标准
(DES)加密算法被认为是高度不安全的。今天介绍一下AES 256加密解密。
什么是什么是 AES 256??
高级加密标准 (英语:Advanced Encryption Standard,缩写:AES ),在密码学中又称Rijndael加密法,是美国联邦
政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。
AES是一种对称加密算法。它旨在易于在硬件和软件以及受限环境中实施,并提供针对各种攻击技术的良好防御。AES
是能够使用大小为128、192和256位的密钥处理128位块的块密码。每个密码分别使用128位,192位和256位的加密密
钥对128位块中的数据进行加密和解密。它使用相同的密钥进行加密和解密,因此发送方和接收方都必须知道并使用相
同的秘密密钥。
在下面的加密和解密示例中,我在UTF-8字符集中使用了base64编码。用于显示程序的输出。也可以以字节数组格式存储和
验证数据。
AES 256加密加密
Java程序中,用于使用AES 256位对密码(或任何信息)进行加密。
private static String secretKey = "boooooooooom!!!!";
private static String salt = "ssshhhhhhhhhhh!!!!";
public static String encrypt(String strToEncrypt, String secret)
{
try
{
byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec ivspec = new IvParameterSpec(iv);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
}
catch (Exception e)
{
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
AES 256解密解密
Java程序,用于使用AES 256位解密密码(或任何信息)。
private static String secretKey = "boooooooooom!!!!";
private static String salt = "ssshhhhhhhhhhh!!!!";
public static String decrypt(String strToDecrypt, String secret) {
try
{
byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec ivspec = new IvParameterSpec(iv);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
}
catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
评论0