Skip to content

DES加解密 in Python

des

python
# poetry add pycryptodome
from Crypto.Cipher import DES
from base64 import b64encode, b64decode
import math


class DES_ECB:

    @staticmethod
    def _pad(text, block_size):
        no_of_blocks = math.ceil(len(text)/float(block_size))
        pad_value = int(no_of_blocks * block_size - len(text))

        if pad_value == 0:
            return text + chr(block_size) * block_size
        else:
            return text + chr(pad_value) * pad_value

    @staticmethod
    def _unpad(padded_text):
        pad_value = ord(padded_text[-1])
        return padded_text[:-pad_value]

    def encrypt_as_b64(self, key, plaintext):
        size = 8
        key = key[:size].encode()
        plaintext = self._pad(plaintext, size).encode()
        code = DES.new(key, DES.MODE_ECB).encrypt(plaintext)
        return b64encode(code).decode()

    def decrypt_as_text(self, key, ciphertext):
        size = 8
        key = key[:size].encode()
        ciphertext = b64decode(ciphertext)
        decrypted_text = DES.new(key, DES.MODE_ECB).decrypt(ciphertext)
        return self._unpad(decrypted_text.decode())

key = "hph3c_z01500"
plaintext = "123456"

des_ecb = DES_ECB()
encrypted_text = des_ecb.encrypt_as_b64(key, plaintext)
print(f"Encrypted: {encrypted_text}")

decrypted_text = des_ecb.decrypt_as_text(key, encrypted_text)
print(f"Decrypted: {decrypted_text}")

Released under the MIT License.