当前位置:   article > 正文

AES-256-GCM Java实现_java aes256

java aes256
  1. import javax.crypto.Cipher;
  2. import javax.crypto.KeyGenerator;
  3. import javax.crypto.spec.GCMParameterSpec;
  4. import java.nio.charset.StandardCharsets;
  5. import java.security.Key;
  6. import java.security.SecureRandom;
  7. import java.security.Security;
  8. import java.util.Set;
  9. public class AES256GCMUtil {
  10. private final static String ALGO = "AES_256/GCM/NOPADDING";
  11. public static final int AES_KEY_SIZE = 256;
  12. public static final int GCM_IV_LENGTH = 12;
  13. public static final int TLEN = 128;
  14. static {
  15. Set<String> algorithms = Security.getAlgorithms("Cipher");
  16. if (!algorithms.contains(ALGO)) {
  17. throw new IllegalArgumentException("AES256 encrypt and decrypy system can not used");
  18. }
  19. }
  20. public static void main(String[] args) throws Exception {
  21. /* Check Option Format.Option or parameters must is true then process next code*/
  22. if(args.length == 0) {
  23. System.out.println("Option error!You need to enter three parameters.Enter -h or --help to get some tips.");
  24. System.exit(1);
  25. }else if(args.length == 1 && (args[0].equals("-h") || args[0].equals("--help"))) {
  26. System.out.println();
  27. System.out.println("You need to enter three parameters, namely type, text and key.\n");
  28. System.out.println("Type : \n\t-e or --encrypt for encrypt.");
  29. System.out.println("\t-d or --decrypt for decrypt.");
  30. System.out.println("\nFor example : \n");
  31. System.out.println("\t\"D:\\>java AES256GCMUtil -e yzysdtc 123456\" For encrypt,source text is \"yzystdc\",Key is \"123456\"\n");
  32. System.out.println("\t\"D:\\>java AES256GCMUtil -d 2ddb531030ad15b168d4cb32b8e2e3c78b6683cca6dcf15e3f4c148f47943e62b974ef 123456\" For decrypt,encrypted text is \"2ddb531030ad15b168d4cb32b8e2e3c78b6683cca6dcf15e3f4c148f47943e62b974ef\",Key is \"123456\"");
  33. System.exit(1);
  34. }else if(args.length != 3) {
  35. System.out.println("Option error!You need to enter three parameters.Enter -h or --help to get some tips.");
  36. System.exit(1);
  37. }else if(!(args[0].equals("-e") || args[0].equals("--encrypt") || args[0].equals("-d") || args[0].equals("--decrypt"))) {
  38. System.out.println("Option error!You need to enter three parameters.Enter -h or --help to get some tips.");
  39. System.out.println("First option error,only have -e or --encrypt or -d or --decrypt");
  40. System.exit(1);
  41. }
  42. /* Check Option Format.Option and parameters all is True*/
  43. AES256GCMUtil app = new AES256GCMUtil();
  44. if(args[0].equals("-e") || args[0].equals("--encrypt")) {
  45. System.out.println("\nEncryption:\n");
  46. System.out.println(app.encrypt(args[1], args[2]));
  47. System.out.println("");
  48. System.exit(0);
  49. }else if(args[0].equals("-d") || args[0].equals("--decrypt")) {
  50. System.out.println("\nDecryption:\n");
  51. System.out.println(app.decrypt(args[1], args[2]));
  52. System.out.println("");
  53. System.exit(0);
  54. }
  55. }
  56. public String encrypt(String txt, String pwd) throws Exception {
  57. Cipher cipher = Cipher.getInstance(ALGO);
  58. byte[] iv = new byte[GCM_IV_LENGTH];
  59. SecureRandom secureRandom = new SecureRandom();
  60. secureRandom.nextBytes(iv);
  61. cipher.init(Cipher.ENCRYPT_MODE, generateKey(pwd), new GCMParameterSpec(TLEN, iv));
  62. byte[] txtBytes = txt.getBytes(StandardCharsets.UTF_8);
  63. byte[] enctyptBytes = cipher.doFinal(txtBytes);
  64. byte[] message = new byte[GCM_IV_LENGTH + enctyptBytes.length];
  65. System.arraycopy(iv, 0, message, 0, GCM_IV_LENGTH);
  66. System.arraycopy(enctyptBytes, 0, message, GCM_IV_LENGTH, enctyptBytes.length);
  67. return bytearrayToHex(message);
  68. }
  69. public String decrypt(String txt, String pwd) throws Exception {
  70. byte[] txtBytes = hexStringToByteArray(txt);
  71. byte[] iv = new byte[GCM_IV_LENGTH];
  72. byte[] content = new byte[txtBytes.length - GCM_IV_LENGTH];
  73. System.arraycopy(txtBytes, 0, iv, 0, GCM_IV_LENGTH);
  74. System.arraycopy(txtBytes, GCM_IV_LENGTH, content, 0, content.length);
  75. Cipher cipher = Cipher.getInstance(ALGO);
  76. GCMParameterSpec params = new GCMParameterSpec(TLEN, iv);
  77. cipher.init(Cipher.DECRYPT_MODE, generateKey(pwd), params);
  78. return new String(cipher.doFinal(content), StandardCharsets.UTF_8);
  79. }
  80. public Key generateKey(String keystr) throws Exception {
  81. KeyGenerator kg = KeyGenerator.getInstance("AES");
  82. SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN");
  83. secureRandom.setSeed(keystr.getBytes(StandardCharsets.UTF_8));
  84. kg.init(AES_KEY_SIZE, secureRandom);
  85. return kg.generateKey();
  86. }
  87. public static byte[] hexStringToByteArray(String hexString) {
  88. hexString = hexString.replaceAll(" ", "");
  89. int len = hexString.length();
  90. byte[] bytes = new byte[len / 2];
  91. for (int i = 0; i < len; i += 2) {
  92. bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
  93. .digit(hexString.charAt(i+1), 16));
  94. }
  95. return bytes;
  96. }
  97. public static String byteToHex(byte b){
  98. String hex = Integer.toHexString(b & 0xFF);
  99. if(hex.length() < 2){
  100. hex = "0" + hex;
  101. }
  102. return hex;
  103. }
  104. public static String bytearrayToHex(byte[] b) {
  105. String hex= new String("");
  106. int lengthofb;
  107. for(lengthofb=0;lengthofb<b.length;lengthofb++) {
  108. hex=hex + byteToHex(b[lengthofb]);
  109. }
  110. return hex;
  111. }
  112. }

用法,将上面的代码复制粘贴到文本文件中,并且保存为 AES256GCMUtil.java 。然后,在保存该文件的目录打开命令行(cmd)或者打开命令行之后,转移到保存该文件的目录。

-e 加密,后需两个参数,一个被加密的原文,一个密钥

-d 解密,后需两个参数,一个被解密的密文,一个密钥

由于伽罗瓦计数器模式(GCM)的的AES算法,会在原文头部当中填充一个随机数,所以每次加密后的密文都不一致。不用担心,解密后,随机数会被删除的。

 

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

闽ICP备14008679号