def mac(key, msg): # Source: PKI for machine readable travel document offering # ICC read-only access # Release:1.1 # October 01,2004 # p46 of 57 # print 'MAC' # print '---' size = len(msg) / 8 y = "\x00" * 8 tdesa = DES.new(key[0:8], DES.MODE_CBC, y) # print 'IV: ' + binToHexRep(y) for i in range(size): # print 'x' + str(i) + ': ' + binToHexRep(msg[i*8:i*8+8]) y = tdesa.encrypt(msg[i * 8 : i * 8 + 8]) # print 'y' + str(i) + ': ' + binToHexRep(y) tdesb = DES.new(key[8:16]) tdesa = DES.new(key[0:8]) b = tdesb.decrypt(y) # print 'b: ' + binToHexRep(b) a = tdesa.encrypt(b) # print 'a: ' + binToHexRep(a) return a
def DESMAC(message, key, ssc): "iso 9797-1 Algorithm 3 (Retail MAC)" # DES for all blocks # DES3 for last block tdesa = DES.new(key[0:8], DES.MODE_ECB, DES_IV) tdesb = DES.new(key[8:16], DES.MODE_ECB, DES_IV) if ssc: mac = tdesa.encrypt(ToBinary(ssc)) else: mac = DES_IV message += PADBlock('') for y in range(len(message) / 8): current = message[y * 8:(y * 8) + 8] left = right = '' for x in range(len(mac)): left += '%02x' % ord(mac[x]) right += '%02x' % ord(current[x]) machex = '%016x' % xor(int(left, 16), int(right, 16)) # print machex mac = tdesa.encrypt(ToBinary(machex)) # print mac mac = tdesb.decrypt(mac) return tdesa.encrypt(mac)
def main(): print 'enter input:' inp = sys.stdin.readline() inp = _normalize(inp, 16) key8 = get_random_bytes(8) key16 = get_random_bytes(16) iv8 = get_random_bytes(8) iv16 = get_random_bytes(16) print 'key8\t', _to_hex(key8) print 'key16\t', _to_hex(key16) print 'iv8\t', _to_hex(iv8) print 'iv16\t', _to_hex(iv16) print 'DES, ECB mode' des = DES.new(key8, DES.MODE_ECB) enc = des.encrypt(inp) print '\tencoded:', _to_hex(enc) print '\tentropy:', _entropy_hex(_to_hex(enc)) print 'DES, CBC mode' des = DES.new(key8, DES.MODE_CBC, iv8) enc = des.encrypt(inp) print '\tencoded:', _to_hex(enc) print '\tentropy:', _entropy_hex(_to_hex(enc)) print 'AES, ECB mode' aes = AES.new(key16, AES.MODE_ECB) enc = aes.encrypt(inp) print '\tencoded:', _to_hex(enc) print '\tentropy:', _entropy_hex(_to_hex(enc)) print 'DES, CBC mode' aes = AES.new(key16, AES.MODE_CBC, iv16) enc = aes.encrypt(inp) print '\tencoded:', _to_hex(enc) print '\tentropy:', _entropy_hex(_to_hex(enc))
def encrypt_change(old, new): """Encrypt old and new passwords for a DND change password request. Returns a tuple consisting of the old password encrypted using the new one as a key, and the new password encrypted using the old one as a key, both encoded as a string of ASCII octal digits as required by the DND protocol. old -- Old cleartext password (str) new -- New cleartext password (str) """ if len(old) < DES.key_size: pad = chr(0) * (DES.key_size - len(old)) old += pad if len(new) < DES.key_size: pad = chr(0) * (DES.key_size - len(new)) new += pad okey = DES.new(old, DES.MODE_ECB) nkey = DES.new(new, DES.MODE_ECB) old_w_new = nkey.encrypt(old); del(nkey) new_w_old = okey.encrypt(new); del(okey) return (encode_octal(old_w_new), encode_octal(new_w_old))
def DeCrypt(str): global DES_KEY global RSA_CACHE size = len(str) if size < 32 + 2: return str keylen = size - 32 - 2 KeyId = str[0:2] DesData = str[2+keylen:] if keylen > 0: rsadeskey = str[2:2+keylen].decode("hex") dk = RSA_CACHE.get(rsadeskey) if dk == None: rsapri = ImportRsaPriKey(KeyId) dk = rsapri.decrypt(rsadeskey) RSA_CACHE[rsadeskey] = dk des = DES.new(dk, DES.MODE_ECB) dd = des.decrypt(DesData.decode("hex")) return dd.lstrip('0') else: if not DES_KEY: DES_KEY = ImportDesKey(KeyId) des = DES.new(DES_KEY, DES.MODE_ECB) dd = des.decrypt(DesData.decode("hex")) return dd.lstrip('0')
def instantiateClassDesLib(self): if self.DES_KEY == '': showerror(title='ERROR', message='No Key! Please enter the DES Key first.') else: iv = Random.get_random_bytes(8) self.DES_INSTANCE1 = DES.new(self.DES_KEY, DES.MODE_CFB, iv) self.DES_INSTANCE2 = DES.new(self.DES_KEY, DES.MODE_CFB, iv) self.DES_INSTANCE_FLAG = True
def __removeDESLayer(self, cryptedHash, rid): Key1,Key2 = self.__cryptoCommon.deriveKey(int(rid)) Crypt1 = DES.new(Key1, DES.MODE_ECB) Crypt2 = DES.new(Key2, DES.MODE_ECB) decryptedHash = Crypt1.decrypt(cryptedHash[:8]) + Crypt2.decrypt(cryptedHash[8:]) return decryptedHash
def removeDESLayer(cryptedHash, rid): Key1, Key2 = deriveKey(rid) Crypt1 = DES.new(Key1, DES.MODE_ECB) Crypt2 = DES.new(Key2, DES.MODE_ECB) decryptedHash = Crypt1.decrypt(cryptedHash[:8]) + Crypt2.decrypt(cryptedHash[8:]) return decryptedHash
def derive_key(self, ipek, ksn): """Derive a unique key given the ipek and ksn Keyword arguments: ipek (BitArray) -- Initial Pin Encryption Key ksn (BitArray) -- Key Serial Number """ c_mask = BitArray(hex='0xc0c0c0c000000000c0c0c0c000000000') ksn_offset = 2 ctr_offset = -3 right_offset = 8 # Registers taken from documentation curkey = ipek ksnr = BitArray(bytes=ksn.bytes[ksn_offset:]) r3 = self.copy_counter(ksnr) r8 = self.reset_counter(ksnr.bytes) sr = BitArray(hex='0x100000') while (sr.bytes[0] != '\x00') or (sr.bytes[1] != '\x00') or (sr.bytes[2] != '\x00'): tmp = self.copy_counter(sr) tmp = tmp & r3 if (tmp.bytes[0] != '\x00') or (tmp.bytes[1] != '\x00') or (tmp.bytes[2] != '\x00'): # Step 2 n_ctr = BitArray(bytes=r8.bytes[ctr_offset:]) | sr r8 = BitArray(bytes=r8.bytes[:ctr_offset]+n_ctr.bytes) # Step 3 r8a = r8 ^ BitArray(bytes=curkey.bytes[right_offset:]) # Step 4 cipher = DES.new(curkey.bytes[:DES.key_size], DES.MODE_ECB) r8a = BitArray(bytes=cipher.encrypt(r8a.bytes)) # Step 5 r8a = BitArray(bytes=curkey.bytes[right_offset:]) ^ r8a # Step 6 curkey = curkey ^ c_mask # Step 7 r8b = BitArray(bytes=curkey.bytes[right_offset:]) ^ r8 # Step 8 cipher = DES.new(curkey.bytes[:DES.key_size], DES.MODE_ECB) r8b = BitArray(bytes=cipher.encrypt(r8b.bytes)) # Step 9 r8b = BitArray(bytes=curkey.bytes[right_offset:]) ^ r8b # Step 10 / 11 curkey = BitArray(bytes=r8b.bytes+r8a.bytes) sr >>= 1 self._cur_key = curkey return curkey
def decrypt_single_salted_hash(rid, hbootkey, enc_hash, lmntstr, salt): if enc_hash == "": return "" (des_k1,des_k2) = sid_to_key(rid) d1 = DES.new(des_k1, DES.MODE_ECB) d2 = DES.new(des_k2, DES.MODE_ECB) cipher = AES.new(hbootkey[:16], AES.MODE_CBC, salt) obfkey = cipher.decrypt(enc_hash) hash = d1.decrypt(obfkey[:8]) + d2.decrypt(obfkey[8:16]) return hash
def ChallengeResponse(challenge, NTHash): """ Return Challenge Response""" key1 = expand_key(NTHash[0:7]) key2 = expand_key(NTHash[7:14]) key3 = expand_key(NTHash[14:16]+"\x00"*5) cr1 = (DES.new(key1, DES.MODE_ECB)).encrypt(challenge) cr2 = (DES.new(key2, DES.MODE_ECB)).encrypt(challenge) cr3 = (DES.new(key3, DES.MODE_ECB)).encrypt(challenge) return (cr1 + cr2 + cr3)
def retailMac(self, data): '''Compute the Retail MAC for an APDU''' paddingSize = 8 - ((len(data) / 2) % 8) workData = data + "8000000000000000"[0:paddingSize * 2] des = DES.new(self.toBinaryDES(self.cmacKey[0:16]), DES.MODE_CBC, self.toBinaryDES("0000000000000000")) res = des.encrypt(self.toBinaryDES(workData)) lastBlock = res[len(res) - 8:] des = DES.new(self.toBinaryDES(self.cmacKey[16:32]), DES.MODE_ECB) lastBlock = des.decrypt(lastBlock) des = DES.new(self.toBinaryDES(self.cmacKey[0:16]), DES.MODE_ECB) return self.toHexDES(des.encrypt(lastBlock))
def getPackets(self): # values do not matter at all datakey = "\x96\x03\xc7\xc0\x53\x37\xd2\xf0" firstiv = "\x08\xd9\xcb\xd4\xc1\x5e\xc0\xff" keycrypter = DES.new(self.getKEK(), DES.MODE_ECB) key = keycrypter.encrypt(datakey) datacrypter = DES.new(key, DES.MODE_CBC, firstiv) # to be obtained from http://users.physik.fu-berlin.de/~mkarcher/ATRAC/LP2.wav file = open("/tmp/LP2.wav") file.read(60) data = file.read(testframes*192) return [(datakey,firstiv,datacrypter.encrypt(data))]
def decrypt_single_hash(rid, hbootkey, enc_hash, lmntstr): (des_k1, des_k2) = sid_to_key(rid) d1 = DES.new(des_k1, DES.MODE_ECB) d2 = DES.new(des_k2, DES.MODE_ECB) md5 = MD5.new() md5.update(hbootkey[:0x10] + pack("<L", rid) + lmntstr) rc4_key = md5.digest() rc4 = ARC4.new(rc4_key) obfkey = rc4.encrypt(enc_hash) hash = d1.decrypt(obfkey[:8]) + d2.decrypt(obfkey[8:]) return hash
def calcMAC_1d( self, s, zResetICV = False ): " Pad string and calculate MAC according to B.1.2.2 - " +\ "Single DES plus final 3DES """ e = DES.new( self.ses_C_MAC[:8], DES.MODE_ECB ) d = DES.new( self.ses_C_MAC[8:], DES.MODE_ECB ) s = pad80( s ) q = len( s ) / 8 h = zResetICV and ZERO8 or self.icv for i in xrange(q): h = e.encrypt( bxor( h, s[8*i:8*(i+1)] )) h = d.decrypt( h ) h = e.encrypt( h ) self.icv = ( self.i & M_ICV_ENC ) and self.k_icv.encrypt( h ) or h return h
def try_to_crack_hash(input_hash): if "NETLM" in input_hash: user, remainder = input_hash.split(":") ignore, hash_type, server_challenge, lmhash = remainder.split("$") server_challenge = server_challenge.decode('hex') lmhash = lmhash.decode('hex') for password in dictionary: opassword = password password = password.upper() if len(password) > 14: password = password[:14] password += "\x00" * (14 - len(password)) part_1 = password[:7] d_1 = DES.new(des_7_to_8(part_1), DES.MODE_ECB) part_2 = password[7:] d_2 = DES.new(des_7_to_8(part_2), DES.MODE_ECB) lm = d_1.encrypt("KGS!@#$%") + d_2.encrypt("KGS!@#$%") p_1 = des_7_to_8(lm[:7]) p_2 = des_7_to_8(lm[7:14]) p_3 = des_7_to_8(lm[14:] + "\x00\x00\x00\x00\x00") pd_1 = DES.new(p_1, DES.MODE_ECB) pd_2 = DES.new(p_2, DES.MODE_ECB) pd_3 = DES.new(p_3, DES.MODE_ECB) if pd_1.encrypt(server_challenge) + pd_2.encrypt(server_challenge) + pd_3.encrypt(server_challenge) == \ lmhash: return opassword pass elif "NETNTLM" in input_hash: user, remainder = input_hash.split(":") ignore, hash_type, server_challenge, ntlmhash = remainder.split("$") server_challenge = server_challenge.decode('hex') ntlmhash = ntlmhash.decode('hex') for password in (i.encode('utf-16le') for i in dictionary): lm = hlnew("md4", password).digest() p_1 = des_7_to_8(lm[:7]) p_2 = des_7_to_8(lm[7:14]) p_3 = des_7_to_8(lm[14:] + "\x00\x00\x00\x00\x00") pd_1 = DES.new(p_1, DES.MODE_ECB) pd_2 = DES.new(p_2, DES.MODE_ECB) pd_3 = DES.new(p_3, DES.MODE_ECB) if pd_1.encrypt(server_challenge) + pd_2.encrypt(server_challenge) + pd_3.encrypt(server_challenge) == \ ntlmhash: return password.decode('utf-16le') else: user, ignore, domain, server_challenge, nthash, remainder = input_hash.split(":") user = user.upper().encode('utf-16le') domain = domain.encode('utf-16le') server_challenge = server_challenge.decode('hex') nthash = nthash.decode('hex') remainder = remainder.decode('hex') for password in (i.encode('utf-16le') for i in dictionary): if hmnew(hmnew(hlnew("md4", password).digest(), user + domain).digest(), server_challenge + remainder).digest() == nthash: return password.decode('utf-16le') return None
def findPassword(CCH16, CCR24): # Prepare arguments for processing CCH16 = HexToByte(CCH16) CCR24 = CCR24.replace(':', ' ') CCR24 = CCR24.upper() timer = 0 print "\n--< This may take a while..." print "--< Each dot below represents 10,000 attempted passwords." print "\n--< Cracking", for guess in dictionary: # Track/display timer timer += 1 if timer%10000 == 0: print ".", # Create nt_hash for this guess using MD4 hashing algorithm. guess = guess.strip() # Remove newline ('\n') uGuess = guess.encode('utf-16-le') # Convert to utf-16le nt_hash = MD4.new(uGuess).hexdigest() # Split nt_hash into three DES keys. # Add the parity bits to the DES keys to make them 8-bytes each. des_key_1 = HexToByte(addParity(nt_hash[0:14])) des_key_2 = HexToByte(addParity(nt_hash[14:28])) des_key_3 = HexToByte(addParity(nt_hash[28:] + "0000000000")) # Create DES encryption objects with keys. des_1 = DES.new(des_key_1, DES.MODE_ECB) des_2 = DES.new(des_key_2, DES.MODE_ECB) des_3 = DES.new(des_key_3, DES.MODE_ECB) # Calculate 24-byte Client Challenge Response for this guess # with the DES objects and the 16-byte Client Challenge Hash. ccr24_part1 = des_1.encrypt(CCH16) ccr24_part2 = des_2.encrypt(CCH16) ccr24_part3 = des_3.encrypt(CCH16) ccr24_guess = ByteToHex(ccr24_part1 + ccr24_part2 + ccr24_part3) #print " ccr24 --> ", ccr24_guess #DEBUG #print "CCR24 -----> ", CCR24, "\n" #DEBUG # Compare the guess (ccr24_guess) with the original (CCR24). if ccr24_guess == CCR24: return guess # If no password found, return None return "FAILED - dictionary exhausted..."
def __decryptHash(self, rid, cryptedHash, constant): # Section 2.2.11.1.1 Encrypting an NT or LM Hash Value with a Specified Key # plus hashedBootKey stuff Key1,Key2 = self.__cryptoCommon.deriveKey(rid) Crypt1 = DES.new(Key1, DES.MODE_ECB) Crypt2 = DES.new(Key2, DES.MODE_ECB) rc4Key = self.MD5( self.__hashedBootKey[:0x10] + pack("<L",rid) + constant ) rc4 = ARC4.new(rc4Key) key = rc4.encrypt(cryptedHash) decryptedHash = Crypt1.decrypt(key[:8]) + Crypt2.decrypt(key[8:]) return decryptedHash
def keysFinder(games, queue): chars = range(48, 58, 2) + range(97, 123,2); keys = []; for game in games: found = False; bingame = binascii.unhexlify(game); for i in chars: for j in chars: for k in chars: for l in chars: key = chr(i)+chr(j)+chr(k)+chr(l); x = DES.new(key+'0000'); dec = x.decrypt(bingame); # If it starts with Key= search for Puzzle if (dec[:4] == 'Key='): if (dec.count('Puzzle')>0): found = True; splitted = dec.split(' & '); puzzlekey = splitted[0].split('=')[1]; keys += [puzzlekey]; if found: break; if found: break; if found: break; if not found: raise BaseException("Key not found"); # Put found keys in the queue queue.put(keys);
def rafraichir( self ): self.afficher( u"Récupération de la liste des émissions..." ) # On remet a 0 la liste des fichiers self.listeFichiers.clear() # On recupere la page qui contient les donnees chiffrees pageEmissionsChiffree = self.API.getPage( "http://www.m6replay.fr/catalogue/catalogueWeb3.xml" ) # # N.B. : La page http://www.m6replay.fr/catalogue/catalogueWeb4.xml semble contenir # des videos non presentent sur le site... # Il faudrait voir ce qu'il en retourne (pourquoi ne sont-elles pas sur le site ? les liens fonctionnent-ils ?) # # Classe pour dechiffrer la page decryptor = DES.new( "ElFsg.Ot", DES.MODE_ECB ) # Page des emissions dechiffree pageEmissions = decryptor.decrypt( base64.decodestring( pageEmissionsChiffree ) ) # On cherche la fin du fichier XML finXML = pageEmissions.find( "</template_exchange_WEB>" ) + len( "</template_exchange_WEB>" ) # On enleve ce qui est apres la fin du fichier XML pageEmissions = pageEmissions[ : finXML ] # Handler handler = M6ReplayHandler( self.listeFichiers ) # On parse le fichier xml xml.sax.parseString( pageEmissions, handler ) self.sauvegarderCache( self.listeFichiers ) self.afficher( "Fichier sauvegarde" )
def transform(self, dt_input, dt_key1=None, dt_key2=None, dt_iv=None, dt_mode='dec'): '''Return DES transformed output''' des = DES.new(str(dt_key1), DES.MODE_ECB) if dt_mode == 'dec': return des.decrypt(str(dt_input)) else: return des.encrypt(str(dt_input))
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 decToken(cls,token,skey): re={} try: token=token.replace(" ","+") to = base64.b64decode(token) #to = to.decode('uft-8') #logging.info('decToken type') #logging.info(str(type(to))) if len(token)%8>0: token = token + ' '*(8-len(token)%8) if len(skey)%8>0: skey = skey + ' '*(8-len(skey)%8) obj = DES.new(skey,DES.MODE_ECB) to=obj.decrypt(to) #to=to.decode('utf-8') to=to.split("||") if to[0]: re['auID']=int(to[0]) else: re['auID']=0 re['udid']=to[1] re['flag']=to[2] re['lang']=to[3] re['nick']=to[4] re['email']=to[5] re['platform']=to[6] re['createTime']=to[7] except Exception, e: return re
def bits_decrypt(bits, password, ngoodbits): from Crypto.Cipher import DES obj = DES.new(password, DES.MODE_ECB) # convert to string cypher = bits2string(bits) # decrypt plain = obj.decrypt(cypher) # print('d:Plain (padded): %r' % plain) # extra stuff ngood_bytes = nbytes_to_hold(ngoodbits) nextra_bytes = len(plain) - ngood_bytes # print('d:removing %d pad chars' % nextra_bytes) extra_chars = plain[-nextra_bytes:] assert len(extra_chars) == nextra_bytes if extra_chars != PAD_CHAR * nextra_bytes: msg = ( "While decrypting, obtained plain %r of len %d. " "I'm looking for %d bits, " "which takes %d bytes, giving %d extra bytes. The extra " "stuff is %r, which is not all %r." % (plain, len(plain), ngoodbits, ngood_bytes, nextra_bytes, extra_chars, PAD_CHAR) ) raise ValueError(msg) interesting_chars = plain[:-nextra_bytes] interesting_bits = string2bits(interesting_chars) goodbits = interesting_bits[:ngoodbits] return np.array(goodbits)
def DES_celler(message, key, *args, **kwargs): """DES test celler block size 8 bytes key size 8 bytes """ from Crypto.Cipher import DES from Crypto import Random bsize = DES.block_size ksize = DES.key_size if debug: print ( "Cipher: DES\n" + "Block Size: {0}\n" "Key Size: {1}\n" "Mode: {2}\n" ).format(bsize, ksize, 'ECB') iv = Random.new().read(bsize) des = DES.new(key, DES.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 encrypt(pwd): obj = DES.new('abcdefgh', DES.MODE_ECB) if len(pwd) % 8 != 0: # will have to pad to next multiple of 8 newLen = ((len(pwd)/8) + 1) * 8 pads = newLen - len(pwd) return (obj.encrypt(pwd + 'X'*pads), pads)
def spremi(self): if uiGeneriraj.comboBox.currentIndex()== 0: uiGeneriraj.labelIspis.clear() uiGeneriraj.labelIspis.setText(QtGui.QApplication.translate("FormGeneriraj", "<html><head/><body><p><span style=\" color:#006400;\">Uspješno generiran </span></p><p><span style=\" color:#ff0000;\">simetrični ključ</span></p></body></html>", None, QtGui.QApplication.UnicodeUTF8)) sifra = "".join( [random.choice(string.digits+string.letters) for i in xrange(8)] ) obj = DES.new(sifra, DES.MODE_ECB) writeTajniKljuc=open('tajni_kljuc.txt','w') writeTajniKljuc.write(sifra) writeTajniKljuc.close() else: uiGeneriraj.labelIspis.clear() uiGeneriraj.labelIspis.setText(QtGui.QApplication.translate("FormGeneriraj", "<html><head/><body><p><span style=\" color:#006400;\">Uspješno generirani </span></p><p><span style=\" color:#ff0000;\">asimetrični ključevi</span></p></body></html>", None, QtGui.QApplication.UnicodeUTF8)) random_generator = Random.new().read key = RSA.generate(1024, random_generator) publicKey = key.publickey() writePrivatniKljuc=open('privatni_kljuc.txt','w') writePrivatniKljuc.write(key.exportKey('PEM')) writePrivatniKljuc.close() writeJavniKljuc=open('javni_kljuc.txt','w') writeJavniKljuc.write(publicKey.exportKey('PEM')) writeJavniKljuc.close()
def decryptData(self, decryptKey, privParameters, encryptedData): if DES is None: raise error.StatusInformation( errorIndication=errind.decryptionError ) snmpEngineBoots, snmpEngineTime, salt = privParameters # 8.3.2.1 if len(salt) != 8: raise error.StatusInformation( errorIndication=errind.decryptionError ) # 8.3.2.2 noop # 8.3.2.3 desKey, iv = self.__getDecryptionKey(decryptKey, salt) # 8.3.2.4 -> 8.1.1.3 if len(encryptedData) % 8 != 0: raise error.StatusInformation( errorIndication=errind.decryptionError ) desObj = DES.new(desKey, DES.MODE_CBC, iv) # 8.3.2.6 return desObj.decrypt(encryptedData.asOctets())
def rafraichir( self ): logger.debug( "récupération de la liste des chaines, des émissions et des fichiers" ) # Remet a 0 la liste des fichiers self.listeFichiers.clear() # Recupere la page qui contient les infos sur M6 pageInfos = self.getPage( self.urlInfosXML ) # Extrait l'URL du catalogue try : urlCatalogue = re.findall( "http://www.m6replay.fr/catalogue/\w+.xml", pageInfos )[ 0 ] print urlCatalogue except: logger.error( "impossible de recuperer l'URL du catalogue" ) return # Recupere le catalogue chiffre catalogue = self.getPage( urlCatalogue ) # Classe pour dechiffrer le catalogue decryptor = DES.new( "ElFsg.Ot", DES.MODE_ECB ) # Page des emissions (catalogue dechiffre) pageEmissions = decryptor.decrypt( base64.decodestring( catalogue ) ) # Cherche la fin du fichier XML finXML = pageEmissions.find( "</template_exchange_WEB>" ) + len( "</template_exchange_WEB>" ) # Enleve ce qui est apres la fin du fichier XML pageEmissions = pageEmissions[ : finXML ] # Handler handler = M6ReplayHandler( self.listeFichiers ) # Parse le fichier xml try : xml.sax.parseString( pageEmissions, handler ) except: logger.error( "impossible de parser le fichier XML" ) return # Sauvegarde la liste dans le cache self.sauvegarderCache( self.listeFichiers ) logger.debug( "liste des programmes sauvegardée" )
def decrypt(self, ct): ct = ct.decode("hex") # Extract iv from ciphertext iv = ct[:BS] ct = ct[BS:] cipher = DES.new(self.key, DES.MODE_CFB, iv) return unpad(cipher.decrypt(ct))
def des_ofb_encrypt(m, k, iv=b'\x00' * 8, blocksize=8, padding="PKCS7"): m = pad(m, blocksize=blocksize, padding=padding) result = DES.new(k, mode=DES.MODE_OFB, IV=iv).encrypt(m) return result
def _cipher(self): return DES.new(self.key, DES.MODE_CBC, self.iv)
def desEncrypt(input, key): cipher = DES.new(key, DES.MODE_OFB, IV) msg = cipher.encrypt(padInput(input)) # pads input to fulfil block size return msg
def DESencrypt(plain_text, key): cipher = DES.new(key.encode('utf8'), DES.MODE_ECB) cipher_text = cipher.encrypt(pad(plain_text.encode('utf8'), BLOCK_SIZE)) return cipher_text
def Decrypt(self, key, ciphertext): IV = b64decode(key[key.rfind('IV:') + 3:]) key = b64decode(key[4:key.rfind('IV:')]) des = DES.new(key, DES.MODE_CFB, IV) return des.decrypt(ciphertext)
) else: pgp_hexmsg = argv[1] pgp_key = 'Mickey' pgp_msg = bytes.fromhex(pgp_hexmsg) pgp_msgblob = pgpy.PGPMessage.from_blob(pgp_msg) pgp_dec_message = pgp_msgblob.decrypt(pgp_key) #print(pgp_dec_message.message.__class__.__name__) if isinstance(pgp_dec_message.message, str): print("PGP Decrypted Message: " + pgp_dec_message.message) if isBase64(pgp_dec_message.message): des_key = b'APMEXTPR' des_msg = b64decode(pgp_dec_message.message) des_cipher = DES.new(des_key, DES.MODE_ECB) plaintext = des_cipher.decrypt(des_msg) padding = plaintext[-1] print("DES Decrypted Message: " + plaintext[:-padding].decode()) else: print("PGP Deccrypted Message (hex): ") print(''.join(format(x, '02x') for x in pgp_dec_message.message)) try: s = pgp_dec_message.message.decode('utf-8') print("PGP Decrypted Message:") print("######## PGP DECRYPTED MESSAGE ########") print(s) print("######## PGP DECRYPTED MESSAGE END ########") except Exception: print("Failed to decode the hex")
def decrypt(msg, key): des_cipher = DES.new(key, DES.MODE_CBC, key) plaintext = remove_padding((des_cipher.decrypt(msg)).decode('utf8')) return plaintext
def encrypt(plain_text, key, mode): enc_obj = DES.new(key, mode) return enc_obj.encrypt(plain_text)
# -*- coding:utf8 -*- from Crypto.Cipher import DES from Crypto.Cipher import DES3 key = 'TMPAY888' key1 = 'TMPAY8888' vector = key msg = '123456' answer = '831D0C85791F1BCC' print answer E = DES.new(key, DES.MODE_CFB, vector) out = E.encrypt(msg) print out out = out.encode('hex_codec') print out out = out.encode('base64') print out E = DES.new(key, DES.MODE_OPENPGP, vector) out = E.encrypt(msg) print out out = out.encode('hex_codec') print out out = out.encode('base64') print out E = DES.new(key, DES.MODE_OFB, vector) out = E.encrypt(msg) print out
def decode_des(data,key,IV): m = DES.new(key,DES.MODE_CBC,IV) cipher = base64.b64decode(data) results = m.decrypt(cipher) return results
''' from Crypto.Cipher import DES from scapy.all import * import binascii # Leemos el pcap pcap = rdpcap("exfiltracion_111abda47b950e6cd474a43583372c4f.pcapng") # Sacamos la key que se deduce de la dirección ipv6 origen key = pcap[1][IPv6].src key = key.split(':') # Necesitamos padding para la key c73f1db9a244aff != c73f1db9a2044aff for i in xrange(len(key)): if len(key[i])==1: key[i] = str("0" + key[i]) ckey = ''.join(key) # Sacamos los paquetes ordenando por puerto UDP origen hexdata='' for packet in sorted(pcap, key= lambda x:x[UDP].sport,reverse=False): hexdata += ''.join((packet[DNSQR].qname).replace('.des','').replace('.','')) # Pasamos los datos para descifrarlos con des ecb hexdata_to_binary = binascii.unhexlify(hexdata) key = binascii.unhexlify(ckey) des = DES.new(key, DES.MODE_ECB) flag_text = des.decrypt(hexdata_to_binary) print "#"*100 print flag_text print "#"*100
bs = Blowfish.block_size key = b'An arbitrarily long key' iv = Random.new().read(bs) ##Warn: B304 cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv) plaintext = b'docendo discimus ' plen = bs - divmod(len(plaintext), bs)[1] padding = [plen] * plen padding = pack('b' * plen, *padding) msg = iv + cipher.encrypt(plaintext + padding) key = b'-8B key-' nonce = Random.new().read(DES.block_size / 2) ctr = Counter.new(DES.block_size * 8 / 2, prefix=nonce) ##Warn: B304 cipher = DES.new(key, DES.MODE_CTR, counter=ctr) plaintext = b'We are no longer the knights who say ni!' msg = nonce + cipher.encrypt(plaintext) key = b'Super secret key' ##Warn: B304 cipher = XOR.new(key) plaintext = b'Encrypt me' msg = cipher.encrypt(plaintext) ##Warn: B304 cipher = Cipher(algorithms.ARC4(key), mode=None, backend=default_backend()) encryptor = cipher.encryptor() ct = encryptor.update(b"a secret message") ##Warn: B304
padding = pack('b'*plen, *padding) bs = pycrypto_blowfish.block_size # ruleid:insecure-cipher-algorithm-blowfish cipher = pycrypto_blowfish.new(key, pycrypto_blowfish.MODE_CBC, iv) msg = iv + cipher.encrypt(plaintext + padding) bs = pycryptodomex_blowfish.block_size # ruleid:insecure-cipher-algorithm-blowfish cipher = pycryptodomex_blowfish.new(key, pycryptodomex_blowfish.MODE_CBC, iv) msg = iv + cipher.encrypt(plaintext + padding) key = b'-8B key-' plaintext = b'We are no longer the knights who say ni!' nonce = Random.new().read(pycrypto_des.block_size/2) ctr = Counter.new(pycrypto_des.block_size*8/2, prefix=nonce) # ruleid:insecure-cipher-algorithm-des cipher = pycrypto_des.new(key, pycrypto_des.MODE_CTR, counter=ctr) msg = nonce + cipher.encrypt(plaintext) nonce = Random.new().read(pycryptodomex_des.block_size/2) ctr = Counter.new(pycryptodomex_des.block_size*8/2, prefix=nonce) # ruleid:insecure-cipher-algorithm-des cipher = pycryptodomex_des.new(key, pycryptodomex_des.MODE_CTR, counter=ctr) msg = nonce + cipher.encrypt(plaintext) key = b'Super secret key' plaintext = b'Encrypt me' # ruleid:insecure-cipher-algorithm-xor cipher = pycrypto_xor.new(key) msg = cipher.encrypt(plaintext) # ruleid:insecure-cipher-algorithm-xor cipher = pycryptodomex_xor.new(key) msg = cipher.encrypt(plaintext)
def do_des(key, chl): key = key56_to_key64(key) obj = DES.new(key) return obj.encrypt(chl)
def des_decrypt(ciphers, key): plaintext = [] key = DES.new(key, DES.MODE_ECB) for cipher in ciphers: plaintext.append(key.decrypt(cipher)) return plaintext
def decrypt_des(key, data): iv = key cipher = DES.new(key, DES.MODE_CBC, iv) return cipher.decrypt(data)
def decryption(self): #decrypt the file with the key and des and return the decrypt text des = DES.new(self.pasword, DES.MODE_ECB) decrypt_text = des.decrypt(self.data) return decrypt_text
def desEncrypt(input, key): cipher = DES.new(key, DES.MODE_OFB, IV) msg = cipher.encrypt(padInput(input)) return msg
def DecryptHashFromSamDomainAccount(syskey, rid, F, V, password_type='NT'): ''' syskey: must be returned by ExtractSysKey() rid: the RID of the user (e.g. 500 for Administrator) F: the value of "SAM\Domains\Account\F" (user independant) V: the value of "SAM\Domains\Account\$RID\V" (user dependant) Returns the encrypted hash ('NT' or 'LM') for a specific user (rid) ''' # First let's check the parameters if len(syskey) != 16: logging.error('Invalid parameters: syskey must be 16 bytes long.') return (-1, None) if password_type not in ['NT', 'LM']: logging.error('Invalid parameters: password_type must either be NT or LM.') return (-2, None) if len(F) < 0xa0: logging.error('Invalid parameters: F is not long enough.') return (-3, None) # We need to extract two pieces f1 = F[0x70:0x80] f2 = F[0x80:0xA0] # Depending on the type of password required, let's compute some parameters if password_type == 'LM': password_str = "LMPASSWORD\0" else: password_str = "NTPASSWORD\0" rc4_key = MD5.new(f1 + ascii_str + syskey + numeric_str).digest() bootkey = ARC4.new(rc4_key).encrypt(f2) ''' Open 'SAM\Domains\Account\Users' For each 'SAM\Domains\Account\Users\$RID (ie $RID != 'Names') do + READ V[0xa0] if it is 20 then READ offset = V[0x9c:0xa0] (4 bytes) + READ ENC_LM = V[offset+4:offset+20] (16 bytes) + READ V[0xac] if it is 20 then READ offset (if necessary) and EITHER READ ENC_NTLM = V[offset+24:offset+24+16] IF there is an LM stored OR READ ENC_NTLM = V[offset+8:offset+8+16] IF there is no LM stored done ''' try: LMisAvailable = (V[0xa0] == '\x14') NTisAvailable = (V[0xac] == '\x14') hash_offset = struct.unpack("<L", V[0x9c:0xa0])[0] + 0xCC except: logging.error('V buffer is too short to be valid.') return (-4, None) logging.debug('LMisAvailable = %s, NTisAvailable = %s' % (LMisAvailable,NTisAvailable)) if not LMisAvailable and not NTisAvailable: logging.debug('No hash to extract within this buffer.') return (0, '') if password_type == 'NT': if not NTisAvailable: logging.debug('No NT hash to extract within this buffer.') return (0, '') if LMisAvailable: hash_offset += 24 else: hash_offset += 8 else: if not LMisAvailable: logging.debug('No LM hash to extract within this buffer.') return (0, '') hash_offset += 8 # Extract the encrypted hash. encrypted_hash = V[hash_offset:hash_offset+16].encode('hex') logging.debug('Encrypted hash is %s' % encrypted_hash) #Perform the final decryption of the hash (des_k1,des_k2) = rid_to_key(rid) d1 = DES.new(des_k1, DES.MODE_ECB) d2 = DES.new(des_k2, DES.MODE_ECB) md5 = MD5.new() md5.update(bootkey[:0x10] + struct.pack("<L",rid) + password_str) rc4_key = md5.digest() rc4 = ARC4.new(rc4_key) obfkey = rc4.encrypt(encrypted_hash.decode('hex')) h = d1.decrypt(obfkey[:8]) + d2.decrypt(obfkey[8:]) return (0, h)
def DESdecrypt(cipher_text, key): decipher = DES.new(key.encode('utf8'), DES.MODE_ECB) msg_dec = decipher.decrypt(cipher_text) return unpad(msg_dec, BLOCK_SIZE)
#!/usr/python # -*- coding: utf-8 -*- from Crypto.Cipher import DES from Crypto import Random des = DES.new('01234567', DES.MODE_ECB) text = 'PYCONES_____2015' #cipher dechiper with DES mode ECB cipher_text = des.encrypt(text) print('Cipher_text' + cipher_text) decipher_text = des.decrypt(cipher_text) print('Decipher_text' + decipher_text) #cipher dechiper with DES mode ECB with random iv iv = Random.get_random_bytes(8) des1 = DES.new('01234567', DES.MODE_ECB, iv) cipher_text = des1.encrypt(text) print('Cipher_text' + cipher_text) decipher_text = des1.decrypt(cipher_text) print('Decipher_text' + decipher_text)
from Crypto.Cipher import DES, DES3, ARC2, ARC4, Blowfish, AES from Crypto.Random import get_random_bytes key = b'-8B key-' DES.new( key, DES.MODE_OFB ) # Noncompliant: DES works with 56-bit keys allow attacks via exhaustive search key = DES3.adjust_key_parity(get_random_bytes(24)) cipher = DES3.new( key, DES3.MODE_CFB ) # Noncompliant: Triple DES is vulnerable to meet-in-the-middle attack key = b'Sixteen byte key' cipher = ARC2.new( key, ARC2.MODE_CFB) # Noncompliant: RC2 is vulnerable to a related-key attack key = b'Very long and confidential key' cipher = ARC4.new( key ) # Noncompliant: vulnerable to several attacks (see https://en.wikipedia.org/wiki/RC4#Security) key = b'An arbitrarily long key' cipher = Blowfish.new( key, Blowfish.MODE_CBC ) # Noncompliant: Blowfish use a 64-bit block size makes it vulnerable to birthday attacks
#! /usr/bin/env python # -*- coding:utf-8 -*- from Crypto.Util.number import inverse, long_to_bytes import Crypto.Cipher.DES as DES N = eval(open("pubkey").read()) p = N[1022] * 2 - N[1023] q = (N[1023] * inverse(2**1023,p)) % p ciphertext = int(open("encrypted").readline().rstrip()) c = (ciphertext * inverse(q, p)) % p x = "" for i in range(len(N)): s = bin(c)[2:] if c % 2**(i+1): x += "1" w = (N[i] * inverse(q, p)) % p c -= w else: x += "0" message = long_to_bytes(int(x,2)) KEY = "testpass" plaintext = DES.new(KEY, DES.MODE_ECB).decrypt(message) print plaintext
def desDecrypt(input, key): cipher = DES.new(key, DES.MODE_OFB, IV) msg = cipher.decrypt(input) return msg
def decrypt(cipher_text, key, mode): enc_obj = DES.new(key, mode) return (enc_obj.decrypt(cipher_text))
def initialDES(key): if (len(key) < 8): raise Exception("The length of keys is not enough") return DES.new(key[0:8])
def write_encrypted(password, filename, plaintext): with open(filename, 'wb') as output: des = DES.new(password.encode('utf-8'), DES.MODE_ECB) ciphertext = des.encrypt(plaintext.encode('utf-8')) output.write(ciphertext)
A, B, sharedSecretKey = getSharedKey() #Recieving ceasar encrypted variables ceasarEncRSAMsg = c.recv(1024) c.send("Ceasar Encrypted RSA Message Recieved") ceasarEncDESKey = c.recv(8) c.send("Ceasar Encrypted DES Key Recieved") ceasarEncPrivateKey = c.recv(1024) c.send("Ceasar Encrypted RSA Message Recieved") c.close() #Decryption of ceasear encrypted variables encRSAMsg = decCeasarCipher(ceasarEncRSAMsg, sharedSecretKey) key = decCeasarCipher(ceasarEncDESKey, sharedSecretKey) encRSAPrivateKey = decCeasarCipher(ceasarEncPrivateKey, sharedSecretKey) des = DES.new(key) #Decryption of encrypted RSA private key using the DES key privateKey = des.decrypt(encRSAPrivateKey) privateKey = RSA.importKey(privateKey) #Decryption of encrypted RSA message using privateKey decrypted = privateKey.decrypt(encRSAMsg) print decrypted
def des_lm_encrypt(k): des = DES.new(k, DES.MODE_ECB) return des.encrypt(DES_CONSTANT)
def decrypt_config(): """ """ des = DES.new( base64.b64decode( _SOURCE ), DES.MODE_ECB) out = json.loads(des.decrypt(open(_CONFIG_FILE, "rb").read())) #out = json.load(open(_CONFIG_FILE, "r")) return out['username'], out['password']