AES-GCM-256加解密Java实现

AES-GCM-256加解与解密不太好找,记录一下

public class AESUtil {
    private static Logger log = LoggerFactory.getLogger(AESUtil.class);

    private static String gcm256algorithm = "AES/GCM/PKCS5Padding";

    public static void main(String[] args) {
        KeyGenerator generator = null;
        try {
            generator = KeyGenerator.getInstance("AES");
            //初始化密钥生成器,AES要求密钥长度为128位、192位、256位
            generator.init(256);
            SecretKey secretKey = generator.generateKey();
            String gcmSecretKey = Base64.encodeBase64String(secretKey.getEncoded());
            System.out.println("生成密钥key: "+gcmSecretKey +"\n");

            String toDoStr = "文本加密测试";
            System.out.println("明文文本:"+toDoStr);
            String encryptResult = AEGCMEncrypt(toDoStr,gcmSecretKey);
            System.out.println("加密结果: "+encryptResult);

            String decryptResult = AEGCMDecrypt(encryptResult,gcmSecretKey);
            System.out.println("解密结果: "+decryptResult +"\n");


        } catch (NoSuchAlgorithmException e) {
            log.error("密钥生成异常,error:", e);
        }
    }

	//解密
    public static String AEGCMDecrypt(String content, String keyStr) {
        try {
            if (StringUtils.isEmpty(content) || StringUtils.isEmpty(keyStr)) {
                throw new Exception("AESGCM256解密异常,检查文本或密钥");
            }
            Cipher cipher = Cipher.getInstance(gcm256algorithm);
            SecretKey key = new SecretKeySpec(Base64.decodeBase64(keyStr), "AES");

            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] message = Base64.decodeBase64(content);
            // 这里的12和16是加密的时候设置的偏移参数及加密长度
            if (message.length < 12 + 16) throw new IllegalArgumentException();
            GCMParameterSpec params = new GCMParameterSpec(128, message, 0, 12);
            cipher.init(Cipher.DECRYPT_MODE, key, params);
            byte[] decryptData = cipher.doFinal(message, 12, message.length - 12);
            String decript = new String(decryptData);
            return decript;
        } catch (Exception e) {
            log.error("AESGCM256解密文本处理失败,error:{}", e);
        }
        return null;
    }
	
	//加密
    public static String AEGCMEncrypt(String content, String keyStr) {
        try {
            if (StringUtils.isEmpty(content) || StringUtils.isEmpty(keyStr)) {
                throw new Exception("AESGCM256加密异常,检查文本或密钥");
            }

            SecretKey secretKey = new SecretKeySpec(Base64.decodeBase64(keyStr), "AES");

            Cipher cipher = Cipher.getInstance(gcm256algorithm);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] iv = cipher.getIV();
            assert iv.length == 12;// 偏移参数及长度要在解密的时候保持一致
            byte[] encryptData = cipher.doFinal(content.getBytes());
            assert encryptData.length == content.getBytes().length + 16;
            byte[] message = new byte[12 + content.getBytes().length + 16];
            System.arraycopy(iv, 0, message, 0, 12);
            System.arraycopy(encryptData, 0, message, 12, encryptData.length);
            return Base64.encodeBase64String(message);
        } catch (Exception e) {
            log.error("AESGCM256加密文本处理失败,error:{}", e);
        }
        return null;

    }
}

执行结果

生成密钥key: Z4pes8zNTtcEwimyeQv4mj8w64XiI96lX3smgv+LTDQ=

明文文本:文本加密测试
加密结果: damPhVQ9ZfLUnP1YQ/ddu2KotZkze6QQ1lyRuarVV3BBn3hQDf6mEW844WsHPg==
解密结果: 文本加密测试
  • 8
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值