java gcm_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 这行配置没被屏蔽。如屏蔽了,去掉签名的#

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值