没有额外模块的Python AES加密

时间:2014-08-12 10:08:54

标签: python aes python-3.4

是否可以使用AES加密/解密数据而无需安装额外的模块?我需要发送/接收来自C#的数据,这些数据是使用System.Security.Cryptography引用加密的。

更新 我曾尝试使用PyAES,但这太旧了。我更新了一些东西以使其成功,但它并没有。 我也无法安装,因为最新版本为3.3,而我的版本为3.4

6 个答案:

答案 0 :(得分:8)

标准库中提供的可用加密服务是those。如您所见,AES未列出,但建议使用pycrypto 额外模块

您只需使用 pip easy_install 安装它,然后如 pycrypto 的页面所示:

from Crypto.Cipher import AES
obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
message = "The answer is no"
print obj.encrypt(message)

不使用额外模块的唯一方法是自己编写函数代码,但是下载额外模块并使用它的不同之处是什么?

如果您想要一个纯Python的AES实现,您可以下载并导入检查pyaes

答案 1 :(得分:6)

PYAES应该适用于任何版本的Python3.x.无需修改库。

以下是Python3.x的pyaes CTR模式的完整工作示例 (https://github.com/ricmoo/pyaes

import pyaes

# A 256 bit (32 byte) key
key = "This_key_for_demo_purposes_only!"
plaintext = "Text may be any length you wish, no padding is required"

# key must be bytes, so we convert it
key = key.encode('utf-8')

aes = pyaes.AESModeOfOperationCTR(key)    
ciphertext = aes.encrypt(plaintext)

# show the encrypted data
print (ciphertext)

# DECRYPTION
# CRT mode decryption requires a new instance be created
aes = pyaes.AESModeOfOperationCTR(key)

# decrypted data is always binary, need to decode to plaintext
decrypted = aes.decrypt(ciphertext).decode('utf-8')

# True
print (decrypted == plaintext)

如果您收到任何错误,请告诉我

答案 2 :(得分:4)

我正在使用Cryptography库。

  

Cryptography是一个积极开发的库,提供   加密配方和原语。它支持Python 2.6-2.7,   Python 3.3+和PyPy。

Here is an example如何使用该库:

flush()

答案 3 :(得分:3)

Here is a self-contained implementation of AES compatible with Python 3

使用示例:

aesmodal = AESModeOfOperation() 
key = [143,194,34,208,145,203,230,143,177,246,97,206,145,92,255,84]
iv = [103,35,148,239,76,213,47,118,255,222,123,176,106,134,98,92]

size = aesmodal.aes.keySize["SIZE_128"]

mode,orig_len,ciphertext = aesmodal.encrypt("Hello, world!", aesmodal.modeOfOperation["OFB"], key, size, iv)
print(ciphertext)
plaintext = aesmodal.decrypt(ciphertext, orig_len, mode, key, size, iv)
print(plaintext)

答案 4 :(得分:2)

添加到@ enrico.bacis'回答:AES未在标准库中实现。它在PyCrypto库中实现,该库稳定且经过良好测试。如果您需要AES,请添加PyCrypto作为代码的依赖项。

虽然AES原语在理论上足够简单,你可以在纯Python中编写它们的实现,但强烈建议你不这样做。这是加密的第一条规则:不要自己实现它。特别是,如果你只是在自己的加密库中滚动,你几乎肯定会让自己受到某种旁​​道攻击。

答案 5 :(得分:0)

具有加密模块的Python 3.6

from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)
token = f.encrypt(b"my deep dark secret")
print(token)


f.decrypt(token)