没有额外模块的Python AES加密

Ant*_*ton 11 python aes python-3.4

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

更新 我尝试使用PyAES,但这太旧了.我更新了一些东西以使其成功,但事实并非如此.我也无法安装,因为它的最新版本是3.3我的版本3.4.

Vla*_*den 10

我正在使用密码学库。

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

这是如何使用该库的示例

>>> import os
>>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
>>> from cryptography.hazmat.backends import default_backend
>>> backend = default_backend()
>>> key = os.urandom(32)
>>> iv = os.urandom(16)
>>> cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
>>> encryptor = cipher.encryptor()
>>> ct = encryptor.update(b"a secret message") + encryptor.finalize()
>>> decryptor = cipher.decryptor()
>>> decryptor.update(ct) + decryptor.finalize()
'a secret message'
Run Code Online (Sandbox Code Playgroud)


enr*_*cis 9

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

你只需要使用pipeasy_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)
Run Code Online (Sandbox Code Playgroud)

没有使用额外模块的唯一方法是自己编写函数代码,但下载额外模块并使用它的区别是什么?

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


Ale*_*ecz 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)
Run Code Online (Sandbox Code Playgroud)

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