def protocol(P, G): a = get_random_key(P) b = get_random_key(P) fake_A = G fake_B = G private_A = get_key(fake_B, a, P) private_B = get_key(fake_A, b, P) def sha(s): return sha1(hex(int(s))).digest()[0:16] AES_A = sha(private_A) msg_A = 'hi, B' cipher_A = aes.encryptData(AES_A, msg_A) AES_M = sha(0) msg_AM = aes.decryptData(AES_M, cipher_A) assert msg_AM == msg_A AES_B = sha(private_B) msg_B = aes.decryptData(AES_B, cipher_A) cipher_B = aes.encryptData(AES_B, msg_B) msg_BM = aes.decryptData(AES_M, cipher_B) assert msg_BM == msg_A assert AES_M == AES_A
def upload_to_dropbox(backupConfig, backupArchive): print("Login to dropbox...") try: try: from dropbox import client, rest, session except ImportError, e: print("Dropbox sdk not found, please download and install the \ latest dropbox sdk from https://www.dropbox.com/developers/reference/sdk" ) raise e sess = session.DropboxSession(backupConfig.dropboxAppKey, backupConfig.dropboxAppSecret, backupConfig.dropboxAccessType) if backupConfig.dropboxAccessToken == gEmptyStr or not backupConfig.dropboxAccessToken: requestToken = sess.obtain_request_token() url = sess.build_authorize_url(requestToken) # Make the user sign in and authorize this token print("url: %s" % url) print( "Please visit this website and press the 'Allow' button, then hit 'Enter' here." ) raw_input() accessToken = sess.obtain_access_token(requestToken) # encrypt access token dropboxAccessTokenAesKey = aes.generateRandomKey(16) accessTokenKey = aes.encryptData(dropboxAccessTokenAesKey, accessToken.key) accessTokenSecret = aes.encryptData(dropboxAccessTokenAesKey, accessToken.secret) backupConfig.configParser.set( backupConfig.DropboxSection, "access_token", "%s:%s:%s" % (accessTokenKey.encode("hex"), accessTokenSecret.encode("hex"), dropboxAccessTokenAesKey.encode("hex"))) client = client.DropboxClient(sess) else: # read access token if not backupConfig.dropboxAccessToken or backupConfig.dropboxAccessToken == gEmptyStr: raise Exception("Cannot read access_token in config file %s" % backupConfig.configPath) accessTokenKey, accessTokenSecret, dropboxAccessTokenAesKey = backupConfig.dropboxAccessToken.split( ":") accessTokenKey = aes.decryptData( binascii.unhexlify(dropboxAccessTokenAesKey), binascii.unhexlify(accessTokenKey)) accessTokenSecret = aes.decryptData( binascii.unhexlify(dropboxAccessTokenAesKey), binascii.unhexlify(accessTokenSecret)) sess.set_token(accessTokenKey, accessTokenSecret) # init client client = client.DropboxClient(sess) # send backup file with open(backupArchive) as f: print("Upload %s to dropbox..." % (backupArchive)) response = client.put_file( "%s/%s" % (backupConfig.dropboxBackupDir, os.path.basename(allBackupArchive)), f)
def decryptPassword(key,password,method='aes',keyfile=None): if keyfile: key = getKeyFromFile(keyfile,key) if not key: return None password = binascii.unhexlify(password) if method.lower() == 'des': return decryptDes(key,password) elif method.lower() == 'aes': return aes.decryptData(hashlib.md5(key).digest(),password) else: password = aes.decryptData(hashlib.md5(key).digest(),password) return decryptDes(key,password)
def computeEncryptionKey(password, dictOwnerPass, dictUserPass, dictOE, dictUE, fileID, pElement, dictKeyLength = 128, revision = 3, encryptMetadata = False, passwordType = None): ''' Compute an encryption key to encrypt/decrypt the PDF file @param password: The password entered by the user @param dictOwnerPass: The owner password from the standard security handler dictionary @param dictUserPass: The user password from the standard security handler dictionary @param dictOE: The owner encrypted string from the standard security handler dictionary @param dictUE:The user encrypted string from the standard security handler dictionary @param fileID: The /ID element in the trailer dictionary of the PDF file @param pElement: The /P element of the Encryption dictionary @param dictKeyLength: The length of the key @param revision: The algorithm revision @param encryptMetadata: A boolean extracted from the standard security handler dictionary to specify if it's necessary to encrypt the document metadata or not @param passwordType: It specifies the given password type. It can be 'USER', 'OWNER' or None. @return: A tuple (status,statusContent), where statusContent is the encryption key in case status = 0 or an error message in case status = -1 ''' try: if revision != 5: keyLength = dictKeyLength/8 lenPass = len(password) if lenPass > 32: password = password[:32] elif lenPass < 32: password += paddingString[:32-lenPass] md5input = password + dictOwnerPass + struct.pack('<i',int(pElement)) + fileID if revision > 3 and not encryptMetadata: md5input += '\xFF'*4 key = hashlib.md5(md5input).digest() if revision > 2: counter = 0 while counter < 50: key = hashlib.md5(key[:keyLength]).digest() counter += 1 key = key[:keyLength] elif revision == 2: key = key[:5] return (0, key) else: if passwordType == 'USER': password = password.encode('utf-8')[:127] kSalt = dictUserPass[40:48] intermediateKey = hashlib.sha256(password + kSalt).digest() ret = aes.decryptData('\0'*16+dictUE, intermediateKey) elif passwordType == 'OWNER': password = password.encode('utf-8')[:127] kSalt = dictOwnerPass[40:48] intermediateKey = hashlib.sha256(password + kSalt + dictUserPass).digest() ret = aes.decryptData('\0'*16+dictOE, intermediateKey) return ret except: return (-1, 'ComputeEncryptionKey error: %s %s' % (str(sys.exc_info()[0]),str(sys.exc_info()[1])))
def loadPrivAndg(self, pwd): f = open('keys/priv.key', 'r') priv = eval(aes.decryptData(pwd, base64.b64decode(f.read().strip()))) f.close() f = open('keys/g.txt', 'r') g = eval(aes.decryptData(pwd, base64.b64decode(f.read().strip()))) f.close() if self.pub == None: self.pub = self.loadPubKey() params = eval(base64.b64decode(self.pub).split('|')[1]) self.priv = priv self.g = g self.params = params pwd = '0' * len(pwd)
def computeEncryptionKey(password, dictOwnerPass, dictUserPass, dictOE, dictUE, fileID, pElement, dictKeyLength = 128, revision = 3, encryptMetadata = False, passwordType = None): ''' Compute an encryption key to encrypt/decrypt the PDF file @param password: The password entered by the user @param dictOwnerPass: The owner password from the standard security handler dictionary @param dictUserPass: The user password from the standard security handler dictionary @param dictOE: The owner encrypted string from the standard security handler dictionary @param dictUE:The user encrypted string from the standard security handler dictionary @param fileID: The /ID element in the trailer dictionary of the PDF file @param pElement: The /P element of the Encryption dictionary @param dictKeyLength: The length of the key @param revision: The algorithm revision @param encryptMetadata: A boolean extracted from the standard security handler dictionary to specify if it's necessary to encrypt the document metadata or not @param passwordType: It specifies the given password type. It can be 'USER', 'OWNER' or None. @return: A tuple (status,statusContent), where statusContent is the encryption key in case status = 0 or an error message in case status = -1 ''' if revision != 5: keyLength = dictKeyLength/8 lenPass = len(password) if lenPass > 32: password = password[:32] elif lenPass < 32: password += paddingString[:32-lenPass] md5input = password + dictOwnerPass + struct.pack('<I',abs(int(pElement))) + fileID if revision > 3 and not encryptMetadata: md5input += '\xFF'*4 key = hashlib.md5(md5input).digest() if revision > 2: counter = 0 while counter < 50: key = hashlib.md5(key[:keyLength]).digest() counter += 1 key = key[:keyLength] elif revision == 2: key = key[:5] return (0, key) else: if passwordType == 'USER': password = password.encode('utf-8')[:127] kSalt = dictUserPass[40:48] intermediateKey = hashlib.sha256(password + kSalt).digest() ret = aes.decryptData('\0'*16+dictUE, intermediateKey) elif passwordType == 'OWNER': password = password.encode('utf-8')[:127] kSalt = dictOwnerPass[40:48] intermediateKey = hashlib.sha256(password + kSalt + dictUserPass).digest() ret = aes.decryptData('\0'*16+dictOE, intermediateKey) return ret
def send(): if config.found_convo: #This is here because we don't want another thread to check again if a relay node was found already. return address = config.my_data.find("data", "all")[0]['address'] privatekey = config.my_data.find("data", "all")[0]["privatekey"] privatekey = filter(None, re.findall("[0-9]*", privatekey)) privatekey = PrivateKey(int(privatekey[0]), int(privatekey[1]), int(privatekey[2]), int(privatekey[3]), int(privatekey[4])) sock = socket.socket() sock.connect(find_node()) sock.send(json.dumps({"cmd":"find_convo", "address":address})) config.found_convo = True print "In contact with relay node" while True: data = sock.recv(1024000) if not data: config.found_convo = False break else: data += "\n" data = data.split("\n") for x in data: try: x = json.loads(x) except ValueError: continue from_ = x['from'] message = base64.b64decode(x['message']) message = aes.decryptData(decrypt(base64.b64decode(x['key']), privatekey), message) config.cache.insert("messages", {"from":from_, "message":message, "time":x['time']}) #So that the web ui can then access them config.cache.save()
def get_seed(self, seedarg): path = os.path.join('wallets', seedarg) if not os.path.isfile(path): if get_network() == 'testnet': debug('seedarg interpreted as seed, only available in testnet because this probably has lower entropy') return seedarg else: raise IOError('wallet file not found') #debug('seedarg interpreted as wallet file name') try: import aes except ImportError: print 'You must install slowaes\nTry running: sudo pip install slowaes' sys.exit(0) fd = open(path, 'r') walletfile = fd.read() fd.close() walletdata = json.loads(walletfile) if walletdata['network'] != get_network(): print 'wallet network(%s) does not match joinmarket configured network(%s)' % ( walletdata['network'], get_network()) sys.exit(0) password = getpass.getpass('Enter wallet decryption passphrase: ') password_key = btc.bin_dbl_sha256(password) decrypted_seed = aes.decryptData(password_key, walletdata['encrypted_seed'] .decode('hex')).encode('hex') return decrypted_seed
def read(id, addr): data = db.messages.find("messages", {"to": addr}) my_key = db.data.find("data", "all")[0]["privatekey"] if my_key.startswith("PrivateKey(") and my_key.endswith(")"): my_key = eval(my_key) else: return "You have an invalid key." for x in data: try: aeskey = decrypt(base64.b64decode(x['key']), my_key) if x['id'] == id: msg = """ ID: {0} From: {1} Title: {2} {3} """.format( x['id'], x['from'], x['title'], aes.decryptData(aeskey, base64.b64decode(x['message']))) return msg except KeyError: continue return "Message with that ID doesn't exist"
def decrypt_privkey(encr_privkey, pw): bin_pwhash = bin_hash_password(pw) bin_encr_privkey = encr_privkey.decode('hex') privkey = aes.decryptData(bin_pwhash, bin_encr_privkey) return privkey
def get_seed(self, seedarg): path = os.path.join('wallets', seedarg) if not os.path.isfile(path): if get_network() == 'testnet': debug( 'seedarg interpreted as seed, only available in testnet because this probably has lower entropy' ) return seedarg else: raise IOError('wallet file not found') #debug('seedarg interpreted as wallet file name') try: import aes except ImportError: print 'You must install slowaes\nTry running: sudo pip install slowaes' sys.exit(0) fd = open(path, 'r') walletfile = fd.read() fd.close() walletdata = json.loads(walletfile) if walletdata['network'] != get_network(): print 'wallet network(%s) does not match joinmarket configured network(%s)' % ( walletdata['network'], get_network()) sys.exit(0) password = getpass.getpass('Enter wallet decryption passphrase: ') password_key = btc.bin_dbl_sha256(password) decrypted_seed = aes.decryptData( password_key, walletdata['encrypted_seed'].decode('hex')).encode('hex') return decrypted_seed
def _parse_dropbox(self): self.dropboxAccessToken = self.configParser.get(self.DropboxSection, "access_token") if self.backupWithDropbox != gEmptyStr and self.backupWithDropbox: # get dropbox auth info self.dropboxUser = self.configParser.get(self.DropboxSection, "User") if self.dropboxUser: self.dropboxUser = self.dropboxUser.strip() self.dropboxPassStr = self.configParser.get(self.DropboxSection, "Password") if self.dropboxPassStr: self.dropboxPassStr = self.dropboxPassStr.strip() if not self.dropboxUser or gEmptyStr == self.dropboxUser: self.dropboxUser = raw_input("Your user name for dropbox: ") self.configParser.set(self.DropboxSection, "User", self.dropboxUser) self.dropboxPassStr = "" if not self.dropboxPassStr or self.dropboxPassStr == gEmptyStr: self.dropboxPassStr = getpass.getpass("Your password for dropbox user %s: " % (self.dropboxUser)) self.dropboxPassKey = aes.generateRandomKey(16) # set password with aes encryption tmpPass = aes.encryptData(dropboxPassKey, dropboxPassStr) self.configParser.set(self.DropboxSection, "Password", tmpPass.encode("hex") + gSepChar + self.dropboxPassKey.encode("hex")) # reset access token when username or password changes self.dropboxAccessToken = gEmptyStr else: self.dropboxPass, self.dropboxPassKey = self.dropboxPassStr.split(":") self.dropboxPass = aes.decryptData(binascii.unhexlify(self.dropboxPassKey), binascii.unhexlify(self.dropboxPass)) self.dropboxAppKey = self.configParser.get(self.DropboxSection, "APP_KEY") self.dropboxAppSecret = self.configParser.get(self.DropboxSection, "APP_SECRET") self.dropboxAccessType = "dropbox" self.dropboxBackupDir = self.configParser.get(self.DropboxSection, "target_dir") if not self.dropboxBackupDir: self.dropboxBackupDir = "/" else: self.dropboxBackupDir = self.dropboxBackupDir.rstrip("/")
def read(id, addr): data = db.messages.find("messages", {"to":addr}) my_key = db.data.find("data", "all")[0]["privatekey"] if my_key.startswith("PrivateKey(") and my_key.endswith(")"): my_key = eval(my_key) else: return "You have an invalid key." for x in data: try: aeskey = decrypt(base64.b64decode(x['key']), my_key) if x['id'] == id: msg = """ ID: {0} Time: {4} From: {1} Title: {2} {3} """.format(x['id'], x['from'], x['title'], emoticons.apply_emoticons(aes.decryptData(aeskey, base64.b64decode(x['message']))).encode("utf-8"), x['time']) return msg except KeyError: continue return "Message with that ID doesn't exist"
def getseed(encseed, pw, ethaddr): try: seed = aes.decryptData(pw, encseed.decode('hex')) ethpriv = sha3(seed) assert eth_privtoaddr(ethpriv) == ethaddr except: raise Exception("Decryption failed. Bad password?") return seed
def decryptData(self): self.password = getpass.getpass("Password: "******"rb") as file: try: self.data = aes.decryptData(hashlib.md5(self.password).hexdigest(), file.read()) except: print "Password incorrect" self.decryptData()
def encrypt(file): enc1 = open(file, "r") enc = enc1.read() key = "\xed\xac\xbe\x88<.\xd9H8D\xb2'\x19\xb9IG" ret = aes.decryptData(key, enc, mode=2) f = open(file, "w+") f.write(ret) print("Decrypted: " + file)
def decryptData(self): self.password = getpass.getpass("Password: "******"rb") as file: try: self.data = aes.decryptData( hashlib.md5(self.password).hexdigest(), file.read()) except: print "Password incorrect" self.decryptData()
def decode_privkey(text, password): ''' Decode private key from text. ''' keystring = aes.decryptData(aes_key(password), b64decode(text)) k = keystring.split(":") if not k.pop(0) == "CHECK": print("Incorrect password to decode private key. Exiting.") exit() ks = map(long, k) return rsa.PrivateKey(ks[0], ks[1], ks[2], ks[3], ks[4])
def upload_to_dropbox(backupConfig, backupArchive): print("Login to dropbox...") try: try: from dropbox import client, rest, session except ImportError, e: print("Dropbox sdk not found, please download and install the \ latest dropbox sdk from https://www.dropbox.com/developers/reference/sdk") raise e sess = session.DropboxSession(backupConfig.dropboxAppKey, backupConfig.dropboxAppSecret, backupConfig.dropboxAccessType) if backupConfig.dropboxAccessToken == gEmptyStr or not backupConfig.dropboxAccessToken: requestToken = sess.obtain_request_token() url = sess.build_authorize_url(requestToken) # Make the user sign in and authorize this token print("url: %s" % url) print("Please visit this website and press the 'Allow' button, then hit 'Enter' here.") raw_input() accessToken = sess.obtain_access_token(requestToken) # encrypt access token dropboxAccessTokenAesKey = aes.generateRandomKey(16) accessTokenKey = aes.encryptData(dropboxAccessTokenAesKey, accessToken.key) accessTokenSecret = aes.encryptData(dropboxAccessTokenAesKey, accessToken.secret) backupConfig.configParser.set( backupConfig.DropboxSection, "access_token", "%s:%s:%s" % (accessTokenKey.encode("hex"), accessTokenSecret.encode("hex"), dropboxAccessTokenAesKey.encode("hex"))) client = client.DropboxClient(sess) else: # read access token if not backupConfig.dropboxAccessToken or backupConfig.dropboxAccessToken == gEmptyStr: raise Exception("Cannot read access_token in config file %s" % backupConfig.configPath) accessTokenKey, accessTokenSecret, dropboxAccessTokenAesKey = backupConfig.dropboxAccessToken.split(":") accessTokenKey = aes.decryptData(binascii.unhexlify(dropboxAccessTokenAesKey), binascii.unhexlify(accessTokenKey)) accessTokenSecret = aes.decryptData(binascii.unhexlify(dropboxAccessTokenAesKey), binascii.unhexlify(accessTokenSecret)) sess.set_token(accessTokenKey, accessTokenSecret) # init client client = client.DropboxClient(sess) # send backup file with open(backupArchive) as f: print("Upload %s to dropbox..." % (backupArchive)) response = client.put_file("%s/%s" % (backupConfig.dropboxBackupDir, os.path.basename(allBackupArchive)), f)
def checkAuth(self, username, pwd): aes_key = self.passToAesKey(pwd) sql = self.mysql.where('username', username).select('key').query() key = sql['key'] try: pin = aes.decryptData(aes_key, base64.b64decode(key.strip())) if pin == '1337': return True else: return False except Exception as e: return False
def basic_protocol(p, g): # A->B Send "p", "g", "A" a, A = keygen(p, g) # B->A Send "B" b, B = keygen(p, g) # A->B Send AES-CBC(SHA1(s)[0:16], iv=random(16), msg) + iv s_A = pow(B, a, p) aeskey_A = derivekey(s_A) msg_A = 'hello world' cipher_A = aes.encryptData(aeskey_A, msg_A) # B->A Send AES-CBC(SHA1(s)[0:16], iv=random(16), A's msg) + iv s_B = pow(A, b, p) aeskey_B = derivekey(s_B) msg_B = aes.decryptData(aeskey_B, cipher_A) cipher_B = aes.encryptData(aeskey_B, msg_B) # (A checks B's msg?) check_A = aes.decryptData(aeskey_A, cipher_B) assert msg_A == check_A and msg_B == msg_A
def processtx(txhex): tx = deserialize(txhex) ethaddr = b58check_to_hex(script_to_address(tx['outs'][1]['script'])) data = '' for o in tx['outs'][2:]: data += b58check_to_bin(script_to_address(o['script'])) data = data[1:1 + ord(data[0])] pubkey = data[-33:] shared = multiply(pubkey, our_privkey) email = aes.decryptData(shared[:16], data[:-33]) print "Tx:", h print "Ethereum address:", ethaddr print "Email:", email
def processtx(txhex): tx = deserialize(txhex) ethaddr = b58check_to_hex(script_to_address(tx['outs'][1]['script'])) data = '' for o in tx['outs'][2:]: data += b58check_to_bin(script_to_address(o['script'])) data = data[1:1 + ord(data[0])] pubkey = data[-33:] shared = multiply(pubkey,our_privkey) email = aes.decryptData(shared[:16],data[:-33]) print "Tx:",h print "Ethereum address:",ethaddr print "Email:",email
def resend(self, src, dest): key = src.recv(172) # print "Received this base64 encoded aes key: " + key aeskey = decrypt(base64.b64decode(key), eval(privatekey)) data = src.recv(44) while data: print "Received: " + data uncrypted = aes.decryptData(str(aeskey), base64.b64decode(str(data))) # .encode("utf-8") dest.sendall(uncrypted) data = src.recv(44) src.close() dest.close() print ("Client quit normally\n")
def PYimportEncryptedKeyring(b64_keyring): PYclearKeys() encrypted_keyring = base64.b64decode(b64_keyring) #try legacy method, then new method (old aes module didn't use OpenPGP format) #TODO: eventually remove legacy AES module try: keyring = json.loads(aes.decryptData(window.Parley.currentUser.attributes.passwords.local[0:32],encrypted_keyring)) except: decrypt = gpg.decrypt(encrypted_keyring,passphrase=window.Parley.currentUser.attributes.passwords.local) keyring = json.loads(decrypt.data) gpg.import_keys(keyring['private']) gpg.import_keys(keyring['public']) return True
def login(): pwd = essence.passToAesKey(request.form['password'].strip().replace(u'\xbe', '').replace(u'\x7f', ')')) try: essence.ran = True f = open('keys/priv.key', 'r') priv = eval(aes.decryptData(pwd, base64.b64decode(f.read().strip()))) essence.priv = priv f.close() f = open('00z', 'w+') f.write(pwd) f.close() except Exception as e: print e return render_template('problem.html', problem = 'Incorrect decryption password entered.') return redirect('/me')# pubkey = pub)
def getseed(encseed, pw, ethaddr): try: seed = aes.decryptData(pw, binascii.unhexlify(encseed)) except Exception as e: raise DecryptionException("AES Decryption error. Bad password?") try: ethpriv = sha3(seed) eth_privtoaddr(ethpriv) assert eth_privtoaddr(ethpriv) == ethaddr except Exception as e: # print ("eth_priv = %s" % eth_privtoaddr(ethpriv)) # print ("ethadd = %s" % ethaddr) # traceback.print_exc() raise DecryptionException("Decryption failed. Bad password?") return seed
def _parse_dropbox(self): self.dropboxAccessToken = self.configParser.get( self.DropboxSection, "access_token") if self.backupWithDropbox != gEmptyStr and self.backupWithDropbox: # get dropbox auth info self.dropboxUser = self.configParser.get(self.DropboxSection, "User") if self.dropboxUser: self.dropboxUser = self.dropboxUser.strip() self.dropboxPassStr = self.configParser.get( self.DropboxSection, "Password") if self.dropboxPassStr: self.dropboxPassStr = self.dropboxPassStr.strip() if not self.dropboxUser or gEmptyStr == self.dropboxUser: self.dropboxUser = raw_input("Your user name for dropbox: ") self.configParser.set(self.DropboxSection, "User", self.dropboxUser) self.dropboxPassStr = "" if not self.dropboxPassStr or self.dropboxPassStr == gEmptyStr: self.dropboxPassStr = getpass.getpass( "Your password for dropbox user %s: " % (self.dropboxUser)) self.dropboxPassKey = aes.generateRandomKey(16) # set password with aes encryption tmpPass = aes.encryptData(dropboxPassKey, dropboxPassStr) self.configParser.set( self.DropboxSection, "Password", tmpPass.encode("hex") + gSepChar + self.dropboxPassKey.encode("hex")) # reset access token when username or password changes self.dropboxAccessToken = gEmptyStr else: self.dropboxPass, self.dropboxPassKey = self.dropboxPassStr.split( ":") self.dropboxPass = aes.decryptData( binascii.unhexlify(self.dropboxPassKey), binascii.unhexlify(self.dropboxPass)) self.dropboxAppKey = self.configParser.get(self.DropboxSection, "APP_KEY") self.dropboxAppSecret = self.configParser.get(self.DropboxSection, "APP_SECRET") self.dropboxAccessType = "dropbox" self.dropboxBackupDir = self.configParser.get(self.DropboxSection, "target_dir") if not self.dropboxBackupDir: self.dropboxBackupDir = "/" else: self.dropboxBackupDir = self.dropboxBackupDir.rstrip("/")
def decrypt(password, ciphertext, msgdgst='md5'): ''' Decrypt the ciphertext using the password using an openssl compatible decryption algorithm. It is the same as creating a file with ciphertext contents and running openssl like this: $ cat ciphertext # ENCRYPTED <ciphertext> $ egrep -v '^#|^$' | \\ openssl enc -d -aes-256-cbc -base64 -salt -pass pass:<password> -in ciphertext @param password The password. @param ciphertext The ciphertext to decrypt. @param msgdgst The message digest algorithm. @returns the decrypted data. ''' # unfilter -- ignore blank lines and comments filtered = '' for line in ciphertext.split('\n'): line = line.strip() if re.search('^\s*$', line) or re.search('^\s*#', line): continue filtered += line + '\n' # Base64 decode raw = base64.b64decode(filtered) assert( raw[:8] == 'Salted__' ) salt = raw[8:16] # get the salt # Now create the key and iv. key, iv = get_key_and_iv(password, salt, msgdgst=msgdgst) if key is None: return None # The original ciphertext ciphertext = raw[16:] # Decrypt #cipher = AES.new(key, AES.MODE_CBC, iv) #padded_plaintext = cipher.decrypt(ciphertext) plaintext = aes.decryptData(key, iv + ciphertext) #padding_len = ord(padded_plaintext[-1]) #plaintext = padded_plaintext[:-padding_len] return plaintext
def decrypt(password, ciphertext, msgdgst="md5"): """ Decrypt the ciphertext using the password using an openssl compatible decryption algorithm. It is the same as creating a file with ciphertext contents and running openssl like this: $ cat ciphertext # ENCRYPTED <ciphertext> $ egrep -v '^#|^$' | \\ openssl enc -d -aes-256-cbc -base64 -salt -pass pass:<password> -in ciphertext @param password The password. @param ciphertext The ciphertext to decrypt. @param msgdgst The message digest algorithm. @returns the decrypted data. """ # unfilter -- ignore blank lines and comments filtered = "" for line in ciphertext.split("\n"): line = line.strip() if re.search("^\s*$", line) or re.search("^\s*#", line): continue filtered += line + "\n" # Base64 decode raw = base64.b64decode(filtered) assert raw[:8] == "Salted__" salt = raw[8:16] # get the salt # Now create the key and iv. key, iv = get_key_and_iv(password, salt, msgdgst=msgdgst) if key is None: return None # The original ciphertext ciphertext = raw[16:] # Decrypt # cipher = AES.new(key, AES.MODE_CBC, iv) # padded_plaintext = cipher.decrypt(ciphertext) plaintext = aes.decryptData(key, iv + ciphertext) # padding_len = ord(padded_plaintext[-1]) # plaintext = padded_plaintext[:-padding_len] return plaintext
def _set_db_info(self): if not self.dbConf: return False for dbtype in self.dbType: dbConf = self.dbConf.get(dbtype, None) if dbConf is None or not dbConf.dbList: continue # set user and password/key if not dbConf.dbUser or dbConf.dbUser == gEmptyStr: dbConf.dbUser = raw_input("Your user name for %s: " % dbtype) self.configParser.set(dbtype, "User", dbConf.dbUser) dbConf.dbPass = "" if not dbConf.dbPass or dbConf.dbPass == gEmptyStr: dbConf.dbPass = getpass.getpass( "Your password for %s user %s: " % (dbtype, dbConf.dbUser)) dbConf.dbPassKey = aes.generateRandomKey(16) # set password with aes encryption tmpPass = aes.encryptData(dbConf.dbPassKey, dbConf.dbPass) self.configParser.set( dbtype, "Password", tmpPass.encode("hex") + gSepChar + dbConf.dbPassKey.encode("hex")) else: dbConf.dbPass, dbConf.dbPassKey = dbConf.dbPass.split(":") dbConf.dbPass = aes.decryptData( binascii.unhexlify(dbConf.dbPassKey), binascii.unhexlify(dbConf.dbPass)) # set dump command if dbtype == self.MysqlSection: dbPort = "-P %s" % dbConf.dbPort if dbConf.dbPort != gEmptyStr else "" dbConf.dumpCmd = "mysqldump %s -u %s --password=%s -B {0} -r %s/{0}" % \ (dbPort, dbConf.dbUser, dbConf.dbPass, gTmpDir) elif dbtype == self.MongoDBSection: dbPort = "--port %s" % dbConf.dbPort if dbConf.dbPort != gEmptyStr else "" dbConf.dumpCmd = "mongodump %s -u %s -p %s -d {0} -o %s/mongodb" % \ (dbPort, dbConf.dbUser, dbConf.dbPass, gTmpDir) else: print("Fatal error: database type %s is not supported" % dbtype) sys.exit(1) return True
def send(): if config.found_convo: #This is here because we don't want another thread to check again if a relay node was found already. return address = config.my_data.find("data", "all")[0]['address'] privatekey = config.my_data.find("data", "all")[0]["privatekey"] privatekey = filter(None, re.findall("[0-9]*", privatekey)) privatekey = PrivateKey(int(privatekey[0]), int(privatekey[1]), int(privatekey[2]), int(privatekey[3]), int(privatekey[4])) sock = socket.socket() sock.connect(find_node()) sock.send(json.dumps({"cmd": "find_convo", "address": address})) config.found_convo = True print "In contact with relay node" while True: data = sock.recv(1024000) if not data: config.found_convo = False break else: data += "\n" data = data.split("\n") for x in data: try: x = json.loads(x) except ValueError: continue from_ = x['from'] message = base64.b64decode(x['message']) message = aes.decryptData( decrypt(base64.b64decode(x['key']), privatekey), message) config.cache.insert("messages", { "from": from_, "message": message, "time": x['time'] }) #So that the web ui can then access them config.cache.save()
def _set_db_info(self): if not self.dbConf: return False for dbtype in self.dbType: dbConf = self.dbConf.get(dbtype, None) if dbConf is None or not dbConf.dbList: continue # set user and password/key if not dbConf.dbUser or dbConf.dbUser == gEmptyStr: dbConf.dbUser = raw_input("Your user name for %s: " % dbtype) self.configParser.set(dbtype, "User", dbConf.dbUser) dbConf.dbPass = "" if not dbConf.dbPass or dbConf.dbPass == gEmptyStr: dbConf.dbPass = getpass.getpass("Your password for %s user %s: " % (dbtype, dbConf.dbUser)) dbConf.dbPassKey = aes.generateRandomKey(16) # set password with aes encryption tmpPass = aes.encryptData(dbConf.dbPassKey, dbConf.dbPass) self.configParser.set(dbtype, "Password", tmpPass.encode("hex") + gSepChar + dbConf.dbPassKey.encode("hex")) else: dbConf.dbPass, dbConf.dbPassKey = dbConf.dbPass.split(":") dbConf.dbPass = aes.decryptData(binascii.unhexlify(dbConf.dbPassKey), binascii.unhexlify(dbConf.dbPass)) # set dump command if dbtype == self.MysqlSection: dbPort = "-P %s" % dbConf.dbPort if dbConf.dbPort != gEmptyStr else "" dbConf.dumpCmd = "mysqldump %s -u %s --password=%s -B {0} -r %s/{0}" % \ (dbPort, dbConf.dbUser, dbConf.dbPass, gTmpDir) elif dbtype == self.MongoDBSection: dbPort = "--port %s" % dbConf.dbPort if dbConf.dbPort != gEmptyStr else "" dbConf.dumpCmd = "mongodump %s -u %s -p %s -d {0} -o %s/mongodb" % \ (dbPort, dbConf.dbUser, dbConf.dbPass, gTmpDir) else: print("Fatal error: database type %s is not supported" % dbtype) sys.exit(1) return True
def aes_decrypt(self, ciphertext, key, iv): decoded = ciphertext.decode('base64') password = aes.decryptData(key, iv.encode('utf-8') + decoded) return unicode(password, 'utf-8')
def getseed(encseed,pw,ethaddr): seed = aes.decryptData(pbkdf2(pw),encseed.decode('hex')) ethpriv = sha3(seed) if eth_privtoaddr(ethpriv) != ethaddr: raise Exception("ethaddr does not match!") return seed
# VALUES password = "******" pw = pbkdf2(password) # 3e661b9345173538b11e0e7e954025d2 encseed = binascii.unhexlify( "d93b5ca93c8db8706256c73457c2d45f741a051274ed685300faa975f8525cc33d020d4e6f5277d2d796008671fc218ef2fb7979699806ded8784591d0b1304c07251b9451dfd125b7f1f15f516b3f130dac1b9e031aba8dbf9000246dce0f285c344c934e194507f1f06b85efc6427150ab9c31c9d142cb41a9665452bdb82da55535257a79e0c96980882c2ae817524abb32ae750d38135b7026a32ede9d99d486342e060844822eb89017e2d59b4e7b448d00fc5499a3f19cd98a4bb6453f0b2a382facc80217e4d5104703aad7623f21fd844c5f8e280b02a5fc6e1a01601e6cb685e7ec4b61aed3ff25a963193a49b6441ae90acc0f24db7e942efdffa6a77f12bcebc0c2cfd4345087a719a77e39ffd7d4daaa62f90a98aeb139831e53f165b44b5796e74013cc570a280cfec7f21a35d26740897742a6fb3bcbbf487df27c8656327d2b37796f7627491a837ce8eb30160d17ceb26af9f547e1e3a8d2b4fc75d2fdb958d75b8ea99097c941624afa99acd46036c1c70dab33f3c6b866a7da4206cdb8246e7e0ebdb455387bdcc7221789fb49dff2f8a94916d1e1f1aadcfaac7815fdbc6e7d151ae214656f1b463feb1021c7f4e7644ad1a76cf807648c29cb3036f563f2da1818bb6ac229289e66461ca3cc1dd7a454f7fdff334888feef9573b9f7a2e3e90272da0274c3b0121d56957cc6d932aef5c43ec1b0b511f0a2922e7acc786672eaae75ee5b909a84e4faea1fa88b3c72ef1ba2aa67b1cbdda2bf1ea5ba67b0a5aa245ce3ab710f78f5ddc6172a15311e066a78209891f59b1204f7ddc3798d3d092307b3d4f91f6b1c6415079f51ff88ce17dfcc8d05a4eb6196917e84c5e684a9d317c1760db2" ) seed = "oznszcw6irhg7reba2xauvwi3btr3qhztmkdljkmimbzw3dqwkq3daf2wlm3kj5f2cidsxelc253q4nalv4kgsoxb376knnlwny7llehqznk2ymjbqcna7yyitdx252j32ll52uemoctiiiginoodn42acyhs33fnbejd47k3jw77omxpgyshjii5ze2db4u52udbqu3anv6wwiebtz6s2xrusji4i6w5gwumah57rnpcip57bw3gixlkzjeq52aagwnn5nrf5tjslfo2pdjb6ylkrfh6x5qhpzxdpdsdfnx3oatx6nlzuh532ci5pcwwest4i5qlwbrwidizmxr3vcmbfwkdtkm37laocfmyqyjvbtza6scsojjmicqwhigijhiqaugsqzuyzixl3hdfkdx6bfiixtzeawr53nhh2zt2jystsjtn2wypae2o4rzvjkurzee4j3gf5k7ymmkc74dw2x6qc4zwsbf3opukeyog336sxmdh7qxulx7d6d632yxt6dslvsl4wq5s5j5sjevku5wynnikr6aomj7fpnrl6ucnkwkgwnphldp46elaowrhaaq7bti3xwehghq27l6c" print("pw = %s " % binascii.hexlify(pbkdf2(password))) print("encseed = %s " % binascii.hexlify(encseed)) print("seed[%d] = %s " % (len(seed), seed)) print("DECRYPTION aes.py") try: decrypted = aes.decryptData(pw, encseed) print("decrypted[%d] = %s" % (len(decrypted), decrypted)) except Exception, e: decrypted = "" print("AES Decryption error. Bad password?") if seed == decrypted: print("OK") else: print("KO") print("DECRYPTION pycryptodome") decrypted = decrypt(encseed, pw) print("decrypted[%d] = %s" % (len(decrypted), binascii.hexlify(decrypted))) if seed == decrypted: print("OK")
from NTRU.main import * import base64 import aes n = NTRU() pub, params = n.generateNTRUKeys() msg = "Hello world! I am intangere!" aeskey = str(uuid.uuid4().hex) aesMsg = base64.b64encode(aes.encryptData(aeskey, msg)) aesParts = n.splitNthChar(7, aesMsg) print params encryptedParts = n.encryptParts([71,29,491531], pub, aesParts) decryptedParts = n.decryptParts(params, encryptedParts) print "Pubkey: %s" % pub print "Params: %s" % params print "Message: %s" % msg print "Aes Message: %s" % aesMsg print "Ntru Parts: %s" % encryptedParts print "Decrypted Message: %s" % decryptedParts print "Decrypted Aes Message: %s" % aes.decryptData(aeskey, base64.b64decode(decryptedParts))
def decrypted(pwd, s): return aes.decryptData(dhash(pwd), base58_to_str(s))
def decrypt_file(self, key, in_filename, out_filename): #out_filename = os.path.splitext(in_filename)[0] with open(in_filename, 'rb') as infile: with open(out_filename, 'wb') as outfile: outfile.write(aes.decryptData(key, infile.read()))
def getseed(encseed, pw, ethaddr): pw = pbkdf2(pw) seed = aes.decryptData(pw, binascii.unhexlify(encseed)) ethpriv = sha3(seed) if eth_privtoaddr(ethpriv) == ethaddr: return seed
class EC_KEY(object): def __init__(self, k): secret = string_to_number(k) self.pubkey = ecdsa.ecdsa.Public_key(generator_secp256k1, generator_secp256k1 * secret) self.privkey = ecdsa.ecdsa.Private_key(self.pubkey, secret) self.secret = secret def get_public_key(self, compressed=True): return point_to_ser(self.pubkey.point, compressed).encode('hex') def sign_message(self, message, compressed, address): private_key = ecdsa.SigningKey.from_secret_exponent(self.secret, curve=SECP256k1) public_key = private_key.get_verifying_key() signature = private_key.sign_digest_deterministic( Hash(msg_magic(message)), hashfunc=hashlib.sha256, sigencode=ecdsa.util.sigencode_string) assert public_key.verify_digest(signature, Hash(msg_magic(message)), sigdecode=ecdsa.util.sigdecode_string) for i in range(4): sig = base64.b64encode( chr(27 + i + (4 if compressed else 0)) + signature) try: self.verify_message(address, sig, message) return sig except Exception: continue else: raise Exception("error: cannot sign message") @classmethod def verify_message(self, address, signature, message): sig = base64.b64decode(signature) if len(sig) != 65: raise Exception("Wrong encoding") nV = ord(sig[0]) if nV < 27 or nV >= 35: raise Exception("Bad encoding") if nV >= 31: compressed = True nV -= 4 else: compressed = False recid = nV - 27 h = Hash(msg_magic(message)) public_key = MyVerifyingKey.from_signature(sig[1:], recid, h, curve=SECP256k1) # check public key public_key.verify_digest(sig[1:], h, sigdecode=ecdsa.util.sigdecode_string) # check that we get the original signing address addr = public_key_to_bc_address( point_to_ser(public_key.pubkey.point, compressed)) if address != addr: raise Exception("Bad signature") # ecies encryption/decryption methods; aes-256-cbc is used as the cipher; hmac-sha256 is used as the mac @classmethod def encrypt_message(self, message, pubkey): pk = ser_to_point(pubkey) if not ecdsa.ecdsa.point_is_valid(generator_secp256k1, pk.x(), pk.y()): raise Exception('invalid pubkey') ephemeral_exponent = number_to_string( ecdsa.util.randrange(pow(2, 256)), generator_secp256k1.order()) ephemeral = EC_KEY(ephemeral_exponent) ecdh_key = (pk * ephemeral.privkey.secret_multiplier).x() ecdh_key = ('%064x' % ecdh_key).decode('hex') key = hashlib.sha512(ecdh_key).digest() key_e, key_m = key[:32], key[32:] iv_ciphertext = aes.encryptData(key_e, message) ephemeral_pubkey = ephemeral.get_public_key( compressed=True).decode('hex') encrypted = 'BIE1' + ephemeral_pubkey + iv_ciphertext mac = hmac.new(key_m, encrypted, hashlib.sha256).digest() return base64.b64encode(encrypted + mac) def decrypt_message(self, encrypted): encrypted = base64.b64decode(encrypted) if len(encrypted) < 85: raise Exception('invalid ciphertext: length') magic = encrypted[:4] ephemeral_pubkey = encrypted[4:37] iv_ciphertext = encrypted[37:-32] mac = encrypted[-32:] if magic != 'BIE1': raise Exception('invalid ciphertext: invalid magic bytes') try: ephemeral_pubkey = ser_to_point(ephemeral_pubkey) except AssertionError, e: raise Exception('invalid ciphertext: invalid ephemeral pubkey') if not ecdsa.ecdsa.point_is_valid(generator_secp256k1, ephemeral_pubkey.x(), ephemeral_pubkey.y()): raise Exception('invalid ciphertext: invalid ephemeral pubkey') ecdh_key = (ephemeral_pubkey * self.privkey.secret_multiplier).x() ecdh_key = ('%064x' % ecdh_key).decode('hex') key = hashlib.sha512(ecdh_key).digest() key_e, key_m = key[:32], key[32:] if mac != hmac.new(key_m, encrypted[:-32], hashlib.sha256).digest(): raise Exception('invalid ciphertext: invalid mac') return aes.decryptData(key_e, iv_ciphertext)
def getseed(encseed, pw, ethaddr): try: seed = aes.decryptData(pw, binascii.unhexlify(encseed)) except Exception, e: raise DecryptionException("AES Decryption error. Bad password?")
import ecdsa import aes ################################## transactions DUST_THRESHOLD = 0 DUST_SOFT_LIMIT = 100000 MIN_RELAY_TX_FEE = 100000 RECOMMENDED_FEE = 100000 COINBASE_MATURITY = 100 COIN = 100000000 # AES encryption EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s)) DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e)) def strip_PKCS7_padding(s): """return s stripped of PKCS7 padding""" if len(s)%16 or not s: raise ValueError("String of len %d can't be PCKS7-padded" % len(s)) numpads = ord(s[-1]) if numpads > 16: raise ValueError("String ending with %r can't be PCKS7-padded" % s[-1]) if s[-numpads:] != numpads*chr(numpads): raise ValueError("Invalid PKCS7 padding") return s[:-numpads] # backport padding fix to AES module aes.strip_PKCS7_padding = strip_PKCS7_padding
fake_A = P fake_B = P private_A = get_key(fake_B, a, P) private_B = get_key(fake_A, b, P) def sha(s): return sha1(hex(int(s))).digest()[0:16] AES_A = sha(private_A) msg_A = "12345" cipher_A = aes.encryptData(AES_A, msg_A) AES_M = sha(0) msg_AM = aes.decryptData(AES_M, cipher_A) assert msg_AM == msg_A AES_B = sha(private_B) msg_B = aes.decryptData(AES_B, cipher_A) cipher_B = aes.encryptData(AES_B, msg_B) msg_BM = aes.decryptData(AES_M, cipher_B) assert msg_BM == msg_A assert AES_M == AES_A
################################## transactions FEE_STEP = 10000 RECOMMENDED_FEE = 50000 COINBASE_MATURITY = 100 COIN = 100000000 # supported types of transction outputs TYPE_ADDRESS = 0 TYPE_PUBKEY = 1 TYPE_SCRIPT = 2 # AES encryption EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s)) DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e)) def strip_PKCS7_padding(s): """return s stripped of PKCS7 padding""" if len(s)%16 or not s: raise ValueError("String of len %d can't be PCKS7-padded" % len(s)) numpads = ord(s[-1]) if numpads > 16: raise ValueError("String ending with %r can't be PCKS7-padded" % s[-1]) if s[-numpads:] != numpads*chr(numpads): raise ValueError("Invalid PKCS7 padding") return s[:-numpads] # backport padding fix to AES module aes.strip_PKCS7_padding = strip_PKCS7_padding
def aes_decrypt(ciphertext, key, iv): decoded = ciphertext.decode('base64') password = aes.decryptData(key, iv.encode('utf-8') + decoded) return unicode(password, 'utf-8')
def decode(self, message): decoded_message = aes.decryptData(self.encode_password, base64.b64decode(unicode(message))) return decoded_message
def decryptAES(key, data, mode=2): """decrypt data with aes key""" return aes.decryptData(key, data, mode)
def decode(self, message): decoded_message = aes.decryptData(self.encode_password, base64.b64decode(unicode(message)) ) return decoded_message
def decrypt(ciphertext, key, iv): decoded = base64.b64decode(ciphertext) password = aes.decryptData(key, iv.encode('utf-8') + decoded) return unicode(password, 'utf-8')
import sqlite3 import serializeBTC as ser import Crypto.Cipher.AES as AES import Crypto.Hash.SHA256 as SHA256 import scrypt from itertools import izip from array import array from bitcoin.bip38 import Bip38 from bitcoin.key import CKey from bitcoin.base58 import CBase58Data, CBitcoinAddress Hash = lambda x: hashlib.sha256(hashlib.sha256(x).digest()).digest() # AES encryption EncodeAES = lambda secret, s: b58encode(aes.encryptData(secret,s)) DecodeAES = lambda secret, e: aes.decryptData(secret, b58decode(e)) # Electrum uses base64, which is fine when it's stored in the computer, but base58 was created for readibiity by humans # AES encryption #EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s)) #DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e)) #BIO0038 def encryptBIP0038(pubkey, privkey, secret): k = CKey() #decode the wallet import format by base58 decoding then dropping the last 4 bytes and the first byte decoded = b58decode(privkey) decoded = decoded[:-4] decoded = decoded[1:] k.generate(decoded)
def mitm_protocol(): # A->M Send "p", "g", "A" a, A = keygen() # M->B Send "p", "g", "p" B_idea_of_A = p # B->M Send "B" b, B = keygen() # M->A Send "p" A_idea_of_B = p # A->M Send AES-CBC(SHA1(s)[0:16], iv=random(16), msg) + iv s_A = pow(A_idea_of_B, a, p) aeskey_A = derivekey(s_A) msg_A = 'hello world' cipher_A = aes.encryptData(aeskey_A, msg_A) # M->B Relay that to B # (check we can decrypt) aeskey_M = derivekey(0) msg_AM = aes.decryptData(aeskey_M, cipher_A) assert msg_AM == msg_A # B->M Send AES-CBC(SHA1(s)[0:16], iv=random(16), A's msg) + iv s_B = pow(B_idea_of_A, b, p) aeskey_B = derivekey(s_B) msg_B = aes.decryptData(aeskey_B, cipher_A) cipher_B = aes.encryptData(aeskey_B, msg_B) # M->A Relay that to A msg_BM = aes.decryptData(aeskey_M, cipher_B) assert msg_BM == msg_A assert aeskey_M == aeskey_A