Created
January 22, 2014 08:17
-
-
Save xdqi/8555193 to your computer and use it in GitHub Desktop.
Make AES-256-CFB of pycrypto and M2Crypto compatible
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from hashlib import sha256 | |
from Crypto.Cipher import AES | |
from Crypto import Random | |
from base64 import * | |
import os | |
import M2Crypto | |
default_passphrase = 'test' | |
def kec(str_data, str_key=default_passphrase): | |
crypt_key = sha256(str_key.encode('rot-13')).digest() | |
data_flow = b64encode(str_data.encode('utf-8')).encode('rot-13') | |
iv = Random.new().read(AES.block_size) | |
raw_data = iv + AES.new(crypt_key, AES.MODE_CFB, iv).encrypt(data_flow) | |
return raw_data#encodestring(raw_data).encode('rot-13') | |
def kdc(crypt_data, str_key=default_passphrase): | |
raw_crypted_data = crypt_data#decodestring(crypt_data.encode('rot-13')) | |
str_data = raw_crypted_data[AES.block_size:] | |
crypt_key = sha256(str_key.encode('rot-13')).digest() | |
iv = raw_crypted_data[0: AES.block_size] | |
raw_data = AES.new(crypt_key, AES.MODE_CFB, iv).decrypt(str_data) | |
return b64decode(raw_data.encode('rot-13')).decode('utf-8') | |
def kem(str_data, str_key=default_passphrase): | |
crypt_key = sha256(str_key.encode('rot-13')).digest() | |
data_flow = b64encode(str_data.encode('utf-8')).encode('rot-13') | |
miv = os.urandom(16) | |
cryptor = M2Crypto.EVP.Cipher(alg='aes_256_cfb', key=crypt_key, iv=miv, op=1) | |
raw_data = miv | |
a = cryptor.update(data_flow) | |
b = cryptor.final() | |
raw_data += a+b | |
return raw_data#encodestring(raw_data).encode('rot-13') | |
def kdm(crypt_data, str_key=default_passphrase): | |
raw_crypted_data = crypt_data#decodestring(crypt_data.encode('rot-13')) | |
str_data = raw_crypted_data[16:] | |
crypt_key = sha256(str_key.encode('rot-13')).digest() | |
miv = raw_crypted_data[0: 16] | |
cryptor = M2Crypto.EVP.Cipher('aes_256_cfb', crypt_key, iv=miv, op=0, i=0) | |
raw_data = cryptor.update(str_data) | |
raw_data += cryptor.final() | |
return b64decode(raw_data.encode('rot-13')).decode('utf-8') |
kec、kdc:基于 pycrypto 的加/解密
kem、kdm:基于 M2Crypto 的加/解密
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
需要让 kec(基于 pycrypto)和 kem(基于 M2Crypto)兼容