AES加密例子(python和php版本)

python版本
输入的加密字符必须是16的倍数,php的默认补零,所以解密的时候还需要rtrim掉零。python没有自动做这件事情,所以要自己补零。

class MyCrypt():
    def __init__(self, key):
        self.key = key
        self.mode = AES.MODE_CBC
        self.padding = '\0'
 
    def encrypt(self, text):
        cryptor = AES.new(self.key, self.mode)
        length = 16
        count = text.count('')
        if count < length:
            add = (length - count) + 1
            text += (self.padding * add)
        elif count > length:
            add = (length - (count % length)) + 1
            text += (self.padding * add)
        self.ciphertext = cryptor.encrypt(text)
        return self.ciphertext
 
    def decrypt(self, text):
        cryptor = AES.new(self.key, self.mode)
        plain_text = cryptor.decrypt(text)
        return plain_text.rstrip("\0")
 
if __name__ == '__main__':
    key = '1234567890abcdef'
    data = '{"a": "123中文", sss} '
    ec = MyCrypt(key)
    encrpt_data = ec.encrypt(data)
    decrpt_data = ec.decrypt(encrpt_data)
    print encrpt_data, decrpt_data, decrpt_data == data
 
    from base64 import b64encode, b64decode
    print b64encode(encrpt_data)

PHP版本:

<?php
$privateKey = "1234567890abcdef";
$iv 	= "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
$data 	= '{"a": "123中文", sss}  ';
 
//加密
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $privateKey, $data, MCRYPT_MODE_CBC, $iv);
$edata = base64_encode($encrypted);
echo $edata;
echo '<br/>';
 
//解密
$encryptedData = base64_decode('6PIG4DBcjsDDxY9GtHq2TXjTVE5linoc/7i8CdJNTU0=');
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $privateKey, $encryptedData, MCRYPT_MODE_CBC, $iv);
echo(rtrim($decrypted, "\0"));
?>



fatkun

5条评论

你好啊,我用Python3加密,加密字符串中有中文就会出现报错,这是为什么?

发表评论

电子邮件地址不会被公开。