class AESCipher:
BLOCK_SIZE = 16
class PKCS7Encoder():
class InvalidBlockSizeError(Exception):
"""Raised for invalid block sizes"""
pass
def __init__(self, block_size=16):
if block_size < 2 or block_size > 255:
raise AESCipher.PKCS7Encoder.InvalidBlockSizeError('The block size must be ' \
'between 2 and 255, inclusive')
self.block_size = block_size
def encode(self, text):
text_length = len(text)
amount_to_pad = self.block_size - (text_length % self.block_size)
if amount_to_pad == 0:
amount_to_pad = self.block_size
pad = chr(amount_to_pad)
return text + pad * amount_to_pad
def decode(self, text):
pad = text[-1]
return text[:-pad]
def __init__(self, key, iv):
self.key = key
self.iv = iv
self.encoder = AESCipher.PKCS7Encoder(AESCipher.BLOCK_SIZE)
def encrypt(self, raw):
data = self.encoder.encode(raw)
cipher = AES.new(self.key, AES.MODE_CBC, self.iv.encode("utf-8"))
return cipher.encrypt(data)
def decrypt(self, enc):
cipher = AES.new(self.key, AES.MODE_CBC, self.iv.encode("utf-8"))
return self.encoder.decode(cipher.decrypt(enc))
구글링으로 여기저기서 조합한 코드다. (출처가 없음은 죄송..)
C#(unity3D) : Padding 알고리즘을 선택할 수 있다
NodeJs : final() 호출하면 알아서 해준다.
Python : 따로 일일이 해줘야 한다.
검색했던 키워드는 python, AES, encryption, pkcs7 padding
python2 와 python3는 문자열, 바이트 처리 방식이 다른 듯 하다.
decode() 안에서 ord()를 사용했는데 python3 넘어오자 그게 필요 없어졌다.
=> TypeError: ord() expected string of length 1, but int found
encrypt 되서 나온 결과물은 base64로 변환해서 전송하는 것이 보통
'Develop' 카테고리의 다른 글
| WPF Binding (0) | 2018.11.12 |
|---|---|
| perforce ignore (0) | 2018.09.05 |
| nodejs zip (0) | 2018.02.27 |
| mac 에서 logcat (0) | 2018.02.22 |
| vscode 지금업데이트 안됨 (0) | 2017.09.18 |