如何使用Java加密消息,然后使用Python针对AES GCM算法解密消息

时间:2019-11-12 07:53:57

标签: java python cryptography aes-gcm python-cryptography

我正在研究使用Java加密消息,然后使用基于AES GCM算法的Python解密消息的问题。

基于python doc,验证标签由加密器证明。 https://cryptography.io/en/latest/hazmat/primitives/symmetric-encryption/#cryptography.hazmat.primitives.ciphers.modes.GCM 但是,在Java中,我不知道如何生成身份验证标记。

这是我的Java代码示例

public class Example {

    public static final int AES_KEY_SIZE = 128; // in bits
    public static final int GCM_NONCE_LENGTH = 12; // in bytes
    public static final int GCM_TAG_LENGTH = 16; // in bytes

    public static void main(String args[]) throws Exception {

        byte[] message = "Hello".getBytes(StandardCharsets.UTF_8);

        SecureRandom secureRandom = SecureRandom.getInstanceStrong();
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(AES_KEY_SIZE, secureRandom);
        SecretKey secretKey = keyGenerator.generateKey();

        // Encrypt
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "SunJCE");
        final byte[] nonce = new byte[GCM_NONCE_LENGTH];
        secureRandom.nextBytes(nonce);
        GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, nonce);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, spec);

        byte[] tag = "World".getBytes(StandardCharsets.UTF_8);
        cipher.updateAAD(tag);
        byte[] cipherText = cipher.doFinal(message);

        System.out.println(Base64.getEncoder().encodeToString(secretKey.getEncoded()));
        System.out.println(Base64.getEncoder().encodeToString(nonce));
        System.out.println(Base64.getEncoder().encodeToString(tag));
        System.out.println(Base64.getEncoder().encodeToString(cipherText));

        cipher.init(Cipher.DECRYPT_MODE, secretKey, spec);
        cipher.updateAAD(tag);
        byte[] plainText = cipher.doFinal(cipherText);

        System.out.println(new String(plainText));
    }
}

这是我的Python代码,该代码无效,因为解密时必须提供“ ValueError:身份验证标签”。 “

    key = base64.b64decode("X3uBZOZdPqJipDsyvCm/zQ==");
    iv = base64.b64decode("Oe6yP87rg8G7dJSj");
    tag = base64.b64decode("V29ybGQ=");
    print (tag)
    msg = base64.b64decode("UvqFC+sWspXrWwdV6XCc7Wahp6l5");

    deCipher = Cipher(algorithms.AES(key), modes.GCM(iv, None), default_backend()).decryptor()
    deCipher.authenticate_additional_data(tag)
    computed_msg = deCipher.update(msg) + deCipher.finalize()
    print (computed_msg)

给出密钥,标签,nonce和cipherText,我的问题是如何编写python代码来解密消息?

0 个答案:

没有答案
相关问题