Python Crypto.Cipher.DES3.MODE_CBC Examples
The following are 30
code examples of Crypto.Cipher.DES3.MODE_CBC().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
Crypto.Cipher.DES3
, or try the search function
.
Example #1
Source File: encryptionencoding.py From chepy with GNU General Public License v3.0 | 12 votes |
def triple_des_encrypt( self, key: str, iv: str = "0000000000000000", mode: str = "CBC", hex_key: bool = False, hex_iv: bool = True, ): """Encrypt raw state with Triple DES Triple DES applies DES three times to each block to increase key size. Key: Triple DES uses a key length of 24 bytes (192 bits).<br>DES uses a key length of 8 bytes (64 bits).<br><br>You can generate a password-based key using one of the KDF operations. IV: The Initialization Vector should be 8 bytes long. If not entered, it will default to 8 null bytes. Padding: In CBC and ECB mode, PKCS#7 padding will be used. Args: key (str): Required. The secret key iv (str, optional): IV for certain modes only. Defaults to '0000000000000000'. mode (str, optional): Encryption mode. Defaults to 'CBC'. hex_key (bool, optional): If the secret key is a hex string. Defaults to False. hex_iv (bool, optional): If the IV is a hex string. Defaults to True. Returns: Chepy: The Chepy object. Examples: >>> Chepy("some data").triple_des_encrypt("super secret password !!", mode="ECB").o b"f8b27a0d8c837edc8fb00ea85f502fb4" """ self.__check_mode(mode) key, iv = self._convert_key(key, iv, hex_key, hex_iv) if mode == "CBC": cipher = DES3.new(key, mode=DES3.MODE_CBC, iv=iv) self.state = cipher.encrypt(pad(self._convert_to_bytes(), 8)) return self elif mode == "ECB": cipher = DES3.new(key, mode=DES3.MODE_ECB) self.state = cipher.encrypt(pad(self._convert_to_bytes(), 8)) return self elif mode == "CTR": cipher = DES3.new(key, mode=DES3.MODE_CTR, nonce=b"") self.state = cipher.encrypt(self._convert_to_bytes()) return self elif mode == "OFB": cipher = DES3.new(key, mode=DES3.MODE_OFB, iv=iv) self.state = cipher.encrypt(self._convert_to_bytes()) return self
Example #2
Source File: keys.py From BitTorrent with GNU General Public License v3.0 | 7 votes |
def getPrivateKeyObject_openssh(data, passphrase): kind = data[0][11: 14] if data[1].startswith('Proc-Type: 4,ENCRYPTED'): # encrypted key ivdata = data[2].split(',')[1][:-1] iv = ''.join([chr(int(ivdata[i:i+2],16)) for i in range(0, len(ivdata), 2)]) if not passphrase: raise BadKeyError, 'encrypted key with no passphrase' ba = md5.new(passphrase + iv).digest() bb = md5.new(ba + passphrase + iv).digest() decKey = (ba + bb)[:24] b64Data = base64.decodestring(''.join(data[4:-1])) keyData = DES3.new(decKey, DES3.MODE_CBC, iv).decrypt(b64Data) removeLen = ord(keyData[-1]) keyData = keyData[:-removeLen] else: keyData = base64.decodestring(''.join(data[1:-1])) try: decodedKey = asn1.parse(keyData) except Exception, e: raise BadKeyError, 'something wrong with decode'
Example #3
Source File: test_CBC.py From FODI with GNU General Public License v3.0 | 6 votes |
def test_aes_192(self): key = '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b' iv = '000102030405060708090a0b0c0d0e0f' plaintext = '6bc1bee22e409f96e93d7e117393172a' +\ 'ae2d8a571e03ac9c9eb76fac45af8e51' +\ '30c81c46a35ce411e5fbc1191a0a52ef' +\ 'f69f2445df4f9b17ad2b417be66c3710' ciphertext = '4f021db243bc633d7178183a9fa071e8' +\ 'b4d9ada9ad7dedf4e5e738763f69145a' +\ '571b242012fb7ae07fa9baac3df102e0' +\ '08b0e27988598881d920a9e64f5615cd' key = unhexlify(key) iv = unhexlify(iv) plaintext = unhexlify(plaintext) ciphertext = unhexlify(ciphertext) cipher = AES.new(key, AES.MODE_CBC, iv) self.assertEqual(cipher.encrypt(plaintext), ciphertext) cipher = AES.new(key, AES.MODE_CBC, iv) self.assertEqual(cipher.decrypt(ciphertext), plaintext)
Example #4
Source File: test_CBC.py From android_universal with MIT License | 6 votes |
def test_aes_256(self): key = '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4' iv = '000102030405060708090a0b0c0d0e0f' plaintext = '6bc1bee22e409f96e93d7e117393172a' +\ 'ae2d8a571e03ac9c9eb76fac45af8e51' +\ '30c81c46a35ce411e5fbc1191a0a52ef' +\ 'f69f2445df4f9b17ad2b417be66c3710' ciphertext = 'f58c4c04d6e5f1ba779eabfb5f7bfbd6' +\ '9cfc4e967edb808d679f777bc6702c7d' +\ '39f23369a9d9bacfa530e26304231461' +\ 'b2eb05e2c39be9fcda6c19078c6a9d1b' key = unhexlify(key) iv = unhexlify(iv) plaintext = unhexlify(plaintext) ciphertext = unhexlify(ciphertext) cipher = AES.new(key, AES.MODE_CBC, iv) self.assertEqual(cipher.encrypt(plaintext), ciphertext) cipher = AES.new(key, AES.MODE_CBC, iv) self.assertEqual(cipher.decrypt(ciphertext), plaintext)
Example #5
Source File: test_CBC.py From android_universal with MIT License | 6 votes |
def test_aes_192(self): key = '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b' iv = '000102030405060708090a0b0c0d0e0f' plaintext = '6bc1bee22e409f96e93d7e117393172a' +\ 'ae2d8a571e03ac9c9eb76fac45af8e51' +\ '30c81c46a35ce411e5fbc1191a0a52ef' +\ 'f69f2445df4f9b17ad2b417be66c3710' ciphertext = '4f021db243bc633d7178183a9fa071e8' +\ 'b4d9ada9ad7dedf4e5e738763f69145a' +\ '571b242012fb7ae07fa9baac3df102e0' +\ '08b0e27988598881d920a9e64f5615cd' key = unhexlify(key) iv = unhexlify(iv) plaintext = unhexlify(plaintext) ciphertext = unhexlify(ciphertext) cipher = AES.new(key, AES.MODE_CBC, iv) self.assertEqual(cipher.encrypt(plaintext), ciphertext) cipher = AES.new(key, AES.MODE_CBC, iv) self.assertEqual(cipher.decrypt(ciphertext), plaintext)
Example #6
Source File: test_CBC.py From android_universal with MIT License | 6 votes |
def test_aes_128(self): key = '2b7e151628aed2a6abf7158809cf4f3c' iv = '000102030405060708090a0b0c0d0e0f' plaintext = '6bc1bee22e409f96e93d7e117393172a' +\ 'ae2d8a571e03ac9c9eb76fac45af8e51' +\ '30c81c46a35ce411e5fbc1191a0a52ef' +\ 'f69f2445df4f9b17ad2b417be66c3710' ciphertext = '7649abac8119b246cee98e9b12e9197d' +\ '5086cb9b507219ee95db113a917678b2' +\ '73bed6b8e3c1743b7116e69e22229516' +\ '3ff1caa1681fac09120eca307586e1a7' key = unhexlify(key) iv = unhexlify(iv) plaintext = unhexlify(plaintext) ciphertext = unhexlify(ciphertext) cipher = AES.new(key, AES.MODE_CBC, iv) self.assertEqual(cipher.encrypt(plaintext), ciphertext) cipher = AES.new(key, AES.MODE_CBC, iv) self.assertEqual(cipher.decrypt(ciphertext), plaintext)
Example #7
Source File: test_CBC.py From FODI with GNU General Public License v3.0 | 6 votes |
def test_aes_128(self): key = '2b7e151628aed2a6abf7158809cf4f3c' iv = '000102030405060708090a0b0c0d0e0f' plaintext = '6bc1bee22e409f96e93d7e117393172a' +\ 'ae2d8a571e03ac9c9eb76fac45af8e51' +\ '30c81c46a35ce411e5fbc1191a0a52ef' +\ 'f69f2445df4f9b17ad2b417be66c3710' ciphertext = '7649abac8119b246cee98e9b12e9197d' +\ '5086cb9b507219ee95db113a917678b2' +\ '73bed6b8e3c1743b7116e69e22229516' +\ '3ff1caa1681fac09120eca307586e1a7' key = unhexlify(key) iv = unhexlify(iv) plaintext = unhexlify(plaintext) ciphertext = unhexlify(ciphertext) cipher = AES.new(key, AES.MODE_CBC, iv) self.assertEqual(cipher.encrypt(plaintext), ciphertext) cipher = AES.new(key, AES.MODE_CBC, iv) self.assertEqual(cipher.decrypt(ciphertext), plaintext)
Example #8
Source File: test_CBC.py From FODI with GNU General Public License v3.0 | 6 votes |
def test_aes_256(self): key = '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4' iv = '000102030405060708090a0b0c0d0e0f' plaintext = '6bc1bee22e409f96e93d7e117393172a' +\ 'ae2d8a571e03ac9c9eb76fac45af8e51' +\ '30c81c46a35ce411e5fbc1191a0a52ef' +\ 'f69f2445df4f9b17ad2b417be66c3710' ciphertext = 'f58c4c04d6e5f1ba779eabfb5f7bfbd6' +\ '9cfc4e967edb808d679f777bc6702c7d' +\ '39f23369a9d9bacfa530e26304231461' +\ 'b2eb05e2c39be9fcda6c19078c6a9d1b' key = unhexlify(key) iv = unhexlify(iv) plaintext = unhexlify(plaintext) ciphertext = unhexlify(ciphertext) cipher = AES.new(key, AES.MODE_CBC, iv) self.assertEqual(cipher.encrypt(plaintext), ciphertext) cipher = AES.new(key, AES.MODE_CBC, iv) self.assertEqual(cipher.decrypt(ciphertext), plaintext)
Example #9
Source File: encryptionencoding.py From chepy with GNU General Public License v3.0 | 6 votes |
def des_encrypt( self, key: str, iv: str = "0000000000000000", mode: str = "CBC", hex_key: bool = False, hex_iv: bool = True, ): """Encrypt raw state with DES DES is a previously dominant algorithm for encryption, and was published as an official U.S. Federal Information Processing Standard (FIPS). It is now considered to be insecure due to its small key size. DES uses a key length of 8 bytes (64 bits).<br>Triple DES uses a key length of 24 bytes. You can generate a password-based key using one of the KDF operations. The Initialization Vector should be 8 bytes long. If not entered, it will default to 8 null bytes. Padding: In CBC and ECB mode, PKCS#7 padding will be used. Args: key (str): Required. The secret key iv (str, optional): IV for certain modes only. Defaults to '0000000000000000'. mode (str, optional): Encryption mode. Defaults to 'CBC'. hex_key (bool, optional): If the secret key is a hex string. Defaults to False. hex_iv (bool, optional): If the IV is a hex string. Defaults to True. Returns: Chepy: The Chepy object. Examples: >>> Chepy("some data").des_encrypt("70617373776f7264", hex_key=True).o b"1ee5cb52954b211d1acd6e79c598baac" To encrypt using a differnt mode >>> Chepy("some data").des_encrypt("password", mode="CTR").o b"0b7399049b0267d93d" """ self.__check_mode(mode) key, iv = self._convert_key(key, iv, hex_key, hex_iv) if mode == "CBC": cipher = DES.new(key, mode=DES.MODE_CBC, iv=iv) self.state = cipher.encrypt(pad(self._convert_to_bytes(), 8)) return self elif mode == "ECB": cipher = DES.new(key, mode=DES.MODE_ECB) self.state = cipher.encrypt(pad(self._convert_to_bytes(), 8)) return self elif mode == "CTR": cipher = DES.new(key, mode=DES.MODE_CTR, nonce=b"") self.state = cipher.encrypt(self._convert_to_bytes()) return self elif mode == "OFB": cipher = DES.new(key, mode=DES.MODE_OFB, iv=iv) self.state = cipher.encrypt(self._convert_to_bytes()) return self
Example #10
Source File: des3.py From scalyr-agent-2 with Apache License 2.0 | 5 votes |
def decryptData(self, decryptKey, privParameters, encryptedData): if DES3 is None: raise error.StatusInformation( errorIndication=errind.decryptionError ) snmpEngineBoots, snmpEngineTime, salt = privParameters if len(salt) != 8: raise error.StatusInformation( errorIndication=errind.decryptionError ) des3Key, iv = self.__getDecryptionKey(decryptKey, salt) if len(encryptedData) % 8 != 0: raise error.StatusInformation( errorIndication=errind.decryptionError ) des3Obj = DES3.new(des3Key, DES3.MODE_CBC, iv) plaintext = null ciphertext = encryptedData.asOctets() cipherblock = iv while ciphertext: plaintext = plaintext + univ.OctetString(map(lambda x,y: x^y, univ.OctetString(cipherblock).asNumbers(), univ.OctetString(des3Obj.decrypt(ciphertext[:8])).asNumbers())).asOctets() cipherblock = ciphertext[:8] ciphertext = ciphertext[8:] return plaintext
Example #11
Source File: Mozilla.py From BrainDamage with Apache License 2.0 | 5 votes |
def decrypt3DES(self, globalSalt, masterPassword, entrySalt, encryptedData): hp = sha1(globalSalt + masterPassword).digest() pes = entrySalt + '\x00' * (20 - len(entrySalt)) chp = sha1(hp + entrySalt).digest() k1 = hmac.new(chp, pes + entrySalt, sha1).digest() tk = hmac.new(chp, pes, sha1).digest() k2 = hmac.new(chp, tk + entrySalt, sha1).digest() k = k1 + k2 iv = k[-8:] key = k[:24] return DES3.new(key, DES3.MODE_CBC, iv).decrypt(encryptedData)
Example #12
Source File: easycard.py From Easy-Card with MIT License | 5 votes |
def getID(data, isEncrypt, key, iv, encode): size = len(data) if size % 16 != 0: data += '\x06' * (16 - size % 16) des3 = DES3.new(key, DES3.MODE_CBC, iv) if isEncrypt: result = des3.encrypt(data).encode(encode).rstrip() else: result = des3.decrypt(data.decode(encode)) return result
Example #13
Source File: remmina_password_exposer.py From Remmina-password-exposer with GNU General Public License v2.0 | 5 votes |
def show_remmina_accounts(debug=False): diz = {} res = [] fs = open(REMMINA_FOLDER+REMMINA_PREF) fso = fs.readlines() fs.close() for i in fso: if re.findall(r'secret=', i): r_secret = i[len(r'secret='):][:-1] if debug: print('**secret found {}'.format(r_secret)) for f in os.listdir(REMMINA_FOLDER): if re.findall(REGEXP_ACCOUNTS, f): fo = open( REMMINA_FOLDER+f, 'r') for i in fo.readlines(): if re.findall(r'^password=', i): r_password = i[len(r'password='):][:-1] if re.findall(r'^name=', i): r_name = i.split('=')[1][:-1] if re.findall(r'username=', i): r_username = i.split('=')[1][:-1] if debug: print(fo, 'found', f) password = base64.b64decode(r_password) secret = base64.b64decode(r_secret) diz[r_name] = DES3.new(secret[:24], DES3.MODE_CBC, secret[24:]).decrypt(password) if sys.version_info.major == 3: pval = diz[r_name].decode(CHARSET) else: pval = diz[r_name] r = (r_name, r_username, pval, diz[r_name]) res.append(r) print('{} {} {} [raw:{}]'.format(*r)) fo.close() return res
Example #14
Source File: keys.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
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
Example #15
Source File: Mozilla.py From Radium with Apache License 2.0 | 5 votes |
def decrypt3DES(self, globalSalt, masterPassword, entrySalt, encryptedData): hp = sha1(globalSalt + masterPassword).digest() pes = entrySalt + '\x00' * (20 - len(entrySalt)) chp = sha1(hp + entrySalt).digest() k1 = hmac.new(chp, pes + entrySalt, sha1).digest() tk = hmac.new(chp, pes, sha1).digest() k2 = hmac.new(chp, tk + entrySalt, sha1).digest() k = k1 + k2 iv = k[-8:] key = k[:24] return DES3.new(key, DES3.MODE_CBC, iv).decrypt(encryptedData)
Example #16
Source File: pylocky_decryptor.py From pylocky_decryptor with Apache License 2.0 | 5 votes |
def _make_des3_decryptor(key, iv): if debug: print("Before getting decryptor") decryptor = DES3.new(key, DES3.MODE_CBC, iv) if debug: print("Decryptor returned") return decryptor
Example #17
Source File: Transform.py From deprecated-binaryninja-python with GNU General Public License v2.0 | 5 votes |
def populate_transform_menu(menu, obj, action_table): aes_menu = menu.addMenu("AES") aes_ecb_menu = aes_menu.addMenu("ECB mode") aes_cbc_menu = aes_menu.addMenu("CBC mode") action_table[aes_ecb_menu.addAction("Encrypt")] = lambda: obj.transform_with_key(lambda data, key: aes_encrypt_transform(data, key, AES.MODE_ECB, "")) action_table[aes_ecb_menu.addAction("Decrypt")] = lambda: obj.transform_with_key(lambda data, key: aes_decrypt_transform(data, key, AES.MODE_ECB, "")) action_table[aes_cbc_menu.addAction("Encrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: aes_encrypt_transform(data, key, AES.MODE_CBC, iv)) action_table[aes_cbc_menu.addAction("Decrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: aes_decrypt_transform(data, key, AES.MODE_CBC, iv)) blowfish_menu = menu.addMenu("Blowfish") blowfish_ecb_menu = blowfish_menu.addMenu("ECB mode") blowfish_cbc_menu = blowfish_menu.addMenu("CBC mode") action_table[blowfish_ecb_menu.addAction("Encrypt")] = lambda: obj.transform_with_key(lambda data, key: blowfish_encrypt_transform(data, key, Blowfish.MODE_ECB, "")) action_table[blowfish_ecb_menu.addAction("Decrypt")] = lambda: obj.transform_with_key(lambda data, key: blowfish_decrypt_transform(data, key, Blowfish.MODE_ECB, "")) action_table[blowfish_cbc_menu.addAction("Encrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: blowfish_encrypt_transform(data, key, Blowfish.MODE_CBC, iv)) action_table[blowfish_cbc_menu.addAction("Decrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: blowfish_decrypt_transform(data, key, Blowfish.MODE_CBC, iv)) cast_menu = menu.addMenu("CAST") cast_ecb_menu = cast_menu.addMenu("ECB mode") cast_cbc_menu = cast_menu.addMenu("CBC mode") action_table[cast_ecb_menu.addAction("Encrypt")] = lambda: obj.transform_with_key(lambda data, key: cast_encrypt_transform(data, key, CAST.MODE_ECB, "")) action_table[cast_ecb_menu.addAction("Decrypt")] = lambda: obj.transform_with_key(lambda data, key: cast_decrypt_transform(data, key, CAST.MODE_ECB, "")) action_table[cast_cbc_menu.addAction("Encrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: cast_encrypt_transform(data, key, CAST.MODE_CBC, iv)) action_table[cast_cbc_menu.addAction("Decrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: cast_decrypt_transform(data, key, CAST.MODE_CBC, iv)) des_menu = menu.addMenu("DES") des_ecb_menu = des_menu.addMenu("ECB mode") des_cbc_menu = des_menu.addMenu("CBC mode") action_table[des_ecb_menu.addAction("Encrypt")] = lambda: obj.transform_with_key(lambda data, key: des_encrypt_transform(data, key, DES.MODE_ECB, "")) action_table[des_ecb_menu.addAction("Decrypt")] = lambda: obj.transform_with_key(lambda data, key: des_decrypt_transform(data, key, DES.MODE_ECB, "")) action_table[des_cbc_menu.addAction("Encrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: des_encrypt_transform(data, key, DES.MODE_CBC, iv)) action_table[des_cbc_menu.addAction("Decrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: des_decrypt_transform(data, key, DES.MODE_CBC, iv)) des3_menu = menu.addMenu("Triple DES") des3_ecb_menu = des3_menu.addMenu("ECB mode") des3_cbc_menu = des3_menu.addMenu("CBC mode") action_table[des3_ecb_menu.addAction("Encrypt")] = lambda: obj.transform_with_key(lambda data, key: des3_encrypt_transform(data, key, DES3.MODE_ECB, "")) action_table[des3_ecb_menu.addAction("Decrypt")] = lambda: obj.transform_with_key(lambda data, key: des3_decrypt_transform(data, key, DES3.MODE_ECB, "")) action_table[des3_cbc_menu.addAction("Encrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: des3_encrypt_transform(data, key, DES3.MODE_CBC, iv)) action_table[des3_cbc_menu.addAction("Decrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: des3_decrypt_transform(data, key, DES3.MODE_CBC, iv)) rc2_menu = menu.addMenu("RC2") rc2_ecb_menu = rc2_menu.addMenu("ECB mode") rc2_cbc_menu = rc2_menu.addMenu("CBC mode") action_table[rc2_ecb_menu.addAction("Encrypt")] = lambda: obj.transform_with_key(lambda data, key: rc2_encrypt_transform(data, key, ARC2.MODE_ECB, "")) action_table[rc2_ecb_menu.addAction("Decrypt")] = lambda: obj.transform_with_key(lambda data, key: rc2_decrypt_transform(data, key, ARC2.MODE_ECB, "")) action_table[rc2_cbc_menu.addAction("Encrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: rc2_encrypt_transform(data, key, ARC2.MODE_CBC, iv)) action_table[rc2_cbc_menu.addAction("Decrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: rc2_decrypt_transform(data, key, ARC2.MODE_CBC, iv)) action_table[menu.addAction("RC4")] = lambda: obj.transform_with_key(lambda data, key: rc4_transform(data, key)) action_table[menu.addAction("XOR")] = lambda: obj.transform_with_key(lambda data, key: xor_transform(data, key))
Example #18
Source File: TDES.py From msldap with MIT License | 5 votes |
def setup_cipher(self): if self.mode == cipherMODE.ECB: self._cipher = _pyCryptoDES3.new(self.key, _pyCryptoDES3.MODE_ECB) elif self.mode == cipherMODE.CBC: self._cipher = _pyCryptoDES3.new(self.key, _pyCryptoDES3.MODE_CBC, self.IV) else: raise Exception('Unknown cipher mode!')
Example #19
Source File: des3.py From scalyr-agent-2 with Apache License 2.0 | 5 votes |
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() cipherblock = iv ciphertext = null while plaintext: cipherblock = des3Obj.encrypt( univ.OctetString(map(lambda x,y:x^y, univ.OctetString(cipherblock).asNumbers(), univ.OctetString(plaintext[:8]).asNumbers())).asOctets() ) ciphertext = ciphertext + cipherblock plaintext = plaintext[8:] return univ.OctetString(ciphertext), privParameters # 5.1.1.3
Example #20
Source File: encryptionencoding.py From chepy with GNU General Public License v3.0 | 5 votes |
def blowfish_encrypt( self, key: str, iv: str = "0000000000000000", mode: str = "CBC", hex_key: bool = False, hex_iv: bool = True, ): """Encrypt raw state with Blowfish Blowfish is a symmetric-key block cipher designed in 1993 by Bruce Schneier and included in a large number of cipher suites and encryption products. AES now receives more attention. IV: The Initialization Vector should be 8 bytes long. Args: key (str): Required. The secret key iv (str, optional): IV for certain modes only. Defaults to '0000000000000000'. mode (str, optional): Encryption mode. Defaults to 'CBC'. hex_key (bool, optional): If the secret key is a hex string. Defaults to False. hex_iv (bool, optional): If the IV is a hex string. Defaults to True. Returns: Chepy: The Chepy object. Examples: >>> Chepy("some data").blowfish_encrypt("password", mode="ECB").o b"d9b0a79853f139603951bff96c3d0dd5" """ self.__check_mode(mode) key, iv = self._convert_key(key, iv, hex_key, hex_iv) if mode == "CBC": cipher = Blowfish.new(key, mode=Blowfish.MODE_CBC, iv=iv) self.state = cipher.encrypt(pad(self._convert_to_bytes(), 8)) return self elif mode == "ECB": cipher = Blowfish.new(key, mode=Blowfish.MODE_ECB) self.state = cipher.encrypt(pad(self._convert_to_bytes(), 8)) return self elif mode == "CTR": cipher = Blowfish.new(key, mode=Blowfish.MODE_CTR, nonce=b"") self.state = cipher.encrypt(self._convert_to_bytes()) return self elif mode == "OFB": cipher = Blowfish.new(key, mode=Blowfish.MODE_OFB, iv=iv) self.state = cipher.encrypt(self._convert_to_bytes()) return self
Example #21
Source File: encryptionencoding.py From chepy with GNU General Public License v3.0 | 5 votes |
def triple_des_decrypt( self, key: str, iv: str = "0000000000000000", mode: str = "CBC", hex_key: bool = False, hex_iv: bool = True, ): """Decrypt raw state encrypted with DES. Triple DES applies DES three times to each block to increase key size. Key: Triple DES uses a key length of 24 bytes (192 bits).<br>DES uses a key length of 8 bytes (64 bits).<br><br>You can generate a password-based key using one of the KDF operations. IV: The Initialization Vector should be 8 bytes long. If not entered, it will default to 8 null bytes. Padding: In CBC and ECB mode, PKCS#7 padding will be used. Args: key (str): Required. The secret key iv (str, optional): IV for certain modes only. Defaults to '0000000000000000'. mode (str, optional): Encryption mode. Defaults to 'CBC'. hex_key (bool, optional): If the secret key is a hex string. Defaults to False. hex_iv (bool, optional): If the IV is a hex string. Defaults to True. Returns: Chepy: The Chepy object. Examples: >>> c = Chepy("f8b27a0d8c837edce87dd13a1ab41f96") >>> c.hex_to_str() >>> c.triple_des_decrypt("super secret password !!") >>> c.o b"some data" """ self.__check_mode(mode) key, iv = self._convert_key(key, iv, hex_key, hex_iv) if mode == "CBC": cipher = DES3.new(key, mode=DES3.MODE_CBC, iv=iv) self.state = unpad(cipher.decrypt(self._convert_to_bytes()), 8) return self elif mode == "ECB": cipher = DES3.new(key, mode=DES3.MODE_ECB) self.state = unpad(cipher.decrypt(self._convert_to_bytes()), 8) return self elif mode == "CTR": cipher = DES3.new(key, mode=DES3.MODE_CTR, nonce=b"") self.state = cipher.decrypt(self._convert_to_bytes()) return self elif mode == "OFB": cipher = DES3.new(key, mode=DES3.MODE_OFB, iv=iv) self.state = cipher.decrypt(self._convert_to_bytes()) return self
Example #22
Source File: encryptionencoding.py From chepy with GNU General Public License v3.0 | 5 votes |
def des_decrypt( self, key: str, iv: str = "0000000000000000", mode: str = "CBC", hex_key: bool = False, hex_iv: bool = True, ): """Decrypt raw state encrypted with DES. DES is a previously dominant algorithm for encryption, and was published as an official U.S. Federal Information Processing Standard (FIPS). It is now considered to be insecure due to its small key size. DES uses a key length of 8 bytes (64 bits).<br>Triple DES uses a key length of 24 bytes. You can generate a password-based key using one of the KDF operations. The Initialization Vector should be 8 bytes long. If not entered, it will default to 8 null bytes. Padding: In CBC and ECB mode, PKCS#7 padding will be used. Args: key (str): Required. The secret key iv (str, optional): IV for certain modes only. Defaults to '0000000000000000'. mode (str, optional): Encryption mode. Defaults to 'CBC'. hex_key (bool, optional): If the secret key is a hex string. Defaults to False. hex_iv (bool, optional): If the IV is a hex string. Defaults to True. Returns: Chepy: The Chepy object. Examples: >>> Chepy("1ee5cb52954b211d1acd6e79c598baac").hex_to_str().des_decrypt("password").o b"some data" """ self.__check_mode(mode) key, iv = self._convert_key(key, iv, hex_key, hex_iv) if mode == "CBC": cipher = DES.new(key, mode=DES.MODE_CBC, iv=iv) self.state = unpad(cipher.decrypt(self._convert_to_bytes()), 8) return self elif mode == "ECB": cipher = DES.new(key, mode=DES.MODE_ECB) self.state = unpad(cipher.decrypt(self._convert_to_bytes()), 8) return self elif mode == "CTR": cipher = DES.new(key, mode=DES.MODE_CTR, nonce=b"") self.state = cipher.decrypt(self._convert_to_bytes()) return self elif mode == "OFB": cipher = DES.new(key, mode=DES.MODE_OFB, iv=iv) self.state = cipher.decrypt(self._convert_to_bytes()) return self
Example #23
Source File: mozilla.py From LaZagneForensic with GNU Lesser General Public License v3.0 | 5 votes |
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)
Example #24
Source File: mozilla.py From LaZagneForensic with GNU Lesser General Public License v3.0 | 5 votes |
def decrypt3DES(self, globalSalt, master_password, entrySalt, encryptedData): """ User master key is also encrypted (if provided, the master_password could be used to encrypt it) """ # See http://www.drh-consultancy.demon.co.uk/key3.html hp = sha1(globalSalt + master_password).digest() pes = entrySalt + '\x00' * (20 - len(entrySalt)) chp = sha1(hp + entrySalt).digest() k1 = hmac.new(chp, pes + entrySalt, sha1).digest() tk = hmac.new(chp, pes, sha1).digest() k2 = hmac.new(chp, tk + entrySalt, sha1).digest() k = k1 + k2 iv = k[-8:] key = k[:24] return DES3.new(key, DES3.MODE_CBC, iv).decrypt(encryptedData)
Example #25
Source File: cisco_pwdecrypt.py From cisco_pwdecrypt with Apache License 2.0 | 5 votes |
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)
Example #26
Source File: keys.py From python-for-android with Apache License 2.0 | 4 votes |
def _fromString_PRIVATE_OPENSSH(Class, data, passphrase): """ Return a private key object corresponding to this OpenSSH private key string. If the key is encrypted, passphrase MUST be provided. Providing a passphrase for an unencrypted key is an error. The format of an OpenSSH private key string is:: -----BEGIN <key type> PRIVATE KEY----- [Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,<initialization value>] <base64-encoded ASN.1 structure> ------END <key type> PRIVATE KEY------ The ASN.1 structure of a RSA key is:: (0, n, e, d, p, q) The ASN.1 structure of a DSA key is:: (0, p, q, g, y, x) @type data: C{str} @type passphrase: C{str} @return: a C{Crypto.PublicKey.pubkey.pubkey} object @raises BadKeyError: if * a passphrase is provided for an unencrypted key * a passphrase is not provided for an encrypted key * the ASN.1 encoding is incorrect """ lines = [x + '\n' for x in data.split('\n')] kind = lines[0][11:14] if lines[1].startswith('Proc-Type: 4,ENCRYPTED'): # encrypted key ivdata = lines[2].split(',')[1][:-1] iv = ''.join([chr(int(ivdata[i:i + 2], 16)) for i in range(0, len(ivdata), 2)]) if not passphrase: raise EncryptedKeyError('encrypted key with no passphrase') ba = md5(passphrase + iv).digest() bb = md5(ba + passphrase + iv).digest() decKey = (ba + bb)[:24] b64Data = base64.decodestring(''.join(lines[3:-1])) keyData = DES3.new(decKey, DES3.MODE_CBC, iv).decrypt(b64Data) removeLen = ord(keyData[-1]) keyData = keyData[:-removeLen] else: b64Data = ''.join(lines[1:-1]) keyData = base64.decodestring(b64Data) try: decodedKey = berDecoder.decode(keyData)[0] except Exception, e: raise BadKeyError, 'something wrong with decode'
Example #27
Source File: PEM.py From android_universal with MIT License | 4 votes |
def encode(data, marker, passphrase=None, randfunc=None): """Encode a piece of binary data into PEM format. Args: data (byte string): The piece of binary data to encode. marker (string): The marker for the PEM block (e.g. "PUBLIC KEY"). Note that there is no official master list for all allowed markers. Still, you can refer to the OpenSSL_ source code. passphrase (byte string): If given, the PEM block will be encrypted. The key is derived from the passphrase. randfunc (callable): Random number generation function; it accepts an integer N and returns a byte string of random data, N bytes long. If not given, a new one is instantiated. Returns: The PEM block, as a string. .. _OpenSSL: https://github.com/openssl/openssl/blob/master/include/openssl/pem.h """ if randfunc is None: randfunc = get_random_bytes out = "-----BEGIN %s-----\n" % marker if passphrase: # We only support 3DES for encryption 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()) # Encrypt with PKCS#7 padding data = objenc.encrypt(pad(data, objenc.block_size)) elif passphrase is not None: raise ValueError("Empty password") # Each BASE64 line can take up to 64 characters (=48 bytes of data) # b2a_base64 adds a new line character! 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
Example #28
Source File: _PBES.py From android_universal with MIT License | 4 votes |
def decrypt(data, passphrase): """Decrypt a piece of data using a passphrase and *PBES1*. The algorithm to use is automatically detected. :Parameters: data : byte string The piece of data to decrypt. passphrase : byte string The passphrase to use for decrypting the data. :Returns: The decrypted data, as a binary string. """ enc_private_key_info = DerSequence().decode(data) encrypted_algorithm = DerSequence().decode(enc_private_key_info[0]) encrypted_data = DerOctetString().decode(enc_private_key_info[1]).payload pbe_oid = DerObjectId().decode(encrypted_algorithm[0]).value cipher_params = {} if pbe_oid == _OID_PBE_WITH_MD5_AND_DES_CBC: # PBE_MD5_DES_CBC hashmod = MD5 ciphermod = DES elif pbe_oid == _OID_PBE_WITH_MD5_AND_RC2_CBC: # PBE_MD5_RC2_CBC hashmod = MD5 ciphermod = ARC2 cipher_params['effective_keylen'] = 64 elif pbe_oid == _OID_PBE_WITH_SHA1_AND_DES_CBC: # PBE_SHA1_DES_CBC hashmod = SHA1 ciphermod = DES elif pbe_oid == _OID_PBE_WITH_SHA1_AND_RC2_CBC: # PBE_SHA1_RC2_CBC hashmod = SHA1 ciphermod = ARC2 cipher_params['effective_keylen'] = 64 else: raise PbesError("Unknown OID for PBES1") pbe_params = DerSequence().decode(encrypted_algorithm[1], nr_elements=2) salt = DerOctetString().decode(pbe_params[0]).payload iterations = pbe_params[1] key_iv = PBKDF1(passphrase, salt, 16, iterations, hashmod) key, iv = key_iv[:8], key_iv[8:] cipher = ciphermod.new(key, ciphermod.MODE_CBC, iv, **cipher_params) pt = cipher.decrypt(encrypted_data) return unpad(pt, cipher.block_size)
Example #29
Source File: _PBES.py From FODI with GNU General Public License v3.0 | 4 votes |
def decrypt(data, passphrase): """Decrypt a piece of data using a passphrase and *PBES1*. The algorithm to use is automatically detected. :Parameters: data : byte string The piece of data to decrypt. passphrase : byte string The passphrase to use for decrypting the data. :Returns: The decrypted data, as a binary string. """ enc_private_key_info = DerSequence().decode(data) encrypted_algorithm = DerSequence().decode(enc_private_key_info[0]) encrypted_data = DerOctetString().decode(enc_private_key_info[1]).payload pbe_oid = DerObjectId().decode(encrypted_algorithm[0]).value cipher_params = {} if pbe_oid == _OID_PBE_WITH_MD5_AND_DES_CBC: # PBE_MD5_DES_CBC hashmod = MD5 ciphermod = DES elif pbe_oid == _OID_PBE_WITH_MD5_AND_RC2_CBC: # PBE_MD5_RC2_CBC hashmod = MD5 ciphermod = ARC2 cipher_params['effective_keylen'] = 64 elif pbe_oid == _OID_PBE_WITH_SHA1_AND_DES_CBC: # PBE_SHA1_DES_CBC hashmod = SHA1 ciphermod = DES elif pbe_oid == _OID_PBE_WITH_SHA1_AND_RC2_CBC: # PBE_SHA1_RC2_CBC hashmod = SHA1 ciphermod = ARC2 cipher_params['effective_keylen'] = 64 else: raise PbesError("Unknown OID for PBES1") pbe_params = DerSequence().decode(encrypted_algorithm[1], nr_elements=2) salt = DerOctetString().decode(pbe_params[0]).payload iterations = pbe_params[1] key_iv = PBKDF1(passphrase, salt, 16, iterations, hashmod) key, iv = key_iv[:8], key_iv[8:] cipher = ciphermod.new(key, ciphermod.MODE_CBC, iv, **cipher_params) pt = cipher.decrypt(encrypted_data) return unpad(pt, cipher.block_size)
Example #30
Source File: PEM.py From FODI with GNU General Public License v3.0 | 4 votes |
def encode(data, marker, passphrase=None, randfunc=None): """Encode a piece of binary data into PEM format. Args: data (byte string): The piece of binary data to encode. marker (string): The marker for the PEM block (e.g. "PUBLIC KEY"). Note that there is no official master list for all allowed markers. Still, you can refer to the OpenSSL_ source code. passphrase (byte string): If given, the PEM block will be encrypted. The key is derived from the passphrase. randfunc (callable): Random number generation function; it accepts an integer N and returns a byte string of random data, N bytes long. If not given, a new one is instantiated. Returns: The PEM block, as a string. .. _OpenSSL: https://github.com/openssl/openssl/blob/master/include/openssl/pem.h """ if randfunc is None: randfunc = get_random_bytes out = "-----BEGIN %s-----\n" % marker if passphrase: # We only support 3DES for encryption 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()) # Encrypt with PKCS#7 padding data = objenc.encrypt(pad(data, objenc.block_size)) elif passphrase is not None: raise ValueError("Empty password") # Each BASE64 line can take up to 64 characters (=48 bytes of data) # b2a_base64 adds a new line character! 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