python 和php 对称加密 CBC 填充 向量

PHP

$this->timeStamp=$this->getUnixTimestamp();#获取毫秒时间戳
        $this->sign=sha1(self::appId."-".self::agentKey."-".(string)$this->timeStamp);#appid+秘钥+毫秒时间戳
        $arr=[
            "appId"=>self::appId,
            "agentKey"=>self::agentKey,
            "timeStamp"=>(string)$this->timeStamp,
            "sign"=>$this->sign
        ];#加签名
        $aes = new Aes();
        $string=json_encode($arr);
        $iv=self::iv;
        $key=self::agentKey;
        $this->spec=$aes->encrypt($string,$key,$iv);
		
	class Aes
	
		function encrypt($data,$key,$iv): string
		{
			$data = $this->pkcs5Pad($data, 16);
			$data = openssl_encrypt($data, 'AES-128-CBC', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
			return base64_encode($data);
		}
		function pkcs5Pad($text, $blocksize): string
		{
			$pad = $blocksize - (strlen($text) % $blocksize);
			return $text . str_repeat(chr($pad), $pad);

		}

PYTHON

pip install -i https://mirrors.aliyun.com/pypi/simple pycrypto

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pycryptodome

from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
import time
from config import Config
import json
import hashlib

def add_to_16(text):
  if len(text.encode('utf8')) % 16:
    add = 16 - (len(text.encode('utf8')) % 16)
  else:
    add = 0
  text = text + '\0' * add
  return text

# 加密
def encrypt():
    #key = '9999999999999999'.encode('utf8')
    #iv = b'qqqqqqqqqqqqqqqq'
    t = time.time()
    t=int(round(t * 1000))#毫秒级
    signstr=Config.APPID+"-"+Config.AGENTKEY+"-"+str(t)
    sign=hashlib.sha1(signstr.encode("utf8"))
    sign=sign.hexdigest()
    text=json.dumps({"appId":Config.APPID,"agentKey":Config.AGENTKEY,"timeStamp":str(t),"sign":sign})
    cryptos = AES.new(Config.AGENTKEY.encode('utf-8'),AES.MODE_CBC,Config.IV.encode('utf-8'))
    #且Block大小为16Byte.  加密的key大小为:16,24,32,对应到128bit, 192bit, 256bit加密
    text=pkcs5Pad(text,16)
    cipher_text = cryptos.encrypt(text.encode('utf-8'))
    # 因为AES加密后的字符串不一定是ascii字符集的,输出保存可能存在问题,所以这里转为16进制字符串
    return cipher_text#b2a_hex(cipher_text)
# 解密后去掉空格
def decrypt(text):
  key = '9999999999999999'.encode('utf8')
  mode = AES.MODE_CBC
  iv = b'qqqqqqqqqqqqqqqq'
  cryptos = AES.new(key, mode, iv)
  plain_text = cryptos.decrypt(a2b_hex(text))
  return bytes.decode(plain_text).rstrip('\0')

def pkcs5Pad(text, blocksize):
    #16分组数据长度,填充补齐最后一块数据,
    #例如需要补5个字节,在后面填充5个\x05
    #补12个字节则填充12个\x0c
    pad = blocksize - (len(text) % blocksize)
    pk=""
    n=chr(pad)
    for k in range(pad):
        pk=pk+n
    return text + pk

Config


     APPID="123123213233312332123"
     AGENTID="1231231232"
     AGENTKEY="0000000000000000"
     IV="1234512345612345"

猜你喜欢

转载自blog.csdn.net/zhang804633234/article/details/120918025