20
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PyCrypto で OpenSSL AES-256-CBC の暗号文を復号

Posted at

OpenSSL 1.0.1g の EVP_BytesToKey() を読みながらテスト
Python 2.6.6, PyCrypto 2.0.1

暗号文作成

まずは openssl コマンドで暗号文を作成。パスワードは password

$# ターミナルに出力するため BASE64 エンコードしている
$ echo 'This is plain text !' | openssl aes-256-cbc -e -k password | openssl base64 -e
U2FsdGVkX1/Ab5WcN6HAN6ppt5YvoqTzD2VuQBbtmLIzAeTkYZFRUjtjwu/M5oMO

復号処理

PyCryto の AES で復号する

import base64
from hashlib import md5
from Crypto.Cipher import AES

encoded = 'U2FsdGVkX1/Ab5WcN6HAN6ppt5YvoqTzD2VuQBbtmLIzAeTkYZFRUjtjwu/M5oMO'
encrypted = base64.b64decode(encoded)
print 'encrypted: '+ repr(encrypted)
## encrypted: 'Salted__\xc0o\x95\x9c7\xa1\xc07\xaai\xb7\x96/\xa2\xa4\xf3\x0fen@\x16\xed\x98\xb23\x01\xe4\xe4a\x91QR;c\xc2\xef\xcc\xe6\x83\x0e'

# Salted__ に続く 8 バイトが salt
salt = encrypted[8:16]
print 'salt: '+ repr(salt)
## salt: '\xc0o\x95\x9c7\xa1\xc07'

secret = 'password'
# 簡略化しているが、OpenSSL の KDF の真似
hash1 = md5(secret + salt)
hash2 = md5(hash1.digest() + secret + salt)
hash3 = md5(hash2.digest() + secret + salt)
key = hash1.digest() + hash2.digest()
iv = hash3.digest()
print 'key: '+ repr(key)
print 'iv: '+ repr(iv)
## key: "\x1e\xfdh\xb0_\x05\xe1\x83x\xa5\xfe\x1d8&E#<'\x9f\xaf\x0e\xcba\x12\\KX\x897X\x90\x0c"
## iv: '4-\\iNh-\xc7\x99\tg\xe2\xbb\xcd\x12\xf5'


cipher = AES.new(key, AES.MODE_CBC, iv)
## salt を除いたデータを decrypt する
decrypted = cipher.decrypt(encrypted[16:])
print 'decrypted: '+ repr(decrypted)
print 'original: '+ repr(decrypted[0:-ord(decrypted[-1])])
## decrypted: 'This is plain text !\n\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b'
## original: 'This is plain text !\n'

参考文献

20
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?