android - 在 Android 上向 AES-GCM 添加额外的经过身份验证的数据

标签 android encryption spongycastle aes-gcm

我正在尝试将额外的身份验证数据 (AAD) 添加到 Android 上的 AES-GCM。我看到 Cipher notes 的 Java 7 版本关于使用 GCMParameterSpecupdateAAD(...) 方法,但鉴于 Android 是基于 Java 6 的,我完全没有想法。我使用 SpongycaSTLe 作为加密库

  GCMParameterSpec s = new GCMParameterSpec(...);
  cipher.init(..., s);
  cipher.updateAAD(...);  // AAD

最佳答案

谢谢@andrey - 我在 BC mailing list 中找到了一个更完整的示例

public void testGCM() {
    try {
        byte iv[] = "123456789012".getBytes();
        byte inMsg[] = "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"
                .getBytes();
        byte aad[] = "123456789012123456789012123456789012345678901234567890123456"
                .getBytes();
        byte key[] = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb".getBytes();

        System.out.println("inMsgLen===" + inMsg.length);

        // encrypt
        AEADParameters parameters = new AEADParameters(
                new KeyParameter(key), 128, iv, aad);
        GCMBlockCipher gcmEngine = new GCMBlockCipher(new AESFastEngine());
        gcmEngine.init(true, parameters);

        byte[] encMsg = new byte[gcmEngine.getOutputSize(inMsg.length)];
        int encLen = gcmEngine.processBytes(inMsg, 0, inMsg.length, encMsg,
                0);
        encLen += gcmEngine.doFinal(encMsg, encLen);

        System.out.println("encLen===" + encLen);

        // decrypt
        gcmEngine.init(false, parameters);

        byte[] decMsg = new byte[gcmEngine.getOutputSize(encMsg.length)];
        int decLen = gcmEngine.processBytes(encMsg, 0, encMsg.length,
                decMsg, 0);
        decLen += gcmEngine.doFinal(decMsg, decLen);

        System.out.println("decLen===" + decLen);

        System.out.println("MSG===" + new String(decMsg));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

关于android - 在 Android 上向 AES-GCM 添加额外的经过身份验证的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19519138/

相关文章:

c++ - AES GCM/CTR 相同的输出

php - MySQL 查询返回带有 AES_ENCRYPT 的空白字段

android - 需要对现有 Android 代码有基本的加密理解

java - 尝试在 Android Studio 中绘制矩形矩阵。这不起作用

android 奇怪的 float 数学

java - 如何在主 Activity 中调用myCustomAdapter的公共(public)方法?

java - SimpleCursorAdapter.ViewBinder - 对每一行应用不同的方式 (ListFragment)

ssl - SSL 在使用对称加密 key 时的奇怪行为?

java - 使用 SpongyCaSTLe 的 RSA

android - IV 用于加密转换。预期 IV 长度为 16 但实际为 24