使用AES/GCM/NoPadding加解密遇到几个问题

5 篇文章 0 订阅
1 篇文章 0 订阅

最近项目中在使用AES/GCM/NoPadding进行接口数据加密。不过在使用过程中需要一些问题:

1、解密后中文乱码的问题

2、在linux操作系统里解密失败的问题

在此就这两个问题,做下记录,以分享给大家

首先我参考了这篇博客:https://blog.csdn.net/catoop/article/details/96431206

但实际使用过程中确实遇到了上边两个问题。

第一个问题:中文乱码解决思路是,加密解密时都是用UTF-8进行编码

加密

解密

第二个问题:一开始一直在网上查AES/GCM/NoPadding的问题,结果 一无所获,后来想到查询一下AES在linux下解密失败,果然找到了解决办法。主要原因是,SecureRandom 实现完全隨操作系统本身的内部状态。解决方法就是,调用getInstance 方法之后再调用一次 setSeed 方法

生成加密密钥

好了,问题及解决方案说完了,接下来给大家分享一下完整代码:

public class AESUtils {

    private static Logger logger = LoggerFactory.getLogger(AESUtils.class);

    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/GCM/NoPadding";// 默认的加密算法

    private static final String CHARSET = "UTF-8";

    /**
     * AES 加密操作
     *
     * @param content     待加密内容
     * @param encryptPass 加密密码
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content, String encryptPass) {
        try {
            byte[] iv = new byte[12];
            SecureRandom secureRandom = new SecureRandom();
            secureRandom.nextBytes(iv);
            byte[] contentBytes = content.getBytes(CHARSET);
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            GCMParameterSpec params = new GCMParameterSpec(128, iv);
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(encryptPass),params);
            byte[] encryptData = cipher.doFinal(contentBytes);
            assert encryptData.length == contentBytes.length + 16;
            byte[] message = new byte[12 + contentBytes.length + 16];
            System.arraycopy(iv, 0, message, 0, 12);
            System.arraycopy(encryptData, 0, message, 12, encryptData.length);
            return Base64.getEncoder().encodeToString(message);
        } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException
                | BadPaddingException e) {
            logger.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * AES 解密操作
     *
     * @param base64Content
     * @param encryptPass
     * @return
     */
    public static String decrypt(String base64Content, String encryptPass) {
        try {
            byte[] content = Base64.getDecoder().decode(base64Content);
            if (content.length < 12 + 16)
                throw new IllegalArgumentException();
            GCMParameterSpec params = new GCMParameterSpec(128, content, 0, 12);
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(encryptPass), params);
            byte[] decryptData = cipher.doFinal(content, 12, content.length - 12);
            return new String(decryptData,CHARSET);
        } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
                | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
            logger.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成加密秘钥
     *
     * @return
     * @throws NoSuchAlgorithmException
     */
    private static SecretKeySpec getSecretKey(String encryptPass) throws NoSuchAlgorithmException {
        KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
        // 初始化密钥生成器,AES要求密钥长度为128位、192位、256位
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(encryptPass.getBytes());
        kg.init(128, secureRandom);
        SecretKey secretKey = kg.generateKey();
        return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥
    }

}

 

  • 6
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
好的,这个问题涉及到JS和Java加密解密实现,我会尽力回答。首先,AES-GCM是一种高级加密标准(Advanced Encryption Standard)的加密模式,它是一种块加密模式,可以提供加密和认证功能。而PKCS5Padding是一种填充模式,它可以把不满足块大小的数据填充到块大小,以满足加密算法的要求。 在Node.js中,可以使用node-forge库提供的API实现AES-GCM加密,示例代码如下: ```javascript const forge = require('node-forge'); // 加密 function encrypt(plaintext, key, iv) { const cipher = forge.cipher.createCipher('AES-GCM', key); cipher.start({ iv: iv }); cipher.update(forge.util.createBuffer(plaintext)); cipher.finish(); return { ciphertext: cipher.output.toHex(), tag: cipher.mode.tag.toHex() }; } const plaintext = 'Hello, world!'; const key = forge.random.getBytesSync(32); const iv = forge.random.getBytesSync(12); const encrypted = encrypt(plaintext, key, iv); console.log(encrypted); ``` 在Java中,可以使用javax.crypto库提供的API实现AES/GCM/PKCS5Padding解密,示例代码如下: ```java import javax.crypto.Cipher; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.SecretKeySpec; public class Decryptor { public static String decrypt(String ciphertext, String key, String iv, String tag) throws Exception { byte[] ct = hexStringToByteArray(ciphertext); byte[] k = hexStringToByteArray(key); byte[] i = hexStringToByteArray(iv); byte[] t = hexStringToByteArray(tag); Cipher cipher = Cipher.getInstance("AES/GCM/PKCS5Padding"); SecretKeySpec keySpec = new SecretKeySpec(k, "AES"); GCMParameterSpec gcmSpec = new GCMParameterSpec(t.length * 8, i); cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmSpec); cipher.update(ct); cipher.updateAAD(t); byte[] pt = cipher.doFinal(); return new String(pt); } private static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16)); } return data; } } ``` 以上代码仅供参考,具体实现需要根据实际情况进行调整。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值