+ Development/Python
[Python] pycrypto Module(모듈)을 이용한 암/복호화 하기
:: Teacher ::
2019. 9. 11. 00:30
728x90
반응형
개발을 진행하다보면 특정 데이터에 대해서 암/복호화 하여 사용하는 경우가 있다.
물론 더 복잡하게 Salt / Pepper 암호화 처리를 통해 할 수 있으나, 이번에는 간략하게 Key값을 통한 암/복화를 해보자.
반드시 pycrypto 모듈이 설치 되어 있어야 한다.
# pip를 이용한 pycrypto 설치
$ pip install pycrypto
예제 code )
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
from Crypto import Random
from Crypto.Cipher import AES
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s: s[0:-ord(s[-1])]
class AESCipher:
def __init__(self, key):
self.key = key
def encrypt(self, raw):
raw = pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(raw))
def decrypt(self, enc):
enc = base64.b64decode(enc)
iv = enc[:16]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return unpad(cipher.decrypt(enc[16:]))
if __name__ == '__main__':
key = '!01234!5678998765!43210!'
json_str = 'Test'
cipher = AESCipher(key)
encrypted = cipher.encrypt(json_str)
decrypted = cipher.decrypt(encrypted)
print 'Key:: '+key
print 'Enc:: '+encrypted
print 'Dec:: '+decrypted
--------------------------------------------------
Result
Key:: !01234!5678998765!43210!
Enc:: MzVW4mC3r5ajGWO49Lz9Tnp8iXlw2wTtL2Z2q0Jy+dI=
Dec:: Test
728x90
반응형