誰かがPythonを使用してm2crypto aes256 CBCを使用して暗号化/復号化するコードを提供できますか
5 に答える
M2Crypto のドキュメントはひどいものです。OpenSSL のドキュメント (m2crypto は OpenSSL をラップしています) が役立つ場合があります。あなたの最善の策は、M2Crypto単体テストを見ることです - https://gitlab.com/m2crypto/m2crypto/blob/master/tests/test_evp.py - メソッドを探しますtest_AES()
。
M2Crypto の次のラッパーを使用します ( cryptography.ioから借用):
import os
import base64
import M2Crypto
class SymmetricEncryption(object):
@staticmethod
def generate_key():
return base64.b64encode(os.urandom(48))
def __init__(self, key):
key = base64.b64decode(key)
self.iv = key[:16]
self.key = key[16:]
def encrypt(self, plaintext):
ENCRYPT = 1
cipher = M2Crypto.EVP.Cipher(alg='aes_256_cbc', key=self.key, iv=self.iv, op=ENCRYPT)
ciphertext = cipher.update(plaintext) + cipher.final()
return base64.b64encode(ciphertext)
def decrypt(self, cyphertext):
DECRYPT = 0
cipher = M2Crypto.EVP.Cipher(alg='aes_256_cbc', key=self.key, iv=self.iv, op=DECRYPT)
plaintext = cipher.update(base64.b64decode(cyphertext)) + cipher.final()
return plaintext
m2secretを見てください:
対称鍵アルゴリズムを使用してデータを暗号化および復号化するための小さなユーティリティおよびモジュール。デフォルトでは、CBC を使用する 256 ビット AES (Rijndael) を使用しますが、一部のオプションは構成可能です。パスワードからキーを導出するために使用される PBKDF2 アルゴリズム。
def encrypt_file(key, in_filename, out_filename,iv):
cipher=M2Crypto.EVP.Cipher('aes_256_cfb',key,iv, op=1)
with open(in_filename, 'rb') as infile:
with open(out_filename, 'wb') as outfile:
outfile.write(b)
while True:
buf = infile.read(1024)
if not buf:
break
outfile.write(cipher.update(buf))
outfile.write( cipher.final() )
outfile.close()
infile.close()
def decrypt_file(key, in_filename, out_filename,iv):
cipher = M2Crypto.EVP.Cipher("aes_256_cfb",key , iv, op = 0)
with open(in_filename, 'rb') as infile:
with open(out_filename, 'wb') as outfile:
while True:
buf = infile.read(1024)
if not buf:
break
try:
outfile.write(cipher.update(buf))
except:
print "here"
outfile.write( cipher.final() )
outfile.close()
infile.close()
セキュリティに関して言えば、ドキュメントを読むことに勝るものはありません。
http://chandlerproject.org/bin/view/Projects/MeTooCrypto
時間をかけて理解し、コピーして貼り付けるのに最適なコードを作成したとしても、私が良い仕事をしたかどうかはわかりません. あまり役に立ちませんが、幸運と安全なデータをお祈りします。