【发布时间】:2017-04-10 18:42:59
【问题描述】:
我有一个 Python 应用程序和 PHP 网站,它们通过某些特定的网络层发送消息进行通信。我的任务是使用该通道发送所有经过 AES 加密和 base64 编码的消息。双方手动预共享加密密钥。
在我的 PHP 中,我使用此代码创建了名为 $payload 的最终消息文本:
$key = substr('abdsbfuibewuiuizasbfeuiwhfashgfhj56urfgh56rt7856rh', 0, 32);
$magic = 'THISISANENCRYPTEDMESSAGE';
function crypted($data) {
global $key, $magic;
// serialize
$payload = json_encode($data);
// encrypt and get base64 string with padding (==):
$payload = @openssl_encrypt($payload, 'AES-192-CBC', $key);
// prepend with magic
$payload = $magic.$payload;
return $payload;
}
我在我的 Python 应用程序中收到这样的消息,剥离魔法,获取 base64 字节数据。我找不到样本来制作兼容的 AES 密码来解码此消息的问题。
Key 和“Magic”只是双方预先共享且已知的值,这是正确的吗?我需要静脉注射吗?
这是来自 SO 的 Python 解决方案,它不适用于我的加密消息。
from base64 import b64encode, b64decode
from Crypto.Cipher import AES
class AESCipher:
class InvalidBlockSizeError(Exception):
"""Raised for invalid block sizes"""
pass
def __init__(self, key):
self.key = key
self.iv = bytes(key[0:16], 'utf-8')
def __pad(self, text):
text_length = len(text)
amount_to_pad = AES.block_size - (text_length % AES.block_size)
if amount_to_pad == 0:
amount_to_pad = AES.block_size
pad = chr(amount_to_pad)
return text + pad * amount_to_pad
def __unpad(self, text):
pad = ord(text[-1])
return text[:-pad]
def encrypt( self, raw ):
raw = self.__pad(raw)
cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
return b64encode(cipher.encrypt(raw))
def decrypt( self, enc ):
enc = b64decode(enc)
cipher = AES.new(self.key, AES.MODE_CBC, self.iv )
r = cipher.decrypt(enc) # type: bytes
return self.__unpad(r.decode("utf-8", errors='strict'))
由于解码问题,它在最后一行失败。 “忽略”解码模式返回空字符串。
# with magic: "THISISANENCRYPTEDMESSAGE8wZVLZpm7UNyUf26Kds9Gwl2TBsPRo3zYDFQ59405wI="
# contains: {'test': 'hello world'}
payload = '8wZVLZpm7UNyUf26Kds9Gwl2TBsPRo3zYDFQ59405wI='
aes = AESCipher('abdsbfuibewuiuizasbfeuiwhfashgfh')
print(aes.decrypt(payload))
加注:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "../test.py", line 36, in decrypt
return self.__unpad(cipher.decrypt(enc).decode("utf-8"))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9e in position 0: invalid start byte
我错过了什么?
【问题讨论】:
-
你为什么使用
text[-1](一个x02字节,所以你忽略了最后2个字节)来确定加密数据字符串的长度? -
使用密钥作为 IV 确实不是一个聪明的主意。好像真的不聪明。并且拥有一个完全由 ASCII 字母和数字组成的密钥会显着减少可能的密钥空间。
标签: php python-3.x encryption interop aes