def __init__(self, public_key=None, private_key=None, aes_key=None, iv=None, magic_bytes=MAGIC_BYTES): """ :param public_key: RSA object, required for encrypting :param private_key: RSA object, required for decrypting :param aes_key: 16 bytes length string for symmetric encrypting, required for encrypting :param iv: initialization vector (16 bytes length string), required for encrypting :param magic_bytes: 2 bytes length string for marking enconded message """ self.public_key = public_key self.private_key = private_key self.aes_key = aes_key or Random.new().read(AES.block_size) self.iv = iv or Random.new().read(AES.block_size) self.block_size = AES.block_size self.magic_bytes = magic_bytes self.aes_hashes = {} self.enc_aes_key = None self.aes_key_hash = None self.base_message = None self.rsa_private_cipher = PKCS1_OAEP.new(self.private_key, hashAlgo=SHA256, mgfunc=self._mgf1_fun) \ if self.private_key else None self.rsa_public_cipher = PKCS1_OAEP.new(self.public_key, hashAlgo=SHA256, mgfunc=self._mgf1_fun) \ if self.public_key else None self.aes_cipher = AES.new(self.aes_key, AES.MODE_CBC, self.iv)
def encrypt(plaintext, key, keylen=KEYLEN): """Encrypt bytes using AES-CBC with keys of length `keylen` (defaults to KEYLEN: 256 bits). Key is passed in KDF `PBKDF2` in order to protect weak keys against brute force attacks. @param plaintext: Data to be encrypted. @type plaintext: bytes @param key: Encryption passphrase. @type key: str, bytes @param keylen: Length of the key to use in bytes. Can be either 16, 24 or 32. @type keylen: str, bytes @return: The produced ciphertext. @rtype : bytes @raise ValueError: Incorrect padding. Happens if passphrase is incorrect. """ salt = Random.new().read(AES.block_size) iv = Random.new().read(AES.block_size) key = KDF.PBKDF2(key, salt, dkLen=keylen) plaintext = Padding.pad(plaintext, AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv=iv) return base64.b64encode(salt + iv + cipher.encrypt(plaintext))
def _encrypt_password(self) -> None: """Encrypts the raw password into a form that Instagram accepts.""" if not self.state.public_api_key: return # the api key will be retrieved from the first request, so it will not # be present during the initial request key = Random.get_random_bytes(32) iv = Random.get_random_bytes(12) time = int(datetime.datetime.now().timestamp()) pubkey = base64.b64decode(self.state.public_api_key) rsa_key = RSA.importKey(pubkey) rsa_cipher = PKCS1_v1_5.new(rsa_key) encrypted_key = rsa_cipher.encrypt(key) aes = AES.new(key, AES.MODE_GCM, nonce=iv) aes.update(str(time).encode('utf-8')) encrypted_password, cipher_tag = aes.encrypt_and_digest(bytes(self._unencrypted_password, 'utf-8')) encrypted = bytes([1, int(self.state.public_api_key_id), *list(iv), *list(struct.pack('<h', len(encrypted_key))), *list(encrypted_key), *list(cipher_tag), *list(encrypted_password)]) encrypted = base64.b64encode(encrypted).decode('utf-8') self._encrypted_password = f'#PWD_INSTAGRAM:4:{time}:{encrypted}'
def start_journalist_server(): Random.atfork() journalist.app.run( port=journalist_port, debug=True, use_reloader=False, threaded=True)
def create_entry(self, group = None, title = "", image = 1, url = "", username = "", password = "", comment = "", y = 2999, mon = 12, d = 28, h = 23, min_ = 59, s = 59): """This method creates a new entry. The group which should hold the entry is needed. image must be an unsigned int >0, group a v1Group. It is possible to give an expire date in the following way: - y is the year between 1 and 9999 inclusive - mon is the month between 1 and 12 - d is a day in the given month - h is a hour between 0 and 23 - min_ is a minute between 0 and 59 - s is a second between 0 and 59 The special date 2999-12-28 23:59:59 means that entry expires never. """ if (type(title) is not str or type(image) is not int or image < 0 or type(url) is not str or type(username) is not str or type(password) is not str or type(comment) is not str or type(y) is not int or type(mon) is not int or type(d) is not int or type(h) is not int or type(min_) is not int or type(s) is not int or type(group) is not v1Group): raise KPError("One argument has not a valid type.") elif group not in self.groups: raise KPError("Group doesn't exist.") elif (y > 9999 or y < 1 or mon > 12 or mon < 1 or d > 31 or d < 1 or h > 23 or h < 0 or min_ > 59 or min_ < 0 or s > 59 or s < 0): raise KPError("No legal date") elif (((mon == 1 or mon == 3 or mon == 5 or mon == 7 or mon == 8 or mon == 10 or mon == 12) and d > 31) or ((mon == 4 or mon == 6 or mon == 9 or mon == 11) and d > 30) or (mon == 2 and d > 28)): raise KPError("Given day doesn't exist in given month") Random.atfork() uuid = Random.get_random_bytes(16) entry = v1Entry(group.id_, group, image, title, url, username, password, comment, datetime.now().replace(microsecond = 0), datetime.now().replace(microsecond = 0), datetime.now().replace(microsecond = 0), datetime(y, mon, d, h, min_, s), uuid) self.entries.append(entry) group.entries.append(entry) self._num_entries += 1 return True
def _encode_password(self, password: str = None) -> Optional[str]: """Encrypts the raw password into a form that Instagram accepts.""" if not self.state.public_api_key: return if not any([password, self._raw_password]): return key = Random.get_random_bytes(32) iv = Random.get_random_bytes(12) time = int(datetime.datetime.now().timestamp()) pubkey = base64.b64decode(self.state.public_api_key) rsa_key = RSA.importKey(pubkey) rsa_cipher = PKCS1_v1_5.new(rsa_key) encrypted_key = rsa_cipher.encrypt(key) aes = AES.new(key, AES.MODE_GCM, nonce=iv) aes.update(str(time).encode('utf-8')) encrypted_password, cipher_tag = aes.encrypt_and_digest(bytes(password or self._raw_password, 'utf-8')) encrypted = bytes([1, int(self.state.public_api_key_id), *list(iv), *list(struct.pack('<h', len(encrypted_key))), *list(encrypted_key), *list(cipher_tag), *list(encrypted_password)]) encrypted = base64.b64encode(encrypted).decode('utf-8') encrypted_password = f'#PWD_INSTAGRAM:4:{time}:{encrypted}' if password is not None: return encrypted_password self._encoded_password = encrypted_password
def setKey(self, key): #self._Key=key self._Key = Random.new().read(32) self._value = Random.new().read(AES.block_size) self._aes = AES.new(self._Key, AES.MODE_CBC, self._value)
def encMsg(msg, key): iv = Random.new().read(16) while(sys.getsizeof(iv) != 49): iv = Random.new().read(16) cipher = AES.new(key, AES.MODE_CFB, iv) msg = DIVIDER.join([iv, cipher.encrypt(msg)]) return msg
async def _encrypt_media( self, data: AsyncIterator[bytes], ) -> AsyncIterator[Union[bytes, EncryptedMediaInfo]]: aes256_key = Random.new().read(32) init_vector = Random.new().read(8) counter = Counter.new(64, prefix=init_vector, initial_value=0) cipher = AES.new(aes256_key, AES.MODE_CTR, counter=counter) sha256 = SHA256.new() async for chunk in data: encrypted = cipher.encrypt(chunk) sha256.update(encrypted) yield encrypted yield EncryptedMediaInfo( mxc=MXC("mxc://replace/me"), init_vector=encode_base64(init_vector + b"\x00" * 8), key=encode_base64(aes256_key, urlsafe=True), sha256=encode_base64(sha256.digest()), key_operations=["encrypt", "decrypt"], key_type="oct", key_algorithm="A256CTR", key_extractable=True, version="v2", )
def encrypt(message, publickeysrv): global DEBUG payload = [] timedelta = datetime.datetime.now() if DEBUG: print('[{}] [Main] > Generating signature.'.format( datetime.datetime.now())) #################################################################################################### myhash = SHA256.new(message) signature = PKCS1_v1_5.new(privatekeycli) signature = signature.sign(myhash) if DEBUG: print('[{}] [Main] > Message succesefully signed with signature.'.format( datetime.datetime.now())) # signature encrypt if DEBUG: print('[{}] [Main] > Encrypting signature.'.format( datetime.datetime.now())) cipherrsa = PKCS1_OAEP.new(publickeysrv) sig = cipherrsa.encrypt(signature[:128]) sig = sig + cipherrsa.encrypt(signature[128:]) payload.append(sig) #################################################################################################### if DEBUG: print('[{}] [Main] > Generating 256 bit session key.'.format( datetime.datetime.now())) # creation 256 bit session key sessionkey = Random.new().read(32) # 256 bit # encryption AES of the message if DEBUG: print('[{}] [Main] > Encryption AES of the message.'.format( datetime.datetime.now())) iv = Random.new().read(16) # 128 bit obj = AES.new(sessionkey, AES.MODE_CFB, iv) ciphertext = iv + obj.encrypt(message) # SEND DATA payload.append(ciphertext) # encryption RSA of the session key if DEBUG: print('[{}] [Main] > Encryption RSA of the session key.'.format( datetime.datetime.now())) cipherrsa = PKCS1_OAEP.new(publickeysrv) sessionkey = cipherrsa.encrypt(sessionkey) # SEND DATA payload.append(sessionkey) payload1 = b'\x00\x01\x01\x00'.join(payload) if DEBUG: print('[{}] [Main] > Message succesefully encrypted for {} seconds.'.format( datetime.datetime.now(), (datetime.datetime.now() - timedelta).total_seconds())) payload_recieved = payload1.split(b'\x00\x01\x01\x00') if payload == payload_recieved and len(payload) == 3: if DEBUG: print('[{}] [Main] > Payload not corrupted.'.format( datetime.datetime.now())) return(payload1) else: print('[{}] [Main] > Error : Message corrupted! Payload parts {}/{}/3'.format( datetime.datetime.now(), len(payload), len(payload_recieved))) return(b'')
def __init__(self, filepath=None, password=None, keyfile=None, read_only=False, new = False): """ Initialize a new or an existing database. If a 'filepath' and a 'masterkey' is passed 'load' will try to open a database. If 'True' is passed to 'read_only' the database will open read-only. It's also possible to create a new one, just pass 'True' to new. This will be ignored if a filepath and a masterkey is given this will be ignored. """ if filepath is not None and password is None and keyfile is None: raise KPError('Missing argument: Password or keyfile ' 'needed additionally to open an existing database!') elif type(read_only) is not bool or type(new) is not bool: raise KPError('read_only and new must be bool') elif ((filepath is not None and type(filepath) is not str) or (type(password) is not str and password is not None) or (type(keyfile) is not str and keyfile is not None)): raise KPError('filepath, masterkey and keyfile must be a string') elif (filepath is None and password is None and keyfile is None and new is False): raise KPError('Either an existing database should be opened or ' 'a new should be created.') self.groups = [] self.entries = [] self.root_group = v1Group() self.read_only = read_only self.filepath = filepath self.password = password self.keyfile = keyfile # This are attributes that are needed internally. You should not # change them directly, it could damage the database! self._group_order = [] self._entry_order = [] self._signature1 = 0x9AA2D903 self._signature2 = 0xB54BFB65 self._enc_flag = 2 self._version = 0x00030002 self._final_randomseed = '' self._enc_iv = '' self._num_groups = 1 self._num_entries = 0 self._contents_hash = '' Random.atfork() self._transf_randomseed = Random.get_random_bytes(32) self._key_transf_rounds = 150000 # Due to the design of KeePass, at least one group is needed. if new is True: self._group_order = [("id", 1), (1, 4), (2, 9), (7, 4), (8, 2), (0xFFFF, 0)] group = v1Group(1, 'Internet', 1, self, parent = self.root_group) self.root_group.children.append(group) self.groups.append(group)
def encrypt_for_master(data): # Encrypt the file so it can only be read by the bot master with open('master_public.pem', 'rb') as f: public_key = RSA.importKey(f.read()) session_key = Random.get_random_bytes(32) session_key_encrpyted = PKCS1_OAEP.new(public_key).encrypt(session_key) iv = Random.new().read(AES.block_size) data_encrypted = AES.new(session_key, AES.MODE_CFB, iv).encrypt(data) return iv + session_key_encrpyted + data_encrypted
def test_aes_gcm_with_iv_wrong_iv(self): key = b'Sixteen byte key' plain_text = b'Attack at dawn' hdr = b'To your eyes only' iv = Random.new().read(AES.block_size) mac, cipher_text = AESHandler.aes_gcm_encrypt_with_iv(plain_text, hdr, key, iv) iv = Random.new().read(AES.block_size) decrypt_out = AESHandler.aes_gcm_decrypt_with_iv(cipher_text, hdr, mac, key, iv) self.assertNotEqual(plain_text, decrypt_out)
def encrypt(api_context: ApiContext, request_bytes: bytes, custom_headers: Dict[str, str]) -> bytes: key = Random.get_random_bytes(_AES_KEY_SIZE) iv = Random.get_random_bytes(_BLOCK_SIZE) _add_header_client_encryption_key(api_context, key, custom_headers) _add_header_client_encryption_iv(iv, custom_headers) request_bytes = _encrypt_request_bytes(request_bytes, key, iv) _add_header_client_encryption_hmac(request_bytes, key, iv, custom_headers) return request_bytes
def AES_encrypt_Login(self, user, psw, returnOrdType=3): assert (type(user)) == str assert (type(psw)) == str logger = self._SetLogger(package=__name__) # if isinstance(user, str): b_user = user.encode('utf-8') # covert to bytes # if isinstance(psw, str): b_psw = psw.encode('utf-8') # covert to bytes # b_user = user.encode('utf-8') # covert to bytes # b_psw = psw.encode('utf-8') # covert to bytes logger.info(' encrypting password with user value') b_key = self._prepareKey(user) nounce = Random.get_random_bytes(16) cipher = AES.new(b_key, AES.MODE_CFB, nounce) # - text to be ciphered ciphertext = cipher.encrypt(psw.encode('utf-8')) # covert to bytes # - encrypting della psw b_cipheredPsw = self._AES_cryptedFormatData(nounce, ciphertext, returnOrdType) pswLen = len(b_cipheredPsw) # - cipheredPsw is bytearray ''' h_cipheredPsw = self.bytesToHex(b_cipheredPsw) # hex contenuto in string logger.info(' h_cipheredPsw %s' % h_cipheredPsw) # crypting dello user, usiamo la HexPSW come Key logger.info(' encrypting user value with password in strHex format') b_key = self._prepareKey(b_cipheredPsw) nounce = Random.get_random_bytes(16) cipher = AES.new(b_key, AES.MODE_CFB, nounce) # - text to be ciphered ciphertext = cipher.encrypt(user.encode('utf-8')) # convert to bytes # - encrypting dello user b_cipheredUser = self._AES_cryptedFormatData(nounce, ciphertext, returnOrdType) # - cipheredPsw is bytearray ''' h_cipheredUser = self.bytesToHex(b_cipheredUser) # hex contenuto in string logger.info(' h_cipheredUser %s' % h_cipheredUser) ''' costruzione del dato di ritorno composto dai dati HEX di PSW + USER con l'aggiunta della lunghezza della PSW calcolata sul bytes_data. ''' myData = h_cipheredPsw + h_cipheredUser + '{0:02x}'.format(pswLen) logger = self._SetLogger(package=__name__, exiting=True) return myData
def randECBCBC(message): message = Random.get_random_bytes(random.randint( 5, 10)) + message + Random.get_random_bytes(random.randint(5, 10)) choice = random.randint(0, 1) cipherText = b'' if choice == 1: # CBC aesCBC = AES_CBC() # By default makes random key and iv cipherText = aesCBC.encrypt(message) else: # ECB aesECB = AES.new(Random.get_random_bytes(16), AES.MODE_ECB) cipherText = aesECB.encrypt(pkcs7Pad(message, AES.block_size)) return message, cipherText, 'CBC' if choice == 1 else 'ECB'
def reinit_crypto(): """ When a fork arises, pycrypto needs to reinit From its doc:: Caveat: For the random number generator to work correctly, you must call Random.atfork() in both the parent and child processes after using os.fork() """ if HAS_CRYPTODOME or HAS_CRYPTO: Random.atfork()
def send_precinct(): id = ObjectId(request.args.get('id')) text = request.args.get('text') if session['rank'] == 'worker2.1' or session[ 'rank'] == 'worker2.2' or session['rank'] == 'worker2.3': privatekey = RSA.importKey( db.find_one({'username': session['username']})['privatekey']) myhash = SHA.new(bytes(text, encoding='ascii')) signature = PKCS1_v1_5.new(privatekey) signature = signature.sign(myhash) publickey = RSA.importKey( db.find_one({'rank': 'worker3'})['publickey']) cipherrsa = PKCS1_OAEP.new(publickey) sig = cipherrsa.encrypt(signature[:128]) sig = sig + cipherrsa.encrypt(signature[128:]) sig = bytes(sig) sessionkey = Random.new().read(32) iv = Random.new().read(16) obj = AES.new(sessionkey, AES.MODE_CFB, iv) ciphertext = iv + obj.encrypt(bytes(text, encoding='ascii')) ciphertext = bytes(ciphertext) sessionkey = cipherrsa.encrypt(sessionkey) sessionkey = bytes(sessionkey) applic.update_one({'application': text}, { "$set": { 'check': None, 'level': 'worker3', 'sessionkey': sessionkey, 'application': ciphertext, 'signature': sig, 'publickey1': db.find_one({'username': session['username']})['publickey'] } }) flash('You sent the application!') elif session['rank'] == 'worker3': applic.update_one( {'_id': id}, {"$set": { 'check': None, 'level': 'end', 'status': 'Finished' }}) flash('You finished this case!') return redirect('/profile')
def predict_rating(self, i, k): # predict rating of user i, item k denoted P_i,k enc_obj = ElGamal.construct( (self.p, self.g, self.user_list[i].getPubKey())) encrypted_ratings = self.user_list[i].sendRatings(self.m) sum_of_sims = 0 l = 10 #modified top_l = sorted(range(len(self.simMat[k])), key=lambda i: self.simMat[k][i])[-1 * l:] #modified #print(top_l) #print(self.simMat[k]) for j in range(self.m): if k != j: sum_of_sims += self.simMat[k][j] R_k = self.avg_ratings[k] * 200 #print(R_k) #print(sum_of_sims) #print(R_k*sum_of_sims) a = number.getRandomRange(2, self.p - 1, Random.new().read) first_term = elgEncrypt(enc_obj, pow(self.g, int(R_k * sum_of_sims), self.p), a) result = (1, 1) result = self.addElgamal(result, first_term, self.p) for j in range(self.m): if k != j: a = number.getRandomRange(2, self.p - 1, Random.new().read) R_j = self.avg_ratings[j] * 200 denom = elgEncrypt(enc_obj, pow(self.g, int(R_j), self.p), a) denom_inv = self.inv_pair(denom) inter_result = self.addElgamal(encrypted_ratings[j], denom_inv, self.p) #inter_result = encrypted_ratings[j] inter_result = (inter_result[0]**self.simMat[k][j], inter_result[1]**self.simMat[k][j]) result = self.addElgamal(result, inter_result, self.p) a = number.getRandomRange(2, self.p - 1, Random.new().read) encrypted_denom = elgEncrypt(enc_obj, pow(self.g, sum_of_sims, self.p), a) # send results to user obtain rating predicted_rating = self.user_list[i].calculate_prediction( result, encrypted_denom) result = predicted_rating / 200 #result = self.avg_ratings[k]# only the average if result > 5: result = 5 return result
def encryption_oracle(text, BS): key = Random.get_random_bytes(BS) c = random.randint(1, 2) count = random.randint(5, 10) bts = Random.get_random_bytes(count) bts1 = Random.get_random_bytes(16 - count) text = bts + text + bts1 if (c==1): result = ecb_encode(text, key) elif (c==2): IV = Random.get_random_bytes(16) result = cbc_encode(text, IV, BS, key) detect_ecb(result) print (c) return (result)
def run_3DES(): while True: try: key = DES3.adjust_key_parity(Random.get_random_bytes(24)) break except ValueError: pass nonce = Random.get_random_bytes(16) print("=================") print("Encrypting with 3DES") print("Key: ", to_hex(key)) print("Nonce: ", to_hex(nonce)) cipher = DES3.new(key, DES3.MODE_EAX, nonce) ciphertext = cipher.encrypt(data) #print("Cleartext: ", to_hex(data)) #print("Ciphertext: ", to_hex(ciphertext)) file_out = open("des3.bin", "wb") [file_out.write(x) for x in (cipher.nonce, ciphertext)] file_out.close() file_in = open("des3.bin", "rb") decrypt_nonce, decrypt_ciphertext = [file_in.read(x) for x in (16, -1)] file_in.close() print("=================") print("Decrypting with 3DES") print("Key: ", to_hex(key)) print("Nonce: ", to_hex(decrypt_nonce)) #print("Ciphertext: ", to_hex(decrypt_ciphertext)) decipher = DES3.new(key, DES3.MODE_EAX, decrypt_nonce) cleartext = decipher.decrypt(decrypt_ciphertext) #print("Cleartext: ", to_hex(cleartext)) print("=================") if cleartext == data: print("Decryption successful\n") else: print("Decryption failed\n") return
def _test_random_key(self, bits): elgObj = ElGamal.generate(bits, Random.new().read) self._check_private_key(elgObj) self._exercise_primitive(elgObj) pub = elgObj.publickey() self._check_public_key(pub) self._exercise_public_primitive(elgObj)
def test_tampering(self): password = '******' * 100 key = passwort.generate_key() k1 = passwort.Keychain() k1.use_key(key) k1.set('example.com', passwort.Keychain.PASSWORD_FIELD, password) k1.save(self.temp_filename) v1 = k1.get('example.com', passwort.Keychain.PASSWORD_FIELD) self.assertEqual(v1, password) k2 = passwort.Keychain() k2.use_key(key) k2.load(self.temp_filename) v2 = k2.get('example.com', passwort.Keychain.PASSWORD_FIELD) self.assertEqual(v2, v1) tmp = open(self.temp_filename) data = json.load(tmp) tmp.close() enc_password_value = base64.b64decode(data['example.com']['password']['text']) tampered_value = Random.new().read(16) + enc_password_value[16:] data['example.com']['password']['text'] = base64.b64encode(tampered_value).decode() f = open(self.temp_filename, "w") f.write(json.dumps(data)) f.close() k3 = passwort.Keychain() k3.use_key(key) k3.load(self.temp_filename) with self.assertRaises(NameError): k3.get('example.com', passwort.Keychain.PASSWORD_FIELD)
def getrandbits(self, k): """Return an integer with k random bits.""" if self._randfunc is None: self._randfunc = Random.new().read mask = (1 << k) - 1 return mask & bytes_to_long(self._randfunc(ceil_div(k, 8)))
def build_cipher(self, iv="", alg="aes_128_cbc"): """ :param iv: init vector :param alg: cipher algorithm :return: A Cipher instance """ typ, bits, cmode = alg.split("_") if not iv: if self.iv: iv = self.iv else: iv = Random.new().read(AES.block_size) else: assert len(iv) == AES.block_size if bits not in ["128", "192", "256"]: raise Exception("Unsupported key length") try: assert len(self.key) == int(bits) >> 3 except AssertionError: raise Exception("Wrong Key length") try: return AES.new(self.key, POSTFIX_MODE[cmode], iv), iv except KeyError: raise Exception("Unsupported chaining mode")
def generate_key() -> bytes: """ generate a new random encryption key, suitable for AES encryption we are using """ # and write it to the specified key file return Random.get_random_bytes(KEY_SIZE)
def generate_keys(): random_generator = Random.new().read key = RSA.generate(1024, random_generator) with open(PRIVATE_KEY_FILE, 'wb') as f: f.write(key.exportKey('DER')) with open(PUBLIC_KEY_FILE, 'wb') as f: f.write(key.publickey().exportKey('DER'))
def decrypt(self, ciphertext, key, padding="pkcs1_padding"): if padding == "pkcs1_padding": cipher = PKCS1_v1_5.new(key) if self.with_digest: dsize = SHA.digest_size else: dsize = 0 sentinel = Random.new().read(32 + dsize) text = cipher.decrypt(ciphertext, sentinel) if dsize: _digest = text[-dsize:] _msg = text[:-dsize] digest = SHA.new(_msg).digest() if digest == _digest: text = _msg else: raise DecryptionFailed() else: if text == sentinel: raise DecryptionFailed() elif padding == "pkcs1_oaep_padding": cipher = PKCS1_OAEP.new(key) text = cipher.decrypt(ciphertext) else: raise Exception("Unsupported padding") return text
def encrypt_data(self, login_id, login_password, account_password, certificate_password, given_key=None, file_name=None): plain_data = ';'.join((login_id, login_password, account_password, certificate_password)) if file_name is not None: self.file_name = file_name # key setting random = Random.new() raw_key = given_key if raw_key is None: raw_key = self.raw_key set_key = self.set_key(raw_key) iv = random.read(AES.block_size) encoded_key = set_key.encode() key = strxor.strxor(encoded_key, iv) # Encryption encoded_data = plain_data.encode() padded_data = Padding.pad(encoded_data, AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv) encrypted_data = cipher.encrypt(padded_data) # File writing with open(self.file_name, 'wb') as file: file.write(iv) file.write(encrypted_data)
def _generateRSAKey(self, BITS=2048, PKCS=8): random_generator = Random.new().read passPhrase = self._passPhrase # ValueError: RSA key format is not supported passPhrase = None # Funziona print ('generating..... key') key = Crypto.PublicKey.RSA.generate(BITS, random_generator) print ('created.......', key) print ('encrypting..... key') privateKey = key.exportKey(passphrase=passPhrase, pkcs=PKCS, protection="scryptAndAES128-CBC") print ('creating....... PrivateKey to file:', self._privateKeyFile) file = open(self._privateKeyFile, "wb") file.write(privateKey) file.close() print ('creating....... PublicKey to file:', self._publicKeyFile) file = open(self._publicKeyFile, "wb") file.write(key.publickey().exportKey()) file.close() print ('key.can_encrypt......: ', key.can_encrypt()) print ('key.can_sign.........: ', key.can_sign()) print ('key.has_private......: ', key.has_private())
def hide(self, input_filename, output_filename, data): """ Encrypt and save the data inside the image. :param input_filename: Input image file path :param output_filename: Output image file path :param data: Information to be encrypted and saved :return: """ # Generate a random initialization vector iv = Random.new().read(AES.block_size) encryption_suite = AES.new(self.key, AES.MODE_CBC, iv) # If it is string convert to byte string before use it if isinstance(data, str): data = data.encode() # Encrypt the random initialization vector concatenated # with the padded data cypher_data = encryption_suite.encrypt(iv + pad(data, self.block_size)) # Convert the cypher byte string to a base64 string to avoid # decode padding error cypher_data = base64.b64encode(cypher_data).decode() # Hide the encrypted message in the image with the LSB # (Least Significant Bit) technique. secret = lsb.hide(input_filename, cypher_data) # Save the image file secret.save(output_filename)
def __init__(self,key,iv=None,mode=AES.MODE_CFB): self.key=key self.mode=mode if iv: self.iv = iv else: self.iv = Random.new().read(AES.block_size)
def generate_probable_safe_prime(**kwargs): """Generate a random, probable safe prime. Note this operation is much slower than generating a simple prime. :Keywords: exact_bits : integer The desired size in bits of the probable safe prime. randfunc : callable An RNG function where candidate primes are taken from. :Return: A probable safe prime in the range 2^exact_bits > p > 2^(exact_bits-1). """ exact_bits = kwargs.pop("exact_bits", None) randfunc = kwargs.pop("randfunc", None) if kwargs: print "Unknown parameters:", kwargs.keys() if randfunc is None: randfunc = Random.new().read result = COMPOSITE while result == COMPOSITE: q = generate_probable_prime(exact_bits=exact_bits - 1, randfunc=randfunc) candidate = q * 2 + 1 if candidate.size_in_bits() != exact_bits: continue result = test_probable_prime(candidate, randfunc=randfunc) return candidate
def newkeys(keysize): logger = logging.getLogger(__name__) logger.info("Generating key, size=%dc" % keysize) random_generator = Random.new().read key = RSA.generate(keysize, random_generator) private, public = key, key.publickey() return public, private
def build_cipher(key, iv, alg="aes_128_cbc"): """ :param key: encryption key :param iv: init vector :param alg: cipher algorithm :return: A Cipher instance """ typ, bits, cmode = alg.split("_") if not iv: iv = Random.new().read(AES.block_size) else: assert len(iv) == AES.block_size if bits not in ["128", "192", "256"]: raise AESError("Unsupported key length") try: assert len(key) == int(bits) >> 3 except AssertionError: raise AESError("Wrong Key length") try: return AES.new(tobytes(key), POSTFIX_MODE[cmode], tobytes(iv)), iv except KeyError: raise AESError("Unsupported chaining mode")
def get_random_str(length: int) -> str: """ :param length: :return: a random string of the desired length. """ return Random.get_random_bytes(length).hex()[:length]
def test_generate_3args(self): rsaObj = self.rsa.generate(1024, Random.new().read,e=65537) self._check_private_key(rsaObj) self._exercise_primitive(rsaObj) pub = rsaObj.publickey() self._check_public_key(pub) self._exercise_public_primitive(rsaObj) self.assertEqual(65537,rsaObj.e)
def __init__(self, module, params): from Cryptodome import Random unittest.TestCase.__init__(self) self.module = module self.iv = Random.get_random_bytes(module.block_size) self.key = b(params['key']) self.plaintext = 100 * b(params['plaintext']) self.module_name = params.get('module_name', None)
def test_generate_2arg(self): """RSA (default implementation) generated key (2 arguments)""" rsaObj = self.rsa.generate(1024, Random.new().read) self._check_private_key(rsaObj) self._exercise_primitive(rsaObj) pub = rsaObj.publickey() self._check_public_key(pub) self._exercise_public_primitive(rsaObj)
def generate_nonce(size): """ Generate a secure random for cryptographic use. Args: size: Number of bytes for the nonce Returns: Generated random bytes """ return Random.get_random_bytes(size)
def start_source_server(): # We call Random.atfork() here because we fork the source and # journalist server from the main Python process we use to drive # our browser with multiprocessing.Process() below. These child # processes inherit the same RNG state as the parent process, which # is a problem because they would produce identical output if we # didn't re-seed them after forking. Random.atfork() config.SESSION_EXPIRATION_MINUTES = self.session_expiration source_app = create_app(config) source_app.run( port=source_port, debug=True, use_reloader=False, threaded=True)
def generate_probable_prime(**kwargs): """Generate a random probable prime. The prime will not have any specific properties (e.g. it will not be a *strong* prime). Random numbers are evaluated for primality until one passes all tests, consisting of a certain number of Miller-Rabin tests with random bases followed by a single Lucas test. The number of Miller-Rabin iterations is chosen such that the probability that the output number is a non-prime is less than 1E-30 (roughly 2^{-100}). This approach is compliant to `FIPS PUB 186-4`__. :Keywords: exact_bits : integer The desired size in bits of the probable prime. It must be at least 160. randfunc : callable An RNG function where candidate primes are taken from. prime_filter : callable A function that takes an Integer as parameter and returns True if the number can be passed to further primality tests, False if it should be immediately discarded. :Return: A probable prime in the range 2^exact_bits > p > 2^(exact_bits-1). .. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf """ exact_bits = kwargs.pop("exact_bits", None) randfunc = kwargs.pop("randfunc", None) prime_filter = kwargs.pop("prime_filter", lambda x: True) if kwargs: print "Unknown parameters:", kwargs.keys() if exact_bits is None: raise ValueError("Missing exact_bits parameter") if exact_bits < 160: raise ValueError("Prime number is not big enough.") if randfunc is None: randfunc = Random.new().read result = COMPOSITE while result == COMPOSITE: candidate = Integer.random(exact_bits=exact_bits, randfunc=randfunc) | 1 if not prime_filter(candidate): continue result = test_probable_prime(candidate, randfunc) return candidate
def test_probable_prime(candidate, randfunc=None): """Test if a number is prime. A number is qualified as prime if it passes a certain number of Miller-Rabin tests (dependent on the size of the number, but such that probability of a false positive is less than 10^-30) and a single Lucas test. For instance, a 1024-bit candidate will need to pass 4 Miller-Rabin tests. :Parameters: candidate : integer The number to test for primality. randfunc : callable The routine to draw random bytes from to select Miller-Rabin bases. :Returns: ``PROBABLE_PRIME`` if the number if prime with very high probability. ``COMPOSITE`` if the number is a composite. For efficiency reasons, ``COMPOSITE`` is also returned for small primes. """ if randfunc is None: randfunc = Random.new().read if not isinstance(candidate, Integer): candidate = Integer(candidate) # First, check trial division by the smallest primes if int(candidate) in _sieve_base: return PROBABLY_PRIME try: map(candidate.fail_if_divisible_by, _sieve_base) except ValueError: return COMPOSITE # These are the number of Miller-Rabin iterations s.t. p(k, t) < 1E-30, # with p(k, t) being the probability that a randomly chosen k-bit number # is composite but still survives t MR iterations. mr_ranges = ((220, 30), (280, 20), (390, 15), (512, 10), (620, 7), (740, 6), (890, 5), (1200, 4), (1700, 3), (3700, 2)) bit_size = candidate.size_in_bits() try: mr_iterations = list(filter(lambda x: bit_size < x[0], mr_ranges))[0][1] except IndexError: mr_iterations = 1 if miller_rabin_test(candidate, mr_iterations, randfunc=randfunc) == COMPOSITE: return COMPOSITE if lucas_test(candidate) == COMPOSITE: return COMPOSITE return PROBABLY_PRIME
def _generate_key_and_iv(encalg, cek="", iv=""): if cek and iv: return cek, iv try: _key = Random.get_random_bytes(ENCALGLEN1[encalg]) _iv = Random.get_random_bytes(12) except KeyError: try: _key = Random.get_random_bytes(ENCALGLEN2[encalg]) _iv = Random.get_random_bytes(16) except KeyError: raise Exception("Unsupported encryption algorithm %s" % encalg) if cek: _key = cek if iv: _iv = iv return _key, _iv
def __init__(self, key): self.rndfile = Random.new() if key == None: log.write("Initalizing key") self.key = self.rndfile.read(self.KEY_SIZE) keyfile = open(self.KEYFILE, 'wb'); keyfile.write(self.key) else: self.key = key self.IV = b"jamsomwareiscool"
def encode(self, raw): """ Encodes data :param data: Data to be encoded :type data: str :returns: string -- Encoded data """ raw = bytes(Padding.pad(data_to_pad=raw, block_size=self.bs)) iv = Random.new().read(AES.block_size) cipher = AES.new(self.crypt_key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw))
def enc(enc_key, hmac_key, plaintext=None): plaintext_bytes = plaintext.encode() iv = Random.new().read(IV_SIZE) h = hmac(hmac_key) h.update(plaintext_bytes) hmac_tag = base64.b64encode(h.digest()).decode() ciphertext = base64.b64encode(cipher(enc_key, iv).encrypt(pad(plaintext_bytes))).decode() return dict(algorithm=ALGO_NAME, timestamp=calendar.timegm(time.gmtime()), iv=base64.b64encode(iv).decode(), hmac=hmac_tag, text=ciphertext)
def AES_encrypt(self, clearMsg, returnOrdType=3, returnDataTYPE='bytes'): # print (type (clearMsg), clearMsg) if isinstance(clearMsg, str): clearMsg = clearMsg.encode('utf-8') # covert to bytes # if isinstance(clearMsg, str): clearMsg = bytes(clearMsg, 'utf-8') # covert to bytes # print (type (clearMsg), clearMsg) nounce = Random.get_random_bytes(16) cipher = AES.new(self._key, AES.MODE_CFB, nounce) ciphertext = cipher.encrypt(clearMsg) retValue = self._AES_cryptedFormatData(nounce, ciphertext, returnOrdType) if returnDataTYPE == 'hex': return self.bytesToHex(retValue) elif returnDataTYPE == 'base64': return self.bytesToBase64(retValue) else: return bytes(retValue)
def AES_encrypt(self, clearMsg, returnOrdType=3, returnDataType='bytes'): if isinstance(clearMsg, str): clearMsg = clearMsg.encode('utf-8') # covert to bytes nounce = Random.get_random_bytes(16) cipher = AES.new(self._key, AES.MODE_CFB, nounce) ciphertext = cipher.encrypt(clearMsg) retValue = self._AES_cryptedFormatData(nounce, ciphertext, returnOrdType) ''' retValue is bytearray ''' if returnDataType == 'hex-str': return self.bytesToHex(retValue) # hex contenuto in string elif returnDataType == 'base64': return self.bytesToBase64(retValue) return bytes(retValue)
def encrypt(self, raw): """ Encryptes the parameter raw. :type raw: bytes :rtype: str :param: bytes to be encrypted. :return: A base 64 encoded string. """ raw = self._pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(self.key, AES.MODE_CBC, iv) return base64.urlsafe_b64encode(iv + cipher.encrypt(raw))
def random_range(cls, **kwargs): """Generate a random integer within a given internal. :Keywords: min_inclusive : integer The lower end of the interval (inclusive). max_inclusive : integer The higher end of the interval (inclusive). max_exclusive : integer The higher end of the interval (exclusive). randfunc : callable A function that returns a random byte string. The length of the byte string is passed as parameter. Optional. If not provided (or ``None``), randomness is read from the system RNG. :Returns: An Integer randomly taken in the given interval. """ min_inclusive = kwargs.pop("min_inclusive", None) max_inclusive = kwargs.pop("max_inclusive", None) max_exclusive = kwargs.pop("max_exclusive", None) randfunc = kwargs.pop("randfunc", None) if kwargs: raise ValueError("Unknown keywords: " + str(kwargs.keys)) if None not in (max_inclusive, max_exclusive): raise ValueError("max_inclusive and max_exclusive cannot be both" " specified") if max_exclusive is not None: max_inclusive = max_exclusive - 1 if None in (min_inclusive, max_inclusive): raise ValueError("Missing keyword to identify the interval") if randfunc is None: randfunc = Random.new().read norm_maximum = max_inclusive - min_inclusive bits_needed = cls(norm_maximum).size_in_bits() norm_candidate = -1 while not 0 <= norm_candidate <= norm_maximum: norm_candidate = cls.random( max_bits=bits_needed, randfunc=randfunc ) return norm_candidate + min_inclusive
def _random(**kwargs): """Generate a random natural integer of a certain size. :Keywords: exact_bits : positive integer The length in bits of the resulting random Integer number. The number is guaranteed to fulfil the relation: 2^bits > result >= 2^(bits - 1) max_bits : positive integer The maximum length in bits of the resulting random Integer number. The number is guaranteed to fulfil the relation: 2^bits > result >=0 randfunc : callable A function that returns a random byte string. The length of the byte string is passed as parameter. Optional. If not provided (or ``None``), randomness is read from the system RNG. :Return: a Integer object """ exact_bits = kwargs.pop("exact_bits", None) max_bits = kwargs.pop("max_bits", None) randfunc = kwargs.pop("randfunc", None) if randfunc is None: randfunc = Random.new().read if exact_bits is None and max_bits is None: raise ValueError("Either 'exact_bits' or 'max_bits' must be specified") if exact_bits is not None and max_bits is not None: raise ValueError("'exact_bits' and 'max_bits' are mutually exclusive") bits = exact_bits or max_bits bytes_needed = ((bits - 1) // 8) + 1 significant_bits_msb = 8 - (bytes_needed * 8 - bits) msb = bord(randfunc(1)[0]) if exact_bits is not None: msb |= 1 << (significant_bits_msb - 1) msb &= (1 << significant_bits_msb) - 1 return Integer.from_bytes(bchr(msb) + randfunc(bytes_needed - 1))
def AesEncrypt(key, clearData, block_size=32, retType='hex'): b_clearData = clearData if isinstance(clearData, bytes) else clearData.encode(MY_UNICODE).strip() # covert to bytes b_key = key if isinstance(key, bytes) else key.encode(MY_UNICODE).strip() # covert to bytes # generate nounce b_nounce = Random.new().read(AES.block_size) # oppure nounce = Random.get_random_bytes(AES.block_size) # cript Data cipher = _getCipher(key=b_key, nounce=b_nounce, blkSize=block_size) b_cipheredData = cipher.encrypt(b_clearData) # cript key with cipheredData as key cipher = _getCipher(key=b_cipheredData, nounce=b_nounce, blkSize=block_size) b_cipheredKey = cipher.encrypt(b_key) if retType == 'hex': h_nounce = ''.join("%02x" % b for b in b_nounce) h_key = ''.join("%02x" % b for b in b_cipheredKey) h_data = ''.join("%02x" % b for b in b_cipheredData) myData = '' myData += '{:02x}'.format(len(h_nounce)) myData += '{:02x}'.format(len(h_key)) myData += '{:02x}'.format(len(h_data)) myData += '{:02x}'.format(block_size) myData += h_nounce myData += h_key myData += h_data elif retType == 'base64': nounce = base64.b64encode(b_nounce) data = base64.b64encode(cipheredData) key = base64.b64encode(cipheredKey) elif retType == 'bytes': pass return myData
def PKCS1_OAEP_AES_encrypt(self, data, outFile): # recipient_key = Crypto.PublicKey.RSA.import_key(open("receiver.pem").read()) recipient_key = self._privateKey session_key = Random.get_random_bytes(32) # Encrypt the session key with the public RSA key cipher_rsa = PKCS1_OAEP.new(recipient_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(data) # creazione del file con i dati crypted print ('file {FILE} has been created with encrypted data.'.format(FILE=outFile)) file_out = open(outFile, "wb") file_out.write(cipher_rsa.encrypt(session_key)) [ file_out.write(x) for x in (cipher_aes.nonce, tag, ciphertext) ] return ciphertext
def build_cipher(key, iv, alg="aes_128_cbc"): """ :param key: encryption key :param iv: init vector :param alg: cipher algorithm :return: A Cipher instance """ typ, bits, cmode = alg.split("_") if not iv: iv = Random.new().read(AES.block_size) else: assert len(iv) == AES.block_size if bits not in ["128", "192", "256"]: raise AESError("Unsupported key length") if len(key) != int(bits) >> 3: raise AESError("Wrong Key length") try: return AES.new(tobytes(key), POSTFIX_MODE[cmode], tobytes(iv)), iv except KeyError: raise AESError("Unsupported chaining mode")