๐Ÿ”‘Python์œผ๋กœ AES ์•”ํ˜ธํ™”

t1mmyt1mยท2022๋…„ 3์›” 9์ผ
3

์ „์— ์˜ฌ๋ฆฐ ๊ธ€์˜ ์ฃผ์ œ์˜€๋˜ AES๋ฅผ ํŒŒ์ด์ฌ์œผ๋กœ ์•”ํ˜ธํ™” ํ•ด๋ณด๊ธฐ๋กœ ํ–ˆ๋‹ค...

1. pycryptodome

ํŒŒ์ด์ฌ์„ ์ด์šฉํ•˜์—ฌ ์•”ํ˜ธํ™”๋ฅผ ํ•˜๊ธฐ ์œ„ํ•ด์„œ ๋‚œ pycryptodome์„ ์‚ฌ์šฉํ•  ๊ฒƒ์ด๋‹ค.

pip install PyCryptodome

์œ„์— ์ฝ”๋“œ๋ฅผ ์ž…๋ ฅํ–ˆ๋”๋‹ˆ

Raquirement already satisfied: PyCryptodome in /home/bassel/anaconda3/lib/python3.8/site-packages (3.9.9)

๋ผ๊ณ  ๋‚˜์™”๋‹ค. ๊ทธ๋Ÿผ ์ด์ œ ํŒŒ์ด์ฌ์œผ๋กœ ์ฝ”๋“œ๋ฅผ ์ž…๋ ฅํ•˜๋ฉด ๋œ๋‹ค.

2. Python์œผ๋กœ ์ฝ”๋“œ ์ž…๋ ฅ

from Crypto.Cipher import AES
from secrets import token_bytes

key = token_bytes(16)

def encrypt(msg):
    cipher = AES.new(key, AES.MODE_EAX)
    nonce = cipher.nonce
    ciphertext, tag = cipher.encrypt_and_digest(msg.encode('ascii'))
    return nonce, ciphertext, tag

def decrypt(nonce, ciphertext, tag):
    cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
    plaintext = cipher.decrypt(ciphertext)
    try:
        cipher.verify(tag)
        return plaintext.decode('ascii')
    except:
        return False

nonce, ciphertext, tag = encrypt(input('Enter a message: '))
plaintext = decrypt(nonce, ciphertext, tag)
print(f'Cipher text: {ciphertext}')
if not plaintext:
    print('Message is corrupted')
else:
    print(f'Plain text: {plaintext}')

์ด๋ ‡๊ฒŒ ์ฝ”๋“œ๋ฅผ ์ž…๋ ฅํ–ˆ๋‹ค.

3. ๊ฒฐ๊ณผ

ํ„ฐ๋ฏธ๋„์— ํŒŒ์ผ๋ช…์ธ

python aes_encryption.py

๋ฅผ ์ž…๋ ฅํ–ˆ๋”๋‹ˆ

Enter a message:

๋ผ๊ณ  ๋œฌ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์ž…๋ ฅ์ฐฝ์— ์•„๋ฌด ๋ฉ”์„ธ์ง€๋‚˜ ์ž…๋ ฅํ•ด์„œ enter๋ฅผ ๋ˆ„๋ฅด๋ฉด AES ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ํ†ตํ•ด Cipher text์™€ Plain text๊ฐ€ ์ฐจ๋ก€๋Œ€๋กœ ๋‚˜ํƒ€๋‚œ๋‹ค.

Reference
https://pycryptodome.readthedocs.io/en/latest/src/cipher/aes.html?highlight=AES

0๊ฐœ์˜ ๋Œ“๊ธ€