当前位置:   article > 正文

Java加密与解密的艺术~AES-GCM-NoPadding实现_aes/gcm/nopadding

aes/gcm/nopadding

来源:Java AES加密和解密_一名可爱的技术搬运工-CSDN博客

AES加密

高级加密标准 (AES,Rijndael)是一种分组密码加密和解密算法,是全球使用最广泛的加密算法。 AES使用128、192或256位的密钥来处理128位的块。

本文向您展示了一些Java AES加密和解密示例:

  • AES字符串加密–(加密和解密字符串)。
  • AES基于密码的加密–(密钥将从给定的密码派生)。
  • AES文件加密。 (基于密码)。

在本文中,我们重点介绍通过Galois Counter Mode(GCM)进行的256位AES加密

GCM = CTR + Authentication.

进一步阅读 
阅读本– NIST – Galois /计数器模式(GCM)的建议

不要使用AES电子密码本(ECB)模式 
AES ECB模式或AES/ECB/PKCS5Padding (在Java中)在语义上并不安全 – ECB加密的密文可能泄漏有关纯文本的信息。 这是关于为什么不应该使用ECB加密的讨论

1. Java和AES加密输入。

在AES加密和解密中,我们需要以下输入:

AES加密最佳做法 
不要重复使用具有相同密钥的IV。

1.1 IV(初始值或初始向量),它是随机字节,通常为12个字节或16个字节。 在Java中,我们可以使用SecureRandom生成随机IV。

  1. // 16 bytes IV
  2. public static byte[] getRandomNonce() {
  3. byte[] nonce = new byte[16];
  4. new SecureRandom().nextBytes(nonce);
  5. return nonce;
  6. }
  7. // 12 bytes IV
  8. public static byte[] getRandomNonce() {
  9. byte[] nonce = new byte[12];
  10. new SecureRandom().nextBytes(nonce);
  11. return nonce;
  12. }

1.2 AES密钥,即AES-128AES-256 。 在Java中,我们可以使用KeyGenerator生成AES密钥。

  1. // 256 bits AES secret key
  2. public static SecretKey getAESKey() throws NoSuchAlgorithmException {
  3. KeyGenerator keyGen = KeyGenerator.getInstance("AES");
  4. keyGen.init(256, SecureRandom.getInstanceStrong());
  5. return keyGen.generateKey();
  6. }

1.3从给定密码派生的AES密钥。 在Java中,我们可以使用SecretKeyFactoryPBKDF2WithHmacSHA256从给定的密码生成AES密钥。

  1. // AES key derived from a password
  2. public static SecretKey getAESKeyFromPassword(char[] password, byte[] salt)
  3. throws NoSuchAlgorithmException, InvalidKeySpecException {
  4. SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
  5. // iterationCount = 65536
  6. // keyLength = 256
  7. KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
  8. SecretKey secret = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
  9. return secret;
  10. }

我们使用salt来保护彩虹攻击,它也是一个随机字节,我们可以使用相同的1.1 getRandomNonce生成它。

1.4我们将上述方法分组为一个util类,这样我们就不会一次又一次重复相同的代码。

CryptoUtils.java

  1. package com.mkyong.crypto.utils;
  2. import javax.crypto.KeyGenerator;
  3. import javax.crypto.SecretKey;
  4. import javax.crypto.SecretKeyFactory;
  5. import javax.crypto.spec.PBEKeySpec;
  6. import javax.crypto.spec.SecretKeySpec;
  7. import java.security.NoSuchAlgorithmException;
  8. import java.security.SecureRandom;
  9. import java.security.spec.InvalidKeySpecException;
  10. import java.security.spec.KeySpec;
  11. import java.util.ArrayList;
  12. import java.util.List;
  13. public class CryptoUtils {
  14. public static byte[] getRandomNonce(int numBytes) {
  15. byte[] nonce = new byte[numBytes];
  16. new SecureRandom().nextBytes(nonce);
  17. return nonce;
  18. }
  19. // AES secret key
  20. public static SecretKey getAESKey(int keysize) throws NoSuchAlgorithmException {
  21. KeyGenerator keyGen = KeyGenerator.getInstance("AES");
  22. keyGen.init(keysize, SecureRandom.getInstanceStrong());
  23. return keyGen.generateKey();
  24. }
  25. // Password derived AES 256 bits secret key
  26. public static SecretKey getAESKeyFromPassword(char[] password, byte[] salt)
  27. throws NoSuchAlgorithmException, InvalidKeySpecException {
  28. SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
  29. // iterationCount = 65536
  30. // keyLength = 256
  31. KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
  32. SecretKey secret = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
  33. return secret;
  34. }
  35. // hex representation
  36. public static String hex(byte[] bytes) {
  37. StringBuilder result = new StringBuilder();
  38. for (byte b : bytes) {
  39. result.append(String.format("%02x", b));
  40. }
  41. return result.toString();
  42. }
  43. // print hex with block size split
  44. public static String hexWithBlockSize(byte[] bytes, int blockSize) {
  45. String hex = hex(bytes);
  46. // one hex = 2 chars
  47. blockSize = blockSize * 2;
  48. // better idea how to print this?
  49. List<String> result = new ArrayList<>();
  50. int index = 0;
  51. while (index < hex.length()) {
  52. result.add(hex.substring(index, Math.min(index + blockSize, hex.length())));
  53. index += blockSize;
  54. }
  55. return result.toString();
  56. }
  57. }
  1. package com.mkyong.crypto.utils;

2. AES加密和解密。

AES-GSM是使用最广泛的认证密码。 本示例将在Galois计数器模式(GCM)中使用256位AES加密和解密字符串。

AES-GCM输入:

  • AES密钥(256位)
  • IV – 96位(12字节)
  • 身份验证标签的长度(以位为单位)– 128位(16字节)

2.1在Java中,我们使用AES/GCM/NoPadding表示AES-GCM算法。 对于加密的输出,我们将16字节的IV前缀到加密的文本(密文)之前,因为解密需要相同的IV。

如果IV是众所周知的,可以吗? 
IV公开是可以的,唯一的秘诀就是密钥,对它保密并保密。

本示例将使用AES加密纯文本Hello World AES-GCM ,然后将其解密回原始纯文本。

EncryptorAesGcm.java

  1. package com.mkyong.crypto.encryptor;
  2. import com.mkyong.crypto.utils.CryptoUtils;
  3. import javax.crypto.Cipher;
  4. import javax.crypto.SecretKey;
  5. import javax.crypto.spec.GCMParameterSpec;
  6. import java.nio.ByteBuffer;
  7. import java.nio.charset.Charset;
  8. import java.nio.charset.StandardCharsets;
  9. /**
  10. * AES-GCM inputs - 12 bytes IV, need the same IV and secret keys for encryption and decryption.
  11. * <p>
  12. * The output consist of iv, encrypted content, and auth tag in the following format:
  13. * output = byte[] {i i i c c c c c c ...}
  14. * <p>
  15. * i = IV bytes
  16. * c = content bytes (encrypted content, auth tag)
  17. */
  18. public class EncryptorAesGcm {
  19. private static final String ENCRYPT_ALGO = "AES/GCM/NoPadding";
  20. private static final int TAG_LENGTH_BIT = 128;
  21. private static final int IV_LENGTH_BYTE = 12;
  22. private static final int AES_KEY_BIT = 256;
  23. private static final Charset UTF_8 = StandardCharsets.UTF_8;
  24. // AES-GCM needs GCMParameterSpec
  25. public static byte[] encrypt(byte[] pText, SecretKey secret, byte[] iv) throws Exception {
  26. Cipher cipher = Cipher.getInstance(ENCRYPT_ALGO);
  27. cipher.init(Cipher.ENCRYPT_MODE, secret, new GCMParameterSpec(TAG_LENGTH_BIT, iv));
  28. byte[] encryptedText = cipher.doFinal(pText);
  29. return encryptedText;
  30. }
  31. // prefix IV length + IV bytes to cipher text
  32. public static byte[] encryptWithPrefixIV(byte[] pText, SecretKey secret, byte[] iv) throws Exception {
  33. byte[] cipherText = encrypt(pText, secret, iv);
  34. byte[] cipherTextWithIv = ByteBuffer.allocate(iv.length + cipherText.length)
  35. .put(iv)
  36. .put(cipherText)
  37. .array();
  38. return cipherTextWithIv;
  39. }
  40. public static String decrypt(byte[] cText, SecretKey secret, byte[] iv) throws Exception {
  41. Cipher cipher = Cipher.getInstance(ENCRYPT_ALGO);
  42. cipher.init(Cipher.DECRYPT_MODE, secret, new GCMParameterSpec(TAG_LENGTH_BIT, iv));
  43. byte[] plainText = cipher.doFinal(cText);
  44. return new String(plainText, UTF_8);
  45. }
  46. public static String decryptWithPrefixIV(byte[] cText, SecretKey secret) throws Exception {
  47. ByteBuffer bb = ByteBuffer.wrap(cText);
  48. byte[] iv = new byte[IV_LENGTH_BYTE];
  49. bb.get(iv);
  50. //bb.get(iv, 0, iv.length);
  51. byte[] cipherText = new byte[bb.remaining()];
  52. bb.get(cipherText);
  53. String plainText = decrypt(cipherText, secret, iv);
  54. return plainText;
  55. }
  56. public static void main(String[] args) throws Exception {
  57. String OUTPUT_FORMAT = "%-30s:%s";
  58. String pText = "Hello World AES-GCM, Welcome to Cryptography!";
  59. // encrypt and decrypt need the same key.
  60. // get AES 256 bits (32 bytes) key
  61. SecretKey secretKey = CryptoUtils.getAESKey(AES_KEY_BIT);
  62. // encrypt and decrypt need the same IV.
  63. // AES-GCM needs IV 96-bit (12 bytes)
  64. byte[] iv = CryptoUtils.getRandomNonce(IV_LENGTH_BYTE);
  65. byte[] encryptedText = EncryptorAesGcm.encryptWithPrefixIV(pText.getBytes(UTF_8), secretKey, iv);
  66. System.out.println("\n------ AES GCM Encryption ------");
  67. System.out.println(String.format(OUTPUT_FORMAT, "Input (plain text)", pText));
  68. System.out.println(String.format(OUTPUT_FORMAT, "Key (hex)", CryptoUtils.hex(secretKey.getEncoded())));
  69. System.out.println(String.format(OUTPUT_FORMAT, "IV (hex)", CryptoUtils.hex(iv)));
  70. System.out.println(String.format(OUTPUT_FORMAT, "Encrypted (hex) ", CryptoUtils.hex(encryptedText)));
  71. System.out.println(String.format(OUTPUT_FORMAT, "Encrypted (hex) (block = 16)", CryptoUtils.hexWithBlockSize(encryptedText, 16)));
  72. System.out.println("\n------ AES GCM Decryption ------");
  73. System.out.println(String.format(OUTPUT_FORMAT, "Input (hex)", CryptoUtils.hex(encryptedText)));
  74. System.out.println(String.format(OUTPUT_FORMAT, "Input (hex) (block = 16)", CryptoUtils.hexWithBlockSize(encryptedText, 16)));
  75. System.out.println(String.format(OUTPUT_FORMAT, "Key (hex)", CryptoUtils.hex(secretKey.getEncoded())));
  76. String decryptedText = EncryptorAesGcm.decryptWithPrefixIV(encryptedText, secretKey);
  77. System.out.println(String.format(OUTPUT_FORMAT, "Decrypted (plain text)", decryptedText));
  78. }
  79. }
  1. package com.mkyong.crypto.encryptor;

输出量

纯文本: Hello World AES-GCM

Terminal

  1. ------ AES GCM Encryption ------
  2. Input (plain text) :Hello World AES-GCM
  3. Key (hex) :603d87185bf855532f14a77a91ec7b025c004bf664e9f5c6e95613ee9577f436
  4. IV (hex) :bdb271ce5235996a0709e09c
  5. Encrypted (hex) :bdb271ce5235996a0709e09c2d03eefe319e9329768724755c56291aecaef88cd1e6bdf72b8c7b54d75a94e66b0cd3
  6. Encrypted (hex) (block = 16) :[bdb271ce5235996a0709e09c2d03eefe, 319e9329768724755c56291aecaef88c, d1e6bdf72b8c7b54d75a94e66b0cd3]
  7. ------ AES GCM Decryption ------
  8. Input (hex) :bdb271ce5235996a0709e09c2d03eefe319e9329768724755c56291aecaef88cd1e6bdf72b8c7b54d75a94e66b0cd3
  9. Input (hex) (block = 16) :[bdb271ce5235996a0709e09c2d03eefe, 319e9329768724755c56291aecaef88c, d1e6bdf72b8c7b54d75a94e66b0cd3]
  10. Key (hex) :603d87185bf855532f14a77a91ec7b025c004bf664e9f5c6e95613ee9577f436
  11. Decrypted (plain text) :Hello World AES-GCM
  1. ------ AES GCM Encryption ------

纯文本: Hello World AES-GCM, Welcome to Cryptography!

Terminal

  1. ------ AES GCM Encryption ------
  2. Input (plain text) :Hello World AES-GCM, Welcome to Cryptography!
  3. Key (hex) :ddc24663d104e1c2f81f11aef98156503dafdc435f81e3ac3d705015ebab095c
  4. IV (hex) :b05d6aedf023f73b9e1e2d11
  5. Encrypted (hex) :b05d6aedf023f73b9e1e2d11f6f5137d971aea8c5cdd5b045e0960eb4408e0ee4635cccc2dfeec2c13a89bd400f659be82dc2329e9c36e3b032f38bd42296a8495ac840b0625c097d9
  6. Encrypted (hex) (block = 16) :[b05d6aedf023f73b9e1e2d11f6f5137d, 971aea8c5cdd5b045e0960eb4408e0ee, 4635cccc2dfeec2c13a89bd400f659be, 82dc2329e9c36e3b032f38bd42296a84, 95ac840b0625c097d9]
  7. ------ AES GCM Decryption ------
  8. Input (hex) :b05d6aedf023f73b9e1e2d11f6f5137d971aea8c5cdd5b045e0960eb4408e0ee4635cccc2dfeec2c13a89bd400f659be82dc2329e9c36e3b032f38bd42296a8495ac840b0625c097d9
  9. Input (hex) (block = 16) :[b05d6aedf023f73b9e1e2d11f6f5137d, 971aea8c5cdd5b045e0960eb4408e0ee, 4635cccc2dfeec2c13a89bd400f659be, 82dc2329e9c36e3b032f38bd42296a84, 95ac840b0625c097d9]
  10. Key (hex) :ddc24663d104e1c2f81f11aef98156503dafdc435f81e3ac3d705015ebab095c
  11. Decrypted (plain text) :Hello World AES-GCM, Welcome to Cryptography!
  1. ------ AES GCM Encryption ------

3.基于AES密码的加密和解密。

对于基于密码的加密,我们可以使用定义为RFC 8018的基于密码的密码规范(PKCS)从给定的密码生成密钥。

对于PKCS输入:

  • 密码,您提供。
  • 盐–至少64位(8字节)随机字节。
  • 迭代计数–建议最小迭代计数为1,000。

什么是盐和迭代计数?

  • salt会为给定的密码生成广泛的密钥集。 例如,如果盐是128位,则每个密码将有多达2 ^ 128个密钥。 因此,它增加了彩虹攻击的难度。 此外,攻击者为一个用户的密码构建的彩虹表对于另一用户变得毫无用处。
  • iteration count增加了从密码生成密钥的成本,因此增加了难度并减慢了攻击速度。

3.1对于加密的输出,我们在密文前面加上12 bytes IVpassword salt ,因为我们需要相同的IV和密码盐(用于密钥)进行解密。 此外,我们使用Base64编码器将加密的文本编码为字符串表示形式,以便我们可以以字符串格式(字节数组)发送加密的文本或密文。

如果密码盐是众所周知的,可以吗? 
与IV相同,并且可以公开知道密码盐,唯一的秘诀就是密钥,并对其进行保密和保密。

EncryptorAesGcmPassword.java

  1. package com.mkyong.crypto.encryptor;
  2. import com.mkyong.crypto.utils.CryptoUtils;
  3. import javax.crypto.Cipher;
  4. import javax.crypto.SecretKey;
  5. import javax.crypto.spec.GCMParameterSpec;
  6. import java.nio.ByteBuffer;
  7. import java.nio.charset.Charset;
  8. import java.nio.charset.StandardCharsets;
  9. import java.util.Base64;
  10. /**
  11. * AES-GCM inputs - 12 bytes IV, need the same IV and secret keys for encryption and decryption.
  12. * <p>
  13. * The output consist of iv, password's salt, encrypted content and auth tag in the following format:
  14. * output = byte[] {i i i s s s c c c c c c ...}
  15. * <p>
  16. * i = IV bytes
  17. * s = Salt bytes
  18. * c = content bytes (encrypted content)
  19. */
  20. public class EncryptorAesGcmPassword {
  21. private static final String ENCRYPT_ALGO = "AES/GCM/NoPadding";
  22. private static final int TAG_LENGTH_BIT = 128; // must be one of {128, 120, 112, 104, 96}
  23. private static final int IV_LENGTH_BYTE = 12;
  24. private static final int SALT_LENGTH_BYTE = 16;
  25. private static final Charset UTF_8 = StandardCharsets.UTF_8;
  26. // return a base64 encoded AES encrypted text
  27. public static String encrypt(byte[] pText, String password) throws Exception {
  28. // 16 bytes salt
  29. byte[] salt = CryptoUtils.getRandomNonce(SALT_LENGTH_BYTE);
  30. // GCM recommended 12 bytes iv?
  31. byte[] iv = CryptoUtils.getRandomNonce(IV_LENGTH_BYTE);
  32. // secret key from password
  33. SecretKey aesKeyFromPassword = CryptoUtils.getAESKeyFromPassword(password.toCharArray(), salt);
  34. Cipher cipher = Cipher.getInstance(ENCRYPT_ALGO);
  35. // ASE-GCM needs GCMParameterSpec
  36. cipher.init(Cipher.ENCRYPT_MODE, aesKeyFromPassword, new GCMParameterSpec(TAG_LENGTH_BIT, iv));
  37. byte[] cipherText = cipher.doFinal(pText);
  38. // prefix IV and Salt to cipher text
  39. byte[] cipherTextWithIvSalt = ByteBuffer.allocate(iv.length + salt.length + cipherText.length)
  40. .put(iv)
  41. .put(salt)
  42. .put(cipherText)
  43. .array();
  44. // string representation, base64, send this string to other for decryption.
  45. return Base64.getEncoder().encodeToString(cipherTextWithIvSalt);
  46. }
  47. // we need the same password, salt and iv to decrypt it
  48. private static String decrypt(String cText, String password) throws Exception {
  49. byte[] decode = Base64.getDecoder().decode(cText.getBytes(UTF_8));
  50. // get back the iv and salt from the cipher text
  51. ByteBuffer bb = ByteBuffer.wrap(decode);
  52. byte[] iv = new byte[IV_LENGTH_BYTE];
  53. bb.get(iv);
  54. byte[] salt = new byte[SALT_LENGTH_BYTE];
  55. bb.get(salt);
  56. byte[] cipherText = new byte[bb.remaining()];
  57. bb.get(cipherText);
  58. // get back the aes key from the same password and salt
  59. SecretKey aesKeyFromPassword = CryptoUtils.getAESKeyFromPassword(password.toCharArray(), salt);
  60. Cipher cipher = Cipher.getInstance(ENCRYPT_ALGO);
  61. cipher.init(Cipher.DECRYPT_MODE, aesKeyFromPassword, new GCMParameterSpec(TAG_LENGTH_BIT, iv));
  62. byte[] plainText = cipher.doFinal(cipherText);
  63. return new String(plainText, UTF_8);
  64. }
  65. public static void main(String[] args) throws Exception {
  66. String OUTPUT_FORMAT = "%-30s:%s";
  67. String PASSWORD = "this is a password";
  68. String pText = "AES-GSM Password-Bases encryption!";
  69. String encryptedTextBase64 = EncryptorAesGcmPassword.encrypt(pText.getBytes(UTF_8), PASSWORD);
  70. System.out.println("\n------ AES GCM Password-based Encryption ------");
  71. System.out.println(String.format(OUTPUT_FORMAT, "Input (plain text)", pText));
  72. System.out.println(String.format(OUTPUT_FORMAT, "Encrypted (base64) ", encryptedTextBase64));
  73. System.out.println("\n------ AES GCM Password-based Decryption ------");
  74. System.out.println(String.format(OUTPUT_FORMAT, "Input (base64)", encryptedTextBase64));
  75. String decryptedText = EncryptorAesGcmPassword.decrypt(encryptedTextBase64, PASSWORD);
  76. System.out.println(String.format(OUTPUT_FORMAT, "Decrypted (plain text)", decryptedText));
  77. }
  78. }
  1. package com.mkyong.crypto.encryptor;

输出量

Terminal

  1. ------ AES GCM Password-based Encryption ------
  2. Input (plain text) :AES-GSM Password-Bases encryption!
  3. Encrypted (base64) :KmrvjnMusJTQo/hB7T5BvlQpvi3bVbdjpZP51NT7I/enrIfSQuDfSK6iXgdPzvUP2IE54mwrKiyHqMkG8224lRZ9tXHcclmdh98I8b3B
  4. ------ AES GCM Password-based Decryption ------
  5. Input (base64) :KmrvjnMusJTQo/hB7T5BvlQpvi3bVbdjpZP51NT7I/enrIfSQuDfSK6iXgdPzvUP2IE54mwrKiyHqMkG8224lRZ9tXHcclmdh98I8b3B
  6. Decrypted (plain text) :AES-GSM Password-Bases encryption!
  1. ------ AES GCM Password-based Encryption ------

3.2如果密码不匹配,Java会抛出AEADBadTagException: Tag mismatch!

  1. // change the password to something else
  2. String decryptedText = EncryptorAesGcmPassword.decrypt(encryptedTextBase64, "other password");
  3. System.out.println(String.format(OUTPUT_FORMAT, "Decrypted (plain text)", decryptedText));
  1. // change the password to something else

输出量

Terminal

  1. Exception in thread "main" javax.crypto.AEADBadTagException: Tag mismatch!
  2. at java.base/com.sun.crypto.provider.GaloisCounterMode.decryptFinal(GaloisCounterMode.java:623)
  3. at java.base/com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:1118)
  4. at java.base/com.sun.crypto.provider.CipherCore.fillOutputBuffer(CipherCore.java:1055)
  5. at java.base/com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:855)
  6. at java.base/com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
  7. at java.base/javax.crypto.Cipher.doFinal(Cipher.java:2207)
  8. at com.mkyong.crypto.encryptor.EncryptorAesGcmPassword.decrypt(EncryptorAesGcmPassword.java:88)
  9. at com.mkyong.crypto.encryptor.EncryptorAesGcmPassword.main(EncryptorAesGcmPassword.java:109)
  1. Exception in thread "main" javax.crypto.AEADBadTagException: Tag mismatch!

4. AES文件加密和解密。

此示例是基于AES密码的文件加密。 想法是相同的,但是我们需要一些IO类来处理资源或文件。

这是resources文件夹中的文本文件。

readme.txt

  1. This is line 1.
  2. This is line 2.
  3. This is line 3.
  4. This is line 4.
  5. This is line 5.
  6. This is line 9.
  7. This is line 10.
  1. This is line 1.

4.1此示例类似于3.1 EncryptorAesGcmPassword.java ,但有一些小的更改,例如返回byte[]而不是base64编码的字符串。

  1. public static byte[] encrypt(byte[] pText, String password) throws Exception {
  2. //...
  3. // prefix IV and Salt to cipher text
  4. byte[] cipherTextWithIvSalt = ByteBuffer.allocate(iv.length + salt.length + cipherText.length)
  5. .put(iv)
  6. .put(salt)
  7. .put(cipherText)
  8. .array();
  9. // it works, even if we save the based64 encoded string into a file.
  10. // return Base64.getEncoder().encodeToString(cipherTextWithIvSalt);
  11. // we save the byte[] into a file.
  12. return cipherTextWithIvSalt;
  13. }
  1. public static byte[] encrypt(byte[] pText, String password) throws Exception {

添加encryptFiledecryptFile工作与文件。

  1. public static void encryptFile(String fromFile, String toFile, String password) throws Exception {
  2. // read a normal txt file
  3. byte[] fileContent = Files.readAllBytes(Paths.get(ClassLoader.getSystemResource(fromFile).toURI()));
  4. // encrypt with a password
  5. byte[] encryptedText = EncryptorAesGcmPasswordFile.encrypt(fileContent, password);
  6. // save a file
  7. Path path = Paths.get(toFile);
  8. Files.write(path, encryptedText);
  9. }
  10. public static byte[] decryptFile(String fromEncryptedFile, String password) throws Exception {
  11. // read a file
  12. byte[] fileContent = Files.readAllBytes(Paths.get(fromEncryptedFile));
  13. return EncryptorAesGcmPasswordFile.decrypt(fileContent, password);
  14. }
  1. public static void encryptFile(

4.2从类路径中读取以上readme.txt文件,对其进行加密,然后将加密的数据保存到新文件c:\test\readme.encrypted.txt 。

  1. String password = "password123";
  2. String fromFile = "readme.txt"; // from resources folder
  3. String toFile = "c:\\test\\readme.encrypted.txt";
  4. // encrypt file
  5. EncryptorAesGcmPasswordFile.encryptFile(fromFile, toFile, password);
  1. String password = "password123";

输出量

AES文件加密

4.3读取加密的文件,解密并打印输出。

  1. String password = "password123";
  2. String toFile = "c:\\test\\readme.encrypted.txt";
  3. // decrypt file
  4. byte[] decryptedText = EncryptorAesGcmPasswordFile.decryptFile(toFile, password);
  5. String pText = new String(decryptedText, UTF_8);
  6. System.out.println(pText);
  1. String password = "password123";

输出量

Terminal

  1. This is line 1.
  2. This is line 2.
  3. This is line 3.
  4. This is line 4.
  5. This is line 5.
  6. This is line 9.
  7. This is line 10.
  1. This is line 1.

PS AES图像加密是相同的概念。

下载源代码

$ git clone https://github.com/mkyong/core-java

$ cd java-crypto

让我知道文章是否需要改进。 谢谢。

参考文献

翻译自: Java AES encryption and decryption - Mkyong.com 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/176597?site
推荐阅读
相关标签
  

闽ICP备14008679号