def send(self, recipient, batchID): transaction = { "sender": self.publicKey.toPem(), "recipient": recipient.publicKey.toPem(), "batchID": batchID, } transaction_input = requests.post(NODE_ADRESS+"/transactions/input", json = transaction).json()['transaction_input'] if transaction_input is None: print("invalid transaction") else: transaction['transaction_input'] = transaction_input signature = Ecdsa.sign(hash(transaction), self.privateKey) transaction['signature'] = signature.toBase64() return requests.post(NODE_ADRESS+'/transactions/new', json = transaction) # TESTING # admin = Actor(NODE_ADRESS, ADMIN_PRIVATE_KEY) # # suppliers = [Actor(NODE_ADRESS) for _ in range(10)] # # admin.send(suppliers[0], "123") # suppliers[0].send(suppliers[1], "123") # mine() # suppliers[1].send(suppliers[5], "123") # mine()
def starbank_ecdsa(count, loop): privateKey = PrivateKey() publicKey = privateKey.publicKey() message = "This is the right message" message_f = b"This is the right messages" time_list_sign = [] for l in range(loop): start = time.time() for c in range(count): signature = Ecdsa.sign(message, privateKey) end = time.time() - start # print("["+str(l)+"th starbank_ecdsa:sign second is "+ str(end) + "/"+str(count)+" signature") time_list_sign.append(end) ave_sign = numpy.mean(numpy.array(time_list_sign)) time_list_vrfy = [] for l in range(loop): start = time.time() for c in range(count): if (Ecdsa.verify(message, signature, publicKey) == False): print("err") end = time.time() - start # print("["+str(l)+"th starbank_ecdsa:vrfy second is "+ str(end) + "/"+str(count)+" signature") time_list_vrfy.append(end) ave_vrfy = numpy.mean(numpy.array(time_list_vrfy)) print("starbank_ecdsa:sign average second is " + str(ave_sign) + "/" + str(count) + " signature") print("starbank_ecdsa:vrfy average second is " + str(ave_vrfy) + "/" + str(count) + " signature") return time_list_sign, time_list_vrfy
def sign(key_pair, data): """ Generates transaction signature """ message = json.dumps(data) signature = Ecdsa.sign(message, key_pair) return signature.toBase64()
def createPaymentTestDoubleSpend(self, receiverID, blockChain): coins = self.getCoins(blockChain) amount = 1 coinsToSend = [] coinsToSend.append(coins.pop(0)) paymentCreation = Payment(coinsToSend, self.__id, receiverID) paymentCreation.Sign(Ecdsa.sign(str(paymentCreation), self.__sk)) return paymentCreation
def sign_tx(privateKey, message): ''' Returns a signature for a given wallet and string message. Inputs: - wallet (namedtuple instance) - message (string) ''' signature = Ecdsa.sign(message, privateKey) return signature
def testVerifyRightMessage(self): privateKey = PrivateKey() publicKey = privateKey.publicKey() message = "This is the right message" signature = Ecdsa.sign(message, privateKey) self.assertTrue(Ecdsa.verify(message, signature, publicKey))
def generate_signature(message: str) -> Tuple[Signature, PublicKey]: # Generate new Key private_key = PrivateKey() public_key = private_key.publicKey() # Generate Signature signature = Ecdsa.sign(message, private_key) return signature, public_key
def sign_message(self, hash_t): # Bytearray to base64 hash_b_arr = bytearray(list(hash_t)) hash_b64 = base64.b64encode(hash_b_arr) hash_b64_str = str(hash_b64, 'utf-8') signed = Ecdsa.sign(hash_b64_str, self.privateKey) return signed
def testVerifyWrongMessage(self): privateKey = PrivateKey() publicKey = privateKey.publicKey() message1 = "This is the right message" message2 = "This is the wrong message" signature = Ecdsa.sign(message1, privateKey) self.assertFalse(Ecdsa.verify(message2, signature, publicKey))
def testDerConversion(self): privateKey = PrivateKey() message = "This is a text message" signature1 = Ecdsa.sign(message, privateKey) der = signature1.toDer() signature2 = Signature.fromDer(fromLatin(der)) self.assertEqual(signature1.r, signature2.r) self.assertEqual(signature1.s, signature2.s)
def testDerConversion(self): privateKey = PrivateKey() message = "This is a text message" signature1 = Ecdsa.sign(message, privateKey) der = signature1.toDer(withRecoveryId=True) signature2 = Signature.fromDer(toBytes(der), recoveryByte=True) self.assertEqual(signature1.r, signature2.r) self.assertEqual(signature1.s, signature2.s) self.assertEqual(signature1.recid, signature2.recid)
def testBase64Conversion(self): privateKey = PrivateKey() message = "This is a text message" signature1 = Ecdsa.sign(message, privateKey) base64 = signature1.toBase64() signature2 = Signature.fromBase64(base64) self.assertEqual(signature1.r, signature2.r) self.assertEqual(signature1.s, signature2.s)
def createPaymentTest(self, receiverID, blockChain): coins = self.getCoins(blockChain) if (len(coins) == 0): return None amount = 1 coinsToSend = [] for i in range(0, amount): index = randint(0, len(coins) - 1) coinsToSend.append(coins.pop(index)) paymentCreation = Payment(coinsToSend, self.__id, receiverID) paymentCreation.Sign(Ecdsa.sign(str(paymentCreation), self.__sk)) return paymentCreation
def testAssign(self): # Generated by: openssl ecparam -name secp256k1 -genkey -out privateKey.pem privateKeyPem = File.read("./privateKey.pem") privateKey = PrivateKey.fromPem(privateKeyPem) message = File.read("./message.txt") signature = Ecdsa.sign(message=message, privateKey=privateKey) publicKey = privateKey.publicKey() self.assertTrue(Ecdsa.verify(message=message, signature=signature, publicKey=publicKey))
def testBase64Conversion(self): privateKey = PrivateKey() message = "This is a text message" signature1 = Ecdsa.sign(message, privateKey) base64 = signature1.toBase64(withRecoveryId=True) signature2 = Signature.fromBase64(base64, recoveryByte=True) self.assertEqual(signature1.r, signature2.r) self.assertEqual(signature1.s, signature2.s) self.assertEqual(signature1.recid, signature2.recid)
def send_mock_webhook(payload, timestamp): message = timestamp + payload signature = Ecdsa.sign(message, privateKey) base64_signature = signature.toBase64() # print("Verified:", Ecdsa.verify(message, signature, publicKey)) url = 'https://cryptic-caverns-35958.herokuapp.com/mock_webhook' headers = { 'x-twilio-email-event-webhook-timestamp': timestamp, 'x-twilio-email-event-webhook-signature': base64_signature } data = payload.encode('utf-8') response = requests.post(url, headers=headers, data=data) return response.json()
def sign(self, id): application = Application.objects( Q(id=id) & Q(assignedId=get_jwt_identity()['_id']['$oid'])).get() if application.to_hash() != application.hash: return 'Data Tampered', 403 current_stage = int(application.stage) private_key = User.objects( Q(id=get_jwt_identity()['_id']['$oid'])).get().private_key signatures = application.signatures signatures[current_stage] = Ecdsa.sign( json.dumps(application.to_hash()), PrivateKey.fromPem(private_key)).toBase64() application.update(signatures=signatures) if application.stage == application.stages - 1: application.update(stage=current_stage + 1) application.update(status=1) else: workflow = Workflow.objects(id=application.workflowId).get() new_auth_id = workflow.stages[current_stage + 1]['authId'] new_auth_name = workflow.stages[current_stage + 1]['authName'] application.update(assignedId=new_auth_id) application.update(assignedName=new_auth_name) application.update(stage=current_stage + 1) user = User.objects(Q(id=application.creatorId)).get() send_email_async( get_user_email(), 'notification', get_user_name(), notif= f"You have successfully signed {application.name} created by {user.first_name} with " f"your digital signatures") send_email_async( user.email, 'notification', user.first_name, notif= f"{get_user_name()} has successfully signed your {application.name}. Please check " f"E-Daftar portal for more updates.") return signatures[current_stage], 200
def fetch(method, path, payload=None, query=None, user=None, version="v2"): user = check_user(user or starkbank.user) url = { Environment.production: "https://api.starkbank.com/", Environment.sandbox: "https://sandbox.api.starkbank.com/", }[user.environment] + version url = "{base_url}/{path}{query}".format(base_url=url, path=path, query=urlencode(query)) agent = "Python-{major}.{minor}.{micro}-SDK-{sdk_version}".format( major=python_version.major, minor=python_version.minor, micro=python_version.micro, sdk_version=starkbank.__version__, ) access_time = str(time()) body = dumps(payload) if payload else "" message = "{access_id}:{access_time}:{body}".format(access_id=user.access_id(), access_time=access_time, body=body) signature = Ecdsa.sign(message=message, privateKey=user.private_key()).toBase64() try: request = method( url=url, data=body, headers={ "Access-Id": user.access_id(), "Access-Time": access_time, "Access-Signature": signature, "Content-Type": "application/json", "User-Agent": agent, } ) except Exception as exception: raise UnknownError("{}: {}".format(exception.__class__.__name__, str(exception))) response = Response(status=request.status_code, content=request.content) if response.status == 500: raise InternalServerError() if response.status == 400: raise InputErrors(response.json()["errors"]) if response.status != 200: raise UnknownError(response.content) return response
def sign(dictionary_msg, sender_private_key): _, sk = ppk_get_back_object(private_key=sender_private_key) if config.DIGITAL_SIGNATURE_ALGO == 'ECDSA': h = str(dictionary_msg) signature = Ecdsa.sign(h, sk).toPem() # log_info("[security.digital_signature.sign] ECDSA Signature: {}".format(signature)) return signature elif config.DIGITAL_SIGNATURE_ALGO == 'SCHNORR': h = dict_to_hash(dictionary_msg) signature = schnorr_sign(h, sk) # log_info("[security.digital_signature.sign] Schnorr Signature: {}".format(signature)) return signature else: log_error("[security.digital_signature.sign] Unkown DSA in config -- cannot create digital signature!")
def write_slogan(): filename1 = fd.askopenfilename() f2 = fd.askopenfilename() y = cv2.imread(f2) y = cv2.resize(y, (128, 60), interpolation=cv2.INTER_CUBIC) x = cv2.imread(filename1) x = cv2.resize(x, (128, 60), interpolation=cv2.INTER_CUBIC) def rgb2gray(rgb): return np.dot(rgb[..., :3], [0.2989, 0.5870, 0.1140]) x = rgb2gray(x) y=rgb2gray(y) x = x.astype(str) y = y.astype(str) from ellipticcurve.ecdsa import Ecdsa from ellipticcurve.privateKey import PrivateKey privateKey = PrivateKey() publicKey = privateKey.publicKey() a = [] for i in x: for j in i: m = j.encode(encoding='UTF-8', errors='strict') signature = Ecdsa.sign(m, privateKey) a.append(signature) n = 0 f = 0 for i in y: for j in i: m = j.encode(encoding='UTF-8', errors='strict') valid = Ecdsa.verify(m, a[n], publicKey) if (valid == False): f = 1 break n += 1 if (f == 0): T.insert(tk.END, "Succeessfully Verified!"+'\n') else: T.insert(tk.END, "Verification Unsuccessful."+'\n')
def create_Signature(message, privateKey_input): privateKey_input = '-----BEGIN EC PRIVATE KEY-----\n' + privateKey_input + '\n-----END EC PRIVATE KEY-----\n' privateKey = PrivateKey().fromPem(privateKey_input) signature = Ecdsa.sign(message, privateKey) return str(signature.toBase64())
def create_Signature(message,privateKey_input): privateKey = PrivateKey(secret = int(privateKey_input)) signature = Ecdsa.sign(message, privateKey) return str(signature.toBase64())
def apply_ecdsas(privateKey, input): return Ecdsa.sign(input, privateKey)
def create_Signature(message, str1): # str1 private key privateKey = PrivateKey().fromPem(str1) signature = Ecdsa.sign(message, privateKey) return str(signature.toBase64())
def gen_sign(msg: str, pr_key): return Ecdsa.sign(msg, pr_key)
f_publicKey.write(publicKey.toString()) f_publicKey.close() print('Private Key: ' + privateKey.toString()) print('Public Key: ' + publicKey.toString()) elif option == 2: message = str(input("Message: ")) elif option == 3: if message != None: print('Select key to sign the message') print("1 - private key") print("2 - public key") selectKey = int(input("\ninput: ")) if selectKey == 1: signature = Ecdsa.sign(message, privateKey) print('\nSigned message:') print(signature.toBase64()) f_signature = open("signature.txt", "w") f_signature.write(signature.toBase64()) f_signature.close() elif selectKey == 2: signature = Ecdsa.sign(message, publicKey) print('\nSigned message:') print(signature.toBase64()) f_signature = open("signature.txt", "w") f_signature.write(signature.toBase64()) f_signature.close() else: print("select key error") else:
def Nodes(env, id): privateKey = PrivateKey() publicKey = privateKey.publicKey() w = random.randint(1, 50) #stake prevBlock = genesis global W W = W + w yield env.timeout(0) createNetworkOverlay(id) yield env.timeout(0) hashvalue, signature, j = sortition(privateKey, hashof(genesis), 5, "comittee", w, W) vrfhash = Ecdsa.sign(hashvalue, privateKey) # signature on hash of prg is vrfhash LowestSHA = None round = 1 if j > 0: Lowestpriorityj = 1 print(id, "is a block proposer with sub-users =", j) for subuser in range(1, j + 1): m = hashlib.sha256() m.update((str(vrfhash) + str(subuser)).encode()) newsha = int.from_bytes(m.digest(), 'big') if LowestSHA is None: LowestSHA = newsha Lowestpriorityj = subuser elif newsha < LowestSHA: LowestSHA = newsha Lowestpriorityj = subuser shas[id] = LowestSHA gossip = NetworkMsg(LowestSHA, id, env.now, "shacmpare", round, "step1") # gossip = str(round) + ":" + str(hashvalue) + ":" + str(Lowestpriorityj) + ":" + str(LowestSHA) # delimiter proposedMsgHash = hashlib.sha512( str(gossip).encode('utf-8')).hexdigest() if proposedMsgHash not in NODEMESSAGES[id]: NODEMESSAGES[id].append(proposedMsgHash) sendmsg(id, gossip, env) yield env.timeout(0) # payload = NetworkMsg("hello world", id, env.now, "block", 1, 1) # sign = Ecdsa.sign(str(payload).encode('utf-8'), privateKey) # # sendmsg(id,payload,env) # yield env.timeout(0) # if id==1: # print_msglist() # exit(0) current_time = env.now yield env.timeout(0) LowestSHARecvd = [] while env.now - current_time <= 33000: if not msgQueue[id].empty(): time, msg = msgQueue[id].get() while time <= env.now: if chk_dup(msg, id) == True: print("Time:", env.now, "msg recieved by", id, " for ", time, msg.message) LowestSHARecvd.append(msg.message) sendmsg(id, msg, env) else: # print("Duplicate found") pass #validate if not msgQueue[id].empty(): time, msg = msgQueue[id].get() else: break # print("Time:", env.now, "msg recieved by", id, " for delay", delay) yield env.timeout(time - env.now) if chk_dup(msg, id) == True: print("Time:", env.now, "msg recieved by", id, " for ", time, msg.message) LowestSHARecvd.append(msg.message) sendmsg(id, msg, env) else: # print("Duplicate found") pass # print("Time:", env.now, "msg recieved by", id, " for ", time) else: # print("Q empty") yield env.timeout(1) # print("LOWEST SHA RECVD BY", id, "are") # print(LowestSHARecvd) minimumrcvdhash = min(LowestSHARecvd) yield env.timeout(0) if LowestSHA <= minimumrcvdhash: print("You are a block proposer", id) randomstring = PRG(random.randint(1, 100000000)) newblock = "newblockmsg : " + hashof(genesis) + str(randomstring) newblockmsg = NetworkMsg(newblock, id, env.now, "blockproposal", round, 1) sendmsg(id, newblockmsg, env) yield env.timeout(0) current_time = env.now blockproposal = None while env.now - current_time <= 33000: if not msgQueue[id].empty(): time, msg = msgQueue[id].get() while time <= env.now: if chk_dup(msg, id) == True: print("Time:", env.now, "msg recieved by", id, " for ", time, msg.message) LowestSHARecvd.append(msg.message) sendmsg(id, msg, env) else: # print("Duplicate found") pass #validate if not msgQueue[id].empty(): time, msg = msgQueue[id].get() else: break # print("Time:", env.now, "msg recieved by", id, " for delay", delay) if time - env.now < 0: break yield env.timeout(time - env.now) if chk_dup(msg, id) == True: print("Time:", env.now, "msg recieved by", id, " for ", time, msg.message) LowestSHARecvd.append(msg.message) sendmsg(id, msg, env) else: # print("Duplicate found") pass # print("Time:", env.now, "msg recieved by", id, " for ", time) else: # print("Q empty") yield env.timeout(1)
def prove(message, sk): return Ecdsa.sign(message, sk)
from ellipticcurve.ecdsa import Ecdsa from ellipticcurve.privateKey import PrivateKey # Gerando as chaves chave_privada = PrivateKey() chave_publica = chave_privada.publicKey() mensagem = "Segredo secreto :O" # Gerando a assinatura carloscabral = Ecdsa.sign(mensagem, chave_privada) # Verificando Resposta = Ecdsa.verify(mensagem, carloscabral, chave_publica) print(Resposta)
def scroogeSign(self,msg): return Ecdsa.sign(msg, self.__sk)