如何解密Zend2加密数据?

2 投票
1 回答
1400 浏览
提问于 2025-04-17 15:15

我正在使用Zend2 Crypt模块来加密一些数据。以下是我的代码。

$cipher = BlockCipher::factory('mcrypt', array(
  'algorithm' => 'aes',
));
$cipher->setKey('mypassphrase');
$encrypted = $cipher->encrypt('Hey, I am the secret data');

很好,它运行得很顺利!现在,我需要在Python中解密那个$encrypted的数据(嘿,我就是那个秘密数据)。

我正在使用pycrypto来完成这个任务。请问在我的PHP环境之外,解密数据的步骤是什么呢?

    from Crypto.Cipher import AES
    import base64
    import hashlib

    password = 'mypassphrase'
    key = hashlib.sha256(password).digest()

    decoded = base64.standard_b64decode(encrypted)
    cipher = AES.new(key, AES.MODE_CBC)
    data = cipher.decrypt(decoded)

我需要指定一个IV(初始化向量),因为Zend默认使用的是MODE_CBC模式。我该如何在我的Python代码中指定它呢?

这是Zend2的文档:

加密的输出是一个字符串,默认使用Base64编码,里面包含了HMAC值、IV向量和加密文本。使用的加密模式是CBC(默认情况下IV是随机的),HMAC的默认哈希算法是SHA256。Mcrypt适配器默认使用PKCS#7填充机制进行加密。你可以使用一个特殊的适配器来指定不同的填充方法(Zend\Crypt\Symmetric\Padding)。BlockCipher使用PBKDF2算法生成加密和认证密钥,这个算法是从用户通过setKey()方法指定的密钥中派生出来的。

有没有人能帮我调整我的Python代码来解密这些数据?谢谢!

1 个回答

4

我找到了一种方法,可以解密被Zend2加密的数据。下面是我的代码:

from base64 import b64decode
from Crypto import Random
from Crypto.Cipher import AES
from Crypto.Hash import SHA256, HMAC
from Crypto.Protocol.KDF import PBKDF2

# The hmac starts from 0 to 64 (length).
hmac_size = 64
hmac = data[:hmac_size]

# The cipher text starts after the hmac to the end.
# The cipher text is base64 encoded, so I decoded it.
ciphertext = data[hmac_size:]
ciphertext = b64decode(ciphertext)

# The IV starts from 0 to 16 (length) of the ciphertext.
iv = ciphertext[:16]

# The key size is 256 bits -> 32 bytes.
key_size = 32

# The passphrase of the key.
password = 'mypassphrase'

# The key is generated using PBKDF2 Key Derivation Function.
# In the case of Zend2 Crypt module, the iteration number is 5000, 
# the result length is the key_size * 2 (64) and the HMAC is computed
# using the SHA256 algorithm
the_hash = PBKDF2(password, iv, count=5000, dkLen=64, prf=lambda p, s:
                  HMAC.new(p, s, SHA256).digest())

# The key starts from 0 to key_size (32).
key = the_hash[:key_size]

# The hmac key starts after the key to the end.
key_hmac = the_hash[key_size:]

# HMAC verification
hmac_new = HMAC.new(key_hmac, 'aes%s' % ciphertext, SHA256).hexdigest()
if hmac_new != hmac:
    raise Exception('HMAC verification failed.')

# Instanciate the cipher (AES CBC).
cipher = AES.new(key, AES.MODE_CBC, iv)

# It's time to decrypt the data! The ciphertext starts after the IV (so, 16 after).
data = cipher.decrypt(ciphertext[16:])

任务成功了!

撰写回答