def verifyData(): user_id = request.json["userId"] signedUserId = request.json["signedUserId"] publicKeyFile = request.json["publicKeyFile"] user_id_hash = rsa.compute_hash(user_id.encode("utf-8"), HASH_METHOD) with open(publicKeyFile, 'r', encoding="ascii") as f: file_data = f.read() publicKey = rsa.PublicKey.load_pkcs1(file_data) signedUserId = base64.decodestring(signedUserId.encode("ascii")) try: verify = rsa.verify(user_id.encode("utf-8"), signedUserId, publicKey) verifyResult = "Success" except rsa.pkcs1.VerificationError as e: verifyResult = "Failed" res = { "userId": user_id, # "userIdHash": base64.encodestring(user_id_hash).decode("ascii"), "publicKeyFile": publicKeyFile, # "signedUserId": base64.encodestring(signedUserId).decode("ascii"), "verifyResult": verifyResult } return json.dumps(res)
def request_signature(filename): try: datas = get_by_filenam(filename) user = decrypt_data(request.form['token'].encode('utf-8')) user = json.loads(user) saved_path = stamp_pdf(filename) privkey = rsa.PrivateKey.load_pkcs1(file_open('privatekey.key')) # Open the secret message file and return data to variable data = file_open(saved_path) hash_value = rsa.compute_hash(data, 'SHA-512') # optional # Sign the message with the owners private key signature = rsa.sign(data, privkey, 'SHA-512') sign_name = filename + '-signature' signature_file = os.path.join(app.config['SIGN_FOLDER'], sign_name) s = open(signature_file, 'wb') s.write(signature) headers = { 'Content-Type': 'application/json', 'Accept': 'application/json', } datass = { "$class": "org.example.Document", "fileName": filename, "fileChecksum": datas['fileChecksum'], "fileData": datas['fileData'], "fileTitle": datas['fileTitle'], "signatureFile": sign_name, "owner": 'resource:org.example.User#' + user['email'] } response = requests.put('http://35.226.165.155:3000/api/Document/' + filename, headers=headers, data=json.dumps(datass)) print(response.content) resp = jsonify({ 'message': 'Signature created successfully', 'success': True, 'data': None }) resp.status_code = 200 return resp except: resp = jsonify({ 'message': 'Error happens', 'success': False, 'data': None }) resp.status_code = 400 return resp
def _sign(self, key_file, file_to_sign): file_to_sign = open(file_to_sign, 'rb') file_data = file_to_sign.read() file_to_sign.close() hash_value = rsa.compute_hash(file_data, 'SHA-512') privkey = rsa.PrivateKey.load_pkcs1(Utils().decrypt_file("MyKeys/" + key_file)) signature = rsa.sign(file_data, privkey, 'SHA-512') return (signature)
def onboardPerson(): print("called onboardPerson", file=sys.stderr) validation_result = validateDocumentData(request.data) if validation_result == NO_DATA: return getJsonResponse(400, "Error", "No document data provided") elif validation_result == INVALID_FIELD: return getJsonResponse(400, "Error", "Not all fields are valid") data = request.json["data"] user_id = data["userId"] print(user_id) signedUserId = request.json["signedUserId"] signedUserId = base64.decodestring(signedUserId.encode("ascii")) issuerPrivateKeyFile = getKeys("Munich")["private"] with open(issuerPrivateKeyFile, 'r') as f: file_data = f.read() issuerPrivateKey = rsa.PrivateKey.load_pkcs1(file_data, "PEM") docHash = rsa.compute_hash(json.dumps(data).encode("utf-8"), HASH_METHOD) signedDocHash = rsa.sign_hash(docHash, issuerPrivateKey, HASH_METHOD) signedDocHash = base64.encodestring(signedDocHash).decode("ascii") userPublicKeyFile = getKeys(user_id)["public"] print(userPublicKeyFile) with open(userPublicKeyFile, 'r', encoding="ascii") as f: file_data = f.read() userPublicKey = rsa.PublicKey.load_pkcs1(file_data) try: verify = rsa.verify(user_id.encode("utf-8"), signedUserId, userPublicKey) verifyUserResult = "Success" except rsa.pkcs1.VerificationError as e: verifyUserResult = "Failed" # post to blockchain result = runRawTransaction( 'onboard', [b"Munich", user_id.encode("utf-8"), signedDocHash.encode("utf-8")]) print(result) res = { "docHash": base64.encodestring(docHash).decode("ascii"), "signedDocHash": signedDocHash, "verifyUserResult": verifyUserResult, "smartContractResult": result, # "raw_tx": raw_tx.decode("ascii"), # "payload": payload, } return json.dumps(res)
def resumo_cripto(request): resumo = {'text':''} if request.method == 'POST': try: uploaded_file = request.FILES['document'] data = uploaded_file.read() m = rsa.compute_hash(data,'SHA-256') m = m.hex() resumo['text'] = m except: # Caso o usuário tente gerar um resumo sem antes prover um documento resumo['text'] = ' Entrada de dados inválida!' return render(request, 'blog/resumo_cripto.html', resumo)
def sign(self, doc): pvt = rsa.PrivateKey.load_pkcs1(self.__read_file('private_key.txt')) doc = self.__read_file(doc) sing_hash = rsa.compute_hash(doc, 'SHA-512') signature = rsa.sign(doc, pvt, 'SHA-512') try: with open("signature.txt", "wb") as outfile2: outfile2.write(signature) except IOError: print('erro')
def checkAttestation(): print("called checkAttestation") data = request.json["data"] user_id = data["userId"] signedUserId = request.json["signedUserId"] signedUserId = base64.decodestring(signedUserId.encode("ascii")) docHash = rsa.compute_hash(json.dumps(data).encode("utf-8"), HASH_METHOD) # verify document was signed by issuer issuerId = request.json["issuerId"] issuerPublicKeyFile = getKeys(issuerId)["public"] with open(issuerPublicKeyFile, 'r', encoding="ascii") as f: file_data = f.read() issuerPublicKey = rsa.PublicKey.load_pkcs1(file_data) print(issuerId) print(user_id) SC_getAttestation_payload = { "jsonrpc": "2.0", "method": "invokefunction", "params": [ CONTRACT_HASH, "getAttestation", [ {"type": "String", "value": issuerId}, {"type": "String", "value": user_id} ] ], } SC_getAttestation_res = requests.post( "http://neo-nodes:30333/", json=SC_getAttestation_payload) attestation = SC_getAttestation_res.text # try: # verify = rsa.verify(json.dumps(data).encode( # "utf-8"), attestation.encode("ascii"), issuerPublicKey) # verifyResult = "Success" # except rsa.pkcs1.VerificationError as e: # verifyResult = "Failed" return json.dumps({ # "verifyResult": verifyResult, "result": "X", # "req": json.dumps(SC_getAttestation_payload), "attestationRes": attestation })
def sign(self, file): private_key_load = rsa.PrivateKey.load_pkcs1( self.__read_file('private_key.txt')) file = self.__read_file(file) sign_hash = rsa.compute_hash(file, 'SHA3-256') signature = rsa.sign(file, private_key_load, 'SHA3-256') try: with open("signature.txt", "wb") as outfile2: outfile2.write(signature) print("File has been signed!") except IOError: print('Error! Try again')
def sign(privatekey_dir,message_path,output_dir): # Open private key file and load in key privkey = rsa.PrivateKey.load_pkcs1(file_open(os.path.join(privatekey_dir,'privatekey.key'))) # Open the secret message file and return data to variable message = file_open(message_path) hash_value = rsa.compute_hash(message, 'SHA-512') # optional # Sign the message with the owners private key signature = rsa.sign(message, privkey, 'SHA-512') s = open(os.path.join(output_dir,'signature_file'),'wb') s.write(signature) print(signature) print("length",len(signature))
def signData(): user_id = request.json["userId"] privateKeyFile = request.json["privateKeyFile"] with open(privateKeyFile, 'r') as f: file_data = f.read() privateKey = rsa.PrivateKey.load_pkcs1(file_data, "PEM") user_id_hash = rsa.compute_hash(user_id.encode("utf-8"), HASH_METHOD) signedUserId = rsa.sign_hash(user_id_hash, privateKey, HASH_METHOD) res = { "userId": user_id, # "userIdHash": base64.encodestring(user_id_hash).decode("ascii"), "privateKeyFile": privateKeyFile, "signedUserId": base64.encodestring(signedUserId).decode("ascii") } return json.dumps(res)
def checkAttestation(): print("called checkAttestation") data = request.json["data"] user_id = data["userId"] signedUserId = request.json["signedUserId"] signedUserId = base64.decodestring(signedUserId.encode("ascii")) docHash = rsa.compute_hash(json.dumps(data).encode("utf-8"), HASH_METHOD) # verify document was signed by issuer issuerId = request.json["issuerId"] issuerPublicKeyFile = getKeys(issuerId)["public"] with open(issuerPublicKeyFile, 'r', encoding="ascii") as f: file_data = f.read() issuerPublicKey = rsa.PublicKey.load_pkcs1(file_data) client = Client(host='neo-nodes', port='30333') result = client.invoke_function( CONTRACT_HASH, "getAttestation", [issuerId.encode("utf-8"), user_id.encode("utf-8")]) result = {"tx": "x"} print(json.dumps(result)) attestation = result["tx"] try: # verify = rsa.verify( # docHash, attestation.encode("utf-8"), issuerPublicKey) verifyUserResult = "Success" except rsa.pkcs1.VerificationError as e: verifyUserResult = "Failed" print("X", flush=True) return json.dumps({ "verifyResult": verifyUserResult, # "req": json.dumps(SC_getAttestation_payload), })
print("\n---\n") # ------------------------------------------------------------------------------ # sign/verify # ------------------------------------------------------------------------------ # Note: These are using PKCS#1 v1.5 print("sign/verify") message = b"message" other_message = b"other message" hash = rsa.compute_hash( message, "SHA-256" ) # $ CryptographicOperation CryptographicOperationAlgorithm=SHA256 CryptographicOperationInput=message hash = rsa.compute_hash( message=message, method_name="SHA-256" ) # $ CryptographicOperation CryptographicOperationAlgorithm=SHA256 CryptographicOperationInput=message signature_from_hash = rsa.sign_hash( hash, private_key, "SHA-256" ) # $ CryptographicOperation CryptographicOperationAlgorithm=RSA CryptographicOperationInput=hash signature_from_hash = rsa.sign_hash( hash_value=hash, priv_key=private_key, hash_method="SHA-256" ) # $ CryptographicOperation CryptographicOperationAlgorithm=RSA CryptographicOperationInput=hash signature = rsa.sign( message, private_key, "SHA-256" ) # $ CryptographicOperation CryptographicOperationAlgorithm=RSA CryptographicOperationAlgorithm=SHA256 CryptographicOperationInput=message signature = rsa.sign(
## to sign the message when we encrypt it and to validate it when we decrypt it ## 1. Bob generates a keypair, and gives the public key to Alice. ## This is done such that Alice knows for sure that the key is really Bob’s ## (for example by handing over a USB stick that contains the key). (pk, sk) = rsa.newkeys(512) print('PUBLIC KEY -> ' + str(pk) + '\n') print('SECRET KEY -> ' + str(sk) + '\n') ## 2. Alice writes a message, and encodes it in UTF-8. The RSA module only ## operates on bytes, and not on strings, so this step is necessary. message = input('Enter the message you want to encrypt: ') message = message.encode('utf8') ## we add the signature to the message hash = rsa.compute_hash(message, 'SHA-1') signature = rsa.sign_hash(hash, sk, 'SHA-1') print('\nSignature -> ' + str(signature)) ## 3. Alice encrypts the message using Bob’s public key, and sends the encrypted message. crypto = rsa.encrypt(message, pk) print('\nEncypted message --> ' + str(crypto)) wants_to_modify = input('\nWant to modify the message? (yes or no) ') wants_to_modify = wants_to_modify.lower() if wants_to_modify == 'yes': ## let's an attacker got the message and he decides to change it message = input('\nModify the message: ') message = message.encode('utf8')
def sign(message, privkey): hash = rsa.compute_hash(message, 'SHA-1') signature = rsa.sign_hash(hash, privkey, 'SHA-1') return signature
# This file signs a file with the owner's private key and # verifies the signature with the owners public key import rsa # Open key file and return key data def file_open(file): key_file = open(file, 'rb') key_data = key_file.read() key_file.close() return key_data # Open private key file and load in key privkey = rsa.PrivateKey.load_pkcs1(file_open('privatekey.key')) # Open the secret message file and return data to variable message = file_open('message') hash_value = rsa.compute_hash(message, 'SHA-512') # optional # Sign the message with the owners private key signature = rsa.sign(message, privkey, 'SHA-512') s = open('signature_file', 'wb') s.write(signature) print(signature) print(len(signature)) print(len(hash_value) * 8) # to verify size of hash/output
def get_signed_text(st): return st + '\n' + str( (rsa.sign_hash(rsa.compute_hash(st.encode("utf-8"), "SHA-256"), get_private_key(), "SHA-256")))
def data_thread_function(): while not thread_function_event.is_set(): try: data = data_queue.get(True, latency) if len(data) < 12: print '? len(data): ', len(data) continue packet_id, sequence, xor_key, checksums = struct.unpack_from( '!IIHH', data) message_len = 12 + 4 * checksums if len(data) < message_len + 64: print '? len(data): ', len(data) continue message, signature = data[:message_len], data[ message_len:message_len + 64] try: pub_key, data_len, data_crc32 = packets[packet_id] rsa.verify(message, signature, pub_key) checksum_iteration, iteration_crc32 = checksum_cache[packet_id] if checksum_iteration <= sequence and sequence < checksum_iteration + 64: while checksum_iteration < sequence: iteration_crc32 = zlibdll.crc32_combine( iteration_crc32, data_crc32[0], data_len) checksum_iteration += 1 else: bit = 0 bit_len = data_len iteration_crc32 = data_crc32[0] checksum_iteration = sequence while checksum_iteration: if checksum_iteration & 1: iteration_crc32 = zlibdll.crc32_combine( iteration_crc32, data_crc32[bit], bit_len) bit += 1 bit_len <<= 1 checksum_iteration >>= 1 checksum_iteration = sequence xor_key |= xor_key << 16 for i in range(checksums): checksum = struct.unpack_from('!I', data, 12 + i * 4)[0] ^ xor_key if checksum != iteration_crc32: checksum_queue.put_nowait((time.time(), '\n'.join([ hex(packet_id), str(sequence), str(checksum_iteration), hex(checksum)[2:], hex(iteration_crc32)[2:], '\n' ]))) iteration_crc32 = zlibdll.crc32_combine( iteration_crc32, data_crc32[0], data_len) checksum_iteration += 1 checksum_cache[packet_id] = checksum_iteration, iteration_crc32 except KeyError: print '? ', hex(packet_id), sequence, hex(xor_key), checksums except rsa.pkcs1.VerificationError: # ugly, but i don't want to "unroll" rsa.verify in the try block keylength = rsa.common.byte_size(pub_key.n) encrypted = rsa.transform.bytes2int(signature) decrypted = rsa.core.decrypt_int(encrypted, pub_key.e, pub_key.n) clearsig = rsa.transform.int2bytes(decrypted, keylength) message_hash = rsa.compute_hash(message, 'SHA-256') signature_queue.put_nowait((time.time(), '\n'.join([ hex(packet_id), str(sequence), clearsig[32:64].encode('hex'), message_hash.encode('hex'), '\n' ]))) except Queue.Empty: pass
def do_miner_step(self,step): if(self.transaction == None): if(len(self.topology.transactions) > 0 ): self.transaction = self.topology.transactions[0] self.topology.transactions.pop(0) time_to_validate = random.randint(6,13) self.will_validate = step + time_to_validate elif(step == self.will_validate): self.transaction.validation_step = step self.transaction.validation_public_key = self.public_key.n if(self.transaction.transaction_type == 2): content = "{}{}{}{}{}{}".format(self.transaction.identify,self.transaction.born_step,(self.transaction.born_step+110), self.transaction.origin_public_key,str(self.transaction.origin_signature),self.public_key.n,step) if(self.transaction.transaction_type == 3): content = "{}{}{}{}{}{}".format(self.transaction.identify,self.transaction.born_step,self.transaction.ingress_step, self.transaction.origin_public_key,str(self.transaction.origin_signature),self.public_key.n,step) self.transaction.validation_signature = rsa.sign(content.encode('utf-8'),self.private_key,'SHA-1') self.topology.validated_transactions.append(self.transaction) self.transaction = None if(step in self.block_miner_flow): if(self == self.topology.miners[self.topology.vez]): if(len(self.topology.validated_transactions) == 0 ): pass else: array = [] validated_transactions_array = [] transac = {} array.append(step) array.append(self.public_key.n) for transaction in self.topology.validated_transactions: if(transaction.transaction_type == 2): array.append(transaction.identify) array.append(transaction.origin_public_key) array.append(str(transaction.origin_signature)) array.append(transaction.born_step) array.append((transaction.born_step+110)) array.append(transaction.transaction_type) transac["id"] = transaction.identify transac["pub_key_origin"] = str(transaction.origin_public_key) transac["sign_origin"] = str(transaction.origin_signature) transac["transac_type"] = transaction.transaction_type transac["born_step"] = transaction.born_step transac["make_keys_step"] = (transaction.born_step+110) transac["pub_key_valid"] = transaction.validation_public_key transac["sign_valid"] = str(transaction.validation_signature) transac["valid_step"] = transaction.validation_step else: array.append(transaction.identify) array.append(transaction.origin_public_key) array.append(str(transaction.origin_signature)) array.append(transaction.born_step) array.append(transaction.ingress_step) array.append(transaction.transaction_type) transac["id"] = transaction.identify transac["pub_key_origin"] = str(transaction.origin_public_key) transac["sign_origin"] = str(transaction.origin_signature) transac["transac_type"] = transaction.transaction_type transac["born_step"] = transaction.born_step transac["ingress_step"] = (transaction.ingress_step) transac["pub_key_valid"] = transaction.validation_public_key transac["sign_valid"] = str(transaction.validation_signature) transac["valid_step"] = transaction.validation_step#self.topology.miners_approved.append(transaction) validated_transactions_array.append(transac) hash_block = rsa.compute_hash(repr(array).encode('utf-8'),'SHA-1') content = "{}".format(hash_block) signature = rsa.sign(content.encode('utf-8'),self.private_key,'SHA-1') data = {} data[str(hash_block)] = [] data[str(hash_block)].append({ "miner_public_key" : self.public_key.n, "miner_step" : step, "miner_signature" : str(signature), "transactions" : validated_transactions_array }) self.topology.block_mined_json.append(data) self.topology.nodes_approved = self.topology.validated_transactions.copy() self.topology.validated_transactions = [] if(self.topology.vez == len(self.topology.miners)-1): self.topology.vez = 0 else: self.topology.vez += 1 return