Created
May 2, 2013 03:12
-
-
Save tkoki/5499931 to your computer and use it in GitHub Desktop.
AES暗号をちょろっと使うためのパッケージ。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from Crypto.Cipher import AES | |
from binascii import b2a_hex | |
''' | |
@brief CipherDataクラス | |
ブロック暗号は元のデータの長さがブロック長の倍数になっていない場合パディングが必要なので、それを覚えとくためのクラス。 | |
''' | |
class CipherData: | |
def __init__(self, encrypted_data, padding_length): | |
self.encrypted_data = encrypted_data | |
self.padding_length = padding_length | |
def show(self): | |
print 'CipherData:' | |
print 'encrypted_data = ' + b2a_hex(self.encrypted_data) | |
print 'padding_length = ' + str(self.padding_length) | |
''' | |
@brief AESによる暗号 | |
@param[in] str 暗号化される元データ。 | |
@param[in] key 共通鍵。この長さは16バイト(AES-128)、24バイト(AES-192)、32バイト(AES-256)のいずれかである必要がある。 | |
@retval CipherDataオブジェクト。 | |
''' | |
def encrypt_string(str, key): | |
cipher = AES.new(key, AES.MODE_ECB) | |
residue = len(str) % AES.block_size | |
if residue: | |
padding = AES.block_size - residue | |
else: | |
padding = 0 | |
for i in xrange(padding): | |
str = str + 'X' | |
msg = cipher.encrypt(str) | |
return CipherData(msg, padding) | |
''' | |
@brief AESによる復号 | |
@param[in] cipher_data CipherDataオブジェクト。 | |
@param[in] key 共通鍵。 | |
@retval 元データ。 | |
''' | |
def decrypt_string(cipher_data, key): | |
cipher = AES.new(key, AES.MODE_ECB) | |
msg = cipher.decrypt(cipher_data.encrypted_data) | |
return msg[0:len(msg) - cipher_data.padding_length] | |
''' | |
@brief 使用例 | |
''' | |
def main(): | |
test_key = '0123456789abcdef' | |
test_string = 'Hello World' | |
cipher_data = encrypt_string(test_string, test_key) | |
cipher_data.show() | |
print decrypt_string(cipher_data, test_key) | |
if __name__ == '__main__': | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment