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