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 encrypt_file(in_filename,out_filename, chunk_size, key,iv): des3 = DES3.new (key, DES3.MODE_CFB, iv) chunk = if_file.read(chunk_size) if len (chunk) % 16 != 0;
print " DKeyA: ", newkeyA ### KeyB ### # now do keyB, which is basically the same but starting at byte 2 and prepending new bytes newkeyB = '00' # now create byte 1 from bit 7 of original bytes 0-5, shifted to the correct bit position, which is # the reverse of byte6 in KeyA newkeyBbyte1 = 0x00 for n in range(6): newkeyBbyte1 |= ((int(keyB[n], 16) >> 7 - (n + 1)) & pow(2, n + 1)) newkeyB += "%02X" % newkeyBbyte1 # left shift 1 to create a 0 trailing bit (masked to keep it a single byte) for n in range(6): newkeyB += "%02X" % ((int(keyB[n], 16) << 1) & 0xff) print " DKeyB: ", newkeyB # now create triple-DES key deskeyABA = '' # build key MSB first for n in range(len(newkeyA + newkeyB + newkeyA) - 2, -2, -2): deskeyABA += chr(int((newkeyA + newkeyB + newkeyA)[n:n + 2], 16)) des3 = DES3.new(deskeyABA, DES.MODE_CBC) mifarePWD = des3.encrypt('\0\0\0\0\0\0\0\0') # reverse LSB/MSB for final output mifarePWDout = '' for n in range(len(mifarePWD) - 1, -1, -1): mifarePWDout += "%02X" % int(ord(mifarePWD[n])) print print " MifarePWD: ", mifarePWDout print
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 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, 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_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 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 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, 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_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, 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_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, 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 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 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 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 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 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 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 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 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 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 __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 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, 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__(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 _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 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 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 decrypt_des(enckey, data): cipher = DES3.new(enckey) # set the ciper return cipher.decrypt(data) # decrpyt the data
def encrypt(self, txt, pre, enc, post, pwd, tags=True): # if type(txt) != type('') and type(txt) != type(u''): raise TypeError('Invalid data type for encryption: "%s" !' % str(type(txt))) # # Scramble operation. if not pre or pre == 'N' or pre == 'None': pass elif pre == 'ZLIB' or pre == SCRAMBLE_D['ZLIB']: txt = zlib.compress(txt) elif pre == 'BZ2' or pre == SCRAMBLE_D['BZ2']: txt = bz2.compress(txt) elif pre == 'ROT13' or pre == SCRAMBLE_D['ROT13']: txt = string.translate(txt, ROT) else: raise Exception('Invalid scramble "%s" !' % pre) # # Check RSA key path. if enc in ['RSA', 'RSA'] and not os.path.exists(self.rsa_path): print('RSA encryption must specify a valid path !') self.__error(2, pre, enc, post, field='L') return # pwd = self._fix_password(pwd, enc) # if enc == 'AES' or enc == ENC['AES']: o = AES.new(pwd, mode=3, segment_size=16) elif enc == 'ARC2' or enc == ENC['ARC2']: o = ARC2.new(pwd, mode=3, segment_size=16) elif enc == 'CAST' or enc == ENC['CAST']: o = CAST.new(pwd, mode=3, segment_size=16) elif enc == 'Blowfish' or enc == ENC['Blowfish']: o = Blowfish.new(pwd, mode=3, segment_size=16) elif enc == 'DES3' or enc == ENC['DES3']: o = DES3.new(pwd, mode=3, segment_size=16) elif enc == 'RSA' or enc == ENC['RSA']: # Using Blowfish encryption for RSA. o = Blowfish.new(pwd, Blowfish.MODE_CFB) elif not enc or enc in ['None', ENC['None']]: o = None else: raise Exception('Invalid encryption mode "%s" !' % enc) # # Encryption operation. if o: pad_len = 16 - (len(txt) % 16) padding = (chr(pad_len) * pad_len) txt = o.encrypt(txt + padding) # # Codec operation. if post == 'Base64 Codec' or post == ENCODE_D['Base64 Codec']: if tags: txt = '<#>%s:%s:%s<#>%s' % \ (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post].replace(' Codec',''), ba.b2a_base64(txt).decode()) else: txt = ba.b2a_base64(txt).decode() elif post == 'Base32 Codec' or post == ENCODE_D['Base32 Codec']: if tags: txt = '<#>%s:%s:%s<#>%s' % \ (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post].replace(' Codec',''), base64.b32encode(txt).decode()) else: txt = base64.b32encode(txt).decode() elif post == 'HEX Codec' or post == ENCODE_D['HEX Codec']: if tags: txt = '<#>%s:%s:%s<#>%s' % \ (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post].replace(' Codec',''), ba.b2a_hex(txt).decode()) else: txt = ba.b2a_hex(txt).decode() elif post == 'Quopri Codec' or post == ENCODE_D['Quopri Codec']: if tags: txt = '<#>%s:%s:%s<#>%s' % (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post].replace(' Codec',''), \ ba.b2a_qp(txt, quotetabs=True, header=True).decode()) else: txt = ba.b2a_qp(txt, quotetabs=True, header=True).decode() elif post == 'Json' or post == ENCODE_D['Json']: if tags: # Format : {"pre": "AAA", "enc": "BBB", "post": "CCC", "data": "Blah blah blah"} txt = '{"pre": "%s", "enc": "%s", "post": "%s", "data": "%s"}' % \ (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post], ba.b2a_base64(txt).rstrip().decode()) else: txt = json.dumps( {'data': ba.b2a_base64(txt).rstrip().decode()}) elif post == 'XML': if tags: # Format : <root><pre>AAA</pre> <enc>BBB</enc> <post>CCC</post> <data>Blah blah blah</data></root> txt = '<root>\n<pre>%s</pre><enc>%s</enc><post>%s</post>\n<data>%s</data>\n</root>' % \ (SCRAMBLE_D[pre], ENC[enc], ENCODE_D[post], ba.b2a_base64(txt).rstrip().decode()) else: txt = '<root>\n<data>%s</data>\n</root>' % ba.b2a_base64( txt).rstrip().decode() else: raise Exception('Invalid codec "%s" !' % post) # # The final text must be String, to be used in GUI return txt
# RSA 加密生成 varRSA def rsa_long_encrypt(pub_key_str, msg, length=100): pubobj = rsa.importKey(pub_key_str) pubobj = PKCS1_v1_5.new(pubobj) res = [] for i in range(0, len(msg), length): res.append(pubobj.encrypt(msg[i:i + length])) return "".join(res) enres = rsa_long_encrypt(pub_key_str, key, 200) # 生成RSA varRSA = base64.b64encode(enres) # 将RSA再通过base64加密 # 3DES , 对3DES进行base64处理 varParam = { "passWord": "******", "phoneNumber": "13816109059" } ss = init_str(varParam) des3 = DES3.new(key, DES3.MODE_ECB) res2 = des3.encrypt(ss) var3EDS = base64.b64encode(res2) # 将 RSA 与 3DES 混合 data = varRSA + "|" + var3EDS # 对3DES进行解码 des3 = DES3.new(key, DES3.MODE_ECB) orgResponse = des3.decrypt( base64.b64decode(data)) # 先base64解码,再3DES解码。 解码后原始data
DES_key = keyPriv.decrypt(cipher_text) print('\n\n==> DES key: ') sys.stdout.buffer.write(DES_key) # Reading IV with open('../iv.txt', "rb") as ivFile: iv = ivFile.read() print('\n\n==> Initial Vector: ') sys.stdout.buffer.write(iv) #============ SHA-1 ================================ with open('../cipher.txt', "rb") as cipherFile: hash_value = cipherFile.readline() encrypted_text = cipherFile.read() cipher_decrypt = DES3.new(DES_key, DES3.MODE_CBC, iv) deciphered_text = cipher_decrypt.decrypt(encrypted_text) deciphered_text = deciphered_text.decode("utf-8") print('\n\n==> SHA-1 value: ') sys.stdout.buffer.write(hash_value) #============ SHA-1 ================================ # Authentication sha1_plain_text = sha1(deciphered_text.encode('utf-8')).hexdigest() if sha1_plain_text == hash_value.decode("utf-8").rstrip(): print("\n\n\n#============ Success ================================") print(deciphered_text) deciphered_text.rstrip() with open("message.txt", "w") as outputFile: outputFile.write(deciphered_text)
def test_block_size_64(self): cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64) self.assertEqual(cipher.block_size, DES3.block_size)
def decrypt(string): encrypt = DES3.new(key, DES3.MODE_CBC, IV) decode_string = base64.b64decode(string) plaintext = encrypt.decrypt(decode_string) return unpad(plaintext)
def decrypt(self, key, iv, ciphertext): """ Decrypt ciphered data (user / password) using the key previously found """ data = DES3.new(key, DES3.MODE_CBC, iv).decrypt(ciphertext) return self.remove_padding(data)
default='') parser.add_option("-d", "--dir", type="string", dest="directory", help="directory", default='') (options, args) = parser.parse_args() options.directory = Path(options.directory) key, algo = getKey(options.masterPassword.encode(), options.directory) if key == None: sys.exit() #print(hexlify(key)) logins = getLoginData() if len(logins) == 0: print('no stored passwords') else: print('decrypting login/password pairs') if algo == '1.2.840.113549.1.12.5.1.3' or algo == '1.2.840.113549.1.5.13': for i in logins: assert i[0][0] == CKA_ID print('%20s:' % (i[2]), end='') #site URL iv = i[0][1] ciphertext = i[0][2] print(unpad(DES3.new(key, DES3.MODE_CBC, iv).decrypt(ciphertext), 8), end=',') iv = i[1][1] ciphertext = i[1][2] print(unpad(DES3.new(key, DES3.MODE_CBC, iv).decrypt(ciphertext), 8))
def send_wrapped_apdu_internal(self, data, tar, msl, kic_index, kid_index): # # See ETSI TS 102 225 and ETSI TS 102 226 for more details # about OTA security. # # So far only no signature check, RC or CC are supported. # The only supported ciphering mode is "Triple DES in outer-CBC # mode using two different keys" which is also used for CC. # SPI first octet: set to MSL spi_1 = msl # length of signature if ((spi_1 & 0x03) == 0): # no integrity check len_sig = 0 elif ((spi_1 & 0x03) == 1): # RC len_sig = 4 elif ((spi_1 & 0x03) == 2): # CC len_sig = 8 else: print("Invalid spi_1") exit(0) pad_cnt = 0 # Padding if Ciphering is used if ((spi_1 & 0x04) != 0): # check ciphering bit len_cipher = 6 + len_sig + int(len(data) / 2) pad_cnt = 8 - ( len_cipher % 8 ) # 8 Byte blocksize for DES-CBC (TODO: different padding) # TODO: there is probably a better way to add "pad_cnt" padding bytes for i in range(0, pad_cnt): data = data + '00' # CHL + SPI first octet part_head = ('%02x' % (0x0D + len_sig)) + ('%02x' % (spi_1)) Kic = '00' KID = '00' if ((spi_1 & 0x04) != 0): # check ciphering bit Kic = ( '%02x' % (0x05 + (kic_index << 4)) ) # 05: Triple DES in outer-CBC mode using two different keys if ((spi_1 & 0x03) == 2): # CC KID = ( '%02x' % (0x05 + (kid_index << 4)) ) # 05: Triple DES in outer-CBC mode using two different keys # SPI second octet (01: POR required) + Kic + KID + TAR # TODO: depending on the returned data use ciphering (10) and/or a signature (08) part_head = part_head + '01' + Kic + KID + tar # CNTR + PCNTR (CNTR not used) part_cnt = '0000000000' + ('%02x' % (pad_cnt)) envelopeData = part_head + part_cnt + data # two bytes CPL, CPL is part of RC/CC/DS envelopeData = ('%04x' % int(len(envelopeData) / 2 + len_sig)) + envelopeData if (len_sig == 8): # Padding temp_data = envelopeData len_cipher = int(len(temp_data) / 2) pad_cnt = 8 - ( len_cipher % 8 ) # 8 Byte blocksize for DES-CBC (TODO: add different padding) # TODO: there is probably a better way to add "pad_cnt" padding bytes for i in range(0, pad_cnt): temp_data = temp_data + '00' key = binascii.a2b_hex(args.kid) iv = binascii.a2b_hex('0000000000000000') cipher = DES3.new(key, DES3.MODE_CBC, iv) ciph = cipher.encrypt(binascii.a2b_hex(temp_data)) envelopeData = part_cnt + ciph[len(ciph) - 8:].hex( ) + data ### binascii.b2a_hex().decode('ascii') elif (len_sig == 4): crc32 = binascii.crc32(binascii.a2b_hex(envelopeData)) envelopeData = part_cnt + ('%08x' % (crc32 & 0xFFFFFFFF)) + data elif (len_sig == 0): envelopeData = part_cnt + data else: print("Invalid len_sig") exit(0) # Ciphering (CNTR + PCNTR + RC/CC/DS + data) if ((spi_1 & 0x04) != 0): # check ciphering bit key = binascii.a2b_hex(args.kic) iv = binascii.a2b_hex('0000000000000000') cipher = DES3.new(key, DES3.MODE_CBC, iv) ciph = cipher.encrypt(binascii.a2b_hex(envelopeData)) envelopeData = part_head + ciph.hex( ) ### binascii.b2a_hex(ciph).decode('ascii') else: envelopeData = part_head + envelopeData # ------------------------------------------------------------- # Command (add UDHI: USIM Toolkit Security Header) # TS 23.048 # # 02: UDHDL # 70: IEIA (CPI=70) # 00: IEIDLa # # two bytes CPL # no CHI # envelopeData = '027000' + ('%04x' % int(len(envelopeData) / 2)) + envelopeData # For sending via SMPP, those are the data which can be put into # the "hex" field of the "sendwp" XML file (see examples in libsmpp34). if args.smpp: print("SMPP: " + envelopeData) return ('00', '9000') # SMS-TDPU header: MS-Delivery, no more messages, TP-UD header, no reply path, # TP-OA = TON/NPI 55667788, TP-PID = SIM Download, BS timestamp envelopeData = '400881556677887ff600112912000004' + ( '%02x' % int(len(envelopeData) / 2)) + envelopeData # (82) Device Identities: (83) Network to (81) USIM # (8b) SMS-TPDU envelopeData = '820283818B' + hex_ber_length( envelopeData) + envelopeData # d1 = SMS-PP Download, d2 = Cell Broadcast Download envelopeData = 'd1' + hex_ber_length(envelopeData) + envelopeData (response, sw) = self._tp.send_apdu('a0c20000' + ('%02x' % int(len(envelopeData) / 2)) + envelopeData) if "9e" == sw[0:2]: # more bytes available, get response response = self._tp.send_apdu_checksw('A0C00000' + sw[2:4])[0] # GET RESPONSE # Unwrap response response = response[(int(response[10:12], 16) * 2) + 12:] return (response[6:], response[2:6])
def DES3_decrypt(key, messege): Encrypt_messege = base64.b64decode(messege)[8:] iv = base64.b64decode(messege)[:8] d = DES3.new(key, DES3.MODE_CBC, iv) print("Your Decode Text >>> ", d.decrypt(Encrypt_messege).decode('ascii'))
help="masterPassword", default='') parser.add_option("-d", "--dir", type="string", dest="directory", help="directory", default='') (options, args) = parser.parse_args() key3 = readBsddb(options.directory + 'key3.db') if ord(key3['Version']) == 3: key = extractSecretKey(options.masterPassword) logins = getLoginData() if len(logins) == 0: print 'no stored passwords' else: print 'decrypting login/password pairs' for i in logins: print '%20s:' % i[2], #site URL iv = i[0][1] ciphertext = i[0][2] #login (PKCS#7 padding not removed) print repr(DES3.new(key, DES3.MODE_CBC, iv).decrypt(ciphertext)), ',', iv = i[1][1] ciphertext = i[1][2] #passwd (PKCS#7 padding not removed) print repr(DES3.new(key, DES3.MODE_CBC, iv).decrypt(ciphertext)) else: print 'error key3.db version != 3' sys.exit()
def enc(self, plaintext): plaintext = self.make8string(plaintext) des3 = DES3.new(self.key, DES3.MODE_CBC, self.vec) encmsg = des3.encrypt(plaintext.encode()) return encmsg
print ' Could not select RFID card for APDU processing' host_challenge = card.GetRandom(8) if not card.gp_initialize_update(host_challenge): print 'Can\'t Initialise Update!' card.iso_7816_fail(card.errorcode) card_key_diversification, card_key_info, card_sc_sequence_counter, card_challenge, card_cryptogram = card.gp_initialize_update_response_scp02( card.data) secure_channel_protocol = card_key_info[2:4] if secure_channel_protocol == card.GP_SCP02: # create ENC session key by encrypting derivation data with ENC key session_pad = '000000000000000000000000' derivation_data = '0182' + card_sc_sequence_counter + session_pad # create encryption object with ENC key e_enc = DES3.new(card.ToBinary(enc_key), DES3.MODE_CBC, card.DES_IV) enc_s_key = e_enc.encrypt(card.ToBinary(derivation_data)) # data for cryptograms card_cryptogram_source = host_challenge + card_sc_sequence_counter + card_challenge host_cryptogram_source = card_sc_sequence_counter + card_challenge + host_challenge # check card cryptogram check_cryptogram = string.upper( card.ToHex( card.DES3MAC(card.ToBinary(card_cryptogram_source), enc_s_key, ''))) if not check_cryptogram == card_cryptogram: print 'Key mismatch!' print 'Card Cryptogram: ', card_cryptogram print 'Calculated Cryptogram:', check_cryptogram os._exit(True)
def encrypt(string): pad_len = 8 - len(string) % 8 pad = string + chr(pad_len) * pad_len cipher = DES3.new(key, DES3.MODE_CBC, IV) ctext = cipher.encrypt(pad) return base64.b64encode(ctext)
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(r"\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(r"-----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)
username, mesg = break_message(msg) reply = send_msg(cli_sd, username) if reply == "no user": print("No user with that username") continue ip, port, name = reply.split(':') soc_id = socket.socket() if (soc_id.connect_ex((ip, int(port)))) != 0: continue if "file" in msg.lower(): # print("##send file to the user##") mesg = mesg.split()[1].strip() send_msg(soc_id, "file") key = deffe_Hellman(soc_id, ROLL_NO) cipher = DES3.new(key, DES3.MODE_ECB) send_file(mesg + ":" + USERNAME, soc_id, cipher) # print("done") else: send_msg(soc_id, "msg") key = deffe_Hellman(soc_id, ROLL_NO) mesg = mesg + ":" + USERNAME encrypt_and_send(soc_id, mesg, key) soc_id.close() elif "create" in msg.lower(): if not SIGN_IN: print("you are not signed in. New user=>signup otherwise signin") continue send_msg(cli_sd, "create group")
def test_block_size_64(self): cipher = DES3.new(self.key_192, AES.MODE_EAX, nonce=self.nonce_96) self.assertEqual(cipher.block_size, DES3.block_size)
def run(self, software_name=None): global database_find database_find = False self.manage_advanced_options() if constant.mozilla_software: software_name = constant.mozilla_software specific_path = constant.specific_path # get the installation path path = self.get_path(software_name) if not path: print_debug('WARNING', 'Installation path not found') return # Check if mozilla folder has been found elif not os.path.exists(path): print_debug('INFO', software_name + ' not installed.') return else: if specific_path: if os.path.exists(specific_path): profile_list = [specific_path] else: print_debug( 'WARNING', 'The following file does not exist: %s' % specific_path) return else: profile_list = self.get_firefox_profiles(path) pwdFound = [] for profile in profile_list: print_debug('INFO', 'Profile path found: %s' % profile) if not os.path.exists(profile + os.sep + 'key3.db'): print_debug('WARNING', 'key3 file not found: %s' % self.key3) continue self.key3 = self.readBsddb(profile + os.sep + 'key3.db') if not self.key3: continue # check if passwords are stored on the Json format try: credentials = JsonDatabase(profile) except: database_find = False if not database_find: # check if passwords are stored on the sqlite format try: credentials = SqliteDatabase(profile) except: database_find = False if database_find: masterPassword = '' (globalSalt, masterPassword, entrySalt ) = self.is_masterpassword_correct(masterPassword) # find masterpassword if set if not globalSalt: print_debug('WARNING', 'Master Password is used !') masterPassword = self.found_masterpassword() if not masterPassword: continue # get user secret key key = self.extractSecretKey(globalSalt, masterPassword, entrySalt) if not key: continue # everything is ready to decrypt password for host, user, passw in credentials: values = {} values["URL"] = host # Login loginASN1 = decoder.decode(b64decode(user)) iv = loginASN1[0][1][1].asOctets() ciphertext = loginASN1[0][2].asOctets() login = DES3.new(key, DES3.MODE_CBC, iv).decrypt(ciphertext) # remove bad character at the end try: nb = unpack('B', login[-1])[0] values["Login"] = unicode(login[:-nb]) except: values["Login"] = unicode(login) # Password passwdASN1 = decoder.decode(b64decode(passw)) iv = passwdASN1[0][1][1].asOctets() ciphertext = passwdASN1[0][2].asOctets() password = DES3.new(key, DES3.MODE_CBC, iv).decrypt(ciphertext) # remove bad character at the end try: nb = unpack('B', password[-1])[0] values["Password"] = unicode(password[:-nb]) except: values["Password"] = unicode(password) if len(values): pwdFound.append(values) return pwdFound
def test_parity_option2(self): before_2k = unhexlify("CABF326FA56734324FFCCABCDEFACABF") after_2k = DES3.adjust_key_parity(before_2k) self.assertEqual(after_2k, unhexlify("CBBF326EA46734324FFDCBBCDFFBCBBF"))
# 跟java中DESede通用 # 参考https://www.jianshu.com/p/b6d3ed120383 from Crypto.Cipher import DES3 import base64 text = base64.b64encode(b'1001244624') pad = DES3.block_size - (len(text) % DES3.block_size) print( DES3.new(('x' * 24).encode('utf-8'), DES3.MODE_ECB).encrypt( (text.decode('utf-8') + (chr(pad) * pad)).encode('utf-8')).hex().upper())
def decrypt(self, txt, pre, enc, post, pwd): # if type(txt) != type('') and type(txt) != type(u''): raise TypeError('Invalid data type for decryption: "%s" !' % str(type(txt))) # if not (pre and enc and post): self.guess_pre_enc_post(txt) pre = self.pre enc = self.enc post = self.post if '{' in txt and '}' in txt and '"data":' in txt: temp = json.loads(txt.decode()) txt = temp['data'].encode() del temp elif '<data>' in txt and '</data>' in txt: txt = re.search('<data>(.+)</data>', txt, re.S).group(1) else: txt = re.sub(NO_TAGS, '', txt) else: # If Json. if '{' in txt and '}' in txt and '"data":' in txt: pre = 'Json' temp = json.loads(txt.decode()) txt = temp['data'].encode() del temp # If XML. elif '<data>' in txt and '</data>' in txt: pre = 'XML' txt = re.search('<data>(.+)</data>', txt, re.S).group(1) else: txt = re.sub(NO_TAGS, '', txt) # # Check RSA key path. if enc == 'RSA' and not os.path.exists(self.rsa_path): print('RSA decryption must specify a valid path !') self.__error(2, pre, enc, post) return # # Adapting password for encryption. pwd = self._fix_password(pwd, enc) # # Codec operation. if not pre: self.__error(1, 'None', enc, post) return elif pre == 'Base64 Codec' or pre == ENCODE_D['Base64 Codec']: try: txt = ba.a2b_base64(txt) except: self.__error(1, pre, enc, post) return elif pre == 'Base32 Codec' or pre == ENCODE_D['Base32 Codec']: try: txt = base64.b32decode(txt) except: self.__error(1, pre, enc, post) return elif pre == 'HEX Codec' or pre == ENCODE_D['HEX Codec']: try: txt = ba.a2b_hex(txt) except: self.__error(1, pre, enc, post) return elif pre == 'Quopri Codec' or pre == ENCODE_D['Quopri Codec']: try: txt = ba.a2b_qp(txt, header=True) except: self.__error(1, pre, enc, post) return elif pre == 'Json' or pre == ENCODE_D['Json']: try: txt = ba.a2b_base64(txt) except: self.__error(1, pre, enc, post) return elif pre == 'XML': try: txt = ba.a2b_base64(txt) except: self.__error(1, pre, enc, post) return else: raise Exception('Invalid codec "%s" !' % pre) # if enc == 'AES' or enc == ENC['AES']: o = AES.new(pwd, mode=3, segment_size=16) elif enc == 'ARC2' or enc == ENC['ARC2']: o = ARC2.new(pwd, mode=3, segment_size=16) elif enc == 'CAST' or enc == ENC['CAST']: o = CAST.new(pwd, mode=3, segment_size=16) elif enc == 'Blowfish' or enc == ENC['Blowfish']: o = Blowfish.new(pwd, mode=3, segment_size=16) elif enc == 'DES3' or enc == ENC['DES3']: o = DES3.new(pwd, mode=3, segment_size=16) elif enc == 'RSA' or enc == ENC['RSA']: # Using Blowfish decryption for RSA. o = Blowfish.new(pwd, mode=3, segment_size=16) elif not enc or enc in ['None', ENC['None']]: o = None else: raise Exception('Invalid decrypt "%s" !' % enc) # # Decryption operation. if o: try: temp = o.decrypt(txt) pad_len = ord(temp[-1]) txt = temp[:-pad_len] del temp except: self.__error(2, pre, enc, post) return # # Un-scramble operation. if not post or post == 'N' or post == 'None': pass elif post == 'ZLIB' or post == SCRAMBLE_D['ZLIB']: try: txt = zlib.decompress(txt) except: self.__error(3, pre, enc, post) return elif post == 'BZ2' or post == SCRAMBLE_D['BZ2']: try: txt = bz2.decompress(txt) except: self.__error(3, pre, enc, post) return elif post == 'ROT13' or post == SCRAMBLE_D['ROT13']: txt = string.translate(txt, ROT) else: raise Exception('Invalid scramble "%s" !' % post) # return txt
print 'Generate local random Challenge (rnd_ifd): ' + rnd_ifd print 'Generate local random Challenge (Kifd): ' + Kifd print S= passport.ToBinary(rnd_ifd + rnd_icc + Kifd) if DEBUG or TEST: print 'S: ', passport.HexPrint(S) if DEBUG or TEST: print 'Kenc: ', passport.HexPrint(Kenc) tdes= DES3.new(Kenc,DES.MODE_CBC,passport.DES_IV) Eifd= tdes.encrypt(S) if DEBUG or TEST: print 'Eifd: ', passport.HexPrint(Eifd) print 'Kmac: ', passport.HexPrint(Kmac) Mifd= passport.DESMAC(Eifd,Kmac,'') if DEBUG or TEST: print 'Mifd: ', passport.HexPrint(Mifd) cmd_data= Eifd + Mifd if DEBUG or TEST: print 'cmd_data: ', passport.HexPrint(cmd_data)
) #conn has socket and addr has ip address comming from client key = conn.recv(1024) #Receiving key from client with conn: #----GENERATING IV FOR CBC MODE OF ENCRYPTION------ iv = Random.new().read( DES3.block_size ) #initialize initialization vector(iv) randomly for mode CBC ,i.e., 8 block size #Sending IV to client conn.send(iv) print(addr, " has connected to the server now" ) #print host-name or ip address of client while 1: #Making Encrypting Object cipher_des3 = DES3.new(key, DES3.MODE_CBC, iv) #encrypying object message = input(str("-->")) #input message while len( message ) % 8 != 0: #length of plaintext must be multiple of 8, to make it suitable for CBC mode message += " " message = cipher_des3.encrypt( message.encode('utf-8')) #Encrypt message with 3-des conn.send(message) #sending message to client #Making Decrypting Object decipher_des3 = DES3.new(key, DES3.MODE_CBC, iv) #Decrypting Object inc_msg = conn.recv(1024) #receiving message from client inc_msg = decipher_des3.decrypt(inc_msg) #decryption is done here inc_msg = inc_msg.decode('utf-8') #Bytes to ascii conversion print("Client: ", inc_msg)
def unpad(data): # super naive implementation of PKCS5 return data[:-data[-1]] def pad(data): padlen = 8 - (len(data) % 8) return data + bytes([padlen] * padlen) def usage(): print("USAGE: python3 {} [e]ncrypt/[d]ecrypt <input_file >output_file". format(sys.argv[0])) print(__doc__) exit() if len(sys.argv) != 2: usage() data = sys.stdin.buffer.read() key = generate_bytes(24, KEY_SEED) iv = generate_bytes(8, IV_SEED) des = DES3.new(key, DES3.MODE_CBC, iv) if sys.argv[1].lower() in ["e", "encrypt"]: sys.stdout.buffer.write(des.encrypt(pad(data))) elif sys.argv[1].lower() in ["d", "decrypt"]: sys.stdout.buffer.write(unpad(des.decrypt(data))) else: usage()
from Crypto.Cipher import DES3 from Crypto import Random #key = 'Sixteen byte key' key = input("enter key of size 16 or 24") iv = Random.new().read(DES3.block_size) #DES3.block_size==8 cipher_encrypt = DES3.new(key, DES3.MODE_OFB, iv) plaintext = input("enter message") while len(plaintext) % 8 != 0: plaintext += 'x' encrypted_text = cipher_encrypt.encrypt(plaintext) print(encrypted_text) cipher_decrypt = DES3.new( key, DES3.MODE_OFB, iv ) #you can't reuse an object for encrypting or decrypting other data with the same key. plaintext = cipher_decrypt.decrypt(encrypted_text) print(plaintext)
def des3_encrypt(key, msg): cipher = DES3.new(key, DES3.MODE_OFB, iv) msg = iv + cipher.encrypt(msg) msg = binascii.b2a_hex(msg) return msg.decode()
def encrypt_and_send(soc_id, mesg, key): cipher = DES3.new(key, DES3.MODE_ECB) mesg = encryption(mesg, cipher, True) soc_id.sendall(mesg)
def _encrypt_des3(self, text): secret_key_bytes = base64.b64decode(self._secret_key) text = self._pad(text, 8) cipher = DES3.new(secret_key_bytes, DES3.MODE_ECB) cipher_text = cipher.encrypt(str.encode(text)) return base64.b64encode(cipher_text).decode("utf-8")