def get_private_key(password): salt = b"a revolution without dancing is a revolution not worth having" kdf = PBKDF2(password, salt, 64, 1000) key = kdf[:32] return key
def decrypt(self, key, ciphertext): aes_key = PBKDF2(key, self.get_salt(), 32, 50000) cipher = AES.new(aes_key, self.AES_CIPHER_MODE, ciphertext[32:32 + 16]) plaintext = cipher.decrypt(ciphertext[48:]).decode("ascii", "ignore").strip() return plaintext
def crypt_pbkdf2_hmacsha256(salt, data): return PBKDF2(data, salt, dkLen = 32, count = 20000, prf = lambda p, s: HMAC.new(p, s, SHA256).digest())
def create_new_user(email, password): """ Step 1: The User generates a secret. User inputs an email and a password into the client. Step 2: The Client generates an encryption key. The client gener-ates an encryptionKey of 64 random bytes using the browser’s native function Crypto.getRandomValues(). Step 3: The Client encrypts the encryption key. The Client selects a Key Derivation Function (KDF). The default choice is PBKDF2. PBKDF2 is a password- based key derivation function that uses a password, a variable-length salt, and an iteration count and applies a pseudorandom function to these to produce a key. Our implementation uses SHA-256 as the pseudorandom function. The Client selects the number off KDF iterations to run. The default choice is 100,000. The client runs the KDF with the password as the secret, the email as the salt and the relevant number of iterations. The KDF function returns a key, which we will call passwordDerivedKey. The Client runs the AES-CBC encryption algorithm, with the encryptionKey as the plaintext, the passwordDerivedKey as the secret, and 16 random bytes as the IV (using the browser’s native function Crypto.getRandomValues()), returning the encryptedEncryptionKey cipher, composed of the encryptedEncryptionKey, the IV and the encryption algorithm mode. Step 4: The Client hashes the password. The Client runs PBKDF2 with SHA- 256 as the pseudorandom function, using the passwordDerivedKey as the secret and the password as the salt, running a single iteration. This returns the passwordHash. The passwordHash serves as the Client’s authentication key against the Server. Step 5: The Client generates a forgot password hash. The client hashes the passwordDerivedKey using SHA-512, returning a passwordDerivedKeyHash (this will be used for the ”forgot password” flow). Step 6: The Client generates and encrypts an asymmetric key pair for secure client-to-client communication. The Client runs RSA-OAEP 2048 with a SHA-1 hashing algorithm to generate a pair of both an asymmetricPublicKey 5and asymmetricPrivateKey. The Client runs the AES-CBC encryption algorithm, with the asymmetricPrivateKey as the plaintext and the encryptionKey as the se- cret, returning the encryptedAsymmetricPrivateKey cipher, composed of the en- cryptedAsymmetricPrivateKey, the IV and the encryption algorithm mode. For now, these asymmetricPublicKey and encryptedAsymmetricPrivateKey have no function but will be used later on as asymmetric keys for secure client-to-client communica- tion. """ ##key to be either 16, 24 or 32 bytes long (for AES-128, AES-196 and AES-256, respectively) encryptionKey = get_random_bytes(32) ##this will be in bytes and have length 32 bytes passwordDerivedKey = generate_scrypt_key(password, email, 32)[0] ##this will also be in bytes and have length 16 ##step3 encryptedEncryptionKey = aes_encrypt_CBC(passwordDerivedKey, encryptionKey) ##checking for correct AES encryption text = aes_decrypt_CBC(passwordDerivedKey, encryptedEncryptionKey) if text != encryptionKey: logger.error("Encryption and decryption of encryption_key couldnt be done") logger.success("Encryption and decryption of encryption_key done successfully") ##step4: passwordhash, The passwordHash serves as the Client’s authentication key against the Server. passwordHash = PBKDF2(passwordDerivedKey, password, 64, count=10, hmac_hash_module=SHA256) ##length will be 64 bytes ##step5: (this will be used for the ”forgot password” flow). passwordDerivedKeyHash = hashlib.sha512(passwordDerivedKey).hexdigest() ##step6: asymmetricPublicKey, asymmetricPrivateKey = generate_rsa_keypair() encryptedAsymmetricPrivateKey = aes_encrypt_CBC(encryptionKey, asymmetricPrivateKey) return {"KDF": "scrypt", "iterations": N, "email": email, "passwordHash": passwordHash.hex(), "passwordDerivedKeyHash": passwordDerivedKeyHash, "encryptedEncryptionKey": encryptedEncryptionKey.hex(), "asymmetricPublicKey": asymmetricPublicKey.hex(), "encryptedAsymmetricPrivateKey": encryptedAsymmetricPrivateKey.hex()}
def create(self, did, mode, email=None, password=False, phone=None, wallet=None, category=1001) : """ Main function to create a repository for a user category is 1001 for person and 2001 for company DID is used to generate an ethereum private key email is used to recover in case of did keys are lost Talao smart contract is deployed on talaonet """ # Setup with DID as password, deterministic way to generate an address if not did : logging.error('did malformed') return False if did.split(':')[1] not in ['web', 'tz', 'ethr', 'key'] : logging.error('did not supported') return False repository = Repository() if repository.load(mode, did) : logging.error('A repository already exists for this DID') return False self.did = did self.email = email if email else "" if category not in [1001, 2001] : logging.error('wrong category') return False self.category = category self.private_key = '0x' + PBKDF2(self.did.encode(), SALT, 32, count=1000000, hmac_hash_module=SHA512).hex() self.address = helpers.ethereum_pvk_to_address(self.private_key) self.public_key = helpers.ethereum_pvk_to_pub(self.private_key) self.jwk = helpers.ethereum_to_jwk(self.private_key, 'ethr') # create RSA key RSA_key = RSA.generate(2048) self.RSA_private = RSA_key.exportKey('PEM') self.RSA_public = RSA_key.publickey().exportKey('PEM') logging.info('RSA key generated') # Setup an AES key named 'private' to encrypt private data and to be shared with partnership private = get_random_bytes(16) self.private = private.hex() # Setup an AES key named 'secret' to encrypt secret data FIXME secret = get_random_bytes(16) self.secret = secret.hex() # AES private encrypted with RSA key cipher_rsa = PKCS1_OAEP.new(RSA_key) private_encrypted = cipher_rsa.encrypt(private) # AES secret encrypted with RSA key cipher_rsa = PKCS1_OAEP.new(RSA_key) secret_encrypted = cipher_rsa.encrypt(secret) try : # Ether transfer from TalaoGen wallet ether_transfer(self.address, mode.ether2transfer,mode) logging.info('ether transfer done ') # Talao tokens transfer from TalaoGen wallet token_transfer(self.address, mode.talao_to_transfer, mode) logging.info('token transfer done') # CreateVaultAccess call in the token to declare the identity within the Talao Token smart contract createVaultAccess(self.address, self.private_key, mode) logging.info('vault access created') except : logging.error('init Talao protocol failed') return False # Identity setup contract = mode.w3.eth.contract(mode.workspacefactory_contract,abi=constante.Workspace_Factory_ABI) nonce = mode.w3.eth.getTransactionCount(self.address) bemail = bytes(self.email.lower() , 'utf-8') txn = contract.functions.createWorkspace(self.category, 1, 1, self.RSA_public, private_encrypted, secret_encrypted, bemail).buildTransaction({'chainId': mode.CHAIN_ID, 'gas': 7500000, 'gasPrice': mode.w3.toWei(mode.GASPRICE, 'gwei'), 'nonce': nonce}) signed_txn = mode.w3.eth.account.signTransaction(txn, self.private_key) mode.w3.eth.sendRawTransaction(signed_txn.rawTransaction) transaction_hash = mode.w3.toHex(mode.w3.keccak(signed_txn.rawTransaction)) receipt = mode.w3.eth.waitForTransactionReceipt(transaction_hash, timeout=2000, poll_latency=1) if not receipt['status'] : logging.error('transaction to create repository failed') return False # workspace_contract address to be read in fondation smart contract self.workspace_contract = ownersToContracts(self.address, mode) logging.info('repository has been deployed') # store RSA key in file ./RSA_key/rinkeby, talaonet ou ethereum filename = "./RSA_key/" + mode.BLOCKCHAIN + '/did:talao:' + mode.BLOCKCHAIN + ':' + self.workspace_contract[2:] + ".pem" try : file = open(filename,"wb") file.write( self.RSA_private) file.close() logging.info('RSA key stored on server') except : logging.error('RSA key not stored on server') return False # store Ethereum private key in keystore if not privatekey.add_private_key(self.private_key, mode) : logging.error('private key storage failed') return False else : logging.info('private key stored on server') # ERC725 key 1 issued to Web Relay as the Repository Manager if not add_key(self.address, self.workspace_contract, self.address, self.workspace_contract, self.private_key, mode.relay_address, 1, mode) : logging.error('ERC725 key 1 to repository manager failed') return False else : logging.error('ERC725 key 1 isued to repository manager') # rewrite email for recovery if Claim().add(self.address, self.workspace_contract, self.address, self.workspace_contract, self.private_key, 'email', self.email, 'public', mode)[0] : logging.info('email encryted updated') else : logging.warning('email encrypted not updated') logging.info('end of create repository') return True
def __init__(self, cookie_file=None, domain_name=""): self.salt = b'saltysalt' self.iv = b' ' * 16 self.length = 16 # domain name to filter cookies by # self.domain_name = domain_name self.domain_name = TLDLazy().get_tld_domain( domain_name) if domain_name else None if sys.platform == 'darwin': # running Chrome on OSX my_pass = keyring.get_password('Chrome Safe Storage', 'Chrome').encode( 'utf8') # get key from keyring iterations = 1003 # number of pbkdf2 iterations on mac # self.key = PBKDF2(my_pass, self.salt, iterations=iterations).read(self.length) self.key = PBKDF2(my_pass, self.salt, count=iterations, dkLen=self.length) cookie_file = cookie_file or os.path.expanduser( '~/Library/Application Support/Google/Chrome/Default/Cookies') elif sys.platform.startswith('linux'): # running Chrome on Linux # chrome linux is encrypted with the key peanuts my_pass = get_linux_pass().encode('utf8') iterations = 1 self.key = PBKDF2(my_pass, self.salt, count=iterations, dkLen=self.length) paths = map(os.path.expanduser, [ '~/.config/google-chrome/Default/Cookies', '~/.config/chromium/Default/Cookies', '~/.config/google-chrome-beta/Default/Cookies' ]) cookie_file = cookie_file or next(filter(os.path.exists, paths), None) elif sys.platform == "win32": # Read key from file key_file = (glob.glob( os.path.join(os.getenv('APPDATA', ''), r'..\Local\Google\Chrome\User Data\Local State')) or glob.glob( os.path.join( os.getenv('LOCALAPPDATA', ''), r'Google\Chrome\User Data\Local State')) or glob.glob( os.path.join( os.getenv('APPDATA', ''), r'Google\Chrome\User Data\Local State'))) if isinstance(key_file, list): if key_file: key_file = key_file[0] if key_file: # f = open(key_file, 'rb') # key_file_json = json.load(f) key_file_json = json.loads( open(key_file, 'rb').read().decode()) key64 = key_file_json['os_crypt']['encrypted_key'].encode( 'utf-8') # Decode Key, get rid of DPAPI prefix, unprotect data keydpapi = base64.standard_b64decode(key64)[5:] _, self.key = crypt_unprotect_data(keydpapi, is_key=True) # get cookie file from APPDATA # Note: in windows the \\ is required before a u to stop unicode errors cookie_file = ( cookie_file or windows_group_policy_path() or glob.glob( os.path.join( os.getenv('APPDATA', ''), r'..\Local\Google\Chrome\User Data\Default\Cookies')) or glob.glob( os.path.join(os.getenv('LOCALAPPDATA', ''), r'Google\Chrome\User Data\Default\Cookies')) or glob.glob( os.path.join(os.getenv('APPDATA', ''), r'Google\Chrome\User Data\Default\Cookies'))) else: raise BrowserCookieError( "OS not recognized. Works on Chrome for OSX, Windows, and Linux." ) # if the type of cookie_file is list, use the first element in the list if isinstance(cookie_file, list): if not cookie_file: raise BrowserCookieError('Failed to find Chrome cookie') cookie_file = cookie_file[0] self.tmp_cookie_file = create_local_copy(cookie_file)
def generate_key(password): salt = b'\x83\xdb\xb9\xd3\xdc"\x1e\x0ee"\x0c\xf0=5\xab_\x18\xd7\xd2\x98\x92Q.\xbd\x9cK\x96\x93-J\x08\xe0' return PBKDF2(password, salt, dkLen=32)
def __init__( self, server_id, conf_dir, ): """ :param str server_id: server identifier. :param str conf_dir: configuration directory. """ super().__init__( server_id, conf_dir, ) self.interface = None for edge_router in self.topology.get_all_edge_routers(): if edge_router.addr == self.addr.host: self.interface = edge_router.interface break assert self.interface is not None logging.info("Interface: %s", self.interface.__dict__) self.of_gen_key = PBKDF2(self.config.master_as_key, b"Derive OF Key") self.sibra_key = PBKDF2(self.config.master_as_key, b"Derive SIBRA Key") self.if_states = defaultdict(InterfaceState) self.revocations = ExpiringDict(1000, self.FWD_REVOCATION_TIMEOUT) self.pre_ext_handlers = { SibraExtBase.EXT_TYPE: self.handle_sibra, TracerouteExt.EXT_TYPE: self.handle_traceroute, ExtHopByHopType.SCMP: self.handle_scmp, HORNETPlugin.EXT_TYPE: HORNETPlugin(self.id, conf_dir, self.config.master_as_key, self.addr, self.interface).pre_routing } self.post_ext_handlers = { SibraExtBase.EXT_TYPE: False, TracerouteExt.EXT_TYPE: False, ExtHopByHopType.SCMP: False, HORNETPlugin.EXT_TYPE: False } self.sibra_state = SibraState( self.interface.bandwidth, "%s#%s -> %s" % (self.addr.isd_as, self.interface.if_id, self.interface.isd_as)) self.CTRL_PLD_CLASS_MAP = { PayloadClass.PCB: { PCBType.SEGMENT: self.process_pcb }, PayloadClass.IFID: { IFIDType.PAYLOAD: self.process_ifid_request }, PayloadClass.CERT: defaultdict(lambda: self.relay_cert_server_packet), PayloadClass.PATH: defaultdict(lambda: self.process_path_mgmt_packet), PayloadClass.SIBRA: { SIBRAPayloadType.EMPTY: self.fwd_sibra_service_pkt }, } self.SCMP_PLD_CLASS_MAP = { SCMPClass.PATH: { SCMPPathClass.REVOKED_IF: self.process_revocation }, } self._remote_sock = UDPSocket( bind=(str(self.interface.addr), self.interface.udp_port), addr_type=AddrType.IPV4, ) self._socks.add(self._remote_sock, self.handle_recv) logging.info("IP %s:%d", self.interface.addr, self.interface.udp_port)
def decrypt(self, data, passphrase): check_mode_ccm() # check ccm support if data["cipher"] != "aes": raise Exception("only aes cipher supported") if data["mode"] != "ccm": raise Exception("unknown mode(!=ccm)") if data["adata"] != "": raise Exception("additional authentication data not equal ''") if data["v"] != 1: raise Exception("only version 1 is currently supported") if data["ts"] != self.tag_size * 8: raise Exception("desired tag length != %d" % (self.tag_size * 8)) # Fix padding if len(data["salt"]) % 4: # not a multiple of 4, add padding: data["salt"] += '=' * (4 - len(data["salt"]) % 4) salt = base64.b64decode(data["salt"]) # print "salt", hex_string(salt) if len(salt) != self.salt_size: raise Exception("salt should be %d bytes long" % self.salt_size) dkLen = data["ks"] // 8 if dkLen != 16 and dkLen != 32: raise Exception("key length should be 16 bytes or 32 bytes") key = PBKDF2(passphrase, salt, count=data['iter'], dkLen=dkLen, prf=self.prf) # print "key", hex_string(key) # Fix padding if len(data["iv"]) % 4: # not a multiple of 4, add padding: data["iv"] += '=' * (4 - len(data["iv"]) % 4) if len(data["ct"]) % 4: # not a multiple of 4, add padding: data["ct"] += '=' * (4 - len(data["ct"]) % 4) ciphertext = base64.b64decode(data["ct"]) iv = base64.b64decode(data["iv"]) # print AES.block_size nonce = truncate_iv(iv, len(ciphertext) * 8, data["ts"]) # split tag from ciphertext (tag was simply appended to ciphertext) mac = ciphertext[-(data["ts"] // 8):] # print len(ciphertext) ciphertext = ciphertext[:-(data["ts"] // 8)] # print len(ciphertext) # print len(tag) # print "len", len(nonce) cipher = AES.new(key, AES.MODE_CCM, nonce, mac_len=self.mac_size) plaintext = cipher.decrypt(ciphertext) cipher.verify(mac) return plaintext
def get_private_key(password): salt = b"this is a salt" kdf = PBKDF2(password, salt, 64, 1000) key = kdf[:32] return key
import base64 import binascii from Crypto.Cipher import AES from Crypto.Random import random from Crypto.Protocol.KDF import PBKDF2 from dotenv import load_dotenv load_dotenv() app = Flask(__name__, static_url_path='', template_folder="templates", static_folder="static") app.config['NAME'] = "CookieMonster Pt. 3" app.config['FLAG'] = os.environ['PART_THREE_FLAG'] app.config['KEY'] = PBKDF2(os.environ['COOKIE_JAR_KEY'], bytes(os.environ['PART_THREE_FLAG'], 'ascii'), 16, count=1000000) app.config['COOKIE_ID'] = 'SESSIONID3' app.config['SUPER_SECRET_STRING'] = os.environ['SUPER_SECRET_STRING'] class SessionError(Exception): """Represents an error creating or parsing a session cookie""" pass @app.route('/') def index(): return redirect(url_for('login'))
def _pbkdf2(password, salt, n_bytes, count): # the form of the prf below is taken from the code for PBKDF2 return PBKDF2(password, salt, dkLen=n_bytes, count=count, prf=lambda p,s: HMAC.new(p,s,HASH).digest())
field_number_to_decrypt = int(sys.argv[1]) fields = record.split() try: encrypted_value = binascii.unhexlify(fields[field_number_to_decrypt]) # Trim off the 'v10' that Chrome/ium prepends encrypted_value = encrypted_value[3:] # Default values used by both Chrome and Chromium in OSX and Linux salt = b'saltysalt' iv = b' ' * 16 length = 16 # On Mac, replace MY_PASS with your password from Keychain # On Linux, replace MY_PASS with 'peanuts' my_pass = os.environ['CHROMIUM_DECRYPT_PASS'] my_pass = my_pass.encode('utf8') # 1003 on Mac, 1 on Linux #iterations = 1003 iterations = 1 key = PBKDF2(my_pass, salt, length, iterations) cipher = AES.new(key, AES.MODE_CBC, IV=iv) decrypted = clean_padding(cipher.decrypt(encrypted_value)) fields[field_number_to_decrypt] = decrypted except IndexError: pass print '\t'.join(fields)
def __key_hash_genarator(self): return PBKDF2(self.key, self.salt, prf=lambda p, s: HMAC.new(p, s, SHA256).digest())
def my_rand(n): my_rand.counter += 1 return PBKDF2(master_key, "my_rand:%s" % my_rand.counter, dkLen=n, count=1)
# I am almost well aware I am using two libs that almost do the same. :D from Crypto.Cipher import AES, PKCS1_OAEP from Crypto.Protocol.KDF import PBKDF2 from Crypto.PublicKey import RSA master_key = b'Start wearing purple!' salt = os.urandom(128) # # parser = argparse.ArgumentParser(description='PKI encryption certificate passphrase') # parser.add_argument('passphrase', metavar='P', type=str, nargs='+', # help='PKI encryption certificate passphrase') # # args = parser.parse_args() cert = open('pki/provisioning/certs/encryption-certificate.key').read() # rsa = RSA.import_key(cert, args.passphrase[0]) rsa = RSA.import_key(cert) kfg = PBKDF2(password=master_key, salt=salt) session_key = os.urandom(16) # Encrypt the session key with the public RSA key cipher_rsa = PKCS1_OAEP.new(rsa) file_out = open("encrypted_key.bin", "wb") # Encrypt the session key with the public RSA key file_out.write(cipher_rsa.encrypt(session_key)) # Encrypt the data with the AES session key cipher_aes = AES.new(session_key, AES.MODE_EAX) ciphertext, tag = cipher_aes.encrypt_and_digest(kfg) [file_out.write(x) for x in (cipher_aes.nonce, tag, ciphertext)]
def __init__(self, password): key = PBKDF2(password, SALT, 8, count=1000000, hmac_hash_module=SHA512) self.key = key
def __init__(self, passwd, iterations=10000): salt = "just a random salt" self.key = PBKDF2(passwd, salt, AES_KEY_SIZE, iterations)
clear() Salt_size = 8 salt = '1d2f2' # secrets.token_hex(Salt_size) #'1d2f2' #generates a string of random numbers to use as salt gate = 0 while gate == 0: password = str( input( "Setting up stuff. Enter a password that will be used for decryption: " )) repassword = str(input("Confirm password: "******"Passwords Mismatched! Please try again") if gate == 1: break enc = Encryptor(key, salt) while gate == 1: choice = input( "1. Press '1' to encrypt messsage.\n2. Press '2' to decrypt message.\n3. Press '3' to create QR code without encryption.\n4. Press '4' to read QR code.\n5. Press '5' to generate gcode to 3D print QR code.\n6. Press '6' to exit.\n" ) #clear()
from Crypto.Cipher import AES from Crypto.Protocol.KDF import PBKDF2 from Crypto import Random key_size = 32 #AES256 iterations = 10000 key = b'password' secret = b'a very secret message' length = 16 - (len(secret) % 16) #PKCS7 adds bytes of the length of padding secret += chr(length) * length salt = Random.new().read(key_size) #salt the hash iv = Random.new().read(AES.block_size) derived_key = PBKDF2(key, salt, key_size, iterations) cipher = AES.new(derived_key, AES.MODE_CBC, iv) encodedtext = iv + cipher.encrypt(secret) decodedtext = str(cipher.decrypt(encodedtext)) decodedtext = decodedtext[16:-ord(decodedtext[-1])] #remove iv and padding print encodedtext print decodedtext
if p != 0: entr += p * math.log(p) file.close() return -entr print("Nazwa pliku: ", end="") fileName = input() print("Hasło: ", end="") password = input() print("Kodowanie") inputFile = open(fileName, "rb") outputFile = open(fileName + ".aes", "wb") key = PBKDF2(password, b'salt') iv = get_random_bytes(16) aes = AES.new(key, AES.MODE_CBC, iv) while True: c = inputFile.read(16) if not c: break if len(c) != 16: a = bytes([ord('@')] * (16 - len(c))) c += a outputFile.write(aes.encrypt(c)) outputFile.flush() outputFile.close() inputFile.close()
def newprofile(): adminflag=False pnameok=False while pnameok==False: threadqueues.secureoutput.put("please enter profile name") pname=wait_for_secure_input() print(9) fstring="/media/sf_share/samaritan-VA/current_code/front_end/backend/security/profiles/"+pname+".txt" try: f = open(fstring,"r") f.close() return("PROFILE NAME ALREADY IN USE. PLEASE TRY AGAIN.") except FileNotFoundError: pnameok=True pscheckexit=0 print("here") while(pscheckexit==0): threadqueues.secureoutput.put("PROFILE NAME: "+pname+". Please enter profile password") print(455) pps=wait_for_secure_input() print("here2") threadqueues.secureoutput.put("please confirm password") ppscheck=wait_for_secure_input() print("j") if(ppscheck==pps): pscheckexit=1 else: threadqueues.secureoutput.put("ERROR. PASSWORDS DON'T MATCH. PLEASE TRY AGAIN.") threadqueues.secureoutput.put("Do you wish this to be an admistrative account? Y/N") if(wait_for_secure_input())=="Y": exit=1 while(exit==1): threadqueues.secureoutput.put("PLEASE INPUT MASTER PASSWORD NOW") mspscheck=wait_for_secure_input() if(passwordcheck(mspscheck,"masteradmin")==True): threadqueues.secureoutput.put("MASTER PASSWORD ACCEPTED.") adminflag=True exit=0 else: threadqueues.secureoutput.put("incorrect password please try again (Y) or make ordinary profile instead (N).") rexit=1 while(rexit==1): response=wait_for_secure_input() if(response=="Y"):rexit=0 if(response=="N"): rexit=0 exit=0 else:threadqueues.secureoutput.put("invalid input. please input Y/N.") print(1234) threadqueues.secureoutput.put("please enter default location (this can be changed later)") loc=wait_for_secure_input() storedpassword=sha256_crypt.hash(pps) passwordfile = open("/media/sf_share/samaritan-VA/current_code/front_end/backend/security/keymanagement/pswds.txt", "a") passwordfile.write("\n"+pname+":"+storedpassword) passwordfile.close() profilelistfile=open("/media/sf_share/samaritan-VA/current_code/front_end/backend/security/profiles/profilelist.txt","a") if adminflag==True:privs="1011010" if adminflag==False:privs="0000000" profilelistfile.write("\n"+pname+":"+privs) fstring="/media/sf_share/samaritan-VA/current_code/front_end/backend/security/profiles/"+pname+".txt" f=open(fstring,"wb") profilestringlist=[pname,privs,loc] profilestring="" for i in profilestringlist: profilestring+=(":"+i) salt=get_random_bytes(32) filekey= PBKDF2(pps, salt, dkLen=32) data = bytes(profilestring,"utf-8") cipher = AES.new(filekey, AES.MODE_CBC) # Create a AES cipher object with the key using the mode CBC ciphered_data = cipher.encrypt(pad(data, AES.block_size)) # Pad the input data and then encrypt f.write(salt) f.write(cipher.iv) f.write(ciphered_data) f.close() print("profile created") return "nptest"
def derive_key(salt, passphrase): if not passphrase: return None return PBKDF2(passphrase, salt, 16, 1000)
def derive_key(*, password, salt, iterations, key_length): return PBKDF2(password=password, salt=salt, dkLen=key_length, count=iterations, hmac_hash_module=SHA512)
#!/usr/bin/env python from libs.rsa_py import rsa_functions from Crypto.PublicKey import RSA from Crypto.Protocol.KDF import PBKDF2 import time import base64 iterations = 4096 length = 512 seed = "394329483729326593276493274932573289462347364374877847832487348" salt = "911043357914429888194562610468866919009913916826495585249693846506602119428340566558534146092917724673924692633758" #sqrt 83 master_key = PBKDF2(seed.encode('utf-8'), salt.encode('utf-8'), dkLen=length, count=iterations) print("Master key (" + str(length) + "-byte, " + str(iterations) + " iterations): ") print(base64.b64encode(master_key)) start = time.time() n = 4096 rsa = rsa_functions.RSAPy(n,master_key) rsak = RSA.construct(rsa.keypair) private_key_readable = rsak.exportKey().decode("utf-8") public_key_readable = rsak.publickey().exportKey().decode("utf-8") end = time.time() print(str(n) + "-bit RSA public:") print(str(public_key_readable)) print(str(n) + "-bit RSA private:") print(str(private_key_readable))
from Crypto.Cipher import DES, AES from Crypto.Random import get_random_bytes from Crypto.Protocol.KDF import PBKDF2 print(PBKDF2(b"password", b"salt")) #des = DES.new("key12345") iv = get_random_bytes(8) des = DES.new("key12345".encode("utf-8"), DES.MODE_CBC, iv) encrypted = des.encrypt("secret12".encode("utf-8")) print(encrypted) iv = get_random_bytes(16) aes = AES.new(b"key1234578901238", AES.MODE_CFB, iv) encrypted = aes.encrypt("tesł".encode("utf-8")) print(encrypted)
os.system('time hashcat -a 0 -m 1800 Archivos/archivo_5 Archivos/diccionario_1.dict Archivos/diccionario_2.dict -o fileFull5 --quiet') os.system("cat fileFull5 | " + "sed 's/:/ /g' | " + "awk '{print$2}'" + " >> passFile") print('archivo 5 = '+a.rstrip('\n')) ######################################################################################################################## ######### SE HASHEAN LAS PASSWORD CON PBKDF2 Y CREA UN ARCHIVO DONDE GUARDA LAS PASS HASHEADAS ########################## O = open ('PassNewHash.txt', 'w') with open('passFile', 'r') as g: hola = g.read().splitlines() j = 0 while True: if j < len(hola): hola1 = hola[j] x = PBKDF2( hola1,'hola', 16, 1000, None) y = binascii.b2a_hex(x) #print (y.decode()) O.write(y.decode()+'\n') j = j+1 else: break O.close() g.close() ######################################################################################################################### ######## MEDIANTE SOCKET SE RECIBE LLAVE PÚBLICA, SE CIFRA EL MENSAJE Y SE ENVÍA AL "SERVIDOR" ########################## server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = "127.0.0.1"
#!/usr/bin/env python # by xychix[at]hotmail.com 4 Nov 2016 # from Crypto.Protocol.KDF import PBKDF2 from Crypto.PublicKey import RSA import sys from os import chmod password = sys.argv[1] salt = "VeryInsecure-sshkeygen" # replace with random salt if you can store one master_key = PBKDF2(password, salt, count=1000) # bigger count = better def my_rand(n): my_rand.counter += 1 return PBKDF2(master_key, "my_rand:%s" % my_rand.counter, dkLen=n, count=1) my_rand.counter = 0 print(""" This script wil generate an ssh key from a password. This way you can use ssh-keys on non-persistent machines. However I've seen different keys from the same password. Make sure you run this atleast once on a persistent (offline) machine to save the keys for emergency recovery. """) key = RSA.generate(2048, randfunc=my_rand, e=65537) pubkey = key.publickey() print("your public key:\n%s" % pubkey.exportKey('OpenSSH')) with open("insecure_rsa", 'w') as content_file: chmod("insecure_rsa", 0600)
def encrypt(password, plaintext): "Encrypt using a password string" key = PBKDF2(password, salt, key_bytes) (iv_, ciphertext) = encryptAES(key, iv, plaintext) return ciphertext
def _pbkdf2(self, password, salt, n_bytes, count): return PBKDF2(password, salt, dkLen=n_bytes, count=count, prf=lambda p, s: HMAC.new(p, s, self.HASH).digest())