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 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) elif padding == "pkcs1_oaep_256_padding": cipher = PKCS1_OAEP.new(key, SHA256) text = cipher.decrypt(ciphertext) else: raise Exception("Unsupported padding") return text
def mocksend(msg, timeout=60, tries=3): client.transport.msg = msg load = client.auth.crypticle.loads(msg["load"]) ret = server._encrypt_private( pillar_data, dictkey, target, nonce=load["nonce"], sign_messages=True ) key = client.auth.get_keys() if HAS_M2: aes = key.private_decrypt(ret["key"], RSA.pkcs1_oaep_padding) else: cipher = PKCS1_OAEP.new(key) aes = cipher.decrypt(ret["key"]) pcrypt = salt.crypt.Crypticle(client.opts, aes) signed_msg = pcrypt.loads(ret[dictkey]) # Now encrypt with a different key key = salt.crypt.Crypticle.generate_key_string() pcrypt = salt.crypt.Crypticle(opts, key) pubfn = os.path.join(master_opts["pki_dir"], "minions", "minion") pub = salt.crypt.get_rsa_pub_key(pubfn) ret[dictkey] = pcrypt.dumps(signed_msg) key = salt.utils.stringutils.to_bytes(key) if HAS_M2: ret["key"] = pub.public_encrypt(key, RSA.pkcs1_oaep_padding) else: cipher = PKCS1_OAEP.new(pub) ret["key"] = cipher.encrypt(key) raise salt.ext.tornado.gen.Return(ret)
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 RSA_3072(file_name): print() print('RSA 3072 for ' + file_name + ': ') #KEY GENERATION t1 = datetime.now() key_gen = RSA.generate(3072) t2 = datetime.now() key_speed = t2 - t1 print('TIME TAKEN FOR KEY GENERATION:(micro seconds) ' + str(key_speed.microseconds)) f = open('RSA3072_CSE565.pem', 'wb') f.write(key_gen.export_key('PEM')) f.close() #ENCRYPTION with open(file_name + ".txt", "r") as myfile: data = myfile.read() plaintext = bytes(data, 'utf-8') f = open('RSA3072_CSE565.pem', 'r') key = RSA.import_key(f.read()) # public_key = key.publickey() cipher = PKCS1_OAEP.new(key) t1 = datetime.now() ciphertext = cipher.encrypt(plaintext) t2 = datetime.now() enc_speed = t2 - t1 print('TIME TAKEN FOR ENCRYPTION:(micro seconds) ' + str(enc_speed.microseconds)) with open(file_name + "_Encrypt_RSA3072.txt", "w") as text_file: text_file.write(str(ciphertext)) print("THE ENCRYPTED FILE IS SAVED AS: " + file_name + "_Encrypt_RSA3072.....SUCCESS!") #DECRYPTION try: # private_key = key.has_private() plain = PKCS1_OAEP.new(key) t1 = datetime.now() pt = plain.decrypt(ciphertext) t2 = datetime.now() dec_speed = t2 - t1 print('TIME TAKEN FOR DECRYPTION:(micro seconds) ' + str(dec_speed.microseconds)) plaintext_decrypt = pt.decode('utf-8') # print(plaintext_decrypt) with open(file_name + "_Decrypt_RSA3072.txt", "w") as text_file: text_file.write(plaintext_decrypt) print("THE DECRYPTED FILE IS SAVED AS: " + file_name + "_Decrypt_RSA3072.....SUCCESS!") except (ValueError, KeyError): print("INCORRECT DECRYPTION!") statinfo = os.stat(file_name + ".txt") size = statinfo.st_size enc_byte = enc_speed.microseconds / size dec_byte = dec_speed.microseconds / size print("ENCRYPTION SPEED PER BYTE: " + str(enc_byte)) print("DECRYPTION SPEED PER BYTE: " + str(dec_byte))
def decrypt(data, publickeysrv): global DEBUG timedelta = datetime.datetime.now() if DEBUG: print('[{}] [Main] > Parsing data.'.format(datetime.datetime.now())) payload = data.split(b'\x00\x01\x01\x00') signature = payload[0] ciphertext = payload[1] sessionkey = payload[2] # decryption session key if DEBUG: print('[{}] [Main] > Decrypting session key.'.format( datetime.datetime.now())) cipherrsa = PKCS1_OAEP.new(privatekeycli) sessionkey = cipherrsa.decrypt(sessionkey) # decryption message if DEBUG: print('[{}] [Main] > Decrypting message.'.format( datetime.datetime.now())) iv = ciphertext[:16] obj = AES.new(sessionkey, AES.MODE_CFB, iv) message = obj.decrypt(ciphertext) message = message[16:] if DEBUG: print('[{}] [Main] > Decrypting signature.'.format( datetime.datetime.now())) # decryption signature #################################################################################################### cipherrsa = PKCS1_OAEP.new(privatekeycli) sig = cipherrsa.decrypt(signature[:256]) sig = sig + cipherrsa.decrypt(signature[256:]) if DEBUG: print('[{}] [Main] > Signature verification.'.format( datetime.datetime.now())) # signature verification verification = PKCS1_v1_5.new(publickeysrv).verify(SHA256.new(message), sig) #################################################################################################### if verification == True: if DEBUG: print('[{}] [Main] > Signature succesefully verified.'.format( datetime.datetime.now())) print( '[{}] [Main] > Message successefully decrypted for {} seconds'. format(datetime.datetime.now(), (datetime.datetime.now() - timedelta).total_seconds())) else: print('< SECURITY ALERT >') print( '[{}] [Main] > Error : Signature verification failure, your data not secure, please reconnect.' .format(datetime.datetime.now())) return message.decode('utf-8')
def room_recrypt(self, body, client_pub_key): private_key = RSA.import_key(open("Server_priv.pem").read()) # Decrypt message session key cipher_rsa = PKCS1_OAEP.new(private_key) enc_session_key = b64decode(body.session_key) session_key = cipher_rsa.decrypt(enc_session_key) # Re-encrypt the session key using the clients public key cipher_rsa = PKCS1_OAEP.new(client_pub_key) enc_session_key = cipher_rsa.encrypt(session_key) body.session_key = b64encode(enc_session_key).decode('utf-8')
def msg_sent_get(): for row in c.execute("SELECT recipient,openfield,timestamp FROM transactions WHERE address = ? AND (openfield LIKE ? OR openfield LIKE ? OR openfield LIKE ? OR openfield LIKE ?) ORDER BY timestamp DESC;", (address,) + ("msg=" + '%',) + ("bmsg=" + '%',) + ("enc=msg=" + '%',) + ("enc=bmsg=" + '%',)): try: # get alias c2.execute("SELECT openfield FROM transactions WHERE openfield LIKE ? AND address = ? ORDER BY block_height ASC, timestamp ASC LIMIT 1;", ("alias=" + '%', row[0],)) # asc for first entry msg_recipient = c2.fetchone()[0] # get alias except: msg_recipient = row[0] if row[1].startswith("enc=msg="): msg_sent_digest = row[1].lstrip("enc=msg=") try: #msg_sent_digest = key.decrypt(ast.literal_eval(msg_sent_digest)).decode("utf-8") (cipher_aes_nonce, tag, ciphertext, enc_session_key) = ast.literal_eval(msg_sent_digest) private_key = RSA.import_key(open("privkey.der").read()) # Decrypt the session key with the public RSA key cipher_rsa = PKCS1_OAEP.new(private_key) session_key = cipher_rsa.decrypt(enc_session_key) # Decrypt the data with the AES session key cipher_aes = AES.new(session_key, AES.MODE_EAX, cipher_aes_nonce) msg_sent_digest = cipher_aes.decrypt_and_verify(ciphertext, tag).decode("utf-8") except: msg_sent_digest = "Could not decrypt message" elif row[1].startswith("enc=bmsg="): msg_sent_digest = row[1].lstrip("enc=bmsg=") try: msg_sent_digest = base64.b64decode(msg_sent_digest).decode("utf-8") #msg_sent_digest = key.decrypt(ast.literal_eval(msg_sent_digest)).decode("utf-8") (cipher_aes_nonce, tag, ciphertext, enc_session_key) = ast.literal_eval(msg_sent_digest) private_key = RSA.import_key(open("privkey.der").read()) # Decrypt the session key with the public RSA key cipher_rsa = PKCS1_OAEP.new(private_key) session_key = cipher_rsa.decrypt(enc_session_key) # Decrypt the data with the AES session key cipher_aes = AES.new(session_key, AES.MODE_EAX, cipher_aes_nonce) msg_sent_digest = cipher_aes.decrypt_and_verify(ciphertext, tag).decode("utf-8") except: msg_sent_digest = "Could not decrypt message" elif row[1].startswith("bmsg="): msg_sent_digest = row[1].lstrip("bmsg=") try: msg_sent_digest = base64.b64decode(msg_sent_digest).decode("utf-8") except: msg_received_digest = "Could not decode message" elif row[1].startswith("msg="): msg_sent_digest = row[1].lstrip("msg=") msg_sent.insert(INSERT, ((time.strftime("%Y/%m/%d,%H:%M:%S", time.gmtime(float(row[2])))) + " To " + msg_recipient.replace("alias=", "") + ": " + msg_sent_digest) + "\n")
def __init__(self, public_key=None, private_key=None, passphrase=None): """RSA cipher class. Handles encryption/decryption with a RSA keypair with an optional passphrase protecting the private key. """ self._public_key = self._private_key = None if public_key: self._public_key = PKCS1_OAEP.new(RSA.importKey(public_key)) if private_key: s1, raw, s2 = PKCS8.unwrap(private_key, passphrase=passphrase) self._private_key = PKCS1_OAEP.new(RSA.importKey(raw))
def encrypt(self, msg, key, padding="pkcs1_padding"): if padding == "pkcs1_padding": cipher = PKCS1_v1_5.new(key) if self.with_digest: # add a SHA digest to the message h = SHA.new(msg) msg += h.digest() elif padding == "pkcs1_oaep_padding": cipher = PKCS1_OAEP.new(key) elif padding == "pkcs1_oaep_256_padding": cipher = PKCS1_OAEP.new(key, SHA256) else: raise Exception("Unsupported padding") return cipher.encrypt(msg)
def run(self): bufferSize = 4096 UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM) encryptor = PKCS1_OAEP.new(self.CAPublicKey) encrypted = encryptor.encrypt(self.bytesToSend) #encrypted = encryptor.encrypt(self.bytesToSend.encode()); #print ('Ciphertext Start'); #print (encrypted.hex().upper()); #print ('End'); UDPClientSocket.sendto(encrypted, self.serverAddressPort) msgFromServer = UDPClientSocket.recvfrom(bufferSize) self.message = msgFromServer[0][:64] self.signature = msgFromServer[0][64:] #print(self.signature.hex().upper()) self.messageString = format(msgFromServer[0][:64].decode("utf-8")) responseHash = SHA256.new(data=self.message) self.verified = False try: verified = False verifier = PKCS1_v1_5.new(self.CAPublicKey) verified = verifier.verify(responseHash, self.signature) self.verified = verified except ValueError: self.verified = False
def encrypt_message(a_message, publickey): encryptor = PKCS1_OAEP.new(publickey) encrypted_msg = encryptor.encrypt(a_message) #encrypted_msg = encryptor.encrypt(a_message, 32)[0] encoded_encrypted_msg = base64.b64encode( encrypted_msg) # base64 encoded strings are database friendly return encoded_encrypted_msg
def decrypt(*args, **kwargs): """Decrypt a binary file using a private key. The decryption is provided by `PyCryptodome`_. Args: *args: Input file[s]. **kwargs: Optional Arbitrary keyword arguments. They might represent a RSA private key or the output file[s]. Examples: The first argument is a list while the next argument can be both a string or a list, depending on the keyword. >>> decrypt(['spam.bin'], rsa_private_key='rsa', output=['spam.text']) .. _PyCryptodome: https://www.pycryptodome.org """ rsa_private_key = kwargs.get('rsa_private_key') for file_input_cipher in enumerate(args): filename, file_extension = os.path.splitext(file_input_cipher[1]) file_input = open(file_input_cipher[1], "rb") private_key = RSA.import_key(open(rsa_private_key).read()) enc_session_key, nonce, tag, ciphertext = [ file_input.read(x) for x in ( private_key.size_in_bytes(), 16, 16, -1)] file_input.close() # Decrypt the session key with the public RSA key cipher_rsa = PKCS1_OAEP.new(private_key) session_key = cipher_rsa.decrypt(enc_session_key) # Decrypt the data with the AES session key cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce) data = cipher_aes.decrypt_and_verify(ciphertext, tag) # Decode data decoded_data = data.decode("utf-8") # Generate the decrypted file try: file_output = open(kwargs.get('output')[file_input_cipher[0]], "w") file_output.write(decoded_data) file_output.close() except IndexError as e: print("Did you provided more input files than output files?", e) defout = filename + ".txt" # Default output :) output = input( 'Enter the next output file[' + defout + ']: ') or defout file_output = open(output, "w") file_output.write(decoded_data) file_output.close() except TypeError as e: print(file_input_cipher[0], file_input_cipher[1], ) print(decoded_data)
def encrypt(self, message): if isinstance(message, unicode): message = message.encode('utf8') cipher = PKCS1_OAEP.new(self.key) encryptedMessage = cipher.encrypt(message) return base64.b64encode(encryptedMessage)
def get_RSA_cipher(keytype): ''' Helper to grab either of the two RSA keys as needed. Returns the cipher object and the size of the key.''' with open(f'key.{keytype}') as f: key = f.read() rsakey = RSA.importKey(key) # Returns an RSA cipher object and the size of the RSA key in bytes return (PKCS1_OAEP.new(rsakey), rsakey.size_in_bytes())
def _encrypt_private(self, ret, dictkey, target): ''' The server equivalent of ReqChannel.crypted_transfer_decode_dictentry ''' # encrypt with a specific AES key pubfn = os.path.join(self.opts['pki_dir'], 'minions', target) key = salt.crypt.Crypticle.generate_key_string() pcrypt = salt.crypt.Crypticle(self.opts, key) try: pub = salt.crypt.get_rsa_pub_key(pubfn) except (ValueError, IndexError, TypeError): return self.crypticle.dumps({}) except IOError: log.error('AES key not found') return {'error': 'AES key not found'} pret = {} if HAS_M2: pret['key'] = pub.public_encrypt(six.b(key), RSA.pkcs1_oaep_padding) else: cipher = PKCS1_OAEP.new(pub) if six.PY2: pret['key'] = cipher.encrypt(key) else: pret['key'] = cipher.encrypt( salt.utils.stringutils.to_bytes(key)) pret[dictkey] = pcrypt.dumps(ret if ret is not False else {}) return pret
def main(): host = '127.0.0.1' port = 50001 s = socket.socket() s.bind((host,port)) print("server Started") s.listen(1) while True: c, addr = s.accept() print("Connection from: " + str(addr)) encAESkey=c.recv(1024) #print(encAESkey) privateKey=c.recv(1024) pikey=RSA.import_key(privateKey) RSAdecryptor=PKCS1_OAEP.new(pikey) AESkey=RSAdecryptor.decrypt(encAESkey) print("We encrypt your AESkey:",AESkey) c.send('We got the key. Thank you'.encode()) iv=c.recv(16) encmessage=c.recv(1024) AESdec=AES.new(AESkey,AES.MODE_CBC,iv) c.send('we are ready to decrypt your message'.encode()) decmessage=AESdec.decrypt(encmessage) print(decmessage.decode()) c.send('Your message is decrypted :)'.encode()) c.close()
def decrypt_user_credentials(encoded_key, encoded_iv, encoded_ct): encrypted_key = standard_b64decode(encoded_key) iv = standard_b64decode(encoded_iv) ciphertext = standard_b64decode(encoded_ct) result = get_private_key() if result.failure: return result private_key = RSA.import_key(result.value) cipher_rsa = PKCS1_OAEP.new(private_key, hashAlgo=SHA256) try: session_key = cipher_rsa.decrypt(encrypted_key) cipher_aes = AES.new(session_key, AES.MODE_CBC, iv) creds_plaintext = unpad(cipher_aes.decrypt(ciphertext), AES.block_size) except KeyError as e: error = f"Decryption Error: {repr(e)}" return Result.Fail(error) except ValueError as e: error = f"Decryption Error: {repr(e)}" return Result.Fail(error) split = creds_plaintext.decode("ascii").split(":") if len(split) != 2: error = 'User credentials not formatted correctly, expected 2 strings separated by ":" char.' return Result.Fail(error) user_creds = dict(email=split[0], password=split[1]) return Result.Ok(user_creds)
def encryptDataWithPubKey(data, pubKeyFile=RSA_pubKeyFile, outFile=None): from Cryptodome.PublicKey import RSA from Cryptodome.Random import get_random_bytes from Cryptodome.Cipher import AES, PKCS1_OAEP recipient_key = RSA.import_key(open(pubKeyFile).read()) session_key = get_random_bytes(16) # 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) print () print (ciphertext) print () print (tag) print () if outFile: file_out = open(outFile, "wb") file_out.write(cipher_rsa.encrypt(session_key)) [ file_out.write(x) for x in (ciphertext.nonce, tag, ciphertext) ]
def encrypt(message): publickey = open("public.pem", "rb") public_key = RSA.importKey(publickey.read()) encryptor = PKCS1_OAEP.new(public_key) encrypted_data = encryptor.encrypt(message) print(encrypted_data) decrypt(encrypted_data)
def crypted_transfer_decode_dictentry(self, load, dictkey=None, tries=3, timeout=60): if not self.auth.authenticated: # Return controle back to the caller, continue when authentication succeeds yield self.auth.authenticate() # Return control to the caller. When send() completes, resume by populating ret with the Future.result ret = yield self.message_client.send( self._package_load(self.auth.crypticle.dumps(load)), timeout=timeout, tries=tries, ) key = self.auth.get_keys() cipher = PKCS1_OAEP.new(key) if 'key' not in ret: # Reauth in the case our key is deleted on the master side. yield self.auth.authenticate() ret = yield self.message_client.send( self._package_load(self.auth.crypticle.dumps(load)), timeout=timeout, tries=tries, ) aes = cipher.decrypt(ret['key']) pcrypt = salt.crypt.Crypticle(self.opts, aes) data = pcrypt.loads(ret[dictkey]) if six.PY3: data = salt.transport.frame.decode_embedded_strs(data) raise tornado.gen.Return(data)
def _minion_sign_in_payload(id_): ''' Generates the payload used to authenticate with the master server. This payload consists of the passed in id_ and the ssh public key to encrypt the AES key sent back from the master. :return: Payload dictionary :rtype: dict ''' payload = {} payload['cmd'] = '_auth' payload['id'] = id_ mpub = 'minion_master.pub' token = salt.utils.stringutils.to_bytes( salt.crypt.Crypticle.generate_key_string()) pub_path = os.path.join(__opts__['pki_dir'], 'minion.pub') try: pubkey_path = os.path.join(__opts__['pki_dir'], mpub) pub = salt.crypt.get_rsa_pub_key(pubkey_path) if HAS_M2: payload['token'] = pub.public_encrypt(token, RSA.pkcs1_oaep_padding) else: cipher = PKCS1_OAEP.new(pub) payload['token'] = cipher.encrypt(token) except Exception: pass with salt.utils.files.fopen(pub_path) as f: payload['pub'] = f.read() return payload
def pps_to_csv(): private_key = get_private_key() cipher_priv = PKCS1_OAEP.new(private_key) filename = 'pps.csv' with open(filename, 'w', encoding='utf8') as f: writer = DictWriter( f, fieldnames=['participant_code', 'participant_label', 'payment_amount'] + Constants.fields_with_encryption, lineterminator='\n') writer.writeheader() for player in Player.objects.all(): row = {'participant_code': player.participant.code, 'participant_label': player.participant.label, 'payment_amount': player.total_payment} for f in Constants.fields_with_encryption: encrypted_value = getattr(player, '{}_encrypted'.format(f)) if encrypted_value is None: row[f] = '' else: decrypted_value = cipher_priv.decrypt(encrypted_value) unicode_value = decrypted_value.decode('utf-8') row[f] = unicode_value writer.writerow(row) print('wrote {}'.format(filename))
def set_active_user(self): """ A method for activating a chat with an interlocutor. :return: """ # Запрашиваем публичный ключ пользователя и создаём объект шифрования try: self.current_chat_key = self.transport.key_request( self.current_chat) client_log.debug(f'Загружен открытый ключ для {self.current_chat}') if self.current_chat_key: self.encryptor = PKCS1_OAEP.new( RSA.import_key(self.current_chat_key)) except (OSError, json.JSONDecodeError): self.current_chat_key = None self.encryptor = None client_log.debug(f'Не удалось получить ключ для {self.current_chat}') # Если ключа нет то ошибка, что не удалось начать чат с пользователем if not self.current_chat_key: self.messages.warning( self, 'Ошибка', 'Для выбранного пользователя нет ключа шифрования.') return # Ставим надпись и активируем кнопки self.ui.label_new_message.setText( f'Введите сообщенние для {self.current_chat}:') self.ui.btn_clear.setDisabled(False) self.ui.btn_send.setDisabled(False) self.ui.text_message.setDisabled(False) # Заполняем окно историю сообщений по требуемому пользователю. self.history_list_update()
def rsa_encrypt(self, data, key): data = bytes(data, 'utf-8') key = b64decode(key) key = RSA.importKey(key) cipher_rsa = PKCS1_OAEP.new(key=key, hashAlgo=SHA256.new(), mgfunc=lambda x,y: pss.MGF1(x,y, SHA1)) # cipher_rsa = PKCS1_v1_5.new(key=key) return cipher_rsa.encrypt(data)
def desencriptar(): f = open("textoCifrado.txt", "rb") mensaje = f.read() key = RSA.importKey(open("llaveprivada2.pem", "rb").read()) cifrado = PKCS1_OAEP.new(key) decifrarmensaje = cifrado.decrypt(mensaje) print(decifrarmensaje)
def testEncryptDecrypt3(self): # Verify that OAEP supports labels pt = self.rng(35) xlabel = self.rng(22) cipher = PKCS.new(self.key1024, label=xlabel) ct = cipher.encrypt(pt) self.assertEqual(cipher.decrypt(ct), pt)
def crypted_transfer_decode_dictentry( self, load, dictkey=None, timeout=60, ): if not self.auth.authenticated: yield self.auth.authenticate() ret = yield self.transport.send( self._package_load(self.auth.crypticle.dumps(load)), timeout=timeout, ) key = self.auth.get_keys() if "key" not in ret: # Reauth in the case our key is deleted on the master side. yield self.auth.authenticate() ret = yield self.transport.send( self._package_load(self.auth.crypticle.dumps(load)), timeout=timeout, ) if HAS_M2: aes = key.private_decrypt(ret["key"], RSA.pkcs1_oaep_padding) else: cipher = PKCS1_OAEP.new(key) aes = cipher.decrypt(ret["key"]) pcrypt = salt.crypt.Crypticle(self.opts, aes) data = pcrypt.loads(ret[dictkey]) data = salt.transport.frame.decode_embedded_strs(data) raise salt.ext.tornado.gen.Return(data)
def test_req_server_chan_encrypt_v1(pki_dir): loop = salt.ext.tornado.ioloop.IOLoop.current() opts = { "worker_threads": 1, "master_uri": "tcp://127.0.0.1:4506", "interface": "127.0.0.1", "ret_port": 4506, "ipv6": False, "zmq_monitor": False, "mworker_queue_niceness": False, "sock_dir": ".", "pki_dir": str(pki_dir.join("master")), "id": "minion", "__role": "minion", "keysize": 4096, } server = salt.channel.server.ReqServerChannel.factory(opts) dictkey = "pillar" nonce = "abcdefg" pillar_data = {"pillar1": "meh"} ret = server._encrypt_private(pillar_data, dictkey, "minion", sign_messages=False) assert "key" in ret assert dictkey in ret key = salt.crypt.get_rsa_key(str(pki_dir.join("minion", "minion.pem")), None) if HAS_M2: aes = key.private_decrypt(ret["key"], RSA.pkcs1_oaep_padding) else: cipher = PKCS1_OAEP.new(key) aes = cipher.decrypt(ret["key"]) pcrypt = salt.crypt.Crypticle(opts, aes) data = pcrypt.loads(ret[dictkey]) assert data == pillar_data
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 test_req_chan_decode_data_dict_entry_v1(pki_dir): mockloop = MagicMock() opts = { "master_uri": "tcp://127.0.0.1:4506", "interface": "127.0.0.1", "ret_port": 4506, "ipv6": False, "sock_dir": ".", "pki_dir": str(pki_dir.join("minion")), "id": "minion", "__role": "minion", "keysize": 4096, } master_opts = dict(opts, pki_dir=str(pki_dir.join("master"))) server = salt.channel.server.ReqServerChannel.factory(master_opts) client = salt.channel.client.ReqChannel.factory(opts, io_loop=mockloop) dictkey = "pillar" target = "minion" pillar_data = {"pillar1": "meh"} ret = server._encrypt_private(pillar_data, dictkey, target, sign_messages=False) key = client.auth.get_keys() if HAS_M2: aes = key.private_decrypt(ret["key"], RSA.pkcs1_oaep_padding) else: cipher = PKCS1_OAEP.new(key) aes = cipher.decrypt(ret["key"]) pcrypt = salt.crypt.Crypticle(client.opts, aes) ret_pillar_data = pcrypt.loads(ret[dictkey]) assert ret_pillar_data == pillar_data
def _encrypt_private(self, ret, dictkey, target): """ The server equivalent of ReqChannel.crypted_transfer_decode_dictentry """ # encrypt with a specific AES key pubfn = os.path.join(self.opts["pki_dir"], "minions", target) key = salt.crypt.Crypticle.generate_key_string() pcrypt = salt.crypt.Crypticle(self.opts, key) try: pub = salt.crypt.get_rsa_pub_key(pubfn) except (ValueError, IndexError, TypeError): return self.crypticle.dumps({}) except OSError: log.error("AES key not found") return {"error": "AES key not found"} pret = {} key = salt.utils.stringutils.to_bytes(key) if HAS_M2: pret["key"] = pub.public_encrypt(key, RSA.pkcs1_oaep_padding) else: cipher = PKCS1_OAEP.new(pub) pret["key"] = cipher.encrypt(key) pret[dictkey] = pcrypt.dumps(ret if ret is not False else {}) return pret
def Enc_first(cheque): key = get_random_bytes(32) salt = get_random_bytes(16) ctr = Counter.new(128, initial_value=bytes_to_long(salt)) cipher = AES.new(key, AES.MODE_CTR, counter=ctr) cipher_text = cipher.encrypt(bytes(json.dumps(cheque), 'utf-8')) HMAC_FIRST = b"BBuXaXBdHg+wLPjRJpf3N/NmLq5kuvzGQx3II15/j8o=" mk = hmac.new(b64decode(HMAC_FIRST), salt + cipher_text, hashlib.sha512) dataDE = b64encode(mk.digest() + salt + cipher_text).decode('utf-8') recipient_key = RSA.import_key(open('1RSAcert.pem').read()) cipher_rsa = PKCS1_OAEP.new(recipient_key) dataAB = b64encode(cipher_rsa.encrypt(key)).decode('utf-8') # шифрованный запрос return { "ab": dataAB, "de": dataDE, "kassaid": "122772", "kassatoken": "5373167af64a6e02cae10c2bf5c6a7e4", "check_type": "standart", "test": "0" }
def testEncryptDecrypt1(self): # Encrypt/Decrypt messages of length [0..128-2*20-2] for pt_len in xrange(0,128-2*20-2): pt = self.rng(pt_len) cipher = PKCS.new(self.key1024) ct = cipher.encrypt(pt) pt2 = cipher.decrypt(ct) self.assertEqual(pt,pt2)
def testDecrypt1(self): # Verify decryption using all test vectors for test in self._testData: # Build the key comps = [ long(rws(test[0][x]),16) for x in ('n','e','d') ] key = RSA.construct(comps) # The real test cipher = PKCS.new(key, test[4]) pt = cipher.decrypt(t2b(test[2])) self.assertEqual(pt, t2b(test[1]))
def encrypt(self, msg, key, padding="pkcs1_padding"): if padding == "pkcs1_padding": cipher = PKCS1_v1_5.new(key) if self.with_digest: # add a SHA digest to the message h = SHA.new(msg) msg += h.digest() elif padding == "pkcs1_oaep_padding": cipher = PKCS1_OAEP.new(key) else: raise Exception("Unsupported padding") return cipher.encrypt(msg)
def signature(email, password, key): signature = bytearray(b'\x00') struct = key_to_struct(key) signature.extend(hashlib.sha1(struct).digest()[:4]) cipher = PKCS1_OAEP.new(key) encrypted_login = cipher.encrypt((email + u'\x00' + password).encode('utf-8')) signature.extend(encrypted_login) return base64.urlsafe_b64encode(signature)
def testEncryptDecrypt4(self): # Verify that encrypt() uses the custom MGF global mgfcalls # Helper function to monitor what's requested from MGF def newMGF(seed,maskLen): global mgfcalls mgfcalls += 1 return bchr(0x00)*maskLen mgfcalls = 0 pt = self.rng(32) cipher = PKCS.new(self.key1024, mgfunc=newMGF) ct = cipher.encrypt(pt) self.assertEqual(mgfcalls, 2) self.assertEqual(cipher.decrypt(ct), pt)
def add_issuer_key(self, private_key): """ Adds a private key to the list of keys available for decryption and signatures :return: Boolean - Whether the key is already in the list """ new_key = RSAKey(key=import_rsa_key(private_key), kid=self.__generate_key_id(private_key)) for key in self.issuer_private_keys: if new_key.kid == key.kid: return False self.issuer_private_keys.append(new_key) self.loaded_issuer_private_keys[new_key.kid] = PKCS1_OAEP.new( RSA.importKey(private_key)) return True
def testEncryptDecrypt2(self): # Helper function to monitor what's requested from RNG global asked def localRng(N): global asked asked += N return self.rng(N) # Verify that OAEP is friendly to all hashes for hashmod in (MD2,MD5,SHA1,SHA256,RIPEMD160): # Verify that encrypt() asks for as many random bytes # as the hash output size asked = 0 pt = self.rng(40) cipher = PKCS.new(self.key1024, hashmod, randfunc=localRng) ct = cipher.encrypt(pt) self.assertEqual(cipher.decrypt(ct), pt) self.assertEqual(asked, hashmod.digest_size)
def parse_key_response(self, headerdata): # Init Decryption enc_key = headerdata['keyresponsedata']['keydata']['encryptionkey'] hmac_key = headerdata['keyresponsedata']['keydata']['hmackey'] encrypted_encryption_key = base64.standard_b64decode(enc_key) encrypted_sign_key = base64.standard_b64decode(hmac_key) cipher_rsa = PKCS1_OAEP.new(self.rsa_key) # Decrypt encryption key cipher_raw = cipher_rsa.decrypt(encrypted_encryption_key) encryption_key_data = json.JSONDecoder().decode(cipher_raw) self.encryption_key = self.__base64key_decode(encryption_key_data['k']) # Decrypt sign key sign_key_raw = cipher_rsa.decrypt(encrypted_sign_key) sign_key_data = json.JSONDecoder().decode(sign_key_raw) self.sign_key = self.__base64key_decode(sign_key_data['k'])
def PKCS1_OAEP_AES_decrypt(self, data, inpFile): file_in = open(inpFile, "rb") private_key = self._privateKey enc_session_key, nonce, tag, ciphertext = [ file_in.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1) ] # Decrypt the session key with the public RSA key cipher_rsa = PKCS1_OAEP.new(private_key) session_key = cipher_rsa.decrypt(enc_session_key) # Decrypt the data with the AES session key cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce) data = cipher_aes.decrypt_and_verify(ciphertext, tag) return data
def testEncrypt1(self): # Verify encryption using all test vectors for test in self._testData: # Build the key comps = [ long(rws(test[0][x]),16) for x in ('n','e') ] key = RSA.construct(comps) # RNG that takes its random numbers from a pool given # at initialization class randGen: def __init__(self, data): self.data = data self.idx = 0 def __call__(self, N): r = self.data[self.idx:N] self.idx += N return r # The real test cipher = PKCS.new(key, test[4], randfunc=randGen(t2b(test[3]))) ct = cipher.encrypt(t2b(test[1])) self.assertEqual(ct, t2b(test[2]))
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 test_lookup(self): engine = PlumberyEngine() self.assertEqual(engine.lookup('plumbery.version'), __version__) engine.secrets = {} random = engine.lookup('secret.random') self.assertEqual(len(random), 9) self.assertEqual(engine.lookup('secret.random'), random) md5 = engine.lookup('secret.random.md5') self.assertEqual(len(md5), 32) self.assertNotEqual(md5, random) sha = engine.lookup('secret.random.sha1') self.assertEqual(len(sha), 40) self.assertNotEqual(sha, random) sha = engine.lookup('secret.random.sha256') self.assertEqual(len(sha), 64) self.assertNotEqual(sha, random) id1 = engine.lookup('id1.uuid') self.assertEqual(len(id1), 36) self.assertEqual(engine.lookup('id1.uuid'), id1) id2 = engine.lookup('id2.uuid') self.assertEqual(len(id2), 36) self.assertNotEqual(id1, id2) engine.lookup('application.secret') engine.lookup('database.secret') engine.lookup('master.secret') engine.lookup('slave.secret') original = b'hello world' if HAS_CRYPTO: text = engine.lookup('pair1.rsa_public') self.assertTrue(ensure_string(text).startswith('ssh-rsa ')) key = RSA.importKey(text) cipher = PKCS1_OAEP.new(key) encrypted = cipher.encrypt(original) privateKey = engine.lookup('pair1.rsa_private') self.assertTrue(ensure_string(privateKey).startswith( '-----BEGIN RSA PRIVATE KEY-----')) key = RSA.importKey(engine.lookup('pair1.rsa_private')) cipher = PKCS1_OAEP.new(key) decrypted = cipher.decrypt(encrypted) self.assertEqual(decrypted, original) token = engine.lookup('https://discovery.etcd.io/new') self.assertEqual(token.startswith( 'https://discovery.etcd.io/'), True) self.assertEqual(len(token), 58) self.assertEqual(len(engine.secrets), 13) with self.assertRaises(LookupError): localKey = engine.lookup('local.rsa_private') localKey = engine.lookup('rsa_public.local') try: path = '~/.ssh/id_rsa.pub' with open(os.path.expanduser(path)) as stream: text = stream.read() stream.close() self.assertEqual(localKey.strip(), text.strip()) plogging.info("Successful lookup of local public key") except IOError: pass
def testMemoryview(self): pt = b("XER") cipher = PKCS.new(self.key1024) ct = cipher.encrypt(memoryview(bytearray(pt))) pt2 = cipher.decrypt(memoryview(bytearray(ct))) self.assertEqual(pt, pt2)
def decrypt(self, encryptedMessage): cipher = PKCS1_OAEP.new(self.key) if encryptedMessage is None: return None decryptedMessage = cipher.decrypt(base64.b64decode(encryptedMessage)) return decryptedMessage.decode('utf8')
def encrypt_PKCS1_OAEP(self, message): key = self._publicKey cipher = PKCS1_OAEP.new(key) ciphertext = cipher.encrypt(message) return ciphertext
def decrypt_PKCS1_OAEP(self, ciphertext): key = self._privateKey cipher = PKCS1_OAEP.new(key) message = cipher.decrypt(ciphertext) return message
def testEncrypt2(self): # Verify that encryption fails if plaintext is too long pt = '\x00'*(128-2*20-2+1) cipher = PKCS.new(self.key1024) self.assertRaises(ValueError, cipher.encrypt, pt)
def testDecrypt2(self): # Simplest possible negative tests for ct_size in (127,128,129): cipher = PKCS.new(self.key1024) self.assertRaises(ValueError, cipher.decrypt, bchr(0x00)*ct_size)