加密 &使用 PyCrypto AES 256 解密 [英] Encrypt & Decrypt using PyCrypto AES 256
问题描述
我正在尝试使用 PyCrypto 构建两个接受两个参数的函数:消息和密钥,然后加密/解密消息.
I'm trying to build two functions using PyCrypto that accept two parameters: the message and the key, and then encrypt/decrypt the message.
我在网上找到了几个链接来帮助我,但每个链接都有缺陷:
I found several links on the web to help me out, but each one of them has flaws:
codekoala 的这个使用 os.urandom,这是 PyCrypto 不鼓励的.
This one at codekoala uses os.urandom, which is discouraged by PyCrypto.
此外,我给函数的键不能保证具有预期的确切长度.我该怎么做才能做到这一点?
Moreover, the key I give to the function is not guaranteed to have the exact length expected. What can I do to make that happen ?
另外,有几种模式,推荐哪一种?我不知道该用什么:/
Also, there are several modes, which one is recommended? I don't know what to use :/
最后,IV 到底是什么?我可以为加密和解密提供不同的 IV,还是会返回不同的结果?
Finally, what exactly is the IV? Can I provide a different IV for encrypting and decrypting, or will this return in a different result?
编辑:删除了不安全的代码部分.
Edit: Removed the code part since it was not secure.
推荐答案
这是我的实现,对我有用,有一些修复,并增强了 32 字节和 iv 到 16 字节的密钥和秘密短语的对齐:
Here is my implementation and works for me with some fixes and enhances the alignment of the key and secret phrase with 32 bytes and iv to 16 bytes:
import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES
class AESCipher(object):
def __init__(self, key):
self.bs = AES.block_size
self.key = hashlib.sha256(key.encode()).digest()
def encrypt(self, raw):
raw = self._pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(raw.encode()))
def decrypt(self, enc):
enc = base64.b64decode(enc)
iv = enc[:AES.block_size]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')
def _pad(self, s):
return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)
@staticmethod
def _unpad(s):
return s[:-ord(s[len(s)-1:])]
这篇关于加密 &使用 PyCrypto AES 256 解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!