Skip to content

Instantly share code, notes, and snippets.

@mrluanma
Last active July 23, 2019 06:09
Show Gist options
  • Save mrluanma/917014 to your computer and use it in GitHub Desktop.
Save mrluanma/917014 to your computer and use it in GitHub Desktop.
Python 用 PyCrypto, M2Crypto, ncrypt, cryptography 3DES ECB mode 加密解密 demo。
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend
backend = default_backend()
key = os.urandom(16)
text = b'Hello, there!'
padder = padding.PKCS7(algorithms.TripleDES.block_size).padder()
unpadder = padding.PKCS7(algorithms.TripleDES.block_size).unpadder()
cipher = Cipher(algorithms.TripleDES(key), modes.ECB(), backend=backend)
encryptor = cipher.encryptor()
decryptor = cipher.decryptor()
encrypted_text = encryptor.update(padder.update(text) + padder.finalize()) + encryptor.finalize()
decrypted_text = unpadder.update(decryptor.update(encrypted_text) + decryptor.finalize()) + unpadder.finalize()
assert text == decrypted_text
# -*- Encoding: utf-8 -*-
from M2Crypto.EVP import Cipher
key = 'a' * 16
text = 'Hello, there!'
cipher = Cipher(alg='des_ede_ecb', key=key, op=1, iv='\0'*16)
encrypted_text = cipher.update(text)
encrypted_text += cipher.final()
decipher = Cipher(alg='des_ede_ecb', key=key, op=0, iv='\0'*16)
decrypted_text = decipher.update(encrypted_text)
decrypted_text += decipher.final()
assert text == decrypted_text
# -*- Encoding: utf-8 -*-
from ncrypt.cipher import CipherType, EncryptCipher, DecryptCipher
cipher_type = CipherType('DES-EDE3', 'ECB')
key = 'a' * cipher_type.keyLength()
iv = '\0' * cipher_type.ivLength()
text = 'Hello, there!'
def do_encrypt(cipher_type, key, iv, plain_text):
enc = EncryptCipher(cipher_type, key, iv)
cipher_text = enc.finish(plain_text)
return cipher_text
def do_decrypt(cipher_type, key, iv, cipher_text):
dec = DecryptCipher(cipher_type, key, iv)
plain_text = dec.finish(cipher_text)
return plain_text
encrypted_text = do_encrypt(cipher_type, key, iv, text)
decrypted_text = do_decrypt(cipher_type, key, iv, encrypted_text)
assert text == decrypted_text
# -*- Encoding: utf-8 -*-
from Crypto.Cipher import DES3
BS = DES3.block_size
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-ord(s[-1])]
key = 'a' * 16
text = 'Hello, there!'
cipher = DES3.new(key, DES3.MODE_ECB)
encrypted_text = cipher.encrypt(pad(text))
decrypted_text = unpad(cipher.decrypt(encrypted_text))
assert text == decrypted_text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment