Exemplo n.º 1
0
    def test_generate_and_parse_pem(self):
        d, Q = gen_keypair(P256)
        export_key(d, curve=P256, filepath='p256.key')
        export_key(Q, curve=P256, filepath='p256.pub')

        parsed_d, parsed_Q = import_key('p256.key')
        self.assertEqual(parsed_d, d)
        self.assertEqual(parsed_Q, Q)

        parsed_d, parsed_Q = import_key('p256.pub')
        self.assertTrue(parsed_d is None)
        self.assertEqual(parsed_Q, Q)

        remove('p256.key')
        remove('p256.pub')
Exemplo n.º 2
0
def get_wallet_from_db(port: str) -> str:
    try:
        location = WALLET_DB_LOC + str(port) + ".key"
        priv_key, pub_key_point = import_key(location)
        return priv_key, encode_public_key(pub_key_point)
    except Exception as e:
        return None
Exemplo n.º 3
0
	def setUpClass(cls):
		# getting the json files necessary for the test
		with open("tests/blockchain/test_files/json_block.json", 'r') as f:
			cls.jsons = ast.literal_eval(f.read())

		# getting the private and public keys for the test
		cls.private_key, cls.public_key = import_key('tests/blockchain/test_files/default_keyprv.pem')
Exemplo n.º 4
0
def checkNonce(file, m, r, s):
    _, public_key = keys.import_key(file)
    print("public key: ", public_key)

    # should return True as the signature we just generated is valid.
    valid = ecdsa.verify((r, s), m, public_key)
    print("Is it valid? = ", valid)
    return valid
Exemplo n.º 5
0
 def set_key_from_file(self):
     fname = input('write a file name : ')
     try:
         self._private_key, self._public_key = import_key(fname +
                                                          '.private',
                                                          curve=curve.P256)
         print('private and public keys were successfully reset')
     except Exception as err:
         print('Reseting keys failed : ', err)
Exemplo n.º 6
0
def mine():
    priv_key, q = keys.import_key('./priv_key.key')
    r, s = ecdsa.sign(m, priv_key, curve=curve.secp256k1)

    files={'pub_key': open('./pub_key.pub','rb')}
    values={'r': r, 's': s}

    r = requests.post('http://localhost:5000/mine', files=files, data=values)
    print(r.text)
Exemplo n.º 7
0
def signNonce(file, m):
    private_key, _ = keys.import_key(file)
    print("private key: ", private_key)

    # standard signature, returns two integers
    r, s = ecdsa.sign(m, private_key)
    # should return True as the signature we just generated is valid.
    print("r: ", r)
    print("s: ", s)
    return r, s
Exemplo n.º 8
0
def check():
    r = int(request.form.get("r"))
    s = int(request.form.get("s"))
    print(r, s)

    parsed_d, pub_key = import_key('./pub_key.pub')

    valid = ecdsa.verify((r, s), m, pub_key, curve=curve.secp256k1)

    response = {'message': valid}
    return jsonify(response), 201
Exemplo n.º 9
0
    def import_keys(self, filen='default_key'):
        """
		import the private and public key from disk.

		:param filen: (optional) is the pem file name of key to load
		:type filen: str

		:return: None
		"""
        self.private_key, self.public_key = keys.import_key(
            self.path + 'cryp/.private/' + filen + 'prv.pem', curve=secp256k1)
Exemplo n.º 10
0
def sign_secp256r1(message, private_key_path, hashfunc=keccak_256):
    """Sign the message by secp256r1
    
    :param str message: The message for sign
    :param str private_key_path: The file path of private key
    :param function hashfunc: The hash function
    :rtype: tuple
    :return: The r and s part of signature
    """
    private_key = keys.import_key(private_key_path)[0]
    r, s = ecdsa.sign(message, private_key, hashfunc=hashfunc)
    return str(hex(r)), str(hex(s))
Exemplo n.º 11
0
    def import_publickey(self, filen='default_key'):
        """
		import the public key from disk.

		:param filen: (optional) is the pem file name of key to load
		:type filen: str

		:return: None
		"""
        self.public_key = keys.import_key(self.path + 'cryp/public/' + filen +
                                          'pub.pem',
                                          curve=secp256k1,
                                          public=True)
Exemplo n.º 12
0
def test():

    data = {
        "fullNames":
        'Bertha Matshidiso Kgokong',
        "practiceNumber":
        '1234567890',
        "notes":
        'I believe, we will make it to the moon and we will do it in this century'
    }

    private, public = import_key('/home/zatosh/keys/secp256k1.key')

    transaction = account.create_transaction(data)
    string_transaction = json.dumps(transaction, sort_keys=True).encode()
    signature = ecdsa.sign(string_transaction,
                           private,
                           curve=curve.secp256k1,
                           hashfunc=ecdsa.sha256)

    ##-----------------------------------------

    #Assume we are now - publishing the transaction
    transaction['signature'] = json.dumps(signature)
    to_send = json.dumps(transaction, sort_keys=True)

    #Now Let us See of This code will work . . . .
    trans_result = to_send
    transaction1 = json.loads(trans_result)
    #Add the Transaction to the pool
    string_signature1 = transaction1['signature']
    signature1 = eval(string_signature1)

    transaction1.pop('signature')
    string_transaction1 = json.dumps(transaction1, sort_keys=True).encode()

    key1, key2 = keys.get_public_keys_from_sig(signature1,
                                               string_transaction1,
                                               curve=curve.secp256k1,
                                               hashfunc=ecdsa.sha256)

    is_valid = ecdsa.verify(signature1, string_transaction1, key1,
                            curve.secp256k1, ecdsa.sha256)

    print(
        'Just received transaction broadcast {}: and added it to transaction pool'
        .format(transaction1))

    return "<h3>If this is true, the signatures did match - or else. ---> {}</h3>".format(
        is_valid)
Exemplo n.º 13
0
def transaction():
    priv_key, q = keys.import_key('./priv_key.key')
    r, s = ecdsa.sign(m, priv_key, curve=curve.secp256k1)

    print("Enter the file to public key of recipient")
    file = input()

    print("Enter the amount to send")
    amount = int(input())

    files = {'sender': open('./pub_key.pub','rb'), 'recipient': open(file + '/pub_key.pub','rb')}
    values={'r': r, 's': s, 'amount': amount}

    r = requests.post('http://localhost:5000/transactions/new', files=files, data=values)
    print(r.text)
Exemplo n.º 14
0
def add_transaction():
    data = {
        "fullNames": request.form['fullNames'],
        "practiceNumber": request.form['practiceNumber'],
        "notes": request.form['notes']
    }

    private, public = import_key('/home/zatosh/keys/secp256k1.key')

    transaction = account.create_transaction(data)
    string_transaction = json.dumps(transaction, sort_keys=True).encode()
    signature = ecdsa.sign(string_transaction,
                           private,
                           curve=curve.secp256k1,
                           hashfunc=ecdsa.sha256)

    index = blockchain.add_transaction(public, transaction, signature,
                                       transaction['transaction_id'], mysql)
    is_valid = ecdsa.verify(signature, string_transaction, public,
                            curve.secp256k1, ecdsa.sha256)

    #Publish the transaction on the network
    transaction_publish = transaction
    transaction_publish['signature'] = json.dumps(signature)
    peerserver.broadcast_transaction(transaction_publish,
                                     transaction_publisher)

    transaction_id = transaction['transaction_id']
    response = {
        'message':
        'Transaction id: {} will be added to block {}'.format(
            transaction_id, index),
        'transaction_details':
        transaction,
        'signature_valid':
        is_valid
    }
    return jsonify(response), 201
Exemplo n.º 15
0
def signTransaction(username, transactionData, type='user'):
    privateKey, publicKey = keys.import_key("keys/" + type + "Key/" +
                                            username + '_privkey.pem')
    r, s = ecdsa.sign(transactionData, privateKey, hashfunc=sha384)
    return r, s, transactionData
Exemplo n.º 16
0
def getPublicKey(username, type):
    privateKey, publicKey = keys.import_key("keys/" + type + "Key/" +
                                            username + '_pubkey.pem')
    return str(publicKey).encode('ascii')
Exemplo n.º 17
0
from fastecdsa import curve, ecdsa, keys
from hashlib import sha384

import sys

m = sys.argv[2]  # some message

''' use default curve and hash function (P256 and SHA2) '''

private_key, public_key = keys.import_key(sys.argv[1] + '.key')

print("private key: ",private_key)
print("public key: ",public_key)

# standard signature, returns two integers
r, s = ecdsa.sign(m, private_key)
# should return True as the signature we just generated is valid.

print("r: ",r)
print("s: ",s)
Exemplo n.º 18
0
 def importKeys(self):
   for file in os.listdir(KEYFOLDER):
     if file.endswith(".key"):
       d, Q = keys.import_key(KEYFOLDER+file)
       self.keys.append((d,Q))
Exemplo n.º 19
0
 def import_keys(path):
     return import_key(path)
Exemplo n.º 20
0
from fastecdsa.keys import import_key
from fastecdsa import curve, ecdsa

m = "This is a message"

priv_key, parsed_q = import_key('./priv_key.key')
parsed_d, pub_key = import_key('./pub_key.pub')

r, s = ecdsa.sign(m, priv_key, curve=curve.secp256k1)

print(r)
print(s)

valid = ecdsa.verify((r, s), m, pub_key, curve=curve.secp256k1)

print(valid)
Exemplo n.º 21
0
	def setUpClass(cls):
		# getting the private and public keys for the test
		cls.private_key, cls.public_key = import_key('tests/blockchain/test_files/default_keyprv.pem', curve=secp256k1)
Exemplo n.º 22
0
from fastecdsa import curve, ecdsa, keys
from hashlib import sha384

import sys

m = sys.argv[2]  # some message
''' use default curve and hash function (P256 and SHA2) '''

_, public_key = keys.import_key(sys.argv[1] + '.pub')

print("public key: ", public_key)

# should return True as the signature we just generated is valid.
valid = ecdsa.verify((long(sys.argv[3]), long(sys.argv[4])), m, public_key)

print("Is it valid? = ", valid)