AES-128/GCM + BASE64算法加密

/**
     * AES-128/GCM + BASE64算法加密
     *
     * @param content
     * @param secretKey
     * @return
     */
    private static String aesEncrypt(String content, String secretKey) {
        try {
            byte[] hexStr = HexUtils.fromHexString(secretKey);
            //加密算法:AES/GCM/PKCS5Padding
            Cipher cipher = Cipher.getInstance("AES/GCM/PKCS5Padding");
            SecretKeySpec skeySpec = new SecretKeySpec(hexStr, "AES");

            //随机生成iv 12位
            byte[] iv = new byte[12];
            SecureRandom.getInstance("SHA1PRNG").nextBytes(iv);

            //数据加密, AES-GCM-128
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new GCMParameterSpec(128, iv));
            byte[] encrypted = cipher.doFinal(content.getBytes());          //数据加密

            //iv+加密数据 拼接  iv在前,加密数据在后
            ByteBuffer byteBuffer = ByteBuffer.allocate(iv.length + encrypted.length);
            byteBuffer.put(iv);
            byteBuffer.put(encrypted);
            byte[] cipherMessage = byteBuffer.array();

            //转换为Base64 Base64算法有多种变体, 这里使用的是java.util.Base64
            return Base64.getEncoder().encodeToString(cipherMessage);
        } catch (Exception e) {
            log.error("content:" + content, e);
        }
        return null;
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值