Exemplo n.º 1
0
def main(argv):

    """
        Main procedure to generate C array with keys
    """

    parser = argparse.ArgumentParser(description="Generates SQLite database with"
        " keys and serial number.")
    parser.add_argument('config_file', help="project specific configuration file"
        )
    args = parser.parse_args()

    config = ConfigParser.ConfigParser()
    config.read(args.config_file)
    con = sqlite3.connect(config.get('database', 'filename'))

    while 1:
        serialno = uuid.uuid4().bytes
        oem_factory_token = '%s%s' %(serialno, '\xFF')
        customer_factory_token = '%s%s' %(serialno, '\x00\xFF')

        private_key = generate_private_key(config.get('tools', 'private_key_cmd'))
        public_key = generate_public_key(config.get('tools', 'public_key_cmd'), private_key)
        sk = SigningKey.from_der(private_key)
        pk = VerifyingKey.from_der(public_key)

        embedded_private_key = generate_private_key(config.get('tools', 'private_key_cmd'))
        embedded_public_key = generate_public_key(config.get('tools', 'public_key_cmd'), embedded_private_key)
        embedded_sk = SigningKey.from_der(embedded_private_key)
        embedded_pk = VerifyingKey.from_der(embedded_public_key)

        embedded_private_key_sig = embedded_sk.sign(oem_factory_token, hashfunc=sha256)
        assert embedded_pk.verify(embedded_private_key_sig, oem_factory_token, hashfunc=sha256)

        oem_factory_token_sig = sk.sign(oem_factory_token, hashfunc=sha256)
        assert pk.verify(oem_factory_token_sig, oem_factory_token, hashfunc=sha256)

        customer_factory_token_sig = sk.sign(customer_factory_token, hashfunc=sha256)
        assert pk.verify(customer_factory_token_sig, customer_factory_token, hashfunc=sha256)

        debug_token_sig = sk.sign(serialno, hashfunc=sha256)
        assert pk.verify(debug_token_sig, serialno, hashfunc=sha256)

        public_key_compressed = ecc_compress(pk.to_string())

        with con:
            cur = con.cursor()
            cur.execute(config.get('database', 'create'))
            cur.execute(config.get('database', 'insert'),
                        (sqlite3.Binary(private_key),
                         sqlite3.Binary(public_key),
                         sqlite3.Binary(public_key_compressed),
                         sqlite3.Binary(embedded_private_key),
                         sqlite3.Binary(embedded_public_key),
                         sqlite3.Binary(embedded_sk.to_string()),
                         sqlite3.Binary(serialno),
                         sqlite3.Binary(oem_factory_token_sig),
                         sqlite3.Binary(customer_factory_token_sig),
                         sqlite3.Binary(debug_token_sig)))
Exemplo n.º 2
0
def import_public_key_ecc(s):
    """
    import public ecc key from a hex string
    :param s: a hex string generated by export_keys()
    :return: a VerifyingKey object
    """
    return VerifyingKey.from_string(bytes.fromhex(s), curve=SECP256k1)
Exemplo n.º 3
0
def validate_signature(signature_block, log=logging.getLogger(__name__)):
    """
    Validates signature of verification record or transaction accounting for presence of
        "stripped_hash" in transaction signatures
    :param signature_block: dict of signature
    :param log: message logger
    :return: True on valid signature, False otherwise.
    """

    """ validate signature using provided stripped and full hashes """

    verifying_key = VerifyingKey.from_pem(signature_block["public_key"])

    log.info("Decoding the digest")
    decoded_digest = signature_block["signature"].decode('base64')

    log.info('Performing signature verification')
    # checking stripped hash if this is a transaction signature
    if "stripped_hash" in signature_block and signature_block['stripped_hash']:
        merged_hash = merge_hashes(signature_block["stripped_hash"], signature_block["hash"])
        verifying_key.verify(decoded_digest, str(merged_hash))
    else:
        verifying_key.verify(decoded_digest, str(signature_block["hash"]))
    # signature hash is valid
    return True
Exemplo n.º 4
0
Arquivo: ec.py Projeto: hdknr/jose
 def create_material(self, bits, d=None, x=None, y=None):
     curve = self.curve_for_bits(bits)
     if d:
         return SigningKey.from_secret_exponent(d, curve)
     if x and y:
         point = ec.Point(curve.curve, x, y, curve.order)
         return VerifyingKey.from_public_point(point, curve)
Exemplo n.º 5
0
def loadpubstr(pemstring):
    """
    Load a public key from PEM string
    :param pemstring:
    :return:
    """
    return VerifyingKey.from_pem(pemstring)
Exemplo n.º 6
0
def process_invoicerequest(message, id):

    resolver = PluginManager.get_plugin('RESOLVER', config.resolver_type)

    if isinstance(message, ProtocolMessage):

        invoice_request = InvoiceRequest()
        invoice_request.ParseFromString(message.serialized_message)

        # Validate Public Key
        vk = from_sec(request.headers.get('x-identity').decode('hex')) or VerifyingKey.from_der(request.headers.get('x-identity').decode('hex'))
        allowed_keys = [vk.to_der(), to_sec(vk, False), to_sec(vk, True)]

        if invoice_request.sender_public_key not in allowed_keys:
            log.warn("InvoiceRequest Public Key Does Not Match X-Identity Public Key")
            return create_json_response(False, 'InvoiceRequest Public Key Does Not Match X-Identity Public Key', 400)

        if invoice_request.pki_type == 'x509+sha256':
            log.debug("InvoiceRequest Contains X509 Certificate, Validating")

            if invoice_request.pki_data and not invoice_request.signature:
                log.warn('Submitted InvoiceRequest Missing Signature')
                return create_json_response(False, 'Requests including x509 cert must include signature', 400)

            # Verify signature if cert and signature are present
            if invoice_request.pki_data and invoice_request.signature:

                try:
                    x509_certs = X509Certificates()
                    x509_certs.ParseFromString(invoice_request.pki_data)

                    cert_data = ssl.DER_cert_to_PEM_cert(x509_certs.certificate[0])
                    cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_data)
                except Exception as e:
                    log.warn('Unable to load given x509 certificate [ID: %s]: %s' % (id, str(e)))
                    return create_json_response(False, 'Invalid x509 Certificate', 400)

                try:
                    sig_validate_ir = InvoiceRequest()
                    sig_validate_ir.ParseFromString(message.serialized_message)
                    sig_validate_ir.signature = ""
                    crypto.verify(cert, invoice_request.signature, sig_validate_ir.SerializeToString(), 'sha256')
                    log.info("InvoiceRequest Signature is Valid")
                except Exception as e:
                    log.info('Bad Signature Encountered During Signature Validation [ID: %s]: %s' % (id, str(e)))
                    return create_json_response(False, 'InvoiceRequest Signature Verification Error', 401)

    try:
        log.info('Adding InvoiceRequest %s' % id)
        ret_tx_id = resolver.add_paymentprotocol_message(message, id=id)
        if not ret_tx_id:
            log.error("Unexpected Add InvoiceRequest Failure [ID: %s]" % (id))
            return create_json_response(False, 'Unknown System Error, Please Try Again Later', 503)

        pp_tx_url = '%s/paymentprotocol/%s' % (request.host_url.rstrip('/'), ret_tx_id)
        log.debug('Accepted InvoiceRequest [ID: %s]' % id)
        return create_json_response(status=202, headers={'Access-Control-Expose-Headers': 'Location', 'Location':pp_tx_url})
    except Exception as e:
        log.error("Unexpected exception adding InvoiceRequest [ID: %s]: %s" % (id, str(e)))
        return create_json_response(False, 'Unknown System Error, Please Try Again Later', 503)
Exemplo n.º 7
0
 def __init__(self,jsonObject):
     """
     Validate the signature of an already parsed JSON object
     
     The current implementation is limited to RSA and EC
     signatures and usage of the IETF JOSE algorithms
     
     An invalid signature raises an exception
     """
     if not isinstance(jsonObject, OrderedDict):
         raise TypeError('JCS requires JSON to be parsed into a "OrderedDict"')
     signatureObject = jsonObject['signature']
     clonedSignatureObject = OrderedDict(signatureObject)
     signatureValue = base64UrlDecode(signatureObject.pop('value'))
     algorithmEntry = getAlgorithmEntry(signatureObject['algorithm'])
     hashObject = algorithmEntry[1].new(serializeJson(jsonObject).encode("utf-8"))
     jsonObject['signature'] = clonedSignatureObject
     self.publicKey = signatureObject['publicKey']
     keyType = self.publicKey['type']
     if algorithmEntry[0]:
         if keyType != 'RSA':
             raise TypeError('"RSA" expected')
         self.nativePublicKey = RSA.construct([cryptoBigNumDecode(self.publicKey['n']),
                                               cryptoBigNumDecode(self.publicKey['e'])])
         if not PKCS1_v1_5.new(self.nativePublicKey).verify(hashObject,signatureValue):
             raise ValueError('Invalid Signature!')
     else:
         if keyType != 'EC':
             raise TypeError('"EC" expected')
         self.nativePublicKey = EC.from_string(base64UrlDecode(self.publicKey['x']) + 
                                               base64UrlDecode(self.publicKey['y']),
                                               curve=getEcCurve(self.publicKey['curve']))
         self.nativePublicKey.verify_digest(signatureValue,hashObject.digest())
Exemplo n.º 8
0
    def __init__(self, msg=None, data=None, filename=None, password=None, vals=None, file_obj=None):
        self.verifying_key = None
        self.signing_key = None
        if file_obj is not None:
            self._from_private_key(file_obj, password)
            return
        if filename is not None:
            self._from_private_key_file(filename, password)
            return
        if (msg is None) and (data is not None):
            msg = Message(data)
        if vals is not None:
            self.verifying_key, self.signing_key = vals
        else:
            if msg is None:
                raise SSHException('Key object may not be empty')
            if msg.get_text() != 'ecdsa-sha2-nistp256':
                raise SSHException('Invalid key')
            curvename = msg.get_text()
            if curvename != 'nistp256':
                raise SSHException("Can't handle curve of type %s" % curvename)

            pointinfo = msg.get_binary()
            if pointinfo[0:1] != four_byte:
                raise SSHException('Point compression is being used: %s' %
                                   binascii.hexlify(pointinfo))
            self.verifying_key = VerifyingKey.from_string(pointinfo[1:],
                                                          curve=curves.NIST256p)
        self.size = 256
Exemplo n.º 9
0
def check_for_privkey(keydir, jid, stderr):
    # the "anonymous ID" case
    if jid.startswith("anonid0-"):
        return None

    # the "old-style ID" case
    # FIXME: once it is possible for addons to change from old-style IDs
    # to new, cryptographic IDs on AMO and in Firefox, warn users that
    # continuing to use old-style IDs is less secure, and provide them with
    # instructions for changing to new IDs.
    if not jid.startswith("jid0-"):
        return None

    keypath = os.path.join(keydir, jid)
    if not os.path.isfile(keypath):
        msg = """\
Your package.json says our ID is:
  %(jid)s
But I don't have a corresponding private key in:
  %(keypath)s

If you are the original developer of this package and have recently copied
the source code from a different machine to this one, you should copy the
private key into the file named above.

Otherwise, if you are a new developer who has made a copy of an existing
package to use as a starting point, you need to remove the 'id' property
from package.json, so that we can generate a new id and keypair. This will
disassociate our new package from the old one.

If you're collaborating on the same addon with a team, make sure at least
one person on the team has the private key. In the future, you may not
be able to distribute your addon without it.
"""
        print >> stderr, msg % {"jid": jid, "keypath": keypath}
        return None
    keylines = open(keypath, "r").readlines()
    keydata = {}
    for line in keylines:
        line = line.strip()
        if line:
            k, v = line.split(":", 1)
            keydata[k.strip()] = v.strip()
    if "private-key" not in keydata:
        raise ValueError("invalid keydata: can't find 'private-key' line")
    sk_s = remove_prefix(keydata["private-key"], "private-jid0-", errormsg="unable to parse private-key data")
    from ecdsa import SigningKey, VerifyingKey, NIST256p

    sk = SigningKey.from_string(my_b32decode(sk_s), curve=NIST256p)
    vk = sk.get_verifying_key()

    jid_2 = vk_to_jid(vk)
    if jid_2 != jid:
        raise ValueError("invalid keydata: private-key in %s does not match" " public key for %s" % (keypath, jid))
    vk_s = remove_prefix(keydata["public-key"], "public-jid0-", errormsg="unable to parse public-key data")
    vk2 = VerifyingKey.from_string(my_b32decode(vk_s), curve=NIST256p)
    if vk.to_string() != vk2.to_string():
        raise ValueError("invalid keydata: public-key mismatch")
    return sk
Exemplo n.º 10
0
 def load_public_key(self):
     # Check settings validity
     if self.private_key:
         private_key = self.load_private_key()
         return private_key.get_verifying_key()
     elif self.public_key:
         with open(self.public_key, 'rb') as key_file:
             return VerifyingKey.from_pem(key_file.read())
Exemplo n.º 11
0
    def from_point(cls, point, network=BitcoinMainNet, **kwargs):
        """Create a PublicKey from a point on the SECP256k1 curve.

        :param point: A point on the SECP256k1 curve.
        :type point: SECP256k1.point
        """
        verifying_key = VerifyingKey.from_public_point(point, curve=SECP256k1)
        return cls.from_verifying_key(verifying_key, network=network, **kwargs)
Exemplo n.º 12
0
def hex2key(hex_key):
    key_bytes = unhexlify(hex_key)
    if len(hex_key) == 64:
        return SigningKey.from_string(key_bytes, curve=NIST256p,
                hashfunc=sha256)
    elif len(hex_key) == 128:
        return VerifyingKey.from_string(key_bytes, curve=NIST256p,
                hashfunc=sha256)
    else:
        raise ValueError("Key in hex form is of the wrong length.")
Exemplo n.º 13
0
def verify(pubKey, message, signature):
    try:
        vk = VerifyingKey.from_der(pubKey)
        hashed = _policy_[vk.curve.name][1](message).digest()
        if vk.verify(signature, hashed):
            return True
        else:
            return False
    except Exception,e:
       return False
Exemplo n.º 14
0
    def __init__(self, **kwargs):
        try:
            config = kwargs['config']
        except KeyError:
            client_key = kwargs['client_key']
            server_key = kwargs['server_key']
            identifier = kwargs['identifier']
            try:
                url = kwargs['url']
            except KeyError:
                url = 'https://core.bravecollective.net/api'
        else:
            client_key = config['CORE_AUTH_PRIVATE_KEY']
            server_key = config['CORE_AUTH_PUBLIC_KEY']
            identifier = config['CORE_AUTH_IDENTIFIER']
            try:
                url = config['CORE_AUTH_URL']
            except KeyError:
                url = 'https://core.bravecollective.net/api'

        if isinstance(client_key, SigningKey):
            priv = client_key
        elif hasattr(client_key, 'read'):
            priv_pem = client_key.read()
            priv = SigningKey.from_pem(priv_pem)
        else:
            with open(client_key, 'r') as f:
                priv_pem = f.read()
                priv = SigningKey.from_pem(priv_pem)

        if isinstance(server_key, VerifyingKey):
            pub = server_key
        elif hasattr(server_key, 'read'):
            pub_pem = server_key.read()
            pub = VerifyingKey.from_pem(pub_pem)
        else:
            with open(server_key, 'r') as f:
                pub_pem = f.read()
                pub = VerifyingKey.from_pem(pub_pem)

        self.api = API(url, identifier, priv, pub,
                requests_session)
Exemplo n.º 15
0
def verify_file(args):
    from ecdsa import VerifyingKey

    public_key = VerifyingKey.from_pem(args.verificaitonKey.read())
    signature = args.signature.read()
    message = args.file.read()

    if verify_signature(public_key, message, signature):
        print "Verification OK"
    else:
        print "Verification Failure"
Exemplo n.º 16
0
def validate_encrypted_message(msg, sig_key='sender', sig_required=False):

    # Verify Keys in DER Format
    try:
        sender_key = from_sec(msg.sender_public_key) or VerifyingKey.from_der(msg.sender_public_key)
    except Exception as e:
        log.warn("sender_public_key NOT in DER Format")
        raise EncryptedMessageValidationError('sender_public_key not in DER format')

    try:
        receiver_key = from_sec(msg.receiver_public_key) or VerifyingKey.from_der(msg.receiver_public_key)
    except Exception as e:
        log.warn("receiver_public_key NOT in DER Format")
        raise EncryptedMessageValidationError('receiver_public_key not in DER format')

    # Validate Nonce
    if not msg.nonce or msg.nonce < (int(time.time() * 1000000) - config.ir_nonce_allowable * 1000000):
        log.warn("InvoiceRequest Nonce Missing or Before %d Seconds Ago" % config.ir_nonce_allowable)
        raise NonceValidationError('Invalid Nonce')

    if not msg.signature:
        if not sig_required:
            return
        else:
            raise EncryptedMessageValidationError('Signature Required')

    # Validate Signature
    try:
        sig_verify = msg.signature
        msg.signature = ''
        if sig_key == 'sender':
            sender_key.verify(sig_verify, msg.SerializeToString(), hashfunc=sha256, sigdecode=sigdecode_der)
        elif sig_key == 'receiver':
            receiver_key.verify(sig_verify, msg.SerializeToString(), hashfunc=sha256, sigdecode=sigdecode_der)
        else:
            raise Exception('Invalid sig_key argument')
        msg.signature = sig_verify
    except Exception as e:
        log.warn('Signature Validation Failed: %s' % str(e))
        raise EncryptedMessageValidationError('Invalid Signature')
Exemplo n.º 17
0
def from_sec(string, curve=curves.SECP256k1, hashfunc=sha1, validate_point=True):
    """Convert a public key in SEC binary format to a verifying key."""
    # based on code from https://github.com/richardkiss/pycoin
    if string.startswith(b("\x04")):
        # uncompressed
        return VerifyingKey.from_string(string[1:], curve, hashfunc, validate_point)
    elif string.startswith(b("\x02")) or string.startswith(b("\x03")):
        # compressed
        is_even = string.startswith(b("\x02"))
        x = string_to_number(string[1:])
        order = curve.order
        p = curve.curve.p()
        alpha = (pow(x, 3, p) + (curve.curve.a() * x) + curve.curve.b()) % p
        beta = square_root_mod_prime(alpha, p)
        if is_even == bool(beta & 1):
            y = p - beta
        else:
            y = beta
        if validate_point:
            assert ecdsa.point_is_valid(curve.generator, x, y)
        point = ellipticcurve.Point(curve.curve, x, y, order)
        return VerifyingKey.from_public_point(point, curve, hashfunc)
Exemplo n.º 18
0
def receive_message(args):
    '''
    '''
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.primitives.asymmetric import padding
    from ecdsa import VerifyingKey

    backend = default_backend()
    key_size = 2048

    key_enc = args.message.read(key_size/8)
    iv = args.message.read(16)
    encrypted = args.message.read()

    private_key = serialization.load_pem_private_key(
        args.privateKey.read(),
        password=None,
        backend=backend
    )

    key = private_key.decrypt(
        key_enc,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA1()),
            algorithm=hashes.SHA1(),
            label=None
        )
    )

    plain = decrypt(key, iv, encrypted)

    signature = plain[len(plain)-64:]
    plain = plain[:len(plain)-64]

    name, extension = os.path.splitext(args.message.name)

    name = os.path.basename(name)

    with open(name, 'wb') as plain_file:
        plain_file.write(plain)

    with open('%s.sig' % name, 'wb') as sig_file:
        sig_file.write(signature)

    public_key = VerifyingKey.from_pem(args.verificaitonKey.read())
    if verify_signature(public_key, plain, signature):
        print "Verification OK"
    else:
        print "Verification Failure"
def recover():
	txt1 = "Students reported that students post to discussion forums more frequently and are irrevocable provided the stated conditions are met."
	sig1 = '''a0289c0fa7e87f1ab1e94b577f43691ebd70c04b0e62ca7eaaf1791983d512e7bbc843ee3a2a0430455e9f755f832ccdcd7a46d769ee43467a01453214868094ca228cb5eebc953a39fb9bbaf865f4dbe1dad9b5f9f1bed75671e0db5433f0ed'''.strip().decode('hex')

	txt2 = "But is this enough? And what new threats could be using it as a friend or fan.[2]"
	sig2 = '''a0289c0fa7e87f1ab1e94b577f43691ebd70c04b0e62ca7eaaf1791983d512e7bbc843ee3a2a0430455e9f755f832ccd54d4f8306fe11bd4a28a491ddf596c64cd98c93d7fa9a05acead17e42e96ed1a190a2fddd7c695b8d9bce43f221b4e1b'''.strip().decode('hex')

	public_key_ec = VerifyingKey.from_pem(public_key_ec_pem)
	print "Verify1: " + str(public_key_ec.verify(sig1, txt1))
	print "Verify2: " + str(public_key_ec.verify(sig2, txt2))
	print "curve order:", public_key_ec.curve.order

	key = recover_key(txt1, sig1, txt2, sig2, public_key_ec)
	print key
Exemplo n.º 20
0
	def __init__(self, identity, private, public):
		"""Configure HTDSA signed request/response authentication.
		
		To perform the cryptographic operations required for the HTDSA protocol you must pass in either instances of
		`ecdsa` signing and verifying keys, or their hex-encoded versions which will be converted automatically.
		
		Additionally, the identity token (opaque identifier) assigned to your client application by the provider will
		need to be passed in so we can identify ourselves.
		
		The private key is your application's private key. The public key is the provider's service key you were given
		when registering your application.
		"""
		
		self.identity = identity
		self.private = SigningKey.from_string(unhexlify(private), NIST256p) if isinstance(private, (str, unicode)) else private
		self.public = VerifyingKey.from_string(unhexlify(public), NIST256p) if isinstance(public, (str, unicode)) else public
Exemplo n.º 21
0
    def put(self, ndef_message):
        print "client has put an NDEF message"
        #print ndef_message.pretty()
        keyRecord = ndef_message.pop()
        sigRecord = ndef_message.pop()
        actionRecord = ndef_message.pop()

        vk = VerifyingKey.from_pem(keyRecord.data.decode("utf-8"))
        print vk.to_pem() == keyRecord.data.decode("utf-8")
        
        print "Key created. Yay!"
        try:
            tmp = vk.verify(sigRecord.data, "test", hashfunc=hashlib.sha256())
            print tmp
        except Exception, e:
            print "Signature Error"
Exemplo n.º 22
0
	def __init__(self, key=None, private=False):
		
		self.secretKey = self.verifKey = None
		
		# Recuperation
		if key is not None:
			if private:
				self.secretKey = SigningKey.from_string(key, curve=NIST384p)
				self.verifKey = self.secretKey.get_verifying_key()
			else:
				self.verifKey = VerifyingKey.from_string(key, curve=NIST384p)
		
		# Auto-generation	
		else:
			self.secretKey = SigningKey.generate(curve=NIST384p)
			self.verifKey = self.secretKey.get_verifying_key()
Exemplo n.º 23
0
def check_for_privkey(keydir, jid, stderr):
    keypath = os.path.join(keydir, jid)
    if not os.path.isfile(keypath):
        msg = """\
Your package.json says our ID is:
  %(jid)s
But I don't have a corresponding private key in:
  %(keypath)s

If you are the original developer of this package and have recently copied
the source code from a different machine to this one, you need to copy the
private key into the file named above.

Otherwise, if you are a new developer who has made a copy of an existing
package to use as a starting point, you need to remove the 'id' property
from package.json, so that we can generate a new id and keypair. This will
disassociate our new package from the old one.
"""
        print >>stderr, msg % {"jid": jid, "keypath": keypath}
        return None
    keylines = open(keypath, "r").readlines()
    keydata = {}
    for line in keylines:
        line = line.strip()
        if line:
            k,v = line.split(":", 1)
            keydata[k.strip()] = v.strip()
    if "private-key" not in keydata:
        raise ValueError("invalid keydata: can't find 'private-key' line")
    sk_s = remove_prefix(keydata["private-key"], "private-jid0-",
                         errormsg="unable to parse private-key data")
    from ecdsa import SigningKey, VerifyingKey, NIST256p
    sk = SigningKey.from_string(my_b32decode(sk_s), curve=NIST256p)
    vk = sk.get_verifying_key()

    jid_2 = vk_to_jid(vk)
    if jid_2 != jid:
        raise ValueError("invalid keydata: private-key in %s does not match"
                         " public key for %s" % (keypath, jid))
    vk_s = remove_prefix(keydata["public-key"], "public-jid0-",
                         errormsg="unable to parse public-key data")
    vk2 = VerifyingKey.from_string(my_b32decode(vk_s), curve=NIST256p)
    if vk.to_string() != vk2.to_string():
        raise ValueError("invalid keydata: public-key mismatch")
    return sk
Exemplo n.º 24
0
def is_jose_sig_valid(b64_jpayload, jose_sig, vk_pem):
    jpayload = b64url_dec(b64_jpayload, MalformedSignatureError)

    b64_jheader = dget(jose_sig, 'protected', MalformedSignatureError)
    jheader = b64url_dec(b64_jheader, MalformedSignatureError)

    b64_sig = dget(jose_sig, 'signature', MalformedSignatureError)
    sig_der = b64url_dec(b64_sig, MalformedSignatureError)

    vk = VerifyingKey.from_pem(vk_pem)
    vk_order = vk.curve.order
    b64_sig_string = base64url_encode(sig_der_to_string(sig_der, vk_order))

    try:
        jws.verify(jheader, jpayload, b64_sig_string, vk, is_json=True)
        return True
    except jws.SignatureError:
        return False
Exemplo n.º 25
0
    def valid_signature(self, signature, msg, public_key=None):
        try:
            if type(msg) == str:
                msg = msg.encode("ascii")

            #Parse public key.
            if public_key == None:
                public_key = self.public_key
            else:
                public_key = self.parse_public_key(public_key)

            signature = auto_bytes(signature)
            msg = auto_bytes(msg)
            verify_key = VerifyingKey.from_string(public_key, SECP256k1)
            return verify_key.verify(signature, msg)
        except Exception as e:
            print(e)
            return 0
Exemplo n.º 26
0
    def __init__(self, public_key=None, private_key=None):
        self.id = 0
        if public_key is not None:
            public_key = "#" + public_key

        if private_key is not None:
            private_key = "#" + private_key

        self.public_key = auto_bytes(public_key)
        self.private_key = private_key
        self.addr_version = None
        self.use_compression = 1
        if private_key == "":
            private_key = None

        #Generate key pairs.
        if self.public_key == None and private_key == None:
            self.sign_key = SigningKey.generate(curve=SECP256k1)
            self.verify_key = self.sign_key.get_verifying_key()
            self.private_key = self.sign_key.to_string()
            self.public_key = self.verify_key.to_string()
            return

        #Init public key.
        self.old_verify_str = None
        if self.public_key != None:
            self.public_key = self.parse_public_key(self.public_key)
            self.verify_key = VerifyingKey.from_string(self.public_key, SECP256k1)
            self.sign_key = None
            self.old_verify_str = self.verify_key.to_string()

        #Init private key.
        if self.private_key != None:
            #Construct keys from private key.
            self.private_key = self.parse_private_key(private_key)
            self.sign_key = SigningKey.from_string(self.private_key, SECP256k1) 
            self.verify_key = self.sign_key.get_verifying_key()

            #Check private key corrosponds to public key.
            if self.old_verify_str != None:
                if self.old_verify_str != self.verify_key.to_string():
                    raise Exception("Private key doesn't corrospond to stored public key.")
Exemplo n.º 27
0
def is_jws_sig_valid(b64_jws_sig, vk_pem):
    parts = b64_jws_sig.split('.')
    if len(parts) != 3:
        raise MalformedSignatureError

    # Extract parts to verify signature
    jheader_b64, jbody_b64, sig_der_b64 = parts
    jheader = b64url_dec(jheader_b64)
    jbody = b64url_dec(jbody_b64)
    sig_der = b64url_dec(sig_der_b64)

    vk = VerifyingKey.from_pem(vk_pem)
    vk_order = vk.curve.order
    sig_string_b64 = base64url_encode(sig_der_to_string(sig_der, vk_order))

    try:
        jws.verify(jheader, jbody, sig_string_b64, vk, is_json=True)
        return True
    except jws.SignatureError:
        return False
Exemplo n.º 28
0
def main(argv):

    """
        Main procedure to sign a binary
    """


    parser = argparse.ArgumentParser(description='convert der to raw')
    parser.add_argument('-s','--secretkey_file', help='Secret key', required=True)
    parser.add_argument('-p','--publickey_file', help='Public key', required=True)
    args = parser.parse_args()

    secretkey_file = args.secretkey_file
    publickey_file = args.publickey_file


    privkey = SigningKey.from_der(open(secretkey_file).read())
    pubkey = VerifyingKey.from_der(open(publickey_file).read())

    open(secretkey_file[0:-4] + ".bin", "wb").write(privkey.to_string())
    open(publickey_file[0:-4] + ".bin", "wb").write(pubkey.to_string())
Exemplo n.º 29
0
 def get_ecdsa_verifying_key(pub):
     #some shenanigans required to validate a transaction sig; see
     #python.ecdsa PR #54. This will be a lot simpler when that's merged.
     #https://github.com/warner/python-ecdsa/pull/54/files
     if not pub[0] in ["\x02", "\x03"]:
         log.debug("Invalid pubkey")
         return None    
     is_even = pub.startswith('\x02')
     x = string_to_number(pub[1:])
     order = SECP256k1.order
     p = SECP256k1.curve.p()
     alpha = (pow(x, 3, p) + (SECP256k1.curve.a() * x) + SECP256k1.curve.b()) % p
     beta = square_root_mod_prime(alpha, p)
     if is_even == bool(beta & 1):
         y = p - beta
     else:
         y = beta
     if not point_is_valid(SECP256k1.generator, x, y):
         return None
     
     point = Point(SECP256k1.curve, x, y, order)
     return VerifyingKey.from_public_point(point, SECP256k1,
                                                hashfunc=hashlib.sha256)
Exemplo n.º 30
0
    amount = (amount << 8) | data[1]
    print(f"amount: {amount}€")
else:
    print("no operation 1")

# GET INFO
Le = 0x0
data, sw1, sw2 = connection.transmit([CLA, INS_REQUEST_INFO, P1, P2, Le])
if sw1 == 0x90 and sw2 == 0x00:
    infos = parse_user_info(data)
else:
    print("no operation 6")

# VERIFY THE INFORMATION SIGNATURE
with open("../keys/vk.pem") as f:
    vk = VerifyingKey.from_pem(f.read())

ok = vk.verify(bytearray(infos[3]), bytearray(infos[0] + infos[1] + infos[2]),
               hashlib.sha256)
assert ok

# COMPLETE CHALLENGE
enc = None
Le = 0x0
data, sw1, sw2 = connection.transmit([CLA, INS_REQUEST_CHALLENGE, P1, P2, Le])
if sw1 == 0x90 and sw2 == 0x00:
    conn = connect("../res/paystival.sqlite")
    cur = conn.cursor()
    userid = to2hex(infos[2][0]) + to2hex(infos[2][1]) + to2hex(
        infos[2][2]) + to2hex(infos[2][3])
    cur.execute("SELECT exponent, modulus FROM public_keys WHERE userid=?",
Exemplo n.º 31
0
def verify_signature(data: bytes, signature: str, public_key: str):
    vk = VerifyingKey.from_string(bytes.fromhex(public_key), curve=SECP256k1)
    try:
        return vk.verify(bytes.fromhex(signature), data)
    except BadSignatureError:
        return False
Exemplo n.º 32
0
config.read("config/subscriber.ini")

username = config.get('credential', 'username')
password = config.get('credential', 'password')
topic = config.get('credential', 'topic')
server = config.get('host', 'server')
port = config.getint('host', 'port')
keepalive = config.getint('host', 'keep-alive')
clientid = config.get('credential', 'client')


def on_connect(client, userdata, flags, rc):
    client.subscribe(topic)


vk = VerifyingKey.from_pem(open("config/public192.pem").read())


def on_message(client, userdata, msg):

    msg = msg.payload.split(b' ')
    signature = msg[0]
    message = msg[1]

    if (vk.verify(signature,
                  message,
                  hashfunc=hashlib.sha1,
                  sigdecode=ecdsa.util.sigdecode_der)):
        print(message.decode('utf-8'))
    else:
        BadSignatureError()
Exemplo n.º 33
0
import json
import hashlib
from ecdsa import SigningKey, VerifyingKey, NIST384p, BadSignatureError
import codecs

sk1 = SigningKey.generate()
vk1 = sk1.get_verifying_key()
pubkey = vk1.to_string().encode("hex")
vk = VerifyingKey.from_string(pubkey.decode("hex"))
message = "hello"
sig = sk1.sign(message).encode("hex")
try:
    vk.verify(sig.decode("hex"), message)
    print "Good sig"
except BadSignatureError:
    print "Bad sig"

sk2 = SigningKey.generate()
vk2 = sk2.get_verifying_key()

sk3 = SigningKey.generate()
vk3 = sk3.get_verifying_key()

sk4 = SigningKey.generate()
vk4 = sk4.get_verifying_key()

sk5 = SigningKey.generate()
vk5 = sk5.get_verifying_key()

# GENESIS: 25 COINS TO VK1
Exemplo n.º 34
0
def verify_signature(pubkey, message, signature):
    public_key = VerifyingKey.from_string(unhexlify(pubkey))
    return public_key.verify(signature, message.encode("utf-8"))
def verify_vin(txid, index):
    txdump = dump_tx_ecdsa(txid, index)
    #i, pub, txid, s, r, x, z
    #    |               |   \--- hash
    #    |                \------ pub decoded?
    #     \---------------------- pub orig?
    import pprint
    pprint.pprint(txdump)
    print txdump['z'].decode("hex")
    print int(txdump['z'], 16)

    def fix_pubkey(p):
        if p.startswith("04"):
            return p[2:]
        return p

    txdump['pub'] = fix_pubkey(txdump['pub'])
    #vk = VerifyingKey.from_public_point(int(txdump['x'],16),curve=curve)
    #vk = VerifyingKey.from_string(txdump['pub'], curve=curve)
    #print vk
    #logger.debug("verify --> %s " % (vk.pubkey.verifies(int(digest.encode("hex"), 16), Signature(sig[0], sig[1]))))

    # get raw transaction (txid)  <-- vin[0]: scriptSig
    rpc = BtcRpc("http://*****:*****@127.0.0.1:8332")
    rawtx = rpc.rpc.getrawtransaction(txid)
    jsontxverbose = rpc.rpc.getrawtransaction(txid, 1)
    #pprint.pprint(jsontxverbose)
    jsontx = pybitcointools.deserialize(rawtx)
    pprint.pprint(jsontx)
    scriptSigasm = jsontxverbose['vin'][index]['scriptSig']['asm']

    logger.debug(scriptSigasm)

    scriptSig = jsontx['ins'][index]['script']
    sigpubdecoded = asn1der.decode(
        scriptSig.decode("hex")[1:])  # skip first push
    sig = long(sigpubdecoded[0][0]), long(sigpubdecoded[0][1])
    pubkey = sigpubdecoded[1]
    sighash_type = pubkey[0]

    logger.debug("sighash type: %r" % sighash_type)
    push = pubkey[1]
    btc_pubkey_type = pubkey[2]
    pubkey = pubkey[3:]

    logger.debug("r %s s %s" % (hex(sig[0]), hex(sig[1])))

    logger.debug("pubkey:  %r" % pubkey.encode("hex"))
    logger.debug("txdump: %r" % txdump['pub'])
    '''
    # generate signdata
    # replace input script with funding script of 17SkEw2md5avVNyYgj6RiXuQKNwkXaxFyQ
    for txin in jsontx['ins']:
        txin['script']=''
    funding_txid = jsontxverbose['vin'][index]['txid']
    funding_tx = rpc.rpc.getrawtransaction(funding_txid,1)
    #pprint.pprint(funding_tx)
    funding_script = funding_tx['vout'][0]['scriptPubKey']['hex']
    jsontx['ins'][index]['script']=funding_script
    signdata= pybitcointools.serialize(jsontx) + "01000000"  #SIGHASH ALL
    import hashlib
    digest = hashlib.sha256(hashlib.sha256(signdata.decode("hex")).digest()).digest()
    logger.debug(digest[::-1].encode("hex"))
    pause("--->")
    '''
    pause("create verifying key...")

    vk = VerifyingKey.from_string(txdump['pub'].decode("hex"), curve=curve)
    digest = txdump['z']
    print repr(pubkey)
    print repr(txdump['pub'])
    z = int(digest.decode("hex"), 16)
    verifies = vk.pubkey.verifies(z, Signature(sig[0], sig[1]))
    logger.debug("verify --> %s " % (verifies))
    if not verifies:
        pause("--verify false!--", critical=True)

    #print vk.verify_digest(scriptSigasm.split("[ALL]",1)[0].decode("hex"), digest, sigdecode=ecdsa.util.sigdecode_der)

    return BTCSignature(
        sig=Signature(sig[0], sig[1]),
        h=z,
        pubkey=pubkey,
    )
Exemplo n.º 36
0
def public_from_bytearray(arr):
    return VerifyingKey.from_string(arr, curve=ecdsa.SECP256k1, hashfunc=sha256) 
Exemplo n.º 37
0
 def from_pair(cls, pair):
     x, y = pair
     point = Point(curve=SECP256k1.curve, x=x, y=y, order=SECP256k1.order)
     key = VerifyingKey.from_public_point(point, curve=SECP256k1)
     return cls(key)
Exemplo n.º 38
0
from ecdsa import SigningKey, VerifyingKey
from ecdsa.util import sigdecode_string
from ecdsa.numbertheory import inverse_mod
from hashlib import sha256

priv_key = SigningKey.from_pem(open("private.pem").read())
pub_key = VerifyingKey.from_pem(open("public.pem").read())
print(
    "======================================================================================================="
)
print("Public Key")
print("\tCurve:\t\t\t", pub_key.curve.name)
print("\tGenerator X:\t\t", pub_key.pubkey.generator._Point__x)
print("\tGenerator Y:\t\t", pub_key.pubkey.generator._Point__y)
print("\tGenerator Order:\t", pub_key.pubkey.generator._Point__order)
print("\tPoint X:\t\t", pub_key.pubkey.point._Point__x)
print("\tPoint Y:\t\t", pub_key.pubkey.point._Point__y)
print("Private Key")
print("\tSecret Exponent:\t", priv_key.privkey.secret_multiplier)
print(
    "======================================================================================================="
)
print(
    "======================================================================================================="
)
msg1 = "We are not uncertain with the vote.".encode('utf-8')
msg2 = "We are uncertain with the vote.".encode('utf-8')
print("Hash 1:\t\t\t\t", int.from_bytes(sha256(msg1).digest(),
                                        byteorder='big'))
print("Hash 2:\t\t\t\t", int.from_bytes(sha256(msg2).digest(),
                                        byteorder='big'))
Exemplo n.º 39
0
from elements.chain import BlockChain
from elements.block import Block
from elements.transactions import Transactions
from ecdsa import SigningKey, VerifyingKey
from hashlib import sha256
import binascii

with open('./keys/private_key.pem') as f:
    private_key = SigningKey.from_pem(f.read())

with open('./keys/public_key.pem') as f:
    public_key = VerifyingKey.from_pem(f.read())

PKcoin = BlockChain()

PKcoin.minePendingTransactions(public_key)
print(PKcoin.getBalance(public_key))

newTransaction = Transactions(public_key, 'someaddress', 10)
newTransaction.signTransactions(private_key)
PKcoin.addTransactions(newTransaction)

PKcoin.minePendingTransactions(public_key)
print(PKcoin.getBalance(public_key))
Exemplo n.º 40
0
import threading
import datetime
import sys
import hashlib
import time
import socket
import rsa
import os.path
from pathlib import Path

from ecdsa import VerifyingKey, BadSignatureError

CertPath = str(Path(os.path.dirname(
    os.path.abspath(__file__))).parent) + "\\Certificate\\CA\\"

vk = VerifyingKey.from_pem(open("PublicKeyECDSA.pem").read())

# with 4 hardcoded nodes no random


class PKQThread(threading.Thread):
    def __init__(self, threadID, serverAddressPort, bytesToSend, name,
                 counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
        self.serverAddressPort = serverAddressPort
        self.bytesToSend = bytesToSend
        self.message = b''
        self.messageString = ''
Exemplo n.º 41
0
import hashlib

private = sha256("fd".encode()).hexdigest()

print(type(private))

sk = SigningKey.from_string(unhexlify(private), curve=SECP256k1)
vk = sk.get_verifying_key()

p = hexlify(vk.to_string()).decode()

obj = hashlib.new('ripemd160', p.encode('utf-8'))
ripemd_160_value = obj.hexdigest()
print(private)
print(hexlify(vk.to_string()).decode())

vkString = hexlify(vk.to_string()).decode()
print(vkString)
vk = VerifyingKey.from_string(unhexlify(vkString), curve=SECP256k1)
print(p)
print(ripemd_160_value)



signature = sk.sign("message".encode("utf-8"))
assert vk.verify(signature, "message".encode("utf-8"))

# assert 1>2

print("1")
Exemplo n.º 42
0
def readback(fname):
    "Verify pubkey and signature used in binary file"
    data = open(fname, 'rb').read()

    assert data[0:5] != b'DfuSe', "got DFU, expect raw binary"

    hdr = data[FW_HEADER_OFFSET:FW_HEADER_OFFSET + FW_HEADER_SIZE]

    vals = {}
    for fld, v in zip(FWH_PY_VALUES.split(), struct.unpack(FWH_PY_FORMAT,
                                                           hdr)):
        vals[fld] = v

        if fld == 'version_string':
            v = str(v.split(b'\0', 1)[0], 'ascii')
        elif fld in ('magic_value'):
            v = hex(v)
        elif fld in ('signature', 'future'):
            v = str(b2a_hex(v), 'ascii')
            v = v[0:16] + ' ... ' + v[-16:]
        elif fld == 'install_flags':
            nv = '0x%x =>' % v
            if v & FWHIF_HIGH_WATER:
                nv += ' HIGH_WATER'
            v = nv
        elif fld == 'hw_compat':
            nv = '0x%x => ' % v
            d = []
            if v & MK_1_OK: d.append('Mk1')
            if v & MK_2_OK: d.append('Mk2')
            if v & MK_3_OK: d.append('Mk3')
            if v & ~(MK_1_OK | MK_2_OK | MK_3_OK):
                d.append('?other?')
            v = nv + '+'.join(d)
        elif fld == 'timestamp':
            v = str(b2a_hex(v), 'ascii')
            nv = '20' + '-'.join(v[i:i + 2] for i in range(0, 6, 2)) + ' '
            nv += ':'.join(v[i:i + 2] for i in range(6, 6 + 6, 2))
            v = nv + ' UTC'

        print("%16s: %s" % (fld, v))

    # non-useful value, fixed.
    #print('runtime hdr at: 0x%08x' % (0x08008000 + FW_HEADER_OFFSET))

    a = sha256(data[0:FW_HEADER_OFFSET + FW_HEADER_SIZE - 64])
    a.update(data[FW_HEADER_OFFSET + FW_HEADER_SIZE:])
    chk = sha256(a.digest()).digest()

    #print("sha256^2: %s" % b2a_hex(chk).decode('ascii'))

    # from pubkey
    vk = VerifyingKey.from_pem(
        open("keys/%02d.pubkey.pem" % vals['pubkey_num']).read())

    try:
        ok = vk.verify_digest(vals['signature'], chk)
    except:
        ok = False

    print('%16s: %s' % ("ECDSA Signature",
                        ('CORRECT' if ok else 'Wrong, wrong, wrong!!!')))
Exemplo n.º 43
0
 def verify(signData,rawData,pub):
     signData = binascii.unhexlify(signData)
     pub = VerifyingKey.from_string(bytes().fromhex(pub))
     return pub.verify(signData, rawData)
Exemplo n.º 44
0
 def from_string(cls, string):
     return cls(VerifyingKey.from_string(string, curve=SECP256k1))
Exemplo n.º 45
0
def public_hex_to_verifying_key(hex: str) -> VerifyingKey:
    return VerifyingKey.from_string(bytes.fromhex(hex), curve=ECDSA_CURVE)
Exemplo n.º 46
0
def verify_sign(pubkey, message, signature):
    verifier = VerifyingKey.from_pem(pubkey)
    h = hashlib.sha256(message.encode('utf8'))
    return verifier.verify(binascii.unhexlify(signature), h.digest())
def get_verify_key():
    key1 = """-----BEGIN PUBLIC KEY-----
MEkwEwYHKoZIzj0CAQYIKoZIzj0DAQEDMgAEQr/8RJmJZT+Bh1YMb1aqc2ao5teE
ixOeCMGTO79Dbvw5dGmHJLYyNPwnKkWayyJS
-----END PUBLIC KEY-----"""
    return VerifyingKey.from_pem(key1)
Exemplo n.º 48
0
 def string_to_pub(self, pub):
     return VerifyingKey.from_string(bytearray.fromhex(pub), curve=self.curve)
Exemplo n.º 49
0
dir = os.path.dirname(sys.argv[0])

image = join(dir, 'packer', 'app.image')  # tested image
private = join(dir, 'certs', 'ecprivkey.pem')  # is OK
public = join(dir, 'certs', 'ecpubkey.pem')  # is OK, same as PFX

f = open(image, 'rb')
MSG = f.read(20628)
f.seek(20628)  # signature offset is last 64 bytes
old_signature = f.read(64)
print('OLD SIGNATURE', HEX(old_signature))

sk = SigningKey.from_pem(open(private).read(), hashfunc=hashlib.sha256)
#print('SK ', HEX( sk.to_string() ) )
vk = VerifyingKey.from_pem(open(public).read())
#print('VK ', HEX( vk.to_string() ) )

new_signature = sk.sign(MSG, hashfunc=hashlib.sha256)

try:
    vk.verify(old_signature, MSG, hashfunc=hashlib.sha256)
    print("verify old signature: OK")  # YES !!!
except BadSignatureError:
    print("APP BAD SIGNATURE")

try:
    vk.verify(new_signature, MSG, hashfunc=hashlib.sha256)
    print("verify new signature: OK")  # YES !!!
except BadSignatureError:
    print("NEW BAD SIGNATURE")
Exemplo n.º 50
0
 def addr_to_vk(addr):
     '''
     Convert an address back into a verifying key format so you can verify a signature.
     '''
     return VerifyingKey.from_string(base58.b58decode(bytes(addr, 'utf-8')))
Exemplo n.º 51
0
 def from_pair(cls, pair):
     x, y = pair
     point = Point(curve=SECP256k1.curve, x=x, y=y, order=SECP256k1.order)
     key = VerifyingKey.from_public_point(point, curve=SECP256k1)
     return cls(key)
Exemplo n.º 52
0
def verify_signature(public_key, data, signature):
    vk = VerifyingKey.from_string(bytes.fromhex(public_key), curve=SECP256k1)
    if vk.verify(bytes.fromhex(signature), bytes.fromhex(data)):
        print("Verified")
    else:
        print("Failed")
Exemplo n.º 53
0
 def userFromJSON(d):
     pubkeyString = d['Pubkey']
     privkeyString = d['Privkey']
     pubk = PubKey.from_string(bytearray.fromhex(pubkeyString), curve=Params.CURVE)
     privk = PrivKey.from_string(bytearray.fromhex(privkeyString), curve=Params.CURVE)
     return User(fromValues=True, values=(pubk, privk))
Exemplo n.º 54
0
    def verify_message(self, address, signature, message):
        """Creates a public key from a message signature and verifies message

        Bitcoin uses a compact format for message signatures (for tx sigs it
        uses normal DER format). The format has the normal r and s parameters
        that ECDSA signatures have but also includes a prefix which encodes
        extra information. Using the prefix the public key can be
        reconstructed from the signature.

        |  Prefix values:
        |      27 - 0x1B = first key with even y
        |      28 - 0x1C = first key with odd y
        |      29 - 0x1D = second key with even y
        |      30 - 0x1E = second key with odd y

        If key is compressed add 4 (31 - 0x1F, 32 - 0x20, 33 - 0x21, 34 - 0x22 respectively)

        Raises
        ------
        ValueError
            If signature is invalid
        """

        sig = b64decode(signature.encode('utf-8'))
        if len(sig) != 65:
            raise ValueError('Invalid signature size')

        # get signature prefix, compressed and recid (which key is odd/even)
        prefix = sig[0]
        if prefix < 27 or prefix > 35:
            return False
        if prefix >= 31:
            compressed = True
            recid = prefix - 31
        else:
            compressed = False
            recid = prefix - 27

        # create message digest -- note double hashing
        message_magic = add_magic_prefix(message)
        message_digest = hashlib.sha256(
            hashlib.sha256(message_magic).digest()).digest()

        #
        # use recid, r and s to get the point in the curve
        #

        # get signature's r and s
        r, s = sigdecode_string(sig[1:], _order)

        # ger R's x coordinate
        x = r + (recid // 2) * _order

        # get R's y coordinate (y**2 = x**3 + 7)
        y_values = sqrt_mod((x**3 + 7) % _p, _p, True)
        if (y_values[0] - recid) % 2 == 0:
            y = y_values[0]
        else:
            y = y_values[1]

        # get R (recovered ephemeral key) from x,y
        R = ellipticcurve.Point(_curve, x, y, _order)

        # get e (hash of message encoded as big integer)
        e = int(hexlify(message_digest), 16)

        # compute public key Q = r^-1 (sR - eG)
        # because Point substraction is not defined we will instead use:
        # Q = r^-1 (sR + (-eG) )
        minus_e = -e % _order
        inv_r = numbertheory.inverse_mod(r, _order)
        Q = inv_r * (s * R + minus_e * _G)

        # instantiate the public key and verify message
        public_key = VerifyingKey.from_public_point(Q, curve=SECP256k1)
        key_hex = hexlify(public_key.to_string()).decode('utf-8')
        pubkey = PublicKey.from_hex('04' + key_hex)
        if not pubkey.verify(signature, message):
            return False

        # confirm that the address provided corresponds to that public key
        if pubkey.get_address(compressed=compressed).to_string() != address:
            return False

        return True
Exemplo n.º 55
0
from ecdsa import SigningKey
from ecdsa import VerifyingKey, BadSignatureError

with open("privateBC.pem") as f:
    sk = SigningKey.from_pem(f.read())

sig = sk.sign(b"THIS IS TONYTHIS IS TONYTHIS IS TONYTHIS IS TONY")
with open("signature", "wb") as f:
    f.write(sig)

vk = VerifyingKey.from_pem(open("publicBC.pem").read())
print 'len of Sig :', len(sig)
print 'len of msg :', len("THIS IS TONYTHIS IS TONYTHIS IS TONYTHIS IS TONY")
try:
    vk.verify(sig, b"THIS IS TONYTHIS IS TONYTHIS IS TONYTHIS IS TONY")
    print "good signature"
except BadSignatureError:
    print "BAD SIGNATURE"
Exemplo n.º 56
0
    def on_T_Sub_But1_clicked(self):
        if (self.pass1_edit.text() != self.pass2_edit.text()):
            print('xxx')
            #QtWidgets.QMessageBox.warning(
                #self, 'Error', 'Password do not match')
        else:
            Email_user = self.email_edit.text()
            Pass_user = self.pass1_edit.text()
            #auth.create_user_with_email_and_password(Email_user,Pass_user)
        
            Email = self.lineEdit_7.text()
            print('auth called')
            filename_out = 'test.txt'
            csv_out = open(filename_out,'w')
            csv_out = open(filename_out,'a')
            csv_out.write('Hi')
            Location1 = self.Location.currentText()



            body = {"User Location": Location1,  "User's Name": str(self.lineEdit_5.text()),"User's Field": str(self.lineEdit_6.text()),"Email": self.lineEdit_7.text()}# Sorted Degree Centrality
 #       dcent2 = {"Time of attainment": str(self.Trans_Tim.text),  "Planned Value Created": str(self.lineEdit_5.text), "Preceding Milestones": Predecessors}
        #dcent2 = {"Time": str(self.Trans_Tim.text()), "Project Location": Location1,  "Project Name": str(self.lineEdit_5.text()),"Project Field": str(self.lineEdit_6.text())}#

            json_prep = {"User_info":body}
            json_prep.keys()
            json_dump = json.dumps(json_prep, indent=1, sort_keys=True)
            filename_out2 = '1-User-cert_req.json'
            json_out = open(filename_out2,'w')
            json_out.write(json_dump)
            json_out.close()

        #####-Key_Gen-######
        # Public key (ECDSA)
            sk = ecdsa.SigningKey.generate(curve=ecdsa.SECP256k1)
        

            vk = sk.get_verifying_key()
            #vkk = ecdsa.verifying_key()
            print('private_key_sk')
            sk_string = sk.to_string()
            print(sk)
            print(sk_string.hex())
            sk_pem = sk.to_pem()    # private key pem
            print('public_key_vk')
            vk_string = vk.to_string()
            print(vk)
            print(vk_string.hex())
            vk_pem = vk.to_pem()    # public key pem
            print("uncompressed: {0}".format(vk.to_string("uncompressed").hex()))
            print("compressed: {0}".format(vk.to_string("compressed").hex()))

        ##-Write pem files
            with open("user_private.pem", "wb") as f:
                f.write(sk_pem)
            with open("user_public.pem", "wb") as f:
                f.write(vk_pem)
        ##-Write pem files

        #####-Key_Gen-######

            pk_pr = VerifyingKey.from_pem(open("user_public.pem").read()) # Get Project Promoter public key from their participant pem
            pk_pr = pk_pr.to_string().hex()
            pk_pr = str(pk_pr)

        #####SIGN######
            with open("user_private.pem") as f: # Get Project Promoter private key from their participant pem
                sk_pr = SigningKey.from_pem(f.read())
            with open("1-User-cert_req.json", "rb") as f:
                message = f.read()
            sig = sk_pr.sign(message)
            sig2 = sk_pr.sign(message)
            print('signature')
            print(sig)
            with open("signature2", "wb") as f:
                f.write(sig)
            print(sig)
            with open("signature2", "rb") as f:
                sig2 = f.read()
            print(sig2)
            sig = str(sk_pr.sign(message))
            print(sig)
            print('signature')
            #sig = sig.to_string().hex()
        #####SIGN######    


            today = str(date.today())
            Header = {"Time": today, "User Pub-Key": pk_pr, "User Signature": sig}
            json_prep = {"Proj_info":body, "Header": Header}
            json_prep.keys()
            json_dump = json.dumps(json_prep, indent=1, sort_keys=True)
            filename_out2 = '1-User-cert_req.json'
            json_out = open(filename_out2,'w')
            json_out.write(json_dump)
            json_out.close()



        #####VERIFY######
            # test code to verify signature - will be deployed at server or peer
            vk = VerifyingKey.from_pem(open("user_public.pem").read())
            with open("1-User-cert_req.json", "rb") as f:
                message = f.read()
                sig3 = json.loads(message)
                print(sig3['Header']['User Signature'])
            try:
                vk.verify(sig2, message)
                print('good signature')
                x1 = vk.verify(sig2, message)
                print(x1)
            except BadSignatureError:
                print('BAD SIGNATURE')
Exemplo n.º 57
0
pk = base64.b64decode(pk)
k = SigningKey.from_string(pk, curve=NIST256p)

# 2. Generate a public key
pub = k.get_verifying_key().to_string()
x, y = pub[:32], pub[32:]
x = base64urlencode(base64.b64encode(x))
y = base64urlencode(base64.b64encode(y))
print(f"ECDSA Public key:\n\t" + x.decode("utf-8") + "." + y.decode("utf-8") +
      "\n\t" + data['pub'])

# 3. Check Verification method
x, y = data["pub"].split('.')
vpub = base64.b64decode(base64urldecode(x)) + base64.b64decode(
    base64urldecode(y))
vpub = VerifyingKey.from_string(vpub, curve=NIST256p, hashfunc=sha256)

integrity = sha256(signed['m'].encode('utf-8'))

print(
    f'Verify signature: {vpub.verify(base64.b64decode(signed["s"]), integrity.digest(), hashfunc=sha256)}'
)

# ECDH
epriv = base64urldecode(data["epriv"])
epriv = base64.b64decode(epriv)

# 1. Decode k
ecdh = ECDH(curve=NIST256p)
k = ecdh.load_private_key_bytes(epriv)
Exemplo n.º 58
0
def hex_to_pk(public_key):
    """
    Returns a verifying key from the hex public key.
    """
    return VerifyingKey.from_string(unhex(public_key))
Exemplo n.º 59
0
# send the public key to the server
s.send(pub_client)
#create a shared secret
shared_key = ecc_diffie_hellman(pub_server)

#hash the shared the shared secret
sh_hashed = hashlib.sha256(shared_key).hexdigest()

print "This is the hash for the client's public key: " + hashlib.sha256(
    pub_client).hexdigest()
print "Hash for the shared secret: " + sh_hashed

#receive teh verifying key
pub_sign_server_str = s.recv(1024)
pub_sign_server = VerifyingKey.from_string(pub_sign_server_str, curve=NIST192p)

#receive message sign
v_message = s.recv(1024)

if pub_sign_server.verify(v_message, sh_hashed):
    print "Verified succesfully"
    assert pub_sign_server.verify(v_message, sh_hashed)
else:
    s.close()

#signing key
priv_signature = SigningKey.generate(curve=NIST192p)
#verifying key
pub_signature = priv_signature.get_verifying_key()
Exemplo n.º 60
0
def decode(pr: str) -> Invoice:
    """bolt11 decoder,
    based on https://github.com/rustyrussell/lightning-payencode/blob/master/lnaddr.py
    """

    hrp, decoded_data = bech32_decode(pr)
    if hrp is None or decoded_data is None:
        raise ValueError("Bad bech32 checksum")
    if not hrp.startswith("ln"):
        raise ValueError("Does not start with ln")

    bitarray = _u5_to_bitarray(decoded_data)

    # final signature 65 bytes, split it off.
    if len(bitarray) < 65 * 8:
        raise ValueError("Too short to contain signature")

    # extract the signature
    signature = bitarray[-65 * 8:].tobytes()

    # the tagged fields as a bitstream
    data = bitstring.ConstBitStream(bitarray[:-65 * 8])

    # build the invoice object
    invoice = Invoice()

    # decode the amount from the hrp
    m = re.search("[^\d]+", hrp[2:])
    if m:
        amountstr = hrp[2 + m.end():]
        if amountstr != "":
            invoice.amount_msat = _unshorten_amount(amountstr)

    # pull out date
    invoice.date = data.read(35).uint

    while data.pos != data.len:
        tag, tagdata, data = _pull_tagged(data)
        data_length = len(tagdata) / 5

        if tag == "d":
            invoice.description = _trim_to_bytes(tagdata).decode("utf-8")
        elif tag == "h" and data_length == 52:
            invoice.description_hash = _trim_to_bytes(tagdata).hex()
        elif tag == "p" and data_length == 52:
            invoice.payment_hash = _trim_to_bytes(tagdata).hex()
        elif tag == "x":
            invoice.expiry = tagdata.uint
        elif tag == "n":
            invoice.payee = _trim_to_bytes(tagdata).hex()
            # this won't work in most cases, we must extract the payee
            # from the signature
        elif tag == "s":
            invoice.secret = _trim_to_bytes(tagdata).hex()
        elif tag == "r":
            s = bitstring.ConstBitStream(tagdata)
            while s.pos + 264 + 64 + 32 + 32 + 16 < s.len:
                route = Route(
                    pubkey=s.read(264).tobytes().hex(),
                    short_channel_id=_readable_scid(s.read(64).intbe),
                    base_fee_msat=s.read(32).intbe,
                    ppm_fee=s.read(32).intbe,
                    cltv=s.read(16).intbe,
                )
                invoice.route_hints.append(route)

    # BOLT #11:
    # A reader MUST check that the `signature` is valid (see the `n` tagged
    # field specified below).
    # A reader MUST use the `n` field to validate the signature instead of
    # performing signature recovery if a valid `n` field is provided.
    message = bytearray([ord(c) for c in hrp]) + data.tobytes()
    sig = signature[0:64]
    if invoice.payee:
        key = VerifyingKey.from_string(unhexlify(invoice.payee),
                                       curve=SECP256k1)
        key.verify(sig, message, hashlib.sha256, sigdecode=sigdecode_string)
    else:
        keys = VerifyingKey.from_public_key_recovery(sig, message, SECP256k1,
                                                     hashlib.sha256)
        signaling_byte = signature[64]
        key = keys[int(signaling_byte)]
        invoice.payee = key.to_string("compressed").hex()

    return invoice