def verifyVote(self, privateKey):
        if (self.signature == "" or len(self.signature) == 0):
            return False

        r, s = ecdsa.sign(self.voteHash,
                          privateKey,
                          curve=curve.secp256k1,
                          hashfunc=hl.sha256)
        decoded_r, decoded_s = DEREncoder.decode_signature(self.signature)

        # Se os parâmetros são diferentes, a assinatura é inválida
        if (r != decoded_r or s != decoded_s):
            return False

        # Verifica a assinatura
        valid = ecdsa.verify((r, s),
                             self.voteHash,
                             self.voter,
                             curve=curve.secp256k1,
                             hashfunc=hl.sha256)

        if (not valid):
            return False

        return True
def fast_ecdsa(count, loop):
    private_key = keys.gen_private_key(curve.P256)
    public_key = keys.get_public_key(private_key, curve.P256)
    # standard signature, returns two integers

    with open("message.txt", "rb") as f:
        m = f.read()

    time_list_sign = []
    for l in range(loop):
        start = time.time()
        for c in range(count):
            r, s = ecdsa.sign(m, private_key)
        end = time.time() - start
        # print("["+str(l)+"th fast_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):
            valid = ecdsa.verify((r, s), m, public_key)
        end = time.time() - start
        # print("["+str(l)+"th fast_ecdsa:vrfy second is "+ str(end) + "/"+str(count)+" signature")
        time_list_vrfy.append(end)
    ave_vrfy = numpy.mean(numpy.array(time_list_vrfy))

    print("fast_ecdsa:sign average second is " + str(ave_sign) + "/" +
          str(count) + " signature")
    print("fast_ecdsa:vrfy average second is " + str(ave_vrfy) + "/" +
          str(count) + " signature")
    return time_list_sign, time_list_vrfy
Exemple #3
0
def signdata(priv=None, wif=None, data=None):
    def priv2pemlong(priv):
        skey = ecdsa.SigningKey.from_string(priv, curve=ecdsa.SECP256k1)
        skey = skey.to_pem()
        d = b("").join([
            l.strip() for l in skey.split(b("\n"))
            if l and not l.startswith(b("-----"))
        ])
        raw_data = binascii.a2b_base64(d)
        p, Q = fasn1.decode_key(raw_data)
        return p

    assert data is not None, "no data given!"
    pk = b(priv) if isinstance(priv, str) else priv
    wiff = b(wif) if isinstance(wif, str) else wif
    if pk == None:
        assert wiff is not None, "no keys given!"
        privkey = _wif2priv(wiff)
    else:
        privkey = binascii.unhexlify(pk)
    s = priv2pemlong(privkey)

    order = 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141'
    (r, s) = fecdsa.sign(data, s, fcurve.secp256k1)
    signed = ecdsa.util.sigencode_der(r, s, order)
    return str(binascii.hexlify(signed), 'ascii')
Exemple #4
0
    def export_recovery_seed(self, allow_algs):
        for alg in allow_algs:
            if alg == 0:
                if self._recovery_seed_pri_key is None:
                    self._initialize_recovery_seed()

                S = fastecdsa.keys.get_public_key(self._recovery_seed_pri_key, P256)
                S_enc = encode_pub(S)

                signed_data = struct.pack('>B16s65s', alg, self._aaguid, S_enc)
                sig = DEREncoder.encode_signature(
                    *ecdsa.sign(
                        signed_data,
                        self._attestation_key,
                        hashfunc=hashlib.sha256
                    )
                )
                payload = {
                    1: alg,
                    2: [],
                    3: self._aaguid,
                    4: sig,
                    -1: S_enc,
                }
                return cbor.encode(payload)

        raise UnknownKeyAgreementScheme(allow_algs)
Exemple #5
0
def recordTimeECC(sizes, message):
    """ This function documents the times taken to generate the 
            key, encrypt, and decrypt using the ECC cryptosystem
            Inputs:
                sizes: ECC key sizes
                message: message to encrypt
            Outputs:
                keyTime, encryptTime, decryptTime: times taken to do task
    """
    keyTime, encryptTime, decryptTime = [], [], []
    for size in sizes:
        print("Starting Size: ", size)
        startK = time.time()
        priv_key, pub_key = keys.gen_keypair(size)
        endK = time.time()
        keyTime.append((endK - startK))

        startE = time.time()
        (r, s) = ecdsa.sign(message, priv_key, size)
        endE = time.time()
        encryptTime.append((endE - startE))

        startD = time.time()
        ecdsa.verify((r, s), message, pub_key, size)
        endD = time.time()
        decryptTime.append((endD - startD))

    return keyTime, encryptTime, decryptTime
Exemple #6
0
 def sign(s, message, sigfmt=None):
     "signs `message` and returns a detached signature"
     if sigfmt is None: sigfmt = s.SIGFMT
     if s._key is None: return None
     return s._sigencode(
         fe_ecdsa.sign(message, s._key, curve=s.CURVE, hashfunc=s.HASH),
         sigfmt)
Exemple #7
0
    def gen_transaction(self, sender: str, receiver: str, data: str):
        '''    
        새로운 거래를 생성하는 함수
        sender에서 receiver에게 물품(items)을 전달하는 과정을 Transaction이라고 정의한다.
        1. 사용자는 거래에 들어갈 품목들을 선택한다.(items)
        2. 사용자는 개인키로 전자서명을 생성한다.
        3. Transaction에 공개키를 포함시킨다.
        4. 생성된 Transaction을 P2P네트워크에 전파한다.
        '''
        ret_str = ""
        if self.get_unique_node_count() >= 5 and self.miner_count >= 2:
            digital_signature = ecdsa.sign(sender + receiver + data,
                                           self.private_key)
            new_transaction = self.Transaction(sender, receiver, data,
                                               digital_signature,
                                               self.public_key)
            new_transaction.serialize()
            jdata = json.dumps(new_transaction.__dict__)
            jdata = json.loads(jdata)
            jdata['Type'] = 'transaction'
            new_transaction.deserialize()
            self.transaction_pool.append(new_transaction.item_history)

            self.sendAll(jdata)
            return ret_str
        else:
            ret_str = "Failed to generate transaction: "
            if self.get_unique_node_count() < 5:
                ret_str += "'Too few users in network' "
            if self.miner_count < 2:
                ret_str += "'Too few miners in network'"
            print(ret_str)
            return ret_str
 def sign(self, hash_):
     """
     Signs a hash
     """
     # sign 'hash_', returns two integers; 'curve' is the curve used to sign the message,
     #'hashfunc' is the hash function used to compress the message
     return ecdsa.sign(hash_, self.private_key, curve = curve.secp256k1, hashfunc = hashlib.sha256)
Exemple #9
0
	def test_sign(self):
		with self.assertRaises(TypeError):
			self.cryp.sign("Test")

		self.cryp.private_key = self.private_key
		r, s = ecdsa.sign("Test", self.private_key, curve=secp256k1)
		self.assertEqual(self.cryp.sign("Test"), hex(r) + "," + hex(s))
Exemple #10
0
    def sign(self, message, generic=False):
        """
        Sign a raw sequence of bytes
        :param message: sequence of bytes, raw format or hexadecimal notation
        :param generic: do not specify elliptic curve if set to True
        :return: signature in base58 encoding
        """
        message = scrub_input(message)

        if not self.is_secret:
            raise ValueError("Cannot sign without a secret key.")

        # Ed25519
        if self.curve == b"ed":
            digest = pysodium.crypto_generichash(message)
            signature = pysodium.crypto_sign_detached(digest, self._secret_key)
        # Secp256k1
        elif self.curve == b"sp":
            pk = secp256k1.PrivateKey(self._secret_key)
            signature = pk.ecdsa_serialize_compact(
                pk.ecdsa_sign(message, digest=blake2b_32))
        # P256
        elif self.curve == b"p2":
            r, s = sign(msg=message, d=bytes_to_int(self._secret_key), hashfunc=blake2b_32)
            signature = int_to_bytes(r) + int_to_bytes(s)
        else:
            assert False

        if generic:
            prefix = b'sig'
        else:
            prefix = self.curve + b'sig'

        return base58_encode(signature, prefix).decode()
Exemple #11
0
 def derivesk_authenticate(self, challenge, creds):
     '''
     Find a cred in creds that matches this authenticator's backup seed private key,
     derive the private key, and sign the challenge with it.
     '''
     chosen_cred, pri_key = self.derivesk_find(creds)
     sig = ecdsa.sign(challenge, pri_key, hashfunc=hashlib.sha256)
     return chosen_cred, sig
Exemple #12
0
    def make_credential(self, challenge):
        '''Abstraction of the basic WebAuthn registration operation.'''

        cred = os.urandom(32)
        pri, pub = fastecdsa.keys.gen_keypair(P256)
        self._credentials[cred] = pri
        sig = ecdsa.sign(challenge, pri, hashfunc=hashlib.sha256)
        return pub, cred, sig
Exemple #13
0
def sign(m):
    #generate public key
    private_key, public_key = gen_keypair(secp256k1)

    #generate signature
    r, s = ecdsa.sign(m, private_key, curve=secp256k1, hashfunc=sha256)

    return (public_key, [r, s])
Exemple #14
0
def sign(signing_key: SigningKey, message_digest_bytes: bytes) -> bytes:
    r, s = ecdsa.sign(
        message_digest_bytes.hex(),
        signing_key,
        curve=curve.secp256k1,
        prehashed=True,
    )
    return DEREncoder.encode_signature(r, s)
Exemple #15
0
def sign_msg(msg: str, priv_key: str) -> str:
    '''
    Given a message, and the private key,
    return the signature (in hex). x, and y are joined
    with 'x'
    '''
    r, s = ecdsa.sign(msg, int(priv_key, 16))
    return '{:x}x{:x}'.format(r, s)
Exemple #16
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)
    def signVote(self, privateKey):
        # Assina a cédula
        r, s = ecdsa.sign(self.voteHash,
                          privateKey,
                          curve=curve.secp256k1,
                          hashfunc=hl.sha256)

        # Transforma a assinatura para DER
        self.signature = DEREncoder.encode_signature(r, s)
 def sign(s, message):
     "signs `message` and returns a signature"
     if s._key is None: return None
     sigr, sigs = fe_ecdsa.sign(message,
                                s._key,
                                curve=s.CURVE,
                                hashfunc=s.HASH)
     sig = fe_der.DEREncoder.encode_signature(sigr, sigs)
     return b64.b64encode(sig)
 def sign(self, payload, user_id):
     canonical_payload = json.dumps(payload,
                                    sort_keys=True,
                                    separators=(',', ':'))
     private_key = self.keypairs[user_id]
     r, s = ecdsa.sign(canonical_payload,
                       private_key,
                       curve=curve.secp256k1)
     return {"r": hex(r)[2:], "s": hex(s)[2:]}
 def sign(self, hash_):
     """
     Signs a hash
     """
     # sign 'hash_', returns a signature (<class 'tuple'>, contains 2 elements of <class 'int'>);
     # parameters: 'curve' is the curve used to sign the message,
     # 'hashfunc' is the hash function used to compress the message
     signature = ecdsa.sign(hash_, self.private_key, curve = curve.secp256k1, hashfunc = hashlib.sha256)
     return signature
Exemple #21
0
def sign(msg, private_key):        
    #msg = "a message to sign via ECDSA"  # some message
    # standard signature, returns two integers
    private_key = decode_privkey(private_key)
    r, s = ecdsa.sign(msg, private_key, hashfunc=hashlib.sha256, curve=curve.secp256k1)
    #encoding to pack the r and s components into single byte stream
    rb, sb = encode(r, 256), encode(s, 256)
    signature = base64.b64encode(b'\x00'*(32-len(rb))+rb+b'\x00'*(32-len(sb))+sb)
    return signature
Exemple #22
0
    def test_ecdsa_P256_SHA224_sign(self):
        d = 0xC9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721
        expected = (
            0x53B2FFF5D1752B2C689DF257C04C40A587FABABB3F6FC2702F1343AF7CA9AA3F,
            0xB9AFB64FDC03DC1A131C7D2386D11E349F070AA432A4ACC918BEA988BF75C74C)
        sig = sign('sample', d, curve=P256, hashfunc=sha224)
        self.assertEqual(sig, expected)

        Q = d * P256.G
        self.assertTrue(verify(sig, 'sample', Q, curve=P256, hashfunc=sha224))
Exemple #23
0
    def test_ecdsa_P256_SHA2_sign(self):
        d = 0xC9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721
        expected = (
            0xEFD48B2AACB6A8FD1140DD9CD45E81D69D2C877B56AAF991C34D0EA84EAF3716,
            0xF7CB1C942D657C41D436C7A1B6E29F65F3E900DBB9AFF4064DC4AB2F843ACDA8)
        sig = sign('sample', d, curve=P256, hashfunc=sha256)
        self.assertEqual(sig, expected)

        Q = d * P256.G
        self.assertTrue(verify(sig, 'sample', Q, curve=P256, hashfunc=sha256))
Exemple #24
0
    def test_ecdsa_P256_SHA384_sign(self):
        d = 0xC9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721
        expected = (
            0x0EAFEA039B20E9B42309FB1D89E213057CBF973DC0CFC8F129EDDDC800EF7719,
            0x4861F0491E6998B9455193E34E7B0D284DDD7149A74B95B9261F13ABDE940954)
        sig = sign('sample', d, curve=P256, hashfunc=sha384)
        self.assertEqual(sig, expected)

        Q = d * P256.G
        self.assertTrue(verify(sig, 'sample', Q, curve=P256, hashfunc=sha384))
def make_cert(client_public):
    msg = (pack('<LL', 0x17, 0x20) +
           unhexlify('%064x' % client_public.x)[::-1] + (b'\0' * 0x24) +
           unhexlify('%064x' % client_public.y)[::-1] + (b'\0' * 0x4c))
    s = sign(msg, hs_key())
    s = DEREncoder().encode_signature(s[0], s[1])
    s = pack('<L', len(s)) + s
    msg = msg + s
    msg += b'\0' * (444 - len(msg))  # FIXME not sure this math is right
    return msg
Exemple #26
0
    def test_ecdsa_P256_SHA512_sign(self):
        d = 0xC9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721
        expected = (
            0x8496A60B5E9B47C825488827E0495B0E3FA109EC4568FD3F8D1097678EB97F00,
            0x2362AB1ADBE2B8ADF9CB9EDAB740EA6049C028114F2460F96554F61FAE3302FE)
        sig = sign('sample', d, curve=P256, hashfunc=sha512)
        self.assertEqual(sig, expected)

        Q = d * P256.G
        self.assertTrue(verify(sig, 'sample', Q, curve=P256, hashfunc=sha512))
Exemple #27
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
def digital_signature(curve, message):
    sk, pk = keys.gen_keypair(curve)

    # hash message and sign
    r, s = ecdsa.sign(message, sk, hashfunc=sha256)

    # verify signature
    valid = ecdsa.verify((r, s), message, pk, hashfunc=sha256)

    return valid
Exemple #29
0
	def test_verify_signature(self):
		self.cryp.generate_keys()
		signature_fastecda = ecdsa.sign("Test", self.private_key, curve=secp256k1)
		signature_cryp1 = Cryp.get_signature("Test", self.private_key)
		signature_cryp2 = Cryp.get_signature("Tests", self.cryp.private_key)

		self.assertEqual(signature_fastecda, tuple(map(lambda sig: int(sig, 0), signature_cryp1.split(','))))
		self.assertTrue(Cryp.verify_signature(self.public_key, signature_cryp1, "Test"))
		self.assertFalse(Cryp.verify_signature(self.public_key, signature_cryp1, "Tests"))
		self.assertFalse(Cryp.verify_signature(self.cryp.public_key, signature_cryp1, "Test"))
		self.assertFalse(Cryp.verify_signature(self.public_key, signature_cryp2, "Test"))
Exemple #30
0
 def sign_message_bytes(byts, rel_data_bytes, pk):
     """
     Return tuple of strings.
     """
     bytes_to_sign = None
     if rel_data_bytes is not None:
         bytes_to_sign = byts + rel_data_bytes
     else:
         bytes_to_sign = byts
     r, s = ecdsa.sign(bytes_to_sign, pk, hashfunc=sha256, curve=curve.P256)
     return str(r), str(s)