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 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 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 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 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 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 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 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 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 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 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 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 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 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 _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 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 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 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 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 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 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 encrypt(self, str): cryptor = DES.new(self.__key, self.__mode, self.__iv) return self._encode(cryptor.encrypt(self._pad(str)))
from Crypto.Cipher import DES import base64 def pad(s): return s + (8 - len(s) % 8) * chr(8 - len(s) % 8) msg = "The cake is a lie!\n" key = "1337DEADBEEF1664".decode('hex') iv = "0102030405060708".decode('hex') cipher = DES.new(key, DES.MODE_CBC, iv) print base64.encodestring(cipher.encrypt(pad(msg)))
#------------------------------------------------------------------------------- #Name: Greg Self #Project: DES Encrytion and Decrytion #Description- This is a program that demonstrates how DES is executed in python. #The user is able to enter in a piece of text and it is encrypted #The encrypted text is printed first #Followed by the decrypted text # Please Note to run this program you must install Crypto.Cipher Library #------------------------------------------------------------------------------- from Crypto.Cipher import DES storeDES = DES.new('12345678', DES.MODE_ECB) text = raw_input("Enter a message to be enctypted:") #finding length of input store=len(text) #logic for offset #total slots to fill is 8, will be filled with blank spaces as fillers offset=store % 8 filler=8-offset #newtext = text if offset!= 0: i=0 while i<filler: text=text+str(" ") i=i+1 cipher_text = storeDES.encrypt(text) print("This is the cipher text:") print(cipher_text) storeDES.decrypt(cipher_text)
def descypt(self, s): # 解密 cipherX = DES.new(self.key, DES.MODE_CBC) bytedt = base64.b64decode(s) y = cipherX.decrypt(bytedt) return str(y, 'UTF-8').strip('\0')
def ds_decrypt_single_hash(rid, enc_hash): (des_k1,des_k2) = sid_to_key(rid) d1 = DES.new(des_k1, DES.MODE_ECB) d2 = DES.new(des_k2, DES.MODE_ECB) hash = d1.decrypt(enc_hash[:8]) + d2.decrypt(enc_hash[8:]) return hash
def des_decode(self, des_str): if self.mode == DES.MODE_ECB: obj = DES.new(self.key, self.mode) else: obj = DES.new(self.key, self.mode, self.iv) return self.unpad(obj.decrypt(des_str).decode('utf8', errors='ignore'))
fps_holder = pygame.time.Clock() game_menu = (pygame.image.load('data/pictures/game_menu_s.png'), pygame.image.load('data/pictures/game_menu_u.png'), pygame.image.load('data/pictures/game_menu_i.png'), pygame.image.load('data/pictures/game_menu_k.png'), pygame.image.load('data/pictures/game_menu_z.png')) pictures = { '1tree1': pygame.image.load('data/pictures/1tree1.png'), 'tree1': pygame.image.load('data/pictures/tree1.png'), '1tree2': pygame.image.load('data/pictures/1tree2.png'), 'tree2': pygame.image.load('data/pictures/tree2.png') } save_meta = b'ru74Atbb' save_meta1 = DES.new(save_meta, DES.MODE_ECB) del save_meta # пока так x_hero = 700 y_hero = 500 map_number = [0, 0] sound_button = False music_button = False camera_mode = 0 # цикл главное меню while menu_flag: window.blit(menu_back, (0, 0)) # фон # обработка событий for event in pygame.event.get():
def super_encryption(plaintext, key): ct = "" cipher = DES.new(key) for a_letter in plaintext: ct += cipher.encrypt(a_letter * 8) return ct
plaintext = b'docendo discimus ' plen = bs - divmod(len(plaintext),bs)[1] padding = [plen]*plen padding = pack('b'*plen, *padding) bs = pycrypto_blowfish.block_size cipher = pycrypto_blowfish.new(key, pycrypto_blowfish.MODE_CBC, iv) msg = iv + cipher.encrypt(plaintext + padding) bs = pycryptodomex_blowfish.block_size 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) 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) 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' cipher = pycrypto_xor.new(key) msg = cipher.encrypt(plaintext) cipher = pycryptodomex_xor.new(key) msg = cipher.encrypt(plaintext) cipher = Cipher(algorithms.ARC4(key), mode=None, backend=default_backend()) encryptor = cipher.encryptor()
def __init__(self): self._des = DES.new('afh9Adas')
def crypt_data(file_data, des_key, is_string=False): if is_string: file_data = file_data.encode('utf-8') return DES.new(des_key, DES.MODE_ECB).encrypt(pad_pkcs5(file_data))
def des_encode(self, messages): if self.mode == DES.MODE_ECB: obj = DES.new(self.key, self.mode) else: obj = DES.new(self.key, self.mode, self.iv) return obj.encrypt(self.pad(messages))
def decrypt(ciphertext,key,mode): encobj = DES.new(key,mode) return encobj.decrypt(ciphertext)
def get_clear_pin_block(self, pinblock): key = DES.new(bytes.fromhex(self.decrypt_workingkey())) pin_block = key.decrypt(bytes.fromhex(pinblock)) return pin_block.hex()
def enc(plaintext, key): cipher = DES.new(key, DES.MODE_ECB) return base64.b64encode(cipher.encrypt(plaintext))
block = decrypted if i == 0: intermediate = xor64d(block, IV) else: intermediate = xor64d(block, shared_data[offset - block_size:offset]) output_data[offset:offset + block_size] = intermediate if __name__ == "__main__": plain_text = "alamakot" * 10000 key = "haslo123" IV = get_random_bytes(8) block_size = 8 no_blocks = len(plain_text) // block_size start = time.time() encryptedCBC = encrypt_CBC_serial(key, plain_text) print('CBC Encrypt time serial: ', (time.time() - start)) des = DES.new(key, IV=IV) shared_data = mp.RawArray(ctypes.c_ubyte, encryptedCBC) output_data = mp.RawArray(ctypes.c_ubyte, encryptedCBC) pool = mp.Pool(8) start = time.time() pool.map(de_mapper, range(no_blocks)) print('CBC Decrypt time para: ', time.time() - start) print(bytes(output_data))
from itertools import product from Crypto.Cipher import DES key = string.digits key = [key[i] for i in range(0, len(key), 2)] # print(list(map(ord, list(key)))) for iter_key in product(key, repeat=8): des = DES.new(''.join(iter_key), DES.MODE_ECB) ciphertext = bytes.fromhex(message_hex) plaintext = des.decrypt(ciphertext) if plaintext.decode() == message: print( DES.new(''.join(iter_key), DES.MODE_ECB).decrypt(bytes.fromhex(flag))) break
print("----------------------") print(enc1.rstrip(',')) if ((len(shellcode)/8)==0): print("boo no padding is required") else: padding = 8 * ((len(shellcode)/8)+1) - len(shellcode) shellcode = shellcode + "\x90"*padding print("Padding needed , appended "+str(padding)+""" \\x90 bytes""") print(len(shellcode)) cipher = DES.new("aaaaaaaa") encrypted_data = cipher.encrypt(shellcode) enc2 = "" output= "" for i in bytearray(encrypted_data): enc2+="0x" enc2+= "%02x," %(i & 0xff) output += "\\x" output += '%02x'% i print("Encrypted Shellcode") print("----------------------") print(enc2.rstrip(','))
def encrypt(self, plain_text): plain_text = self.__pad(plain_text) iv = Random.new().read(self.block_size) cipher = DES.new(self.key, DES.MODE_CBC, iv) encrypted_text = cipher.encrypt(plain_text.encode()) return b64encode(iv + encrypted_text).decode("utf-8")
def brute_force_des(cryptogram: bytes, key_alphabet=range(256)) -> None: entropy_threshold = 0.965 possible_keys = product(key_alphabet, repeat=8) for k in possible_keys: k = codes_to_str(k) des = DES.new(k, DES.MODE_ECB) recovered = des.decrypt(cryptogram) e = entropy(recovered) if e < entropy_threshold: print('\nZnaleziono rozwiązanie!\n') print(f'Klucz: {k}') print(f'Wiadomość: {recovered}') return print(f'Nie znaleziono rozwiązania') if __name__ == "__main__": key = 'abcabdbb' data = padd_data(poem.encode(), 8) des = DES.new(key, DES.MODE_ECB) cryptogram = des.encrypt(data) keyAlphabet = list(range(ord('a'), ord('e') + 1)) # bruteforceDES(cryptogram, keyAlphabet)
def DES_decrypt(cipher, key, iv): block_size = DES.block_size d = DES.new(key, DES.MODE_CBC, iv) return d.decrypt(cipher).decode('ascii')
def auth(self, auth_type, password=None): major, minor = int(self.version[6]), int(self.version[10]) if auth_type == "None": if major == 4 or (major == 3 and minor >= 8): self.sock.sendall(b"\x01") self.authenticated = True elif major == 3 and minor == 7: self.sock.sendall(b"\x01") self.authenticated = True return 0, 'OK' else: self.authenticated = True return 0, 'OK' elif auth_type == "VNC Authentication": if major == 4 or (major == 3 and minor >= 7): self.sock.sendall(b"\x02") challenge = self.sock.recv(16) if len(challenge) != 16: raise VNCException("Wrong challenge length") logging.debug('challenge: %s' % challenge) password = password.ljust(8, '\x00')[:8] # make sure it is 8 chars long, zero padded key = self.gen_key(password) logging.debug('key: %s' % key) des = DES.new(key, DES.MODE_ECB) enc = des.encrypt(challenge) logging.debug('enc: %s' % enc) self.sock.sendall(enc) resp = self.sock.recv(4) logging.debug('resp: %s' % repr(resp)) response_code = ord(resp[3:4]) mesg = resp[8:].decode('ascii', 'ignore') if response_code == 0: self.authenticated = True return response_code, 'OK' else: if major == 4 or (major == 3 and minor >= 8): resp = self.sock.recv(4) msg_len = int.from_bytes(resp, byteorder="big") resp = self.sock.recv(msg_len) msg = resp.decode("utf-8") return response_code, msg else: if response_code == 1: return response_code, "failed" elif response_code == 2: return response_code, "failed, too many attempts" else: raise VNCException('Unknown response: %d' % (code))
def des_decrypt(ciphertext, key): byteKey = str.encode(key) des = DES.new(byteKey, DES.MODE_ECB) plain = des.decrypt(ciphertext).decode() return plain
#!/usr/bin/python3 #DES cipher example #Mostafa Dahshan <https://github.com/mdahshan> #References #https://stackoverflow.com/questions/12524994/encrypt-decrypt-using-pycrypto-aes-256 #https://stackoverflow.com/questions/6624453/whats-the-correct-way-to-convert-bytes-to-a-hex-string-in-python-3 from Crypto.Cipher import DES key = bytes.fromhex('0102030405060708') cipher = DES.new(key, DES.MODE_ECB) x = bytes.fromhex('000102030405060708090A0B0C0D0E0F') y = cipher.encrypt(x) z = cipher.decrypt(y) print(z.hex())
import csv, sys from Crypto.Cipher import DES import MySQLdb as mdb import sys import urllib2 import urllib import os import subprocess import time obj = DES.new('abcdefgh', DES.MODE_ECB) #filename = '/home/abdelbar/encryption/csvfile.csv' try: con = mdb.connect('localhost', 'root', '066abde', 'crypt') cur = con.cursor() cur.execute("SELECT VERSION()") ver = cur.fetchone() print "Database version : %s " % ver except mdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit(1) csvfiles = [ os.path.join(root, name) for root, dirs, files in os.walk('/home/abdelbar/encryption/') for name in files if name.endswith((".csv")) ] def criptage(filename):
from Crypto.Cipher import DES import binascii key = open('key').read() iv = '66642069' cipher = DES.new(key, DES.MODE_OFB, iv) plaintext = open('plain.txt').read() msg = iv + cipher.encrypt(plaintext) with open('destiny.enc', 'w') as f: f.write(msg)
def importKey(self, externKey, passphrase=None): """Import an RSA key (public or private half), encoded in standard form. :Parameter externKey: The RSA key to import, encoded as a string. An RSA public key can be in any of the following formats: - X.509 `subjectPublicKeyInfo` DER SEQUENCE (binary or PEM encoding) - `PKCS#1`_ `RSAPublicKey` DER SEQUENCE (binary or PEM encoding) - OpenSSH (textual public key only) An RSA private key can be in any of the following formats: - PKCS#1 `RSAPrivateKey` DER SEQUENCE (binary or PEM encoding) - `PKCS#8`_ `PrivateKeyInfo` DER SEQUENCE (binary or PEM encoding) - OpenSSH (textual public key only) For details about the PEM encoding, see `RFC1421`_/`RFC1423`_. In case of PEM encoding, the private key can be encrypted with DES or 3TDES according to a certain ``pass phrase``. Only OpenSSL-compatible pass phrases are supported. :Type externKey: string :Parameter passphrase: In case of an encrypted PEM key, this is the pass phrase from which the encryption key is derived. :Type passphrase: string :Return: An RSA key object (`_RSAobj`). :Raise ValueError/IndexError/TypeError: When the given key cannot be parsed (possibly because the pass phrase is wrong). .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt .. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt .. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt """ externKey = tobytes(externKey) if passphrase is not None: passphrase = tobytes(passphrase) if externKey.startswith(b('-----')): # This is probably a PEM encoded key lines = externKey.replace(b(" "), b('')).split() keyobj = None # The encrypted PEM format if lines[1].startswith(b('Proc-Type:4,ENCRYPTED')): DEK = lines[2].split(b(':')) if len(DEK) != 2 or DEK[0] != b('DEK-Info') or not passphrase: raise ValueError("PEM encryption format not supported.") algo, salt = DEK[1].split(b(',')) salt = binascii.a2b_hex(salt) import Crypto.Hash.MD5 from Crypto.Cipher import DES, DES3 from Crypto.Protocol.KDF import PBKDF1 if algo == b("DES-CBC"): # This is EVP_BytesToKey in OpenSSL key = PBKDF1(passphrase, salt, 8, 1, Crypto.Hash.MD5) keyobj = DES.new(key, Crypto.Cipher.DES.MODE_CBC, salt) elif algo == b("DES-EDE3-CBC"): # Note that EVP_BytesToKey is note exactly the same as PBKDF1 key = PBKDF1(passphrase, salt, 16, 1, Crypto.Hash.MD5) key += PBKDF1(key + passphrase, salt, 8, 1, Crypto.Hash.MD5) keyobj = DES3.new(key, Crypto.Cipher.DES3.MODE_CBC, salt) else: raise ValueError("Unsupport PEM encryption algorithm.") lines = lines[2:] der = binascii.a2b_base64(b('').join(lines[1:-1])) if keyobj: der = keyobj.decrypt(der) padding = bord(der[-1]) der = der[:-padding] return self._importKeyDER(der) if externKey.startswith(b('ssh-rsa ')): # This is probably an OpenSSH key keystring = binascii.a2b_base64(externKey.split(b(' '))[1]) keyparts = [] while len(keystring) > 4: l = struct.unpack(">I", keystring[:4])[0] keyparts.append(keystring[4:4 + l]) keystring = keystring[4 + l:] e = bytes_to_long(keyparts[1]) n = bytes_to_long(keyparts[2]) return self.construct([n, e]) if bord(externKey[0]) == 0x30: # This is probably a DER encoded key return self._importKeyDER(externKey) raise ValueError("RSA key format is not supported")
from Crypto.Cipher import DES if __name__ == "__main__": key = b"zapatito" iv = b"zapatote" cipher = DES.new(key=key, mode=DES.MODE_CBC, iv=iv) cipher2 = DES.new(key=key, mode=DES.MODE_CBC, iv=iv) with open("tux.bmp", "rb") as image: clear_image = image.read() mod = len(clear_image) % 8 aux = clear_image[64:-mod] encrypted_image = cipher.encrypt(aux) encrypted_image = clear_image[0:64] + encrypted_image + clear_image[-mod:] with open("tux_cbc.bmp", "wb") as new_image: new_image.write(encrypted_image) with open("tux_cbc.bmp", "rb") as image: clear_image = image.read() mod = len(clear_image) % 8 aux = clear_image[64:-mod] encrypted_image = cipher2.decrypt(aux) encrypted_image = clear_image[0:64] + encrypted_image + clear_image[-mod:]
def des_decrypt_transform(data, key, mode, iv): des = DES.new(key, mode, iv) return des.decrypt(data)
def __init__(self, key): from Crypto.Cipher import DES self.des = DES.new(key, DES.MODE_ECB)