【问题标题】:Java - Python AES encryption decryptionJava - Python AES 加密解密
【发布时间】:2019-10-27 14:04:21
【问题描述】:

我有一个使用 AES 来自 Java(v8) 的加密文本,我试图在 python 中使用相同的 SecretKey、Salt 对其进行解密,但是在取消索引超出范围时遇到问题。当我做相反的事情时,即在 python 中加密并在 java 中解密然后我能够得到文本,但带有一些不需要的前缀。

以下是我尝试过的java和python代码。

Java 代码(来自 org.apache.commons.codec.binary.Base64 的 Base64)

public static String encrypt(String secretKey, String salt, String value) throws Exception {
        Cipher cipher = initCipher(secretKey, salt, Cipher.ENCRYPT_MODE);
        byte[] encrypted = cipher.doFinal(value.getBytes());
        return Base64.encodeBase64String(encrypted);
    }

    public static String decrypt(String secretKey, String salt, String encrypted) throws Exception {
        Cipher cipher = initCipher(secretKey, salt, Cipher.DECRYPT_MODE);
        byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
        return new String(original);
    }

    private static Cipher initCipher(String secretKey, String salt, int mode) throws Exception {

        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");

        KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKeySpec skeySpec = new SecretKeySpec(tmp.getEncoded(), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(mode, skeySpec, new IvParameterSpec(new byte[16]));
        return cipher;
    }

    public static void main(String[] args) throws Exception {
        String secretKey = "Secret";
        String fSalt = "tJHnN5b1i6wvXMwzYMRk";
        String plainText = "England";

        String cipherText = encrypt(secretKey, fSalt, plainText);
        System.out.println("Cipher: " + cipherText);
//      cipherText = "6peDTxE1xgLE4hTGg0PKTnuuhFC1Vftsd7NH9DF/7WM="; // Cipher from python
        String dcrCipherText = decrypt(secretKey, fSalt, cipherText);
        System.out.println(dcrCipherText);

    }

Python 代码(3.6 版)和 Pycrypto V2.6

import base64
import hashlib
import os

from Crypto.Cipher import AES

BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)

# unpad = lambda s: s[:-ord(s[len(s) - 1:])]
unpad = lambda s: s[0:-s[-1]]

def get_private_key(secretKey, salt):
    key = hashlib.pbkdf2_hmac('SHA256', secretKey.encode(), salt.encode(), 65536, 32)
    return key


def encrypt(message, salt, secretKey):
    private_key = get_private_key(secretKey, salt)
    message = pad(message)
    iv = os.urandom(BS)  # 128-bit IV
    cipher = AES.new(private_key, AES.MODE_CBC, iv, segment_size=256)
    return base64.b64encode(iv + cipher.encrypt(message))


def decrypt(enc, salt, secretKey):
    private_key = get_private_key(secretKey, salt)
    enc = base64.b64decode(enc)
    iv = enc[:BS]
    cipher = AES.new(private_key, AES.MODE_CBC, iv, segment_size=256)
    return unpad(cipher.decrypt(enc[BS:]))


secretKey = "Secret"
salt = "tJHnN5b1i6wvXMwzYMRk"
plainText = "England"
cipher = encrypt(plainText, salt, secretKey)
print("Cipher: " + bytes.decode(cipher))

# cipher = "0JrZdg9YBRshfTdr1d4zwQ==" # Cipher from java
decrypted = decrypt(cipher, salt, secretKey)
print("Decrypted " + bytes.decode(decrypted))

Java 解密输出:�U�����or���England 当我通过 python 密码时,预期:England Python 解密输出:unpad = lambda s : s[0:-s[-1]] IndexError: index out of range,预期:England

关于这个问题,我也浏览了堆栈上的其他帖子,但是由于他们使用了不同的模式,所以没有成功。

【问题讨论】:

  • 工作样本可以在here找到

标签: java python aes pycrypto pbkdf2


【解决方案1】:

使用pycryptodome 的正确python 3 代码将与Java 代码匹配,如下所示:

import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad,pad
import hashlib

def get_private_key(secretKey, salt):
    # _prf = lambda p,s: HMAC.new(p, s, SHA256).digest()
    # private_key = PBKDF2(secretKey, salt.encode(), dkLen=32,count=65536, prf=_prf )
    # above code is equivalent but slow
    key = hashlib.pbkdf2_hmac('SHA256', secretKey.encode(), salt.encode(), 65536, 32)
    # KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256);
    return key

def encrypt(message, salt, secretKey):
    private_key = get_private_key(secretKey, salt)
    message = pad(message.encode(), AES.block_size)
    iv = "\x00"*AES.block_size  # 128-bit IV
    cipher = AES.new(private_key, AES.MODE_CBC, iv.encode())
    return base64.b64encode(cipher.encrypt(message))


def decrypt(enc, salt, secretKey):
    # _prf = lambda p,s: HMAC.new(p, s, SHA256).digest()
    # private_key = PBKDF2(secretKey, salt.encode(), dkLen=32,count=65536, prf=_prf )
    private_key = get_private_key(secretKey, salt)
    enc = base64.b64decode(enc)
    iv = "\x00"*AES.block_size
    cipher = AES.new(private_key, AES.MODE_CBC, iv.encode())
    return unpad(cipher.decrypt(enc), AES.block_size).decode('utf-8')


secretKey = "Secret"
salt = "tJHnN5b1i6wvXMwzYMRk"
plainText = "England"
enc_datta = encrypt(plainText, salt, secretKey)
print(f"Encrypted: {enc_datta}")
# Encrypted: 0JrZdg9YBRshfTdr1d4zwQ==

cipher = "0JrZdg9YBRshfTdr1d4zwQ==" # Cipher from java
decrypted = decrypt(cipher, salt, secretKey)
print(f"Decrypted: {decrypted}" )
# Decrypted: England

【讨论】:

    【解决方案2】:

    在 python 中,您将 iv(初始化向量)存储在加密消息的前 16 个字节中。

    在 Java 中,您并没有做这样的事情 - 您传递的是一个空的 IV,并且您将包括前 16 个字节在内的整个消息视为密文。

    您需要确保 Java 和 Python 匹配。

    您要么在两者中都不使用 IV,在这种情况下,您将在 Python 中删除该部分。

    或者您在两者中都使用 IV,在这种情况下,您需要更新 Java 代码以在加密时生成随机 IV,并将其添加到加密结果中。解密时,Java 代码需要将前 16 个字节作为 IV 并传递给Cipher

    【讨论】:

    • 感谢回复,我知道IV部分是在python加密中添加的,但是当我在python中删除它时,它会生成java解密方法无法解密的密码并抛出javax.crypto.BadPaddingException: Given final block not properly padded,并且Python 解密也抛出 unpad = lambda s: s[0:-s[-1]] IndexError: index out of range 我尝试了上面提到的 java 中的更改,效果很好,但我无法更改 java 端的逻辑,因为它会影响其他功能。那么你能提供我需要在 Python 解密函数中更改的内容吗?
    • 在 Java 中,您提供 16 个字节,其值为 0 作为 IV(new byte[16] 创建一个 16 个字节的数组,所有这些字节都初始化为零)。所以你需要在 python 中做同样的事情,而不是 iv = os.urandom(BS)iv = enc[:BS] - 你不应该再将 IV 存储在编码的消息中。
    • 我初始化了 iv = "\x00"*BS 并且没有将 iv 添加到密码中,它生成与 java 相同的密码,但 python 无法解密它,得到 unpad = lambda s: s[0:-s[-1]] IndexError: index out of range。我在解密函数中删除了iv = enc[:BS]。你能帮我我还需要做什么,以便它能够正确解密。再次感谢!
    • 好的终于可以通过在python解密函数中将return unpad(cipher.decrypt(enc[BS:]))改为return unpad(cipher.decrypt(enc))解决了。
    猜你喜欢
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多