Skip to content

Instantly share code, notes, and snippets.

@whitekid
Created May 30, 2013 13:54
Show Gist options
  • Save whitekid/5677992 to your computer and use it in GitHub Desktop.
Save whitekid/5677992 to your computer and use it in GitHub Desktop.
MySQL aes_encrypt compatible encrypt/decrypt function
def aes_encrypt(data, key):
"""MySQL aes_encrypt compatible encrypt function"""
import mcrypt
import binascii
m = mcrypt.MCRYPT('rijndael-128', 'ecb')
m.init(key)
# MySQL은 여기다 padding을 붙여서 진행하니까...
# 아래 공식은 다음 주소에서 확인
# http://dev.mysql.com/doc/refman/5.5/en/encryption-functions.html#function_aes-encrypt
# 그리고 padding하는 것은 padding하는 문자의 chr(x)의 값을 padding 한다.
expected_length = 16 * ((len(data) / 16) + 1)
padding_length = expected_length - len(data)
data = data + chr(padding_length) * padding_length
enc = m.encrypt(data)
return binascii.hexlify(enc).upper()
def aes_decrypt(data, key):
"""MySQL aes_decrypt compatible decrypt function"""
import mcrypt
import binascii
m = mcrypt.MCRYPT('rijndael-128', 'ecb')
data = binascii.unhexlify(data)
m.init(key)
dec = m.decrypt(data)
if '\x00' in dec: # Python-mysql은 padding으로 \x00을 사용한다.
dec = dec[:dec.index('\x00')]
# MySQL은 Padding으로 더해진 문자열 갯수를 사용한다.
last = dec[len(dec) - 1]
dec = dec[:-ord(last)]
return dec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment