λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°

Lang/🐍 Python

🐍 Python * Message μ•”ν˜Έν™” AES128, HMAC

1. Root둜 μ ‘μ†ν•œλ‹€.

$ sudo su root

2. μ•”ν˜Έν™”μ— ν•„μš”ν•œ Module을 μ„€μΉ˜ν•œλ‹€.

β—‡ 2020/03/09 - [SW/🐍 Python] - βœ… Solved * [Ubuntu] Crypto install Error and How to Install with Python

3. μ•”ν˜Έν™”, λ³΅ν˜Έν™”μ— λŒ€ν•œ μ½”λ”© 간단 μ„€λͺ…

μ•„λž˜ 전체 μ½”λ“œκ°€ μžˆμŠ΅λ‹ˆλ‹€!

A. import module

B. HMAC hash

C. iv 생성

D. λ³΅ν˜Έν™”

E. μ•”ν˜Έν™”

F. μ‹€ν–‰

 

 

 

μ „μ²΄μ½”λ“œ
# -*- coding: utf-8 -*-

import hmac, binascii
import Crypto.Random
from Crypto.Cipher import AES

def gen_sha256_hashed_key_salt(key):
	salt1 = hmac.new(key).digest()
	return salt1


#iv 값을 랜덀으둜 λ°›μ•„μ˜€λŠ” μ½”λ“œ.
def gen_random_iv():
	return Crypto.Random.OSRNG.posix.new().read(AES.block_size)


#[ λ³΅ν˜Έν™” κ³Όμ • ] μ•”ν˜Έν™” λ¬Έμž₯을 편문으둜 ν•΄λ…ν•˜λŠ” μ½”λ“œ.
def AES256Decrypt(key, iv, cipher):
	encryptor = AES.new(gen_sha256_hashed_key_salt(key), AES.MODE_CBC, IV=iv)
	plain = encryptor.decrypt(cipher)
	plain = plain[0:-ord(plain[-1])]
	return plain


#[ μ•”ν˜Έν™” κ³Όμ • ] 평문을 μ•”ν˜Έν™” ν•˜λŠ” μ½”λ“œ.
def AES256Encrypt(key, plain):
	length = AES.block_size - (len(plain) % AES.block_size)
	plain += chr(length)*length
	iv = gen_random_iv()
	encryptor = AES.new(gen_sha256_hashed_key_salt(key), AES.MODE_CBC, IV=iv)
	return {'cipher': encryptor.encrypt(plain), 'iv': iv}


key = 'password123qwe'

encrypted = AES256Encrypt(key, 'Let me tell you the huge secret! The king has a donkey ear')
decrypted = AES256Decrypt(key, encrypted['iv'], encrypted['cipher'])

print decrypted

 

 


Thanks for πŸ™ˆ