
블록 알고리즘이기 때문에 key, iv와 암호화 대상의 크기는 블록 사이즈만큼 나뉘어 떨어져야 합니다. 그래서 나뉘어 떨어지지 않는 데이터에 대해서는 PKCS 패딩을 적용해야 합니다.
DES는 패리티 비트를 포함한 키의 길이가 64비트이고, 64비트 블록 단위로 데이터를 암호화합니다.
from Cryptodome.Cipher import DES # pip3 install pycryptodomex
padding = lambda s: s + (DES.block_size - len(s.encode()) % DES.block_size) * chr(DES.block_size - len(s.encode()) % DES.block_size)
KEY = b"12345678"
IV = b"abcdefgh"
PLAIN_TEXT = "Hello World"
cipher = DES.new(KEY, DES.MODE_CBC, IV)
cipher_text = cipher.encrypt(padding(PLAIN_TEXT).encode())
print(cipher_text) # b'(4\xc7\x16\x89\xbf!c\xf6\xaah\xb7\x9f\x13Ba'
블록 알고리즘이기 때문에 key, iv와 복호화 대상의 크기는 블록 사이즈만큼 나뉘어 떨어져야 합니다. 동시에 대칭키를 사용하는 암호이기 때문에 암호화에 사용했던 key, iv를 사용해야 정상적으로 복호화가 가능합니다.
DES는 패리티 비트를 포함한 키의 길이가 64비트이고, 64비트 블록 단위로 데이터를 복호화 합니다. 복호화 후 PKCS 패딩이 적용된 상태이기 때문에 역으로 패딩을 없애줍니다.
from Cryptodome.Cipher import DES # pip3 install pycryptodomex
unpadding = lambda s: s[:-ord(s[len(s) - 1:])]
KEY = b"12345678"
IV = b"abcdefgh"
CIPHER_TEXT = b'(4\xc7\x16\x89\xbf!c\xf6\xaah\xb7\x9f\x13Ba'
cipher = DES.new(KEY, DES.MODE_CBC, IV)
plain_text = unpadding(cipher.decrypt(CIPHER_TEXT)).decode()
print(plain_text) # Hello World
DES는 현재 컴퓨팅 파워로는 취약한 크기()를 가지고 있습니다. 따라서 DES를 중첩하여 사용해서 키의 크기를 늘리는 방법으로 사용되었지만, Double DES는 MITM(Meet-In-The-Middle) Attack에 의해 효과적이지 않았습니다.
따라서 DES를 3번 사용하는 3DES(Triple DES)가 사용()됩니다. 키의 크기는 24byte이지만, 중복되는 데이터에 따라 다양하게 사용할 수 있습니다.
# Encrypt
from Cryptodome.Cipher import DES3 # pip3 install pycryptodomex
padding = lambda s: s + (DES3.block_size - len(s.encode()) % DES3.block_size) * chr(DES3.block_size - len(s.encode()) % DES3.block_size)
KEY = b"12345678abcdefghABCDEFGH"
IV = b"abcdefgh"
PLAIN_TEXT = "Hello World"
cipher = DES3.new(KEY, DES3.MODE_CBC, IV)
cipher_text = cipher.encrypt(padding(PLAIN_TEXT).encode())
print(cipher_text) # b'\x83@}e,\x14-KE\x17e\xbfv\xfb15'
# Decrypt
from Cryptodome.Cipher import DES3 # pip3 install pycryptodomex
unpadding = lambda s: s[:-ord(s[len(s) - 1:])]
KEY = b"12345678abcdefghABCDEFGH"
IV = b"abcdefgh"
CIPHER_TEXT = b'\x83@}e,\x14-KE\x17e\xbfv\xfb15'
cipher = DES3.new(KEY, DES3.MODE_CBC, IV)
plain_text = unpadding(cipher.decrypt(CIPHER_TEXT)).decode()
print(plain_text) # Hello World
3DES는 모든 애플리케이션에 대해 2023-12-31일 이후로는 사용을 금지하고 있습니다.