首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在AES-GCM-256中如何计算身份验证标记

在AES-GCM-256中如何计算身份验证标记
EN

Security用户
提问于 2016-05-25 05:04:07
回答 1查看 5.9K关注 0票数 3

我有一个示例代码,它使用AES-GCM-256加密和解密字符串.

我无法理解,身份验证标签是如何在加密端生成的,在解密端是如何使用的。

实际上,这里我既没有在加密端生成身份验证标记,也没有在验证解密端生成身份验证标记,所以它是由库本身在内部完成的。

代码语言:javascript
复制
private static String encrypt(String s, byte[] k) throws Exception {
        SecureRandom r = SecureRandom.getInstance("SHA1PRNG");
        // Generate 128 bit IV for Encryption
        byte[] iv = new byte[12]; r.nextBytes(iv);

        SecretKeySpec eks = new SecretKeySpec(k, "AES");
        Cipher c = Cipher.getInstance("AES/GCM/NoPadding");

        // Generated Authentication Tag should be 128 bits
        c.init(Cipher.ENCRYPT_MODE, eks, new GCMParameterSpec(128, iv));
        byte[] es = c.doFinal(s.getBytes(StandardCharsets.UTF_8));

        // Construct Output as "IV + CIPHERTEXT"
        byte[] os = new byte[12 + es.length];
        System.arraycopy(iv, 0, os, 0, 12);
        System.arraycopy(es, 0, os, 12, es.length);

        // Return a Base64 Encoded String
        return Base64.getEncoder().encodeToString(os);

    }

    private static String decrypt(String eos, byte[] k) throws Exception {
        // Recover our Byte Array by Base64 Decoding
        byte[] os = Base64.getDecoder().decode(eos);

        // Check Minimum Length (IV (12) + TAG (16))
        if (os.length > 28) {
            byte[] iv = Arrays.copyOfRange(os, 0, 12);
            byte[] es = Arrays.copyOfRange(os, 12, os.length);

            // Perform Decryption
            SecretKeySpec dks = new SecretKeySpec(k, "AES");
            Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
            c.init(Cipher.DECRYPT_MODE, dks, new GCMParameterSpec(128, iv));

            // Return our Decrypted String
            return new String(c.doFinal(es), StandardCharsets.UTF_8);
        }
        throw new Exception();
    }
EN

回答 1

Security用户

回答已采纳

发布于 2016-05-25 08:31:23

是的,它是由doFinal方法在内部完成的。根据Javadoc for Cipher类:

doFinal(byte[] input)如果使用像GCM/CCM这样的AEAD模式,则在加密的情况下附加身份验证标记,或者在解密的情况下进行验证。

因此,您不必在加密/解密过程中显式地追加/验证auth标记。

票数 2
EN
页面原文内容由Security提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://security.stackexchange.com/questions/124137

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档