学习使用 Java AES 256位加密 来创建安全密码,并使用解密进行密码验证。 要阅读 simple AES encryption ,请阅读链接的文章。
1. AES – Advanced Encryption Standard
AES是一种 symmetric encryption algorithm 。 它旨在易于在硬件和软件以及受限环境中实施,并提供针对各种攻击技术的良好防御。
AES是能够使用大小为128、192和256位的密钥处理 128 bit blocks 块密码。 每个密码分别使用128位,192位和256位的加密密钥对128位块中的数据进行加密和解密。 它使用 相同的密钥进行加密和解密 ,因此发送方和接收方都必须知道并使用相同的秘密密钥。
在下面的加密和解密示例中,我在UTF-8字符集中使用了base64编码。 用于显示程序的输出。 如果是您的应用程序,则也可以以字节数组格式存储和验证数据。
2. AES 256 Encryption
Java程序,用于使用AES 256位对密码(或任何信息)进行加密。
private static String secretKey = "boooooooooom!!!!"; private static String salt = "ssshhhhhhhhhhh!!!!"; public static String encrypt(String strToEncrypt, String secret) 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;
不要忘记在加密和解密中使用相同的密钥和盐。
3. AES 256 Decryption
Java程序,用于使用AES 256位解密密码(或任何信息)。
private static String secretKey = "boooooooooom!!!!"; private static String salt = "ssshhhhhhhhhhh!!!!"; public static String decrypt(String strToDecrypt, String secret) { 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;
4. Java AES 256 Example
让我们用一个简单的字符串测试我们的 AES256加密和解密 方法。
public static void main(String[] args) String originalString = "howtodoinjava.com"; String encryptedString = AES.encrypt(originalString, secretKey) ; String decryptedString = AES.decrypt(encryptedString, secretKey) ; System.out.println(originalString); System.out.println(encryptedString); System.out.println(decryptedString);
Program output.
howtodoinjava.com biXhp3Ha1fgxVEp48zHrvVoXMStmxPuAPHo3TVz5lHU= howtodoinjava.com
显然,我们能够使用 AES256 加密来加密字符串,并使用解密来从加密的字符串取回原始字符串。
Read More: