AES/GCM/NoPadding加解密

项目使用sonar后,提示AES加密不安全,推荐使用AES/GCM/NoPadding,调整后的完整代码

  private static final String KEY_ALGORITHM_AES = "AES";
  private static final String DEFAULT_CIPHER_ALGORITHM = "AES/GCM/NoPadding";
  private static final String CHARSET = "UTF-8";

  /**
   * 加密
   * @param content
   * @param encryptPass
   * @return
   */
  public static String aesEncrypt(String content, String encryptPass) {
    try {
      byte[] iv = new byte[12];
      SecureRandom secureRandom = new SecureRandom();
      secureRandom.nextBytes(iv);
      byte[] contentBytes = content.getBytes(CHARSET);
      Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
      GCMParameterSpec params = new GCMParameterSpec(128, iv);
      cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(encryptPass), params);
      byte[] encryptData = cipher.doFinal(contentBytes);
      assert encryptData.length == contentBytes.length + 16;
      byte[] message = new byte[12 + contentBytes.length + 16];
      System.arraycopy(iv, 0, message, 0, 12);
      System.arraycopy(encryptData, 0, message, 12, encryptData.length);
      return Base64.getEncoder().encodeToString(message);
    } catch (Exception e) {
      logger.error("aesEncrypt error {}", e.getMessage());
    }
    return null;
  }

  /**
   * 解密
   * @param base64Content
   * @param encryptPass
   * @return
   */
  public static String aesDecrypt(String base64Content, String encryptPass) {
    try {
      byte[] content = Base64.getDecoder().decode(base64Content);
      if (content.length < 12 + 16) {
        throw new IllegalArgumentException();
      }
      GCMParameterSpec params = new GCMParameterSpec(128, content, 0, 12);
      Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
      cipher.init(Cipher.DECRYPT_MODE, getSecretKey(encryptPass), params);
      byte[] decryptData = cipher.doFinal(content, 12, content.length - 12);
      return new String(decryptData, CHARSET);
    } catch (Exception e) {
      logger.error("aesDecrypt error {}", e.getMessage());
    }
    return null;
  }

  /**
   * 秘钥
   * @return
   * @throws NoSuchAlgorithmException
   */
  private static SecretKeySpec getSecretKey(String encryptPass) throws NoSuchAlgorithmException {
    KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM_AES);
    SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
    secureRandom.setSeed(encryptPass.getBytes());
    kg.init(128, secureRandom);
    SecretKey secretKey = kg.generateKey();
    return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM_AES);
  }

https://blog.csdn.net/catoop/article/details/96431206
https://blog.csdn.net/wzl19870309/article/details/104640464


版权声明:本文为hubxx原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。