IT/프로그래밍/Python

PyCrypto를 이용해서 AES방식으로 암호화 하기

third9 2015. 8. 7. 17:47

Python에서 암호화를 위해서 사용한것을 잊어먹지 않기 위해서 작성합니다.


Python 에서 AES 암호화를 위해서 Pypi 검색을 해보니 너무 많아서 어떤걸 사용해야 할지 모르겠다.

개인적으로 보기에 비교적 많이 사용된다고 느낀 PyCrypto, M2Crypto 두 가지 중에서 PyCrypto

이용해서 개발했다.

어찌 보면 상관없지만 그냥 비교를 해놓은 글이 있어서 참조.

Using PyCrypto instead of M2Crypto on Google App Engine

내가 참조하기 위해서 쓴 글이다 보니 코드 위주로만 작성한다. 우선 pip에서 PyCrypto를

설치해놨다고 생각하고 쓴다.

전체 코드 (링크를 참조해서 작성)

# -*- coding: utf-8 -*- 

from Crypto.Cipher import AES
import base64

class MyCrypto:
    def __init__(self):
        BLOCK_SIZE = 32
        PADDING = '|'
        secret = "140b41b22a29beb4061bda66b6747e14"
        cipher = AES.new(secret)

        pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING

        self.encodeAES = lambda s: base64.b64encode(cipher.encrypt(pad(s)))
        self.decodeAES = lambda e: cipher.decrypt(base64.b64decode(e)).rstrip(PADDING)

    def encodeAES(self, data):
        encoded = self.encodeAES(data)
        return encoded

    def decodeAES(self, data):
        decoded = self.decodeAES(data)
        return decoded

def main():
    crypto = MyCrypto()

    encode = crypto.encodeAES('password')
    print("encodeAES: {}".format(encode))

    decode = crypto.decodeAES(encode)
    print("decodeAES: {}".format(decode))

if __name__ == "__main__":
    main()

코드를 보면 아래와 같이 변수가 선언되어있다.

BLOCK_SIZE = 32
PADDING = "|"
secret = "140b41b22a29beb4061bda66b6747e14"
cipher = AES.new(secret)

BLOCK_SIZE는 암호화할 문장의 최소값을 정의한다. encrypt 할 값의 길이가 32 보다

작을 경우 PADDING 의 값으로 빈공간을 채워준다. 관련 로직은 아래의 코드다.

pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING

코드를 보면 입력받은 값 s의 길이를 체크해서 부족한 만큼 PADDING을 붙여준다. 만약 암호화 길이가 두 32를 넘어가면 32의 배수로 체크하여 부족한 만큼 PADDING을 더해준다.

그 외에는 다른 암호화 모듈과 유사하게 비밀키값을 정의하고 암호화를 위한 cipher 객체를

생성한 뒤에 cipher.encrypt(값), cipher.decrypt(값) 를 사용해서 암호화 시키면 된다.

PyCrypto 모듈에 대해서 자세히 알고 싶다면 PyCrypto 링크 참조

잘못된 점이나 의견 주시면 감사하겠습니다.


BlogWriter