2
回答
phpAES算法使用随机的IV,如何用python实现相同的算法呢?
注册华为云得mate10,2.9折抢先购!>>>   

php算法:

class Security {
	public static function encrypt($input, $key) {
	$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
	$input = Security::pkcs5_pad($input, $size);
	$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
	$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
	mcrypt_generic_init($td, $key, $iv);
	$data = mcrypt_generic($td, $input);
	mcrypt_generic_deinit($td);
	mcrypt_module_close($td);
	$data = base64_encode($data);
	return $data;
	}
 
	private static function pkcs5_pad ($text, $blocksize) {
		$pad = $blocksize - (strlen($text) % $blocksize);
		return $text . str_repeat(chr($pad), $pad);
	}
 
	public static function decrypt($sStr, $sKey) {
		$decrypted= mcrypt_decrypt(
		MCRYPT_RIJNDAEL_128,
		$sKey,
		base64_decode($sStr),
		MCRYPT_MODE_ECB
		);
 
		$dec_s = strlen($decrypted);
		$padding = ord($decrypted[$dec_s-1]);
		$decrypted = substr($decrypted, 0, -$padding);
		return $decrypted;
	}	
} 
Security::encrypt($ID_value, $sTOKEN);

python 没有类似mcrypt_create_iv 生成iv这样的算法,尝试用Crypto中的iv = Random.new().read( AES.block_size ) 方式,发现对PHP的加密解内容解密失败,同理php也无法对python

举报
Alfred_lon
发帖于2年前 2回/159阅
共有2个答案 最后回答: 2年前
from Crypto.Cipher import AES
import base64

class Chan():
    """
    处理类
    """
    def __init__(self):
        self.key = ''
        self.BS = 16
        self.mode = AES.MODE_ECB

    def encrypt(self,text):
        """
        亿美渠道商AES加密方法
        """
        encryptor = AES.new(self.key,self.mode)
        padded_text = text + (self.BS - len(text) % self.BS) * chr(len(str(self.BS - len(text) % self.BS)))
        ciphertext = encryptor.encrypt(padded_text)
        return base64.b64encode(ciphertext)







顶部