def __init__( self, cipher_mode=None, initialization_vector=None, key=None, **kwargs): """Initializes a decrypter. Args: cipher_mode (Optional[str]): cipher mode. initialization_vector (Optional[bytes]): initialization vector. key (Optional[bytes]): key. kwargs (dict): keyword arguments depending on the decrypter. Raises: ValueError: when key is not set, block cipher mode is not supported, or initialization_vector is required and not set. """ if not key: raise ValueError('Missing key.') cipher_mode = self.ENCRYPTION_MODES.get(cipher_mode, None) if cipher_mode is None: raise ValueError('Unsupported cipher mode: {0!s}'.format(cipher_mode)) if cipher_mode != DES3.MODE_ECB and not initialization_vector: # Pycrypto does not create a meaningful error when initialization vector # is missing. Therefore, we report it ourselves. raise ValueError('Missing initialization vector.') super(DES3Decrypter, self).__init__() if cipher_mode == DES3.MODE_ECB: self._des3_cipher = DES3.new(key, mode=cipher_mode) else: self._des3_cipher = DES3.new( key, IV=initialization_vector, mode=cipher_mode)
def encrypt_DES3(msg, secret): # pending msg to be a multiple of 8 in length toAdd = 8 - len(msg) % 8 msg += "\0" * toAdd encrypt_msg = base64.encodestring(DES3.new(secret[:24], DES3.MODE_CBC, secret[24:]).encrypt(msg)) # remove extra trailing newline return encrypt_msg[:-1]
def test_des3(self): # The following test vectors have been generated with gpg v1.4.0. # The command line used was: # gpg -c -z 0 --cipher-algo 3DES --passphrase secret_passphrase \ # --disable-mdc --s2k-mode 0 --output ct pt # For an explanation, see test_AES.py . plaintext = 'ac1762037074324fb53ba3596f73656d69746556616c6c6579' ciphertext = '9979238528357b90e2e0be549cb0b2d5999b9a4a447e5c5c7d' key = '7ade65b460f5ea9be35f9e14aa883a2048e3824aa616c0b2' iv='cd47e2afb8b7e4b0' encrypted_iv='6a7eef0b58050e8b904a' plaintext = unhexlify(plaintext) ciphertext = unhexlify(ciphertext) key = unhexlify(key) iv = unhexlify(iv) encrypted_iv = unhexlify(encrypted_iv) cipher = DES3.new(key, DES3.MODE_OPENPGP, iv) ct = cipher.encrypt(plaintext) self.assertEqual(ct[:10], encrypted_iv) self.assertEqual(ct[10:], ciphertext) cipher = DES3.new(key, DES3.MODE_OPENPGP, encrypted_iv) pt = cipher.decrypt(ciphertext) self.assertEqual(pt, plaintext)
def test_unaligned_data_64(self): plaintexts = [ b"7777777" ] * 100 cipher = DES3.new(self.key_192, DES3.MODE_OPENPGP, self.iv_64) ciphertexts = [ cipher.encrypt(x) for x in plaintexts ] cipher = DES3.new(self.key_192, DES3.MODE_OPENPGP, self.iv_64) self.assertEqual(b"".join(ciphertexts), cipher.encrypt(b"".join(plaintexts)))
def __init__(self, passPhrase): key = PBKDF2( bytes(passPhrase), bytes(EncryptDecrypt.SALT), iterations=EncryptDecrypt.ITERACTIONCOUNT ).read(EncryptDecrypt.KEY_LENGTH) iv = '\0\0\0\0\0\0\0\0' self.block_size = 8 if PYCRYPTO: self.enc = DES3.new(key, DES3.MODE_CBC, iv) self.dec = DES3.new(key, DES3.MODE_CBC, iv) else: self.enc = py_des.triple_des( key, py_des.CBC, iv, padmode=py_des.PAD_PKCS5 ) self.dec = py_des.triple_des( key, py_des.CBC, iv, padmode=py_des.PAD_PKCS5 )
def intermediate_hops(self, packet, chain): # packet must be an object with a dbody scalar. assert hasattr(packet, "dbody") assert hasattr(packet, "headers") assert hasattr(packet, "nextaddy") # When compiling intermediate headers, there must already be one, and # only one header; the exit header. assert len(packet.headers) == 1 while len(chain) > 0: numheads = len(packet.headers) thishop = chain.pop() rem_data = self.nodedata(name=thishop) # This uses the rem_data dict to pass the next hop address # to the pktinfo section of Intermediate messages. rem_data['nextaddy'] = packet.nextaddy outer = OuterHeader(rem_data, 0) header = outer.make_header() for h in range(numheads): desobj = DES3.new(outer.inner.des3key, DES3.MODE_CBC, IV=outer.inner.pktinfo.ivs[h]) packet.headers[h] = desobj.encrypt(packet.headers[h]) # All the headers are sorted, now we need to encrypt the payload # with the same IV as the final header. desobj = DES3.new(outer.inner.des3key, DES3.MODE_CBC, IV=outer.inner.pktinfo.ivs[18]) packet.dbody = desobj.encrypt(packet.dbody) assert len(packet.dbody) == 10240 packet.headers.insert(0, header) packet.nextaddy = rem_data['email'] pad = Crypto.Random.get_random_bytes((20 - len(packet.headers)) * 512) packet.payload = ''.join(packet.headers) + pad + packet.dbody assert len(packet.payload) == 20480
def generate_combined_key(key1, key2, check1, check2): component_1 = binascii.unhexlify(key1) component_1_check = binascii.unhexlify(check1) component_2 = binascii.unhexlify(key2) component_2_check = binascii.unhexlify(check2) cipher = DES3.new(component_1) check_value = cipher.encrypt(str(bytearray([0] * 8)))[:3] if component_1_check != check_value: raise ValueError("Component 1 check doesn't match") print("Component 1 check: %s" % binascii.hexlify(check_value)) cipher = DES3.new(component_2) check_value = cipher.encrypt(str(bytearray([0] * 8)))[:3] if component_2_check != check_value: raise ValueError("Component 2 check doesn't match") print("Component 2 check: %s" % binascii.hexlify(check_value)) key = xor_bytes(component_1, component_2) cipher = DES3.new(str(key)) check_value = cipher.encrypt(str(bytearray([0] * 8)))[:3] print("Combined check: %s" % binascii.hexlify(check_value)) print("Combined key: %s" % binascii.hexlify(key)) block = "04536ceffb6abac9".decode("hex") my_str = "9BDAD0048C26FE262A4F73292975088F" BT = my_str.decode("hex") print (BT) cipher1 = DES3.new(BT, DES3.MODE_ECB) crt = cipher1.encrypt(block) print ("EL RESULTADO DE 3DES ES: {}".format(crt.encode("hex"))) pin = 1234 pan = "44444412345678"
def __init__(self, key=None, mode=None, initialization_vector=None, **kwargs): """Initializes the decrypter object. Args: key: optional binary string containing the key. mode: optional mode of operation. initialization_vector: optional initialization vector. kwargs: a dictionary of keyword arguments depending on the decrypter. Raises: ValueError: when key is not set, block cipher mode is not supported, or initialization_vector is required and not set. """ if not key: raise ValueError(u'Missing key.') if mode not in self.ENCRYPTION_MODES: raise ValueError(u'Unsupported mode of operation: {0!s}'.format(mode)) mode = self.ENCRYPTION_MODES[mode] if mode != DES3.MODE_ECB and not initialization_vector: # Pycrypto does not create a meaningful error when initialization vector # is missing. Therefore, we report it ourselves. raise ValueError(u'Missing initialization vector.') super(DES3Decrypter, self).__init__() if mode == DES3.MODE_ECB: self._des3_cipher = DES3.new(key, mode=mode) else: self._des3_cipher = DES3.new(key, mode=mode, IV=initialization_vector)
def test_unaligned_data_64(self): cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64) for wrong_length in range(1,8): self.assertRaises(ValueError, cipher.encrypt, b("5") * wrong_length) cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64) for wrong_length in range(1,8): self.assertRaises(ValueError, cipher.decrypt, b("5") * wrong_length)
def test_loopback_64(self): cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64) pt = get_tag_random("plaintext", 8 * 100) ct = cipher.encrypt(pt) cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64) pt2 = cipher.decrypt(ct) self.assertEqual(pt, pt2)
def test_loopback_64(self): cipher = DES3.new(self.key_192, DES3.MODE_EAX, nonce=self.nonce_96) pt = get_tag_random("plaintext", 8 * 100) ct = cipher.encrypt(pt) cipher = DES3.new(self.key_192, DES3.MODE_EAX, nonce=self.nonce_96) pt2 = cipher.decrypt(ct) self.assertEqual(pt, pt2)
def test_loopback_64(self): cipher = DES3.new(self.key_192, DES3.MODE_CTR, counter=self.ctr_64) pt = get_tag_random("plaintext", 8 * 100) ct = cipher.encrypt(pt) cipher = DES3.new(self.key_192, DES3.MODE_CTR, counter=self.ctr_64) pt2 = cipher.decrypt(ct) self.assertEqual(pt, pt2)
def test_loopback_64(self): cipher = DES3.new(self.key_192, DES3.MODE_OPENPGP, self.iv_64) pt = get_tag_random("plaintext", 8 * 100) ct = cipher.encrypt(pt) eiv, ct = ct[:10], ct[10:] cipher = DES3.new(self.key_192, DES3.MODE_OPENPGP, eiv) pt2 = cipher.decrypt(ct) self.assertEqual(pt, pt2)
def test_unaligned_data_64(self): plaintexts = [ b"7777777" ] * 100 cipher = DES3.new(self.key_192, AES.MODE_CTR, counter=self.ctr_64) ciphertexts = [ cipher.encrypt(x) for x in plaintexts ] cipher = DES3.new(self.key_192, AES.MODE_CTR, counter=self.ctr_64) self.assertEqual(b"".join(ciphertexts), cipher.encrypt(b"".join(plaintexts))) cipher = DES3.new(self.key_192, AES.MODE_CTR, counter=self.ctr_64) ciphertexts = [ cipher.encrypt(x) for x in plaintexts ] cipher = DES3.new(self.key_192, AES.MODE_CTR, counter=self.ctr_64) self.assertEqual(b"".join(ciphertexts), cipher.encrypt(b"".join(plaintexts)))
def test_unaligned_data_64(self): plaintexts = [ b("7777777") ] * 100 cipher = DES3.new(self.key_192, DES3.MODE_CFB, self.iv_64, segment_size=8) ciphertexts = [ cipher.encrypt(x) for x in plaintexts ] cipher = DES3.new(self.key_192, DES3.MODE_CFB, self.iv_64, segment_size=8) self.assertEqual(b("").join(ciphertexts), cipher.encrypt(b("").join(plaintexts))) cipher = DES3.new(self.key_192, DES3.MODE_CFB, self.iv_64, segment_size=64) ciphertexts = [ cipher.encrypt(x) for x in plaintexts ] cipher = DES3.new(self.key_192, DES3.MODE_CFB, self.iv_64, segment_size=64) self.assertEqual(b("").join(ciphertexts), cipher.encrypt(b("").join(plaintexts)))
def decodewithscience(private_key_line,saved_key_line): ## grab the password and the secret key and truncate them on the first = ## private_key = private_key_line.split('=',1) saved_key = saved_key_line.split('=',1) ## base 64 decode the private key and the saved password key decoded_private_key = base64.decodestring(str(private_key[1])) decoded_saved_key = base64.decodestring(str(saved_key[1:])) ## do some magic and decode and print out the decoded password \o/ print "Saved password: " print DES3.new(decoded_private_key[:24],DES3.MODE_CBC,decoded_private_key[24:]).decrypt(decoded_saved_key)
def unwrap(ciphertext, key): """Unwrap a key (typically Triple DES key ) with another Triple DES key. This uses the algorithm from RFC 3217 to decrypt the ciphertext (the previously wrapped key) using the provided key.""" if len(ciphertext) % DES3.block_size != 0: raise DecryptionError("Ciphertext length wrong") cipher = DES3.new(key, DES3.MODE_CBC, RFC3217_IV) tmp = cipher.decrypt(ciphertext)[::-1] cipher = DES3.new(key, DES3.MODE_CBC, tmp[:8]) tmp = cipher.decrypt(tmp[8:]) if tmp[-8:] == _cms_hash(tmp[:-8]): return tmp[:-8] raise DecryptionError("CMS key checksum error")
def wrap(plaintext, key, iv=None): """Wrap one key (typically a Triple DES key) with another Triple DES key. This uses the algorithm from RFC 3217 to encrypt the plaintext (the key to wrap) using the provided key. If the iv is None, it is randomly generated.""" if len(plaintext) % DES3.block_size != 0: raise EncryptionError("Plaintext length wrong") if iv is None: iv = Random.get_random_bytes(8) cipher = DES3.new(key, DES3.MODE_CBC, iv) tmp = iv + cipher.encrypt(plaintext + _cms_hash(plaintext)) cipher = DES3.new(key, DES3.MODE_CBC, RFC3217_IV) return cipher.encrypt(tmp[::-1])
def mbi_crypt(self, nonce): WINCRYPT_CRYPT_MODE_CBC = 1 WINCRYPT_CALC_3DES = 0x6603 WINCRYPT_CALC_SHA1 = 0x8004 # Read key and generate two derived keys key1 = base64.b64decode(self.proof_token) key2 = self._derive_key(key1, "WS-SecureConversationSESSION KEY HASH") key3 = self._derive_key(key1, "WS-SecureConversationSESSION KEY ENCRYPTION") # Create a HMAC-SHA-1 hash of nonce using key2 hash = HMAC.new(key2, nonce, SHA).digest() # # Encrypt nonce with DES3 using key3 # # IV (Initialization Vector): 8 bytes of random data iv = randpool.RandomPool().get_bytes(8) obj = DES3.new(key3, DES3.MODE_CBC, iv) # XXX: win32's Crypt API seems to pad the input with 0x08 bytes # to align on 72/36/18/9 boundary ciph = obj.encrypt(nonce + "\x08\x08\x08\x08\x08\x08\x08\x08") blob = struct.pack("<LLLLLLL", 28, WINCRYPT_CRYPT_MODE_CBC, WINCRYPT_CALC_3DES, WINCRYPT_CALC_SHA1, len(iv), len(hash), len(ciph)) blob += iv + hash + ciph return base64.b64encode(blob)
def makePrivateKeyString_openssh(obj, passphrase): keyType = objectType(obj) if keyType == 'ssh-rsa': keyData = '-----BEGIN RSA PRIVATE KEY-----\n' p,q=obj.p,obj.q if p > q: (p,q) = (q,p) # p is less than q objData = [0, obj.n, obj.e, obj.d, q, p, obj.d%(q-1), obj.d%(p-1),Util.number.inverse(p, q)] elif keyType == 'ssh-dss': keyData = '-----BEGIN DSA PRIVATE KEY-----\n' objData = [0, obj.p, obj.q, obj.g, obj.y, obj.x] else: raise BadKeyError('unknown key type %s' % keyType) if passphrase: iv = common.entropy.get_bytes(8) hexiv = ''.join(['%02X' % ord(x) for x in iv]) keyData += 'Proc-Type: 4,ENCRYPTED\n' keyData += 'DEK-Info: DES-EDE3-CBC,%s\n\n' % hexiv ba = md5.new(passphrase + iv).digest() bb = md5.new(ba + passphrase + iv).digest() encKey = (ba + bb)[:24] asn1Data = asn1.pack([objData]) if passphrase: padLen = 8 - (len(asn1Data) % 8) asn1Data += (chr(padLen) * padLen) asn1Data = DES3.new(encKey, DES3.MODE_CBC, iv).encrypt(asn1Data) b64Data = base64.encodestring(asn1Data).replace('\n','') b64Data = '\n'.join([b64Data[i:i+64] for i in range(0,len(b64Data),64)]) keyData += b64Data + '\n' if keyType == 'ssh-rsa': keyData += '-----END RSA PRIVATE KEY-----' elif keyType == 'ssh-dss': keyData += '-----END DSA PRIVATE KEY-----' return keyData
def __init__(self, key=None, mode=None, initialization_vector=None, **kwargs): """Initializes the decrypter object. Args: key: optional binary string containing the key. mode: optional mode of operation. initialization_vector: optional initialization vector. (defaults to 0) kwargs: a dictionary of keyword arguments depending on the decrypter. Raises: ValueError: when key is not set or, the key or initialization vector size is not supported. """ if not key: raise ValueError(u'Missing key.') if len(key) not in DES3.key_size: raise ValueError(u'Unsupported key size.') if initialization_vector is not None: if len(initialization_vector) != DES3.block_size: raise ValueError(u'Unsupported initialization vector size.') else: initialization_vector = 0 if not mode: raise ValueError(u'Missing mode of operation.') if mode not in self.ENCRYPTION_MODES: raise ValueError(u'Unsupported mode of operation: {0:s}'.format(mode)) mode = self.ENCRYPTION_MODES[mode] super(DES3Decrypter, self).__init__() self._des3_cipher = DES3.new(key, mode=mode, IV=initialization_vector)
def des3_div(key, UID, Sector_number, MIFkey): """""" from Crypto.Cipher import DES3 trailerblock = 4*int(Sector_number)+3 ##van sector naar trailerblock van sector trailerblock = "{:02x}".format(trailerblock) M = MIFkey[:8] M += xor( MIFkey[8:10].decode( "hex" ),UID[:2].decode( "hex" )) M += xor( MIFkey[10:].decode( "hex" ),UID[2:4].decode( "hex" ) ) M += xor( trailerblock.decode( "hex" ), UID[4:6].decode( "hex" ) ) M += UID[6:] cipher = DES3.new( key.decode( "hex" ) ) divkey=cipher.encrypt( M.decode( "hex" ) ).encode( "hex" )[2:14] print "3DES version" print "Masterkey:\t " + key.upper() print "UID:\t\t " + UID.upper() print "Sector:\t\t " + Sector_number.upper() print "Trailer Block:\t " + trailerblock print "Mifare key:\t " + MIFkey.upper() print "Message:\t " + M.upper() print "Diversified key: " + divkey.upper() print return divkey
def EncryDES3(src): #DES3加密 objstr=PKCS5Pading(src) obj = DES3.new(KEY,DES3.MODE_CBC,IV) #return obj.encrypt(objstr) s1=obj.encrypt(objstr) return base64.b64encode(s1)
def packet_decrypt(self, packet): """Unpack a received Mixmaster email message header. The spec calls for 512 Bytes, of which the last 31 are padding. Public key ID [ 16 bytes] Length of RSA-encrypted data [ 1 byte ] RSA-encrypted session key [ 128 bytes] Initialization vector [ 8 bytes] Encrypted header part [ 328 bytes] Padding [ 31 bytes] """ # Unpack the header components. This includes the 328 Byte # encrypted component. (keyid, datalen, sesskey, iv, enc, pad) = struct.unpack('@16sB128s8s328s31s', packet.encheads[0]) if not len(sesskey) == datalen: raise ValidationError("Incorrect session key size") keyid = keyid.encode("hex") log.debug("Message is encrypted to key: %s", keyid) # Use the session key to decrypt the 3DES Symmetric key seckey = self.secring[keyid] if seckey is None: raise ValidationError("Secret Key not found") pkcs1 = PKCS1_v1_5.new(seckey) deskey = pkcs1.decrypt(sesskey, "Failed") # Process the 328 Bytes of encrypted header using our newly discovered # 3DES key obtained from the pkcs1 decryption. desobj = DES3.new(deskey, DES3.MODE_CBC, IV=iv) packet.set_dhead(desobj.decrypt(enc))
def __init__(self, data, ignoreDigestErrors=False): data = data[:512] self.PublicKeyId = hexpad(bigEndian(binaryToByteArray(data[0:16])), 32) self.DataLength = struct.unpack('B', data[16])[0] if self.DataLength != 128: raise Exception("Got an unexpected Data Length from the MixHeader:", self.DataLength) self.TDESKey = data[17:145] self.IV = data[145:153] self.EncHeader = data[153:481] self.Padding = data[481:512] self.TDESKey_Decrypted = 0 ks = getKeyStore() privKey = ks.getPrivateKey(self.PublicKeyId) if not privKey: raise Exception("Could not decrypt MixHeader, Private Key for " + self.PublicKeyId + " not found in keystore: " + str(ks.listPrivateKeys())) rsa = PKCS1_v1_5.new(privKey.getPCPrivateKey()) self.TDESKey_Decrypted = rsa.decrypt(self.TDESKey, "This is most certainly not the key") if self.TDESKey_Decrypted == "This is most certainly not the key": raise Exception("Could not decrypt MixHeader Encrypted Header") des = DES3.new(self.TDESKey_Decrypted, DES3.MODE_CBC, IV=self.IV) self.EncHeader_Decrypted = des.decrypt(self.EncHeader) self.DecryptedHeader = EncryptedMixHeader(self.EncHeader_Decrypted, ignoreDigestErrors)
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 __init__(self, data, decryptionkey=None, decryptioniv=None): data = data[:512] des = DES3.new(decryptionkey, DES3.MODE_CBC, IV=decryptioniv) self.DecryptedData = des.decrypt(data) self.EncryptedToPublicKey = hexpad(bigEndian(binaryToByteArray(self.DecryptedData[0:16])), 32)
def init_crypto_nt6(self): self.iv = self.get_constant_object( 'InitializationVector', 'String', length=16, term=None).v() aes_handle = self.get_constant_object( 'hAesKey', target='Pointer', target_args=dict(target='_KIWI_BCRYPT_HANDLE_KEY')) self.aes_key = aes_handle.key.hardkey.data.v() des_handle = self.get_constant_object( 'h3DesKey', target='Pointer', target_args=dict(target='_KIWI_BCRYPT_HANDLE_KEY')) self.des_key = des_handle.key.hardkey.data.v() try: cipher = AES.new(self.aes_key, AES.MODE_CFB, self.iv) cipher = DES3.new(self.des_key, DES3.MODE_CBC, self.iv[:8]) cipher = None decryption_enabled = True except ValueError as e_ve: decryption_enabled = False logging.warning('init_crypto_nt6 exception {}'.format(e_ve)) finally: return decryption_enabled
def DES3_celler(message, key, *args, **kwargs): """3 DES test celler """ from Crypto.Cipher import DES3 from Crypto import Random bsize = DES3.block_size ksize = DES3.key_size if debug: print ( "Cipher: 3DES\n" + "Block Size: {0}\n" "Key Size: {1}\n" "Mode: {2}\n" ).format(bsize, ksize, 'ECB') iv = Random.new().read(bsize) des = DES3.new(key, DES3.MODE_ECB, iv) # pad the message _message = PKCS7.pad(message, bsize) cipher = des.encrypt(_message) out = kwargs.pop('out', '') if out: save_encrypt(cipher, out) message_ = des.decrypt(cipher) # depad the message message_ = message_[:-bsize] + PKCS7.depad(message_[-bsize:], bsize) return message == message_
def pcf_decrypt(hex_str): bin_str = bytearray(unhexlify(hex_str)) ht = bin_str[0:20] enc = bytes(bin_str[40:]) iv = bin_str ht[19] += 1 hash = sha1() hash.update(bytes(ht)) h2 = hash.digest() ht[19] += 2 hash = sha1() hash.update(bytes(ht)) h3 = hash.digest() key = h2 + h3[0:4] h3des = DES3.new(key, DES3.MODE_CBC, bytes(iv[0:8])) cleartext = h3des.decrypt(enc).decode('utf-8-sig') # TODO: Fix padding. quickfix = "" for c in cleartext: if ord(c) >= 31: quickfix += c print("[*] Result: %s" % quickfix)
def enc(self, filename): encfilename = filename + '.enc' header, filler = self.makeEncInfo(filename) des3 = DES3.new(self.key, DES3.MODE_CBC, self.iv) h = open(filename, 'rb') hh = open(encfilename, 'wb+') enc = header.encode('utf-8') content = h.read(KSIZE) content = enc + content while content: if len(content) < KSIZE: content += filler.encode('utf-8') enc = des3.encrypt(content) hh.write(enc) content = h.read(KSIZE) h.close() hh.close()
def _authentication(self, rnd_icc, kenc, kmac): """ @note: Code fragment from the pyPassport.doc9303.bac.BAC class """ rnd_ifd = os.urandom(8) kifd = os.urandom(16) s = rnd_ifd + rnd_icc + kifd tdes= DES3.new(kenc,DES.MODE_CBC, b'\x00\x00\x00\x00\x00\x00\x00\x00') eifd= tdes.encrypt(s) mifd = mac(kmac, pad(eifd)) cmd_data = eifd + mifd return cmd_data
def dec(self, encfilename): des3 = DES3.new(self.key, DES3.MODE_CBC, self.iv) h = open(encfilename + '.dec', 'wb+') hh = open(encfilename, 'rb') content = hh.read(8) dec = des3.decrypt(content) header = dec.decode() fillersize = int(header.split('#')[0]) content = hh.read(SIZE) while content: dec = des3.decrypt(content) if len(dec) < SIZE: if fillersize != 0: dec = dec[:-fillersize] h.write(dec) content = hh.read(SIZE) h.close() hh.close()
def dec_des3(secret, cipher_file): if len(secret) > 16: return "Error: Secret length should be less than 16 char" if len(secret) < 16: secret += ' ' * (16 - len(secret)) cipher_text = open(cipher_file, 'r').read() iv = 'aaaaaaaa' key = DES3.new(secret, DES3.MODE_OFB, iv) plain_text = key.decrypt(cipher_text) plain_text = plain_text.rstrip() + '\n' plain_file = open('plain.txt', 'w') plain_file.write(str(plain_text)) plain_file.close() return "Plaintext file 'plain.txt' is successfully created"
def en_DES(st, k, mode=0): key = bytes(k, 'utf-8') #key = b'Sixteen byte key' iv = Random.new().read(DES3.block_size) cipher = DES3.new(key, DES3.MODE_OFB, iv) if mode == 0: ciphertext = iv + cipher.encrypt(bytes(st, 'utf-8')) Ct = [] for element in ciphertext: hx = str(hex(element)) hnum = hx[2:] if (len(hnum) < 2): hnum = '0' + hnum Ct.append(hnum) return ''.join(Ct) else: ciphertext = iv + cipher.encrypt(st) return ciphertext
def process_DES3(text): des3 = None length = None while True: key = input("key(must be 16 or 24 bytes): ").encode('utf-8') length = len(key) try: key = DES3.adjust_key_parity(key) des3 = DES3.new(key, DES3.MODE_ECB) break except ValueError: pass target_text = text_padding(text, 8) encrypted = des3.encrypt(target_text) print("encrypted: " + str(encrypted)) decrypted = des3.decrypt(encrypted) decrypted = decrypted.decode('utf-8') print("decrypted: " + decrypted)
def encode(data, marker, passphrase=None, randfunc=None): if randfunc is None: randfunc = get_random_bytes out = '-----BEGIN %s-----\n' % marker if passphrase: salt = randfunc(8) key = PBKDF1(passphrase, salt, 16, 1, MD5) key += PBKDF1(key + passphrase, salt, 8, 1, MD5) objenc = DES3.new(key, DES3.MODE_CBC, salt) out += 'Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,%s\n\n' % tostr( hexlify(salt).upper()) data = objenc.encrypt(pad(data, objenc.block_size)) chunks = [ tostr(b2a_base64(data[i:i + 48])) for i in range(0, len(data), 48) ] out += ''.join(chunks) out += '-----END %s-----' % marker return out
def encrypt(self, plaintext, r=None): if r is None: r = random.randint(1, self.encryptor.n) point = r * self.public_key cipher_key_len = self.cipher_key_len or len(plaintext) #for xor cipher mac_key_len = self.mac_len keys = self.derive_keys(point, cipher_key_len + mac_key_len) cipher_key, mac_key = keys[:cipher_key_len], keys[cipher_key_len:] if self.cipher is DES3: cipher = DES3.new(cipher_key, mode=DES3.MODE_CBC) elif self.cipher is AES: cipher = AES.new(cipher_key, mode=AES.MODE_CBC) elif self.cipher is XOR: cipher = XOR.new(cipher_key) ciphertext = cipher.encrypt(plaintext) cmp_point = sec_encode(r * self.encryptor.G, self.compress_points) mac = hmac.new(mac_key, ciphertext, self.mac_hash).digest() return cmp_point + ciphertext + mac
def cfb_decryption(file: str, key: bytes, iv: bytes) -> list: try: ciphertext = open('3DesEFiles/' + file, "rb") resulttext = open('3DesDFiles/' + file, "wb") # Decryption start = tm.time() cipher = DES3.new(key, DES3.MODE_CFB, iv=iv, segment_size=8) resulttext.write(cipher.decrypt(ciphertext.read())) end = tm.time() ciphertext.close() resulttext.close() return True, end - start except: print("Error at CFB Decryption...") exit(1)
def encrypt_file(file, fileOut): chunk_size = 8192 hex_key = settings.SECRET_KEY[:24].encode() #Create the cipher to decrypt the data des3 = DES3.new(hex_key, DES3.MODE_ECB) with open(file, 'r') as in_file: with open(fileOut, 'wb') as out_file: while True: chunk = in_file.read(chunk_size) if len(chunk) == 0: break elif len(chunk) % 16 != 0: chunk += ' ' * (16 - len(chunk) % 16) chung_bytes = chunk.encode() out_file.write(des3.encrypt(chung_bytes))
def DES3_dec_files(file_name, key, iv): new = DES3.new(key, DES3.MODE_CBC, iv) new_file = input( "write the complete path where you want to save the file with the extension: " ) read_size = 1024 with open(file_name, 'rb') as f1: with open(new_file, 'wb') as f2: while True: data = f1.read(read_size) decode = base64.b64decode(data) if len(data) == 0: break decrypt = new.decrypt(decode) f2.write(decrypt) f2.close() f1.close() print("mission completed successfully\n")
def decrypt(self, encrypted): # TODO: NT version specific, move from here in subclasses. cleartext = '' size = len(encrypted) if size: if size % 8: if not self.aes_key or not self.iv: return cleartext cipher = AES.new(self.aes_key, AES.MODE_CBC, self.iv) else: if not self.des_key or not self.iv: return cleartext #print(binascii.b2a_hex(self.des_key)) #print(len(self.des_key)) cipher = DES3.new(self.des_key, DES3.MODE_CBC, self.iv[:8]) cleartext = cipher.decrypt(encrypted) return cleartext
def calcKCV(keyValue, zAES=False): """Calculate KCV for symmetric key. keyValue - key values as string (DES, 3DES2k, 3DES3k, AES) zAES - True if key is AES (i.e. encrypt block of '01' instead of '00') Return 3B-long string.""" if zAES: assert len(keyValue) in (16, 24, 32), "Wrong length of AES key" block = '\x01' * 16 tkey = AES.new(keyValue, AES.MODE_ECB) else: assert len(keyValue) in (8, 16, 24), "Wrong length of (3)DES key" block = '\x00' * 8 if len(keyValue) == 8: tkey = DES.new(keyValue, DES.MODE_ECB) else: tkey = DES3.new(keyValue, DES.MODE_ECB) return tkey.encrypt(block)[:3]
def encryption_oracle_des(payload): global constant, prefix_len, suffix_len, secret if secret: if constant: payload = random_bytes(prefix_len) + payload + secret else: payload = random_bytes(random.randint(1, 50)) + payload + secret else: if constant: payload = random_bytes(prefix_len) + payload + random_bytes( suffix_len) else: payload = random_bytes(random.randint( 1, 50)) + payload + random_bytes(random.randint(1, 50)) payload = add_padding(payload, DES3.block_size) cipher = DES3.new(key_DES3, DES3.MODE_ECB) return cipher.encrypt(payload)
def sign_parameters(self, secret_key, params64): params_dic = self._url_decode64(params64) if 'Ds_Merchant_Order' in params_dic: order = str(params_dic['Ds_Merchant_Order']) else: order = str( urllib.parse.unquote(params_dic.get('Ds_Order', 'Not found'))) cipher = DES3.new(key=base64.b64decode(secret_key), mode=DES3.MODE_CBC, IV=b'\0\0\0\0\0\0\0\0') diff_block = len(order) % 8 zeros = diff_block and (b'\0' * (8 - diff_block)) or b'' key = cipher.encrypt(str.encode(order + zeros.decode())) if isinstance(params64, str): params64 = params64.encode() dig = hmac.new(key=key, msg=params64, digestmod=hashlib.sha256).digest() return base64.b64encode(dig).decode()
def DES3en(key, in_filename, out_filename=None, chunk_size=24 * 1024): if not out_filename: out_filename = in_filename + '.enc' iv = Random.new().read(DES3.block_size) encryptor = DES3.new(key, DES3.MODE_OFB, iv) filesize = os.path.getsize(in_filename) with open(in_filename, 'rb') as infile: with open(out_filename, 'wb') as outfile: outfile.write(struct.pack('<Q', filesize)) outfile.write(iv) while True: chunk = infile.read(chunk_size) if len(chunk) == 0: break elif len(chunk) % 8 != 0: temp = ' ' * (8 - len(chunk) % 8) chunk += temp.encode('utf-8') outfile.write(encryptor.encrypt(chunk))
def DES3Algorithms(self, data, key, nonce, cryp, prevHash): action = DES3.new(key, mode=DES3.MODE_EAX, nonce=nonce) result = action.encrypt(data) if cryp else action.decrypt(data) # Check if value is same or not Check = True if cryp: sha = SHA1.new() sha.update(data) result = action.nonce + sha.digest() + result else: sha = SHA1.new() sha.update(result) if sha.digest() == prevHash: Check = True else: Check = False # Read key return (result, Check)
def encryptData(self, plainText): """Provides encryption for plaintext content required in request data.""" if(self.debug): print (plainText) md5Key = hashlib.md5(self.apiKey.encode("utf-8")).digest() md5Key = md5Key+md5Key[0:8] blockSize = 8 padDiff = blockSize - len(plainText) % blockSize padding = chr(padDiff)*padDiff cipher = DES3.new(md5Key, DES3.MODE_ECB) plainText += padding encrypted = base64.b64encode(cipher.encrypt(plainText)) return encrypted.decode('utf-8')
def encryptData(self, encryptKey, privParameters, dataToEncrypt): if DES3 is None: raise error.StatusInformation( errorIndication=errind.encryptionError) snmpEngineBoots, snmpEngineTime, salt = privParameters des3Key, salt, iv = self.__getEncryptionKey(encryptKey, snmpEngineBoots) des3Obj = DES3.new(des3Key, DES3.MODE_CBC, iv) privParameters = univ.OctetString(salt) plaintext = dataToEncrypt + univ.OctetString( (0, ) * (8 - len(dataToEncrypt) % 8)).asOctets() ciphertext = des3Obj.encrypt(plaintext) return univ.OctetString(ciphertext), privParameters
def encryptFunc(scheme): global message key = '0123456789abcdef' if scheme == "AES": IV = 16 * '\x00' text2 = '\0' * (16 - len(message) % 16) text = message + text2 encryptor = AES.new(key, AES.MODE_CBC, IV=IV) elif scheme == "DES3": IV = 8 * '\x00' text2 = '\0' * (8 - len(message) % 8) text = message + text2 encryptor = DES3.new(key, DES3.MODE_CBC, IV=IV) elif scheme == "ARC4": IV = 8 * '\x00' text = message encryptor = ARC4.new(key) message = text return encryptor.encrypt
def __init__(self, key=None): super(SimpleCrypt, self).__init__() if callable(key): # Providing a callable is probably more secure than storing the key # directly in your code self.__key = key() else: self.__key = key self._cryptoProvider = None # If the Crypto package is available, use it. self._useDES3 = (self.__key is not None) if self._useDES3: try: from Crypto.Cipher import DES3 except ImportError: self._useDES3 = False if self._useDES3: self.__key = self.__key[:16].rjust(16, "@") self._cryptoProvider = DES3.new(self.__key, DES3.MODE_CBC)
def decrypt(_str, key, iv): result = base64.decodestring(_str) #去空格 result = re.sub('\s+', '', result) #3DES des3 = DES3.new(key, DES3.MODE_CBC, iv) result = des3.encrypt(_str) #去空格 result = result.strip() #去除补位 pad = ord(result[-1]) result = result[:-pad] return result
def encrypt(_str, key, iv): key = base64.decodestring(key) iv = base64.decodestring(iv) des3 = DES3.new(key, DES3.MODE_CBC, iv) #补位 padding = DES3.block_size - (len(_str) % DES3.block_size) _str = _str + padding * chr(padding) # 3DES加密 result = des3.encrypt(_str) # base 64 result = base64.encodestring(result) result = re.sub('\s+', '', result) return result
def decrypt(encoded): key = "3ef136b8b33befbc3426a7b54ec41a377cd3199b00000000".decode('hex') xor_key = [0x12, 0x15, 0x0f, 0x10, 0x11, 0x1c, 0x1a, 0x06, 0x0a, 0x1f, 0x1b, 0x18, 0x17, 0x16, 0x05, 0x19] decoded = base64.b64decode(encoded) xored = "" for i in range(0, len(decoded)): xored += chr(ord(decoded[i]) ^ xor_key[i % len(xor_key)]) cipher = DES3.new(key, DES3.MODE_ECB) decryptedString = cipher.decrypt(xored) password = "" for i in range(0, len(decryptedString)): if decryptedString[i] == '\x00': password = decryptedString[0:i] break return password
def get_secured_apdu(APDU, ICV, sequence_counter): # print('get_secured_apdu start') int_Lc = 0 if len(APDU) > 10: int_Lc = int(APDU[8:10], 16) * 2 + 10 APDU = APDU[:int_Lc] else: APDU = APDU if securitylevel == 0: return APDU, ICV else: # print('APDU before Mod : '+ APDU) APDU = '84' + APDU[2:8] + padding_sw( (len(APDU[10:]) + 16) / 2) + APDU[10:] # print('84', APDU[2:8] , padding_sw((len( APDU[10:])+ 16 )/2) ,APDU[10:]) # print('APDU after Mod : '+ APDU) # print((sequence_counter,default_key,ICV,APDU)) # retail_mac = generate_retail_mac(sequence_counter,default_key,ICV,APDU) retail_mac = generate_apdu_mac(sequence_counter, default_key, ICV, APDU) # print (retail_mac) # print(securitylevel) if securitylevel == 1 or int_Lc == 0: # 若Lc为00,则不加密,仅计算C-MAC后发送 APDU = (APDU + retail_mac).upper() # print('get_secured_apdu end') return APDU, retail_mac else: # 若Lc不为0且securitylevel=3,则发送密文带C-MAC的报文 sk = generate_session_key('0182', sequence_counter, default_key) assert len(sk) == 32 # sk_cbc = sk[0:16] cipher_DES3 = DES3.new(unhexlify(sk), DES.MODE_CBC, unhexlify("0000000000000000")) encrypt_apdu = hexlify( cipher_DES3.encrypt(unhexlify(enc_des_padding(APDU[10:])))) # print(encrypt_apdu.upper()) leng = len(encrypt_apdu + retail_mac) APDU = ('84' + APDU[2:8] + hex(leng / 2)[2:] + encrypt_apdu + retail_mac).upper() # print('get_secured_apdu end') return APDU, retail_mac
def encrypt_3des(plainText): key = 'Sixteen byte key' iv = b'\xf5\x00\xd2+1J\xc5\x19' cipher_encrypt = DES3.new(key, DES3.MODE_OFB, iv) blockSize = 8 padDiff = blockSize - (len(plainText) % blockSize) print('\nPlaintext Before: ' + plainText) plainText = "{}{}".format(plainText, "".join(chr(1) * padDiff)) encrypted_text = cipher_encrypt.encrypt(plainText) encrypted_text2 = base64.b64encode(encrypted_text).decode() print('\nPlaintext After padding: ' + plainText) return encrypted_text2
def decrypt_file(key, in_filename, log_file=None, out_filename=None, chunksize=24 * 1024): log = [] curr_time = ctime() cTime = curr_time.split(' ') date = cTime[3] + "/" + cTime[1] + "/" + cTime[-1] day = cTime[0] clk = cTime[4] log.append(day) log.append(date) log.append(clk) log.append(key) log.append(in_filename) if not out_filename: out_filename = os.path.splitext(in_filename)[0] with open(in_filename, 'rb') as infile: original_size = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0] iv = infile.read(8) decryptor = DES3.new(key, DES3.MODE_OFB, iv) with open(out_filename, 'wb') as outfile: while True: chunk = infile.read(chunksize) if len(chunk) == 0: break outfile.write(decryptor.decrypt(chunk)) outfile.truncate(original_size) outfile.close() log.append(out_filename) #logging with open(log_path, 'a') as logf: writer = csv.writer(logf) writer.writerow(log) logf.close()
def _toString_OPENSSH(self, extra): """ Return a public or private OpenSSH string. See _fromString_PUBLIC_OPENSSH and _fromString_PRIVATE_OPENSSH for the string formats. If extra is present, it represents a comment for a public key, or a passphrase for a private key. @type extra: C{str} @rtype: C{str} """ data = self.data() if self.isPublic(): b64Data = base64.encodestring(self.blob()).replace('\n', '') if not extra: extra = '' return ('%s %s %s' % (self.sshType(), b64Data, extra)).strip() else: lines = ['-----BEGIN %s PRIVATE KEY-----' % self.type()] if self.type() == 'RSA': p, q = data['p'], data['q'] objData = (0, data['n'], data['e'], data['d'], q, p, data['d'] % (q - 1), data['d'] % (p - 1), data['u']) else: objData = (0, data['p'], data['q'], data['g'], data['y'], data['x']) if extra: iv = randbytes.secureRandom(8) hexiv = ''.join(['%02X' % ord(x) for x in iv]) lines.append('Proc-Type: 4,ENCRYPTED') lines.append('DEK-Info: DES-EDE3-CBC,%s\n' % hexiv) ba = md5.new(extra + iv).digest() bb = md5.new(ba + extra + iv).digest() encKey = (ba + bb)[:24] asn1Data = asn1.pack([objData]) if extra: padLen = 8 - (len(asn1Data) % 8) asn1Data += (chr(padLen) * padLen) asn1Data = DES3.new(encKey, DES3.MODE_CBC, iv).encrypt(asn1Data) b64Data = base64.encodestring(asn1Data).replace('\n', '') lines += [b64Data[i:i + 64] for i in range(0, len(b64Data), 64)] lines.append('-----END %s PRIVATE KEY-----' % self.type()) return '\n'.join(lines)
def open_envelope(self): envelope_data = b64decode(get_data(self.envelope_path, 'Envelope data')) crypt_key = self.HexToByte( get_data(self.envelope_path, 'Envelope crypt key')) private_exp = int( int(get_data(self.private_key_path, 'Private exponent'), 16)) public_exp = int( int(get_data(self.public_key_path, 'Public exponent'), 16)) crypt_method = get_mode(get_data(self.envelope_path, 'Crypt Method')) methods = get_methods(self.envelope_path).split(':') modulus = int(int(get_data(self.private_key_path, 'Modulus'), 16)) iv = self.HexToByte( get_data(self.envelope_path, 'Initialization vector')) if methods[1] == 'RSA': RSAEncryptor = RSA.construct((modulus, public_exp, private_exp)) decrypted_key = RSAEncryptor.decrypt((crypt_key, '')) else: generator = int( int(get_data(self.private_key_path, 'Generator'), 16)) k = self.HexToByte( get_data(self.envelope_path, 'Secret number').lower().strip()) ElGamalEncryptor = ElGamal.construct( (modulus, generator, public_exp, private_exp)) decrypted_key = ElGamalEncryptor.decrypt((crypt_key, k)) if (methods[0] == 'AES'): cipher = AES.new(decrypted_key, crypt_method, iv) data = cipher.decrypt(envelope_data) else: cipher = DES3.new(decrypted_key, crypt_method, iv) data = cipher.decrypt(envelope_data) # zapisivanje data-e file = open(self.output_path, 'w') file.write('---BEGIN OS2 CRYPTO DATA---\n') file.write('Description:\n Decrypted Envelope\n\n') file.write('File name:\n ') file.write(self.output_path) file.write('\n\nMethod:\n ' + methods[0] + '\n ' + methods[1] + '\n\n') file.write('Data:\n ') write_to_file(file, data.decode()) file.write('\n\n---END OS2 CRYPTO DATA---')
def decrypt(key, infile, block_zise=4096): #Adjust file name leng = len(infile) x = infile.split('/')[-1] outfile = infile[:leng - len(x)] outfile = outfile + 'decyp_' + x leng = len(outfile) outfile = outfile[:leng - 4] if len(key) < 24: key = key + (24 - len(key)) * 'a' elif len(key) > 24: key = key[:24] count = 0 size_file = 0 with open(infile, 'rb') as fin: fsz = struct.unpack('<Q', fin.read(struct.calcsize('<Q')))[0] hashFile = fin.read(16) if not verifyPassword(hashFile, key): return (False, None, None, None, None) hashFile = fin.read(20) iv = fin.read(8) decipher = DES3.new(key.encode('utf-8'), DES3.MODE_CFB, iv) with open(outfile, 'wb') as fout: while True: data = fin.read(block_zise) n = len(data) if n == 0: break decd = decipher.decrypt(data) n = len(decd) if fsz > n: fout.write(decd) else: fout.write(decd[:fsz]) count += 1 fsz -= n size_file += n verifyFile(infile, outfile) return (True, size_file, block_zise, outfile, count)