Skip to main content
 首页 » 编程设计

python之使用 AES-256 和 PKCS7 填充进行加密

2025年02月15日7arxive

我想使用 python 来加密一些数据,并且发现 pycrypto 作为一种可能的工具。为了加密数据,我需要:

  1. 输入密码字符串
  2. SHA-256 字符串,为 AES-256 提供 key
  3. 将敏感数据表示为 9 位字符 (ascii) 的字符串,如果存在则以 ascii 0 开头(数据将始终采用这种格式)。
  4. 使用 AES-256 加密数据字符串,无盐,使用来自 RFC2315 的 PKCS7 填充,在 ecb 模式下。
  5. 将密文表示为Base64 (RFC 4648),需要24个字符

使用 pycrypto,步骤 1-3 相当简单。 4给我带来了一点麻烦。我不确定 PKCS7 填充是什么,我也不确定如何确保加密不使用 SALT。我希望有人能为我指出正确的方向:第 4 步。

请您参考如下方法:

PyCrypto 没有内置的填充功能。但是实现起来很容易。注意:当输入已经是正确的大小时,PKCS7 Padding 将添加一个额外的字节 block ,这个函数也是如此。 PKCS#7填充在此处解释。

def pad(m): 
    return m+chr(16-len(m)%16)*(16-len(m)%16) 
 
KEY = sha256(passphrase).digest()  #returns 256 bit key 
cipher = AES.new(KEY,AES.MODE_ECB) #creates a AES-256 instance using ECB mode 
ciphertext = cipher.encrypt(pad(data)).encode('base64') 

希望这就是您要找的。 在解密过程中,unpad函数可能会派上用场。

def unpad(ct): 
    return ct[:-ct[-1]] 

在 Python 3 中,unpad 函数可能需要强制转换(取决于用法),如下所示:

def unpad(ct): 
    return ct[:-ord(ct[-1])] 

附言

ECB mode of encryption is not cryptographic secure. Please use higher modes such as CBC, OFB or GCM.

GCM or Galois/Counter Mode provides both data confidentiality as well as authentication (Even for associated data, which need not be encrypted).

It is the most secure mode yet unless you use the same nonce twice