def generate_key_pair(): """ Returns starbank-ecdsa public and private keys (ellipticcurve.privKey, ellipticcurve.pubKey). """ private_key = PrivateKey(curve=p256) public_key = private_key.publicKey() return private_key, public_key
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 testStringConversion(self): privateKey = PrivateKey() publicKey1 = privateKey.publicKey() string = publicKey1.toString() publicKey2 = PublicKey.fromString(fromLatin(string)) self.assertEqual(publicKey1.point.x, publicKey2.point.x) self.assertEqual(publicKey1.point.y, publicKey2.point.y) self.assertEqual(publicKey1.curve, publicKey2.curve)
def testPemConversion(self): privateKey = PrivateKey() publicKey1 = privateKey.publicKey() pem = publicKey1.toPem() publicKey2 = PublicKey.fromPem(pem) self.assertEqual(publicKey1.point.x, publicKey2.point.x) self.assertEqual(publicKey1.point.y, publicKey2.point.y) self.assertEqual(publicKey1.curve, publicKey2.curve)
def testDerConversion(self): privateKey = PrivateKey() publicKey1 = privateKey.publicKey() der = publicKey1.toDer() publicKey2 = PublicKey.fromDer(fromLatin(der)) self.assertEqual(publicKey1.point.x, publicKey2.point.x) self.assertEqual(publicKey1.point.y, publicKey2.point.y) self.assertEqual(publicKey1.curve, publicKey2.curve)
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 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 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 generate_KeyPair(): privateKey = PrivateKey() publicKey = privateKey.publicKey() a = str(privateKey.toPem()) b = str(publicKey.toPem()) a = a.replace('-----BEGIN EC PRIVATE KEY-----\n', '') a = a.replace('\n-----END EC PRIVATE KEY-----\n', '') b = b.replace('-----BEGIN PUBLIC KEY-----\n', '') b = b.replace('\n-----END PUBLIC KEY-----\n', '') return a, b
def private_key_to_public_key(private_key): """ Accept a hex private key and convert it to its respective public key. Because converting a private key to a public key requires SECP256k1 ECDSA signing, this function is the most time consuming and is a bottleneck in the overall speed of the program. Average Time: 0.0031567731 seconds """ pk = PrivateKey().fromString(bytes.fromhex(private_key)) return '04' + pk.publicKey().toString().hex().upper()
def get_wallet(): ''' Returns a named tuple instance with the following attributes: - privatekey - publickey. Access them using: wallet = get_wallet() wallet.privatekey # gives the private key wallet.publickey # gives the public key. ''' prk = PrivateKey() pbk = prk.publicKey() return Wallet(privatekey=prk, publickey=pbk)
def generate_keypair(): """ Generates private key using provided cryptography standard and backend """ private_key = PrivateKey() return private_key
def check_private_key(pem): from ellipticcurve.privateKey import PrivateKey try: assert PrivateKey.fromPem(pem).curve.name == "secp256k1" except: raise Exception( "Private-key must be valid secp256k1 ECDSA string in pem format") return pem
def __init__(self): self.__coins=[] self.__sk= PrivateKey() self.__pk= (self.__sk).publicKey() self.__id=Scrooge.__id if(Scrooge.__id != 0): raise Exception("Only one Scrooge Entity should be created") Scrooge.__id+=1
def ppk_keygen(): ''' PEM (string) DER Bytes formats ''' if config.DIGITAL_SIGNATURE_ALGO == 'ECDSA': # https://github.com/starkbank/ecdsa-python ''' MUST use toPem.... private_key = PrivateKey() private_key.toPem() == PrivateKey.fromPem(private_key.toPem()).toPem() type(private_key.toPem()) == str public_key.toPem() == PublicKey.fromPem(public_key.toPem()).toPem() ''' private_key = PrivateKey() public_key = private_key.publicKey() private_key, public_key = (private_key.toPem(), public_key.toPem()) elif config.DIGITAL_SIGNATURE_ALGO == 'SCHNORR': ''' We guess some private keys that satisfies certain properties.. ie. it's on the curve ''' trying = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 n = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 trying_byte = trying.to_bytes(32, byteorder="big") n_byte = n.to_bytes(32, byteorder="big") # convert msg to BYTE trying_int = schnorr.int_from_bytes(trying_byte) n_int = schnorr.int_from_bytes(n_byte) while (trying_int >= n_int - 1): trying = os.urandom(32) # trying is bytes trying_int = schnorr.int_from_bytes( trying) # convert bytes to integer private_key = trying public_key = schnorr.pubkey_gen(private_key) public_key, private_key = (bytes_to_hex(public_key), bytes_to_hex(private_key)) else: log_error( "[security.ppk_keygen.ppk_keygen] Unknown keygen algo defined") return public_key, private_key
def signMessage(): values = request.get_json() print(values.get('message')) message = hash(values.get('message')) print("#####" + values.get('privateKey') + "#####") privateKey = PrivateKey.fromPem((values.get('privateKey'))) print(privateKey) response = sign_tx(privateKey, message) return jsonify(response.toBase64()), 200
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 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 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 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 create(path=None): """# Generate a new key pair Generates a secp256k1 ECDSA private/public key pair to be used in the API authentications ## Parameters (optional): path [string]: path to save the keys .pem files. No files will be saved if this parameter isn't provided ## Return: private and public key pems """ private = PrivateKey() public = private.publicKey() private_pem = private.toPem() public_pem = public.toPem() if path is not None: with open(os_path.join(path, "private-key.pem"), "w") as file: file.write(private_pem) with open(os_path.join(path, "public-key.pem"), "w") as file: file.write(public_pem) return private_pem, public_pem
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 ppk_get_back_object(public_key=None, private_key=None): if config.DIGITAL_SIGNATURE_ALGO == 'ECDSA': if private_key: private_key = PrivateKey.fromPem(private_key) if public_key: public_key = PublicKey.fromPem(public_key) elif config.DIGITAL_SIGNATURE_ALGO == 'SCHNORR': if private_key: private_key = hex_to_bytes(private_key) if public_key: public_key = hex_to_bytes(public_key) else: log_error( "[security.ppk_keygen.ppk_get_back_object] Unknown keygen algo defined" ) return public_key, private_key
class Wallet(): def __init__(self): self.privateKey = PrivateKey() self.publicKey = self.privateKey.publicKey() self.utxo = {} def get_balance(self , main_utxo): total = 0 for key, value in main_utxo.items(): utxo = value if(utxo.is_mine(self.publicKey)): self.utxo[utxo.id] = utxo total += utxo.value return total def send_funds(self, reciepient, value_sent , main_utxo): if(self.get_balance(main_utxo) < value_sent): print("#Not Enough funds to send transaction. Transaction Discarded.") return None total = 0 inputs = [] for key , value in self.utxo.items(): utxo = value total += utxo.value inputs.append(TransactionInput(utxo.id , utxo)) if(total > value_sent): break #Pass "0" as default argument new_transaction = Transaction("0", self.publicKey, reciepient, value_sent, inputs) new_transaction.generate_signature(self.privateKey) for obj in inputs: self.utxo.pop(obj.transaction_output_id) return new_transaction
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 generate_keys(self): pr_key = PrivateKey() self.private_key = str(pr_key.toPem()) self.public_key = str(pr_key.publicKey().toPem())
def get_key(file_path: str): f = open(file_path, "r") inp = f.read() return PrivateKey().fromPem(inp)
def private_key_to_public_key(private_key): pk = PrivateKey().fromString(bytes.fromhex(private_key)) return '04' + pk.publicKey().toString().hex().upper()