암호학

[Cryptography] Symmetric-Key Cryptography: 3DES (대칭키 암호: 3DES 구현)

lawence 2025. 3. 7. 21:52

 

 

 

3DES

 DES는 블록 암호에 기반하여 설계된 56비트 암호화 알고리즘입니다. 그러나 작은 크기로 너무 약하다는 단점이 있어 쉽게 뚫려버리고 말았습니다. 이 문제를 해결하기 위하여 등장한 암호화 알고리즘이 3DES(Triple DES) 인데, 이는 블록당 3번의 DES 암호화를 수행하여 168비트의 키 암호화 알고리즘 입니다.

 

DES에 비해 보안성은 강화됐지만, 성능은 저하되었습니다.

보안을 강화시키면 편의성이 떨어지는 법이죠

 

아래는 전체 코드입니다. Background와 Description은 위 내용 그대로입니다.

자세한 부분은 전 글을 참고해주세요

https://dash758.tistory.com/42

 

[Cryptography] Symmetric-Key Cryptography (대칭키 암호)

대칭키 암호 대칭키 암호란 송-수신자 사이에 암-복호화에 사용되는 동일한 키를 사용하는 기법을 말합니다.하지만, 서로 동일한 키를 사용하며, 키를 은밀하게 전달하여 서로 사용해야 하는데

dash758.tistory.com

 

 

 

구현

from Crypto.Cipher import DES3
from Crypto.Hash import SHA256 as SHA       #need to initiallize vector because of size

#3DES
'''
Backgraound
-----------------------------------------------------------------------
DES(Data Encryption Standard) is 56-bit key block encryption algorithm.
But, DES is too weak(short) to use less secure
To overcome this weakness, the 3DES(Triple DES) algorithm emerged.
-----------------------------------------------------------------------

Description
-----------------------------------------------------------------------
3DES is a 168-bit key encryption algorithm
because it performs DES three times per block for encryption.
Block encryption is XOR operation that encrypts the result of the previous block's operations with the new secret key.
If so, how to encrypt first block?
It needs Initiallize vector.
'''

class myDES():
    def __init__(self, keytext, ivtext):                            #keytext = Generate 3DES Encrypt key & ivtext = initiallize vector
        hash = SHA.new()                                            #Generate SHA256
        hash.update(keytext.encode('utf-8'))                        #SHA256.update() does not receive string to args. we have to encoding 'utf-8'
        key = hash.digest()                                         #Convert to byte stream
        self.key = key[:24]                                         #3DES's size is 16 bytes ~ 24bytes. so we slice by 24 bytes

        hash.update(ivtext.encode('utf-8'))                         
        iv = hash.digest()                                          #Initiallize hash256 to use initiallize vector
        self.iv = iv[:8]

    def enc(self, plaintext):                                       #Encrypt plaintext
        des3 = DES3.new(self.key, DES3.MODE_CBC, self.iv)           #DES3.new(1, 2, 3) args -> 1. encryption key, 2. MODE, 3. initiallize vector (ECB, CTR MODE don't need iv)
        encmsg = des3.encrypt(plaintext.encode())                   #Encrypt plaintext(encmsg)
        return encmsg                                               #Return EncText
    
    def dec(self, ciphertext):                                      #Decrypt ciphertext(same as above)
        des3 = DES3.new(self.key, DES3.MODE_CBC, self.iv)
        decmsg = des3.decrypt(ciphertext)
        return decmsg
    
def main():
    keytext = 'Offensive'                                           #Set keytext, ivtext, plaintext
    ivtext = '1234'
    msg = 'security'

    myCipher = myDES(keytext, ivtext)                               #Generate object
    ciphered = myCipher.enc(msg)
    deciphered = myCipher.dec(ciphered)
    print(f'ORIGINAL:\t{msg}')
    print(f'CIPHERED:\t{ciphered}')
    print(f'DECIPHERED:\t{deciphered}')

main()

 

실행 결과

ORIGINAL:       security
CIPHERED:       b'\x9c\x82\t\x88R\x9fI\xc7'
DECIPHERED:     b'security'

 

 

 

참고 자료

도서 - 화이트 해커를 위한 암호화 해킹