def __init__(self, dir=None, key='', passphrase=None, cipher=utils.AESCipher): super(LocalRsaProvider, self).__init__(cipher=cipher) self.dir = dir or os.path.join(os.path.expanduser('~'), _LOCAL_RSA_TMP_DIR) utils.makedir_p(self.dir) priv_key_full_path = os.path.join(self.dir, key + self.PRIV_KEY_FILE) pub_key_full_path = os.path.join(self.dir, key + self.PUB_KEY_FILE) try: if os.path.exists(priv_key_full_path) and os.path.exists(pub_key_full_path): with open(priv_key_full_path, 'rb') as f: self.__decrypt_obj = PKCS1_OAEP.new(RSA.importKey(f.read(), passphrase=passphrase)) with open(pub_key_full_path, 'rb') as f: self.__encrypt_obj = PKCS1_OAEP.new(RSA.importKey(f.read(), passphrase=passphrase)) else: private_key = RSA.generate(2048) public_key = private_key.publickey() self.__encrypt_obj = PKCS1_OAEP.new(public_key) self.__decrypt_obj = PKCS1_OAEP.new(private_key) with open(priv_key_full_path, 'wb') as f: f.write(private_key.exportKey(passphrase=passphrase)) with open(pub_key_full_path, 'wb') as f: f.write(public_key.exportKey(passphrase=passphrase)) except (ValueError, TypeError, IndexError) as e: raise ClientError(str(e))
def reset_user_invalid_keys(user, admin_rsa): """ Legacy, recrypts all encrypted objects with user's new pubkey(s) """ otype, oid = ContentType.objects.get_for_model(user), user.id ipubs = OwnerPublicKey.inactive.filter(owner_type=otype, owner_id=oid, active=False) for ipub in ipubs: adminclearkey = PKCS1_OAEP.new(admin_rsa).decrypt(b64decode(ipub.admincipher)) # import inactive key irsa = import_rsa(ipub.adminscopy, adminclearkey) # get matching active public key for user apub = OwnerPublicKey.objects.get(owner_type=otype, owner_id=oid, keytype=ipub.keytype, active=True) # import new active publickey apublickey = import_rsa(apub.publickey) # update encrypted objects encrypting via new active public key for encobj in EncryptedObject.objects.filter(opub=ipub): clearkey = PKCS1_OAEP.new(irsa).decrypt(b64decode(encobj.cipherkey)) encobj.cipherkey = b64encode(PKCS1_OAEP.new(apublickey).encrypt(clearkey)) encobj.opub = apub # point encobj's opub to new pubkey encobj.save() apubs = OwnerPublicKey.objects.filter_pubkey(owner=user) # reset user's private keys outside their own pubkeys if any, eg. practice locations privs = UserPrivateKey.objects.filter( user=user, credtype=CRED_WEBAPP).exclude(opub__in=apubs) reset_keys(privs, admin_rsa) # and remove inactive public keys ipubs.delete()
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) ct = PKCS.encrypt(pt, self.key1024) pt2 = PKCS.decrypt(ct, self.key1024) self.assertEqual(pt,pt2)
def __init__(self, from_file=None, passphrase=None): if from_file == None: # generate a new pair rng = Random.new().read key = RSA.generate(4096 * 2, rng) self.public_key = IdentityPublicKey(key) self.private_key = IdentityPrivateKey(key) else: # read from file: f = open(from_file, "rb") contents = f.read(4096 * 1024) # no more than 4mb f.close() key = RSA.importKey(contents.decode("utf-8", "ignore"), passphrase=passphrase) self.public_key = IdentityPublicKey(key) if key.has_private(): self.private_key = IdentityPrivateKey(key) else: self.private_key = None # ensure the minimum required RSA key size is met: if self.public_key.size() < ENCRYPT_BIT_MINIMUM or (\ self.private_key != None and \ self.private_key.size() < ENCRYPT_BIT_MINIMUM): self.private_key = None self.public_key = None raise ValueError("this RSA key doesn't meet the required " +\ "minimum bit size for proper encryption") if self.private_key != None: self.cipher = PKCS1_OAEP.new(self.private_key.key, hashAlgo=SHA256) else: self.cipher = PKCS1_OAEP.new(self.public_key.key, hashAlgo=SHA256)
def __generate(self, keydata): ''' Generate the pycrypto rsa object ''' if keydata: if 'components' not in keydata: raise ValueError('Invalid keydata, no components') key = RSA.construct(keydata['components']) if key.has_private(): self.priv = key self.pub = key.publickey() self.sign_key = PKCS1_PSS.new(self.priv) self.verify_key = PKCS1_PSS.new(self.pub) self.decrypter = PKCS1_OAEP.new(self.priv) else: self.pub = key self.verify_key = PKCS1_PSS.new(self.pub) self.keydata = keydata else: self.priv = self._gen_key() self.pub = self.priv.publickey() self.sign_key = PKCS1_PSS.new(self.priv) self.verify_key = PKCS1_PSS.new(self.pub) self.keydata = self._gen_keydata(self.priv) self.decrypter = PKCS1_OAEP.new(self.priv) self.encrypter = PKCS1_OAEP.new(self.pub) self.max_msg_size = self.get_max_msg_size() self.enc_chunk_size = self.get_enc_chunk_size()
def share_directory(other_username, dlog): with open(dlog, 'rb') as input: log = pickle.load(input) userList = log['users'] userList.append(other_username) owner_block = log[owner] owner = log['owner'] key = RSA.importKey(open(owner + '.pri').read()) cipher = PKCS1_OAEP.new(key, SHA256.new()) owner_block.decrypt_permission_block(cipher) file_aes_key = owner_block.get_file_encryption_key() file_dsa_key = None user_block = AccessBlock(file_aes_key, file_dsa_key) other_key = RSA.importKey(open(other_username + '.pub').read()) other_cipher = PKCS1_OAEP.new(other_key, SHA256.new()) user_block.encrypt_permission_block(other_cipher) log[other_username] = user_block file_log_hash = SHA256.new() with open(filelog, 'wb') as infile: pickle.dump(log, infile, -1) length = len(log) with open(filelog, 'rb') as outfile: picklelog = outfile.read(length) file_log_hash.update(picklelog) with open(owner + '.dsa', 'rb') as infile: owner_msk = pickle.load(infile) k = random.StrongRandom().randint(1,owner_msk.q-1) sig = owner_msk.sign(file_log_hash.digest(), k) with open(filelog, 'a+b') as outfile: pickle.dump(sig, outfile, -1)
def leftclick(event): name = None select = None s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() port = 9999 s.connect((host, port)) name = listbox1.get("active") select =("SELECT name FROM public.people WHERE age = 19 ") print (select) key = RSA.importKey(open('../public.der').read()) cipher = PKCS1_OAEP.new(key) select = cipher.encrypt(select.encode('utf-8')) print("select is " ) print(select) s.send(select) names = s.recv(1024) print(names) keya = RSA.importKey(open('../private.der').read()) cipher = PKCS1_OAEP.new(keya) message = str_to_list(cipher.decrypt(names).decode('utf-8')) print(message[0][0]) s.close() text1.insert(1.0, "ваыа") name = None names=None
def msg_received_get(addlist): for x in addlist: if x[11].startswith(("msg=", "bmsg=", "enc=msg=", "enc=bmsg=")) and x[3] == address: #print(x[11]) connections.send(s, "aliasget", 10) connections.send(s, x[2], 10) msg_address = connections.receive(s,10)[0][0] if x[11].startswith("enc=msg="): msg_received_digest = x[11].lstrip("enc=msg=") try: #msg_received_digest = key.decrypt(ast.literal_eval(msg_received_digest)).decode("utf-8") (cipher_aes_nonce, tag, ciphertext, enc_session_key) = ast.literal_eval(msg_received_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_received_digest = cipher_aes.decrypt_and_verify(ciphertext, tag).decode("utf-8") except: msg_received_digest = "Could not decrypt message" elif x[11].startswith("enc=bmsg="): msg_received_digest = x[11].lstrip("enc=bmsg=") try: msg_received_digest = base64.b64decode(msg_received_digest).decode("utf-8") #msg_received_digest = key.decrypt(ast.literal_eval(msg_received_digest)).decode("utf-8") (cipher_aes_nonce, tag, ciphertext, enc_session_key) = ast.literal_eval(msg_received_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_received_digest = cipher_aes.decrypt_and_verify(ciphertext, tag).decode("utf-8") except: msg_received_digest = "Could not decrypt message" elif x[11].startswith("bmsg="): msg_received_digest = x[11].lstrip("bmsg=") try: msg_received_digest = base64.b64decode(msg_received_digest).decode("utf-8") except: msg_received_digest = "Could not decode message" elif x[11].startswith("msg="): msg_received_digest = x[11].lstrip("msg=") msg_received.insert(INSERT, ((time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(float(x[1])))) + " From " + msg_address.lstrip("alias=") + ": " + msg_received_digest) + "\n")
def setUp(self): #logging.basicConfig(level=logging.DEBUG) logging.basicConfig(level=logging.ERROR) #self._t0 = int(time.time()) self._key = RSA.generate(2048) self._encrypt = PKCS1_OAEP.new(self._key.publickey()) self._decrypt = PKCS1_OAEP.new(self._key) self._t0 = time.time()
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_file, private_key_file): with open(public_key_file,'rb') as pkf: pubkey_string = pkf.read() self.public_key = RSA.importKey(pubkey_string) with open(private_key_file,'rb') as pkf: privkey_string = pkf.read() self.private_key = RSA.importKey(privkey_string) self.public = PKCS1_OAEP.new(self.public_key) self.private = PKCS1_OAEP.new(self.private_key) self.signer = PKCS1_v1_5.new(self.private_key) self.verifier = PKCS1_v1_5.new(self.public_key)
def messages(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = MessageForm(request.POST) if 'message' in request.POST: # check whether it's valid: if form.is_valid(): # extract data from form.cleaned_data to = form.cleaned_data['message_recipient'] sender = request.user body = form.cleaned_data['message_body'] e = form.cleaned_data['encrypted'] # recipient username might not exist user = User.objects.filter(username=to) if user.exists(): if e: u = User.objects.get(username=to) public_key = RSA.importKey(u.reporter.publickey) cipher = PKCS1_OAEP.new(public_key) enc_data = b64encode(cipher.encrypt(body.encode('UTF-8'))) body = enc_data m = Message(sender=sender, recipient=user.get(), body=body, encrypted=e) m.save() # redirect to same page return HttpResponseRedirect('') # DELETE MESSAGE: If "delete message" was selected... elif 'delete' in request.POST: for d in request.POST.getlist('del'): m = Message.objects.get(id=d) m.delete() # DECRYPT MESSAGE: If "decrypt" was selected... elif 'decrypt' in request.POST: u = User.objects.get(username=request.user) private_key = RSA.importKey(u.reporter.privatekey) # For each checked message... for d in request.POST.getlist('del'): cipher = PKCS1_OAEP.new(private_key) m = Message.objects.get(id=d) try: m.body = cipher.decrypt(b64decode(m.body)).decode(encoding='UTF-8') except: # if invalid ciphertext blob continue m.save() else: form = MessageForm() # Prepare messages for rendering... messages = Message.objects.filter(recipient=request.user) return render(request, 'messages.html', {'form': form, 'messages': messages})
def initActive(self, self_prv_key, peer_pub_key): self.active = True self.self_prv_key = self_prv_key self.peer_pub_key = peer_pub_key self.self_asym_decrypter = PKCS1_OAEP.new(self.self_prv_key) self.peer_asym_encrypter = PKCS1_OAEP.new(self.peer_pub_key) self.self_signer = PKCS1_PSS.new(self.self_prv_key) self.peer_verifier = PKCS1_PSS.new(self.peer_pub_key) return self
def share(self, filename, user): '''probe if file/dir''' folder_metadata = self.dbxclient.metadata(self.cwd + "/" + filename) if folder_metadata['is_dir'] : isdir = True else: isdir = False ''' get shadow file and update permissions''' '''Expect only one level in filename i.e. no dir1/dir2/file.txt''' if isdir: hostdirpath = self.cwd + "/" + filename shadowfile = hostdirpath + "/" + filename + ".sdw" else: shadowfile = self.cwd + "/" + filename + ".sdw" localshadowfile = "users/" + self.username + "/" + filename + ".sdw" with self.dbxclient.get_file(shadowfile) as df: permtable = json.load(df) if not self.username in permtable.keys(): print('You donot have permissions to do this operation') return else: ''' get the key ''' b64cipherkey = permtable[self.username] encryptedkey = base64.decodestring(b64cipherkey) '''Decrypt above key using owner's private key ''' cipher = PKCS1_OAEP.new(RSA.importKey(self.prkey)) decryptedkey = cipher.decrypt(encryptedkey) '''get the public key of user''' row = self.dbhandle.getuser(user) userpbkey = row[0] '''Encrypt above decryptedkey using owner's public key ''' usercipher = PKCS1_OAEP.new(RSA.importKey(userpbkey)) userencryptedkey = usercipher.encrypt(decryptedkey) '''update permissions''' permtable[user] = base64.encodestring(userencryptedkey) with open(localshadowfile, "w+") as sdw: json.dump(permtable, sdw) with open(localshadowfile, "r") as sdw: response = self.dbxclient.put_file(shadowfile, sdw, overwrite=True) #print(("Upload status: ", response) ) return
def encrypt(self, message): # Init RSA with PKCS1_OAEP if self.rsa_key is None: self.load() pkcs = PKCS1_OAEP.new(self.rsa_key, SHA256.new()) # Init AES iv = self.generate_iv() pw = self.generate_pw('My secret password') aes_key = AES.new(pw, AES.MODE_CBC, iv) cipher = PKCS1_OAEP.new(self.rsa_key, SHA256.new()) ciphertext = cipher.encrypt(message) return ciphertext
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 encryptString(self, inputstr): i = 0 obj = bytearray(5) rsaKey, obj = self.createKeyFromString(self.KEY, obj) if rsaKey is None: return "" try: bytes = inputstr.encode('utf-8') bLen = int(((len(bytes) - 1) / 86)) + 1 obj2 = bytearray(bLen * 133) encryptor = PKCS1_OAEP.new(rsaKey) while i < bLen: offset = i * 86 strlen = (len(bytes) - offset if i == ( bLen - 1) else 86) + offset encstr = encryptor.encrypt(bytes[offset:strlen]) obj2[i * 133:i * 133 + len(obj)] = obj obj2[ i * 133 + len(obj):i * 133 + len(obj) + len(encstr)] = encstr i += 1 return base64.urlsafe_b64encode(obj2) except Exception as e: print(e) return ""
def encrypt_string(plaintext): chunk_size = 256 print "Compressing: %d bytes" % len(plaintext) plaintext = zlib.compress(plaintext) print "Encrypting %d bytes" % len(plaintext) rsakey = RSA.import(public_key) rsakey = PKCS1_OAEP.new(rsakey) encrypted = "" offset = 0 while offset < len(plaintext): chunk = plaintext[offset:offset+chunk_size] if len(chunk) % chunk_size !=0: chunk += " " *(chunk_size - len(chunk)) encrypted += rsakey.encrypt(chunk) offset += chunk_size encrypted = encrypted.encode("base64") print "Base64 encoded crypto: %d" % len(encrypted) return encrypted
def redirect(self, encryption_key): """Throws an exception that indicates we should redirect. This is built to work around AWS' API Gateway's limitations. We want to be able to serve both 200s and 302s, but API Gateway only allow one type of response code on success. So to serve both 200s and 302s, we need to throw an exception for at least one of these, and we choose to do this for 302s. The next limitation is that when a lambda function throws exceptions, it returns a dictionary like { stackTrace: [], errorType: "", errorMessage: "" } so in order to pass the redirect url along, we need to fit it into one of these. The API Gateway allows us to read these fields, but not do post processing. So we make the error message be exactly the url we want. """ # TODO: make sure email and password aren't url encoded. cipher = PKCS1_OAEP.new(encryption_key) token = json.dumps({"email": self.email, "password": self.password}) encrypted_token = cipher.encrypt(token) # url encoding can handle the encrypted token, but b64 encoding it makes # it short and arguably nicer to read encoded_encrypted_token = base64.b64encode(encrypted_token) fragment = urllib.urlencode({ "state": self.state, "token_type": "bearer", "access_token": encoded_encrypted_token }) url = REDIRECT_URI + "#" + fragment raise RedirectException(url)
def main(): port = 60005 IP = '127.0.0.1' pub_key = """-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCeNVj2v/gT/eHZm1RSH1w5dkzc MyhA/nbSrAV6KWiDCjKKXK1si5+0llK9eUcCf55F5swag1JYzxxVaJQyMFUAImsV J+3OMysYLDZCN2tAeYzlSZptPs/JY0KaFRNXinDG9EyaTdpvrC4d72KT8qw5eDwS gyR1XwJKoRUGYjki+wIDAQAB -----END PUBLIC KEY-----""" S = socket.socket(socket.AF_INET, socket.SOCK_STREAM) S.settimeout(5) try: S.connect((IP, port)) while 1: plaintext = raw_input("What message should we encrypt?: ").rstrip() if plaintext == "stop": S.close() sys.exit(1) print "Compressing %d bytes" % len(plaintext) plaintext = zlib.compress(plaintext) print "Encrypting %d bytes" % len(plaintext) rsakey = RSA.importKey(pub_key) rsakey = PKCS1_OAEP.new(rsakey) encrypted = rsakey.encrypt(plaintext) S.send(encrypted) except Exception, e: print "Error: " + str(e)
def read_encrypted_logs(username, filelogs): names = [] my_key = RSA.importKey(open(username + '.pri').read()) cipher = PKCS1_OAEP.new(my_key, SHA256.new()) for log in filelogs: file_log_hash = SHA256.new() with open(log, 'rb') as input: dictlog = pickle.load(input) sig = pickle.load(input) owner = dictlog['owner'] with open(owner + '.dsapub', 'rb') as input: owner_msk = pickle.load(input) length = len(dictlog) with open(log, 'rb') as outfile: picklelog = outfile.read(length) file_log_hash.update(picklelog) if not owner_msk.verify(file_log_hash.digest(), sig): print('invalid file') if username in dictlog: block = dictlog[username] block.decrypt_permission_block(cipher) name = decrypt_filename(block.get_file_encryption_key(), log[0:-5]) names.append(name) return names
def rsa_decrypt(data, rsa_priv_key_str): """ When given some `data` and an RSA private key, decrypt the data """ key = RSA.importKey(rsa_priv_key_str) cipher = PKCS1_OAEP.new(key) return cipher.decrypt(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 rename_directory(username, old_filename, new_filename): filelog = oldfilename + '.flog' with open(filelog, 'rb') as input: log = pickle.load(input) sig = pickle.load(input) block = log[username] key = RSA.importKey(open(username + '.pri').read()) cipher = PKCS1_OAEP.new(key, SHA256.new()) block.decrypt_permission_block(cipher) encrypted_new_filename = encrypt_filename(block.get_file_encryption_key(), new_filename) log['encrypted_name'] = encrypted_new_filename new_filelog = encrypted_new_filename + '.dlog' with open(new_filelog, 'wb') as outfile: pickle.dump(log) length = len(log) with open(new_filelog, 'rb') as infile: pickleload = infile.read(length) file_log_hash = SHA256.new() file_log_hash.update(picklelog) with open(username + '.dsa', 'rb') as infile: owner_msk = pickle.load(infile) k = random.StrongRandom().randint(1,owner_msk.q-1) sig = owner_msk.sign(file_log_hash.digest(), k) with open(new_filelog, 'a+b') as outfile: pickle.dump(sig, outfile, -1) return encrypted_new_filename
def decipherRequest(request): key = open('server.pem','r') rsa = RSA.importKey(key) privdecipher = PKCS1_OAEP.new(rsa) key.close() deciphered = privdecipher.decrypt(request.decode('hex')) return json.loads(deciphered)
def encrypt(self, data): offset = 0 encrypted = "".encode() fp = open(self.public_key_path, 'rb') rsa_key = RSA.importKey(fp.read().decode()) oaep_encryptor = PKCS1_OAEP.new(rsa_key) fp.close() print(len(data)) while offset < len(data): chunk = data[offset:offset + self.chunk_size] if len(chunk) % self.chunk_size != 0: try: chunk += " " * (self.chunk_size - len(chunk)) except TypeError: chunk = chunk.decode() chunk += " " * (self.chunk_size - len(chunk)) print('0enc length ' + str(len(chunk))) try: bin_chunk = chunk.encode() except AttributeError: # chunk is already here bin_chunk = chunk print('1enc length ' + str(len(bin_chunk))) encrypted_chunk = oaep_encryptor.encrypt(bin_chunk) print('11enc length ' + str(len(encrypted_chunk))) encrypted += encrypted_chunk offset += self.chunk_size return encrypted
def decrypt_master_key(master_key_cipher, private_key): """ Decrypt a secret key with the provided private RSA key. """ key = RSA.importKey(private_key) cipher = PKCS1_OAEP.new(key) return cipher.decrypt(master_key_cipher)
def encrypt_master_key(master_key, public_key): """ Encrypt a secret key with the provided public RSA key. """ key = RSA.importKey(public_key) cipher = PKCS1_OAEP.new(key) return cipher.encrypt(master_key)
def encrypt_file_rsa(self): ktu = force_integer_input("Key to use:")-1 try: ktu_ac = self.key_list[ktu] print('2: SHA-512 with key rotation, hash chain and plaintext feedback') print('3: 3AES-EDE in CTR mode with independent keys and IV. 512-bit eq.') ver_rsa = 3 try: ver_rsa = int(input('Version: [3] ')) except ValueError: pass if ver_rsa == 2: kte, fnhd = encrypt_rsa_file_sha512v2() elif ver_rsa == 3: kte, fnhd = encrypt_rsa_file_aes_ede3_ctr() else: print('Try again!') print(kte) fnhd = fnhd + ".rsaheader" rsacipher = PKCS1_OAEP.new(ktu_ac,hashAlgo=SHA512) ciphered_header = rsacipher.encrypt(kte) rsah = open(fnhd,"wb") rsah.write(ciphered_header) rsah.close() except IndexError: print("Key not in keystore")
def create_rsa_header(self, prov_key=None): ktu = ask_for_rsa_key(self, False) if ktu == None: showwarning(title="No Key Available",message="No suitable key for encryption is in Keystore.") return False,False,False try: ktu_ac = self.key_list[ktu] # Was 1024 bit previously, don't know why. # Reduced to 128 byte to match the PSK key. if prov_key == None: key_to_encrypt = create_random_key(128) else: key_to_encrypt = prov_key rsa_cipher = PKCS1_OAEP.new(ktu_ac,hashAlgo=SHA512) ciphered_key = rsa_cipher.encrypt(key_to_encrypt) # decrypted_key = rsa_cipher.decrypt(ciphered_key) #print(len(ciphered_key)) header = bytearray() header.append(create_random_upper_half()) header.extend(ciphered_key) header.extend(create_random_key(2047)) return header, key_to_encrypt, True except IndexError: showerror(title="Please report this error",message="Keystore selected key out of index.") return False, False, False
if 'ec' != privateFile.readline().rstrip().decode("utf-8"): print("Error: Incorrect private certificate, EC required.") exit(1) #Read in certificate keys tmpPubKey = '' for line in publicFile: tmpPubKey += line.decode("utf-8") tmpPrivKey = '' for line in privateFile: tmpPrivKey += line.decode("utf-8") #Generate and encrypt AES key via RSA rsaPubKey = RSA.import_key(tmpPubKey) rsaCipher = PKCS1_OAEP.new(rsaPubKey) key = get_random_bytes(32) cipherText = rsaCipher.encrypt(key) #Sign encrypted AES key ecPrivKey = ECC.import_key(tmpPrivKey) ecSigner = DSS.new(ecPrivKey, 'fips-186-3') cipherSig = ecSigner.sign(SHA256.new(cipherText)) #Encrypt directory for dirName, subdirlist, filelist in os.walk(rootDir): for file in filelist: encrypt_file(key, dirName + '/' + file) #Write keyfile and signature to files
def descifrar_clave(self, clave_cifrada): # Descifra la clave de sesión con la clave RSA privada p_key = RSA.import_key(self.clave_privada) cipher_rsa = PKCS1_OAEP.new(p_key) clave = cipher_rsa.decrypt(clave_cifrada) return clave
def encrypt_oaep(self, data): cipher = PKCS1_OAEP.new(self.key) ct = cipher.encrypt(data) return bytes_to_hex(ct)
import pwn from Crypto.PublicKey import RSA, DSA from Crypto.Random import random, atfork from Crypto.Cipher import PKCS1_OAEP _server_pub_enc = RSA.importKey( '-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDGRrsdIqf8K39Ncwzsi9k2lr5G\nJ8aEFkYGrYqOQRbU5xOReMj8wWHgnSUC0fjH0gjffGiUC2HfrrNIQvXKGiSBetOu\nIWOmFiESG8IhrPyvLwX53NbMWeCihzbYGJxGyiL0bvDHxqDxzuvteSaEfNm1miPA\nQ9rs5vFnHM0R3kFjdQIDAQAB\n-----END PUBLIC KEY-----' ) server_pub_enc = PKCS1_OAEP.new(_server_pub_enc) dsakey = DSA.generate(512) parts = ','.join([str(p) for p in [dsakey.y, dsakey.g, dsakey.p, dsakey.q]]) parts_encrypted = [] for i in range(len(parts) / 40 + 1): part = parts[i * 40:(i + 1) * 40] print part part_encrypted = server_pub_enc.encrypt(part).encode('hex') parts_encrypted.append(part_encrypted) r = pwn.remote("52.6.11.111", 4321) r.send(','.join(parts_encrypted)) print r.recvuntil("communications\n") print r.recvuntil('\n') # Only winning move is to play print r.recvuntil('game?\n') print r.recvuntil('\n') r.send(str(100000000000000000000000000) + '\n')
def rsa_encrypt(message, pub): cipher = PKCS1_OAEP.new(pub, SHA) return cipher.encrypt(message)
from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP key = RSA.generate(2048) private_key = key.export_key() public_key = key.publickey().export_key() clear = "The delivery makes the joke.".encode("utf-8") p_key = RSA.import_key(public_key) cipher_rsa = PKCS1_OAEP.new(p_key) ciphertext = cipher_rsa.encrypt(clear) print("clear:") print(clear) print("ciphertext:") print(ciphertext) s_key = RSA.import_key(private_key) decipher_rsa = PKCS1_OAEP.new(s_key) data = decipher_rsa.decrypt(ciphertext) print(data)
def encrypt(message, pub_key): #RSA encryption protocol according to PKCS#1 OAEP cipher = PKCS1_OAEP.new(pub_key) return cipher.encrypt(message)
def load_key(self, pub_key): self.public_key = RSA.importKey(pub_key) self.encryptor = PKCS1_OAEP.new(self.public_key)
s.listen(1) conn, addr = s.accept() print('Connected by ', addr) # receive server's public key data = '' while 1: try: data = conn.recv(1024) data = int(data.decode()) break except ConnectionResetError: print('Broken PIPE!') #send program for client clientPublicKey = RSA.construct((data, 65537)) encryptor = PKCS1_OAEP.new(clientPublicKey) sending_data = str(input("Press Enter To Send File For Client")) print("Send Good File") f = open("good", "rb") l = f.read() sending_data = l conn.send(sending_data) print("Send evil File") f = open("evil", "rb") l = f.read() sending_data = l conn.send(sending_data) print("done!!")
def encryptData(public_key_path, message): pb_key = RSA.importKey(open(public_key_path).read()) cipher = PKCS1_OAEP.new(key=pb_key) return base64.b64encode(cipher.encrypt(str(message).encode())).decode()
def decryptData(private_key_path, ciperText): cp = base64.decodebytes(ciperText.encode()) pr_key = RSA.importKey(open(private_key_path, 'r').read()) de = PKCS1_OAEP.new(key=pr_key) return str(de.decrypt(cp).decode())
def handle_client(client_socket, addr): max_phase = 0 name = "" try: name = client_socket.recv(1024) random_generator = Random.new().read key = RSA.generate(RSA_KEY_SIZE * 8, random_generator) # generate pub and priv key # Send the first message to the client. first_link = URL_PATHS.get(1) send_by_size(client_socket, first_link.encode()) max_phase += 1 # Wait for the client to confirm. response = recv_amount(client_socket, 7) if response is None: return response = response.decode() while response != "CONFIRM": response = recv_amount(client_socket, 7) if response is None: return response = response.decode() # Continue communication by sending the public key to the client. send_by_size(client_socket, key.publickey().exportKey(format='PEM', passphrase=None, pkcs=1)) max_phase += 1 # receive symmetrical key response = recv_amount(client_socket, RSA_CIPHER_BLOCK_SIZE) if response is None: return # decrypt the symmetrical key cipher = PKCS1_OAEP.new(key) try: symmetrical_key = cipher.decrypt(response) if len(symmetrical_key) != AES_KEY_SIZE: send_by_size(client_socket, "Wrong input :(".encode()) return except TypeError: send_by_size(client_socket, "Wrong input :(".encode()) return # create cipher object aes_cipher = AESCipher(symmetrical_key) # continue to ssh send_encrypted(aes_cipher, client_socket, URL_PATHS.get(2)) except socket.error: return finally: client_socket.close() with t_lock: if addr not in progress_by_ip.keys(): progress_by_ip[addr] = {} progress_by_ip[addr][name] = max_phase else: if name not in progress_by_ip[addr].keys(): progress_by_ip[addr][name] = 0 progress_by_ip[addr][name] = max(progress_by_ip[addr][name], max_phase) write_to_log(PROGRESS_LOG, 'a', str(progress_by_ip[addr][name]))
def decryptRSA(ciphertext, private_key): rsa_key = RSA.importKey(private_key) cipher = PKCS1_OAEP.new(rsa_key, hashAlgo=SHA256) decrypted = cipher.decrypt(base64.b64decode(ciphertext)) return decrypted
def descifrarRSA_OAEP(cifrado, key): engineRSADescifrado = PKCS1_OAEP.new(key) datos = engineRSADescifrado.decrypt(cifrado) cadena = datos.decode("utf-8") return cadena
import sys import base64 from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP if __name__ == '__main__': cipher = open("flag.enc", "r").read() key = open("priv.key", "r").read() rsakey = RSA.importKey(key) rsakey = PKCS1_OAEP.new(rsakey) decrypted = rsakey.decrypt(base64.b64decode(cipher)) print decrypted
#!/usr/bin/env python3 from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP import json with open("assets/private.pem") as aeskey_file: key = RSA.import_key(aeskey_file.read(), passphrase="enowars") with open("../service/cryptomat/.aeskey_enc.json") as json_file: data = json.load(json_file) print(data) #convert int list to bytes data = bytes(data) cipher_rsa = PKCS1_OAEP.new(key) enc_key_bytes = cipher_rsa.decrypt(data) enc_key_list = [] #convert back to int list for b in enc_key_bytes: enc_key_list.append(int.from_bytes([b], byteorder='big', signed=False)) print(enc_key_list)
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP secret_code = "Unguessable" # rsa key passw path = os.path.expanduser("~/.ransom/.key") pem_path = "public_key_gen/rsa_key.bin" file_in = open(path, "rb") encoded_key = open(pem_path, "rb").read() private_key = RSA.importKey(encoded_key, passphrase=secret_code) cipher_rsa = PKCS1_OAEP.new(private_key) session_key = cipher_rsa.decrypt(file_in.read()) file_out = open(os.path.expanduser("~/.ransom/.clear_key"), 'wb') file_out.write(session_key) file_out.close()
from Crypto.PublicKey import RSA from Crypto.Random import get_random_bytes from Crypto.Cipher import AES, PKCS1_OAEP with open('EMAIL_ME.txt', 'rb') as f: enc_fernet_key = f.read() print(enc_fernet_key) # Private RSA key private_key = RSA.import_key(open('private.pem').read()) # Private decrypter private_crypter = PKCS1_OAEP.new(private_key) # Decrypted session key dec_fernet_key = private_crypter.decrypt(enc_fernet_key) with open('PUT_ME_ON_DESKTOP.txt', 'wb') as f: f.write(dec_fernet_key) print(f'> Private key: {private_key}') print(f'> Private decrypter: {private_crypter}') print(f'> Decrypted fernet key: {dec_fernet_key}') print('> Decryption Completed')
def decrypt(string, key): # use optimal asymmetric encryption padding ciper = PKCS1_OAEP.new(key) dec = ciper.decrypt(string) return dec
def cifrarRSA_OAEP(cadena, key): datos = cadena.encode("utf-8") engineRSACifrado = PKCS1_OAEP.new(key) cifrado = engineRSACifrado.encrypt(datos) return cifrado
def initiate_session(self): # Perform the initial connection handshake for agreeing on a shared secret if not self.rsaKey: raise RuntimeError("Rsa key must be initialized") iv_length = AES.block_size dh_key_length = 256 # client is the parent - has private rsaKey if self.client: if not self.rsaKey.has_private(): raise RuntimeError("Client needs the private key") # initialize dh my_public_key, my_private_key = create_dh_key() # Receive the challenge from the child (iv g**a) encrypted_data = self.recv() tmpCipher = PKCS1_OAEP.new(self.rsaKey) decrypted_data = tmpCipher.decrypt(encrypted_data) if len(decrypted_data) < iv_length + 1 + dh_key_length: raise RuntimeError("Expected 'IV g**a'") self.iv = int.from_bytes(decrypted_data[:iv_length], byteorder='big') their_public_key = int.from_bytes(decrypted_data[iv_length + 1:], byteorder='big') # Respond to the challenge by the child (iv g**b signed) msg_to_be_signed = decrypted_data[: iv_length] + b' ' + my_public_key.to_bytes( dh_key_length, byteorder='big') h = SHA.new() h.update(msg_to_be_signed) signer = PKCS1_PSS.new(self.rsaKey) signature = signer.sign(h) # send the signed message self.send(msg_to_be_signed + bytes(' ', "ascii") + signature) # Obtain our shared secret shared_hash = calculate_dh_secret(their_public_key, my_private_key) # server is the child - has public rsaKey if self.server: # Generate the IV self.iv = int.from_bytes(Random.new().read(iv_length), byteorder='big') # dh init my_public_key, my_private_key = create_dh_key() # send the challenge challenge = self.iv.to_bytes( AES.block_size, byteorder='big') + bytes( ' ', "ascii") + my_public_key.to_bytes(dh_key_length, byteorder='big') tmpCipher = PKCS1_OAEP.new(self.rsaKey) encrypted_data = tmpCipher.encrypt(challenge) self.send(encrypted_data) # verify the response response = self.recv() if len(response) < iv_length + 1 + dh_key_length + 2: raise RuntimeError("Expected 'IV g**b signed'") iv = int.from_bytes(response[:iv_length], byteorder='big') if iv != self.iv: raise RuntimeError("IV given was incorrect, challenge failed") # verify the signature msg_to_be_verified = response[:(iv_length + 1 + dh_key_length)] signature = response[(iv_length + 1 + dh_key_length + 1):] h = SHA.new() h.update(msg_to_be_verified) signer = PKCS1_PSS.new(self.rsaKey) if not signer.verify(h, signature): raise RuntimeError("Signature was incorrect, challenge failed") their_public_key = int.from_bytes( response[(iv_length + 1):(dh_key_length + iv_length + 1)], byteorder='big') shared_hash = calculate_dh_secret(their_public_key, my_private_key) print("Shared hash: {}".format(shared_hash)) # set up AES cipher self.cipher = AES.new(shared_hash, AES.MODE_CFB, self.iv.to_bytes(iv_length, byteorder='big')) print("Authentication Successful")
def encrypt(string, key): # use optimal asymmetric encryption padding cipher = PKCS1_OAEP.new(key) enc = cipher.encrypt(string) return enc
client_cert = handle_message(clientsocket).decode() client_cert = crypto.load_certificate(crypto.FILETYPE_PEM, client_cert) if not certificate.verify_cert(client_cert): print("Client certificate is false, ending connection") clientsocket.close() sys.exit(1) print("Client certificate is alright") client_pubkey = client_cert.get_pubkey() client_pubkey = RSA.import_key( crypto.dump_publickey(crypto.FILETYPE_PEM, client_pubkey)) session_key = get_random_bytes(16) # Encrypt the session key with the public RSA key cipher_rsa = PKCS1_OAEP.new(client_pubkey) enc_session_key = cipher_rsa.encrypt(session_key) send(clientsocket, enc_session_key) print("sending crypted aes key") cipher = AES.new(session_key, AES.MODE_EAX) while True: data = input("Enter message: ") if data: ciphertext, tag = cipher.encrypt_and_digest(data.encode()) send(clientsocket, cipher.nonce + tag + ciphertext) cipher = AES.new(session_key, AES.MODE_EAX)
def rsa_decrypt(ciphertext, priv): cipher = PKCS1_OAEP.new(priv, SHA) return cipher.decrypt(ciphertext)
#!/usr/bin/python3 from socket import * from base64 import b64decode, b64encode from Crypto.Util.number import bytes_to_long, long_to_bytes from Crypto.Cipher import PKCS1_OAEP from Crypto.PublicKey import RSA s = socket(AF_INET, SOCK_STREAM) s.connect(('crypto.byteband.it', 7002)) while True: x = s.recv(1024) print(x) x = x.split(b'\n') p = x[-6].split(b' ')[-1] n = eval(b'0x' + x[-4]) - 1 assert n % 4 == 0 n = n // 4 key = RSA.RsaKey(e=65537, n=n) rsa = PKCS1_OAEP.new(key) p = rsa.encrypt(b64decode(p)) s.send(b64encode(p) + b'\n')
def decrypt(ciphertext, priv_key): cipher = PKCS1_OAEP.new(priv_key) return cipher.decrypt(ciphertext)
def encrypt(message, pub_key): cipher = PKCS1_OAEP.new(pub_key) return cipher.encrypt(message)
#/usr/bin/env python from Crypto.PublicKey import RSA, DSA from Crypto.Random import random, atfork from Crypto.Cipher import PKCS1_OAEP import SocketServer,threading,os,time import socket from priv import privkey, privkey_enc # corresponding public keys for clients: _server_pub_enc = RSA.importKey('-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDGRrsdIqf8K39Ncwzsi9k2lr5G\nJ8aEFkYGrYqOQRbU5xOReMj8wWHgnSUC0fjH0gjffGiUC2HfrrNIQvXKGiSBetOu\nIWOmFiESG8IhrPyvLwX53NbMWeCihzbYGJxGyiL0bvDHxqDxzuvteSaEfNm1miPA\nQ9rs5vFnHM0R3kFjdQIDAQAB\n-----END PUBLIC KEY-----') server_pub_enc = PKCS1_OAEP.new(_server_pub_enc) server_pub_sig = DSA.construct([6492988819243051335053735606322819439099395961135352303030066825351059776939776358522765113843576255727411249922052441719518573282010295240606387519552263L,5720927070571587652595864015095152811124313453716975619963331476834195150780326792550956895343289380256771573459290257563350163686508250507929578552744739L,6703916277208300332610863417051397338268350992976752494932363399494412092698152568009978917952727431041521105933065433917303157931689721949082879497208537,1022875313346435070370368907571603203095488145799L]) msg = """/------------------------------------------------------------------------------\\ | Welcome to the betting parlor version 2! | | | | Here's how it works: you choose your betting odds and an amount to bet, and | | then you send us your guessed value. We then pick a secure random number. | | If random number % odds == guessed value, you win! | | | | In order to address complaints of cheating, your guessed value is sent to us | | encrypted. Therefore, our random number will not be generated adversarially! | | | | To encourage use of our service after the issues with version 1, we have | | decided to give all new users of the service $100. Wow! Such gratitude! | | | | (Oh, and if you win a billion dollars, we'll give you a flag.) | \______________________________________________________________________________/ """
def __init__(self, key_size=3072): random_generator = Random.new().read self.private_key = RSA.generate(key_size, random_generator) self.public_key = self.private_key.publickey() self.decryptor = PKCS1_OAEP.new(self.private_key) self.encryptor = PKCS1_OAEP.new(self.public_key)
def decrypt(ciphertext, priv_key): #RSA encryption protocol according to PKCS#1 OAEP cipher = PKCS1_OAEP.new(priv_key) return cipher.decrypt(ciphertext)