def AESencrypt(password, plaintext, base64=False):
import hashlib, os
from Crypto.Cipher import AES
SALT_LENGTH = 32
DERIVATION_ROUNDS=1337
BLOCK_SIZE = 16
KEY_SIZE = 32
MODE = AES.MODE_CBC
salt = os.urandom(SALT_LENGTH)
iv = os.urandom(BLOCK_SIZE)
paddingLength = 16 - (len(plaintext) % 16)
paddedPlaintext = plaintext+chr(paddingLength)*paddingLength
derivedKey = password
for i in range(0,DERIVATION_ROUNDS):
derivedKey = hashlib.sha256(derivedKey+salt).digest()
derivedKey = derivedKey[:KEY_SIZE]
cipherSpec = AES.new(derivedKey, MODE, iv)
ciphertext = cipherSpec.encrypt(paddedPlaintext)
ciphertext = ciphertext + iv + salt
if base64:
import base64
return base64.b64encode(ciphertext)
else:
return ciphertext.encode("hex")
def AESdecrypt(password, ciphertext, base64=False):
import hashlib
from Crypto.Cipher import AES
SALT_LENGTH = 32
DERIVATION_ROUNDS=1337
BLOCK_SIZE = 16
KEY_SIZE = 32
MODE = AES.MODE_CBC
if base64:
import base64
decodedCiphertext = base64.b64decode(ciphertext)
else:
decodedCiphertext = ciphertext.decode("hex")
startIv = len(decodedCiphertext)-BLOCK_SIZE-SALT_LENGTH
startSalt = len(decodedCiphertext)-SALT_LENGTH
data, iv, salt = decodedCiphertext[:startIv], decodedCiphertext[startIv:startSalt], decodedCiphertext[startSalt:]
derivedKey = password
for i in range(0, DERIVATION_ROUNDS):
derivedKey = hashlib.sha256(derivedKey+salt).digest()
derivedKey = derivedKey[:KEY_SIZE]
cipherSpec = AES.new(derivedKey, MODE, iv)
plaintextWithPadding = cipherSpec.decrypt(data)
paddingLength = ord(plaintextWithPadding[-1])
plaintext = plaintextWithPadding[:-paddingLength]
return plaintext
a = AESencrypt("password", "ABC")
print AESdecrypt("password", a)
AESsencrypt() 로 ABC 를password 로 암호화
AESdecrypt() 로 password 로 복호화
패스워드를 사용하는 암호화 입니다. (현재 금융권에서 사용하는것으로 알고 있습니다. 그만큼 최고의 안정성 보장) 단지 해쉬 암호화가 아니기 때문에 암호화시 길이일정하지 않습니다.
출처:http://www.floyd.ch/?p=293
'app > python' 카테고리의 다른 글
no module named setuptools (0) | 2014.09.12 |
---|---|
python Fibonacci Sequence (2) | 2014.09.05 |
utf8 string to int (0) | 2014.08.20 |
python image to base64 encode/decode (0) | 2014.07.28 |
python 한글 에러 SyntaxError: Non-ASCII character '' in file ... (0) | 2012.07.29 |