def _do_tdes_test(self, file_name): test_vectors = load_tests(("Crypto", "SelfTest", "Cipher", "test_vectors", "TDES"), file_name, "TDES CBC KAT", { "count" : lambda x: int(x) } ) assert(test_vectors) direction = None for tv in test_vectors: # The test vector file contains some directive lines if isinstance(tv, str): direction = tv continue self.description = tv.desc if hasattr(tv, "keys"): cipher = DES.new(tv.keys, self.des_mode, tv.iv) else: if tv.key1 != tv.key3: key = tv.key1 + tv.key2 + tv.key3 # Option 3 else: key = tv.key1 + tv.key2 # Option 2 cipher = DES3.new(key, self.des3_mode, tv.iv) if direction == "[ENCRYPT]": self.assertEqual(cipher.encrypt(tv.plaintext), tv.ciphertext) elif direction == "[DECRYPT]": self.assertEqual(cipher.decrypt(tv.ciphertext), tv.plaintext) else: assert False
def my_des(msg, key): """ DES 算法加密 :param msg: 需加密的字符串,长度必须为8的倍数,不足添加'=' :param key: 8个字符 :return: 加密后的字符 """ de = DES.new(key, DES.MODE_ECB) mss = msg + (8 - (len(msg) % 8)) * '=' text = de.encrypt(mss.encode()) return binascii.b2a_hex(text).decode()
def runTest(self): from crypto.Cipher import DES from binascii import b2a_hex X = [] X[0:] = [b('\x94\x74\xB8\xE8\xC7\x3B\xCA\x7D')] for i in range(16): c = DES.new(X[i], DES.MODE_ECB) if not (i & 1): # (num&1) returns 1 for odd numbers X[i + 1:] = [c.encrypt(X[i])] # even else: X[i + 1:] = [c.decrypt(X[i])] # odd self.assertEqual(b2a_hex(X[16]), b2a_hex(b('\x1B\x1A\x2D\xDB\x4C\x64\x24\x38')))
def decode(pem_data, passphrase=None): """Decode a PEM block into binary. Args: pem_data (string): The PEM block. passphrase (byte string): If given and the PEM block is encrypted, the key will be derived from the passphrase. Returns: A tuple with the binary data, the marker string, and a boolean to indicate if decryption was performed. Raises: ValueError: if decoding fails, if the PEM file is encrypted and no passphrase has been provided or if the passphrase is incorrect. """ # Verify Pre-Encapsulation Boundary r = re.compile("\s*-----BEGIN (.*)-----\s+") m = r.match(pem_data) if not m: raise ValueError("Not a valid PEM pre boundary") marker = m.group(1) # Verify Post-Encapsulation Boundary r = re.compile("-----END (.*)-----\s*$") m = r.search(pem_data) if not m or m.group(1) != marker: raise ValueError("Not a valid PEM post boundary") # Removes spaces and slit on lines lines = pem_data.replace(" ", '').split() # Decrypts, if necessary if lines[1].startswith('Proc-Type:4,ENCRYPTED'): if not passphrase: raise ValueError("PEM is encrypted, but no passphrase available") DEK = lines[2].split(':') if len(DEK) != 2 or DEK[0] != 'DEK-Info': raise ValueError("PEM encryption format not supported.") algo, salt = DEK[1].split(',') salt = unhexlify(tobytes(salt)) if algo == "DES-CBC": # This is EVP_BytesToKey in OpenSSL key = PBKDF1(passphrase, salt, 8, 1, MD5) objdec = DES.new(key, DES.MODE_CBC, salt) elif algo == "DES-EDE3-CBC": # Note that EVP_BytesToKey is note exactly the same as PBKDF1 key = PBKDF1(passphrase, salt, 16, 1, MD5) key += PBKDF1(key + passphrase, salt, 8, 1, MD5) objdec = DES3.new(key, DES3.MODE_CBC, salt) elif algo == "AES-128-CBC": key = PBKDF1(passphrase, salt[:8], 16, 1, MD5) objdec = AES.new(key, AES.MODE_CBC, salt) else: raise ValueError("Unsupport PEM encryption algorithm (%s)." % algo) lines = lines[2:] else: objdec = None # Decode body data = a2b_base64(b(''.join(lines[1:-1]))) enc_flag = False if objdec: data = unpad(objdec.decrypt(data), objdec.block_size) enc_flag = True return (data, marker, enc_flag)
import pycrypto from crypto.Cipher import DES from Crypto import Random des1 = DES.new('01234567', DES.MODE_ECB) des2 = DES.new('01234567', DES.MODE_ECB) text = 'abcdefghijklmnop' cipher_text = des1.encrypt(text) print(cipher_text) des2.decrypt(cipher_text) print(cipher_text)