java AES256 GCM



public static int MacBitSize = 128;

public static String encrypt(String PlainText, byte[] key, byte[] iv) {
String sR = "";
try {
byte[] plainBytes = PlainText.getBytes("UTF-8");

GCMBlockCipher cipher = new GCMBlockCipher(new AESFastEngine());
AEADParameters parameters =
new AEADParameters(new KeyParameter(key), MacBitSize, iv, null);
cipher.init(true, parameters);

byte[] encryptedBytes = new byte[cipher.getOutputSize(plainBytes.length)];
int retLen = cipher.processBytes(plainBytes, 0, plainBytes.length, encryptedBytes, 0);
cipher.doFinal(encryptedBytes, retLen);
sR = java.util.Base64.getEncoder().encodeToString(encryptedBytes);
} catch (UnsupportedEncodingException | IllegalArgumentException |
IllegalStateException | DataLengthException | InvalidCipherTextException ex) {
System.out.println(ex.getMessage());
}

return sR;
}


public static String decrypt(String EncryptedText, byte[] key, byte[] iv) {
String sR = "";
try {
byte[] encryptedBytes = java.util.Base64.getDecoder().decode(EncryptedText);

GCMBlockCipher cipher = new GCMBlockCipher(new AESFastEngine());
AEADParameters parameters =
new AEADParameters(new KeyParameter(key), MacBitSize, iv, null);

cipher.init(false, parameters);
byte[] plainBytes = new byte[cipher.getOutputSize(encryptedBytes.length)];
int retLen = cipher.processBytes
(encryptedBytes, 0, encryptedBytes.length, plainBytes, 0);
cipher.doFinal(plainBytes, retLen);
sR = new String(plainBytes, Charset.forName("UTF-8"));
} catch (IllegalArgumentException | IllegalStateException |
DataLengthException | InvalidCipherTextException ex) {
System.out.println(ex.getMessage());
}

return sR;
}


public static void main(String[] args) throws IOException {
  String Key = "abcdefqwertyu";
  String IV = "abcdef";
  String encryptedText = encrypt(plainText,Key.getBytes(),IV.getBytes());
  String decryptedText = decrypt(encryptedText, Key.getBytes(),IV.getBytes());
}


一:添加jar包 bcprov-jdk15.jar

二:

  jdk低版本不支持256长度的秘钥加密,需确认一下配置
  进入jdk 的 \jre\lib\security目录 看是否有limited和unlimited文件夹。
  1 没有这个两个文件夹
  下载local_policy.jar 和 US_export_policy.jar替换当前的。下载路径http://pan.baidu.com/s/1dDBY9xB
  2.有这个两个文件夹
  在security文件夹找到java.security文件并打开, 确保 crypto.policy=unlimited 这行配置没被屏蔽。如屏蔽了,去掉签名的#

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM