JAVA中的AES GCM加密和解密 [英] AES GCM encryption and decryption in JAVA

查看:382
本文介绍了JAVA中的AES GCM加密和解密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在JAVA中实现AES/GCM/NoPadding加密和解密..所使用的密钥是接收者的公共密钥和发送者的私有密钥(ECDH)的共享密钥..加密效果很好(有和没有iv).但是,我无法解密...

I am trying to implement AES/GCM/NoPadding encryption and decryption in JAVA .. the key used is a shared key from the public key of the receiver and the private key of the sender (ECDH).. encryption works well (with and without iv). However, I am unable to decrypt...

我得到异常:javax.crypto.BadPaddingException:GCM中的mac检查失败

I get the exception: javax.crypto.BadPaddingException: mac check in GCM failed

public static String encryptString(SecretKey key, String plainText) throws NoSuchProviderException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

        //IvParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");//AES/ECB/PKCS5Padding //"AES/GCM/NoPadding", "BC"
        byte[] plainTextBytes = plainText.getBytes("UTF-8");
        byte[] cipherText;

        //cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);

        cipher.init(Cipher.ENCRYPT_MODE, key);
        return new String(Base64.getEncoder().encode(cipher.doFinal(plainTextBytes)));
      }



           public static String decryptString(SecretKey key, String 
          cipherText) throws NoSuchProviderException, 
          NoSuchAlgorithmException, NoSuchPaddingException, 
          InvalidKeyException, InvalidAlgorithmParameterException, 
          IllegalBlockSizeException, BadPaddingException, 
          UnsupportedEncodingException, ShortBufferException {


        Key decryptionKey = new SecretKeySpec(key.getEncoded(),
                key.getAlgorithm());
       IvParameterSpec ivSpec = new IvParameterSpec(ivString.getBytes("UTF-8"));
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");//AES/GCM/NoPadding", "BC");

        cipher.init(Cipher.DECRYPT_MODE, decryptionKey, ivSpec);
        return new String (Base64.getEncoder().encode(cipher.doFinal(Base64.getDecoder().decode(cipherText.getBytes()))));

    }

推荐答案

对于相同密文的加密和解密,必须使用完全相同的IV,并且对于每次生成不同密文的加密,它都必须不同.IV不是秘密的,因此您可以将其与密文一起发送.通常,它只是简单地放在密文的前面,然后在解密之前将其切掉.

You must use exactly the same IV for encryption and decryption of the same ciphertext and it must be different for each encryption that produces different ciphertexts. The IV is not secret, so you can send it along with the ciphertext. Usually, it is simply prepended to the ciphertext and sliced off before decryption.

这篇关于JAVA中的AES GCM加密和解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆