Exemplo n.º 1
1
	def __init__(self, pubkey=None, raw=False, flags=None, ctx=None):
		if USE_SECP:
			if flags == None:
				flags = secp256k1.FLAG_VERIFY
			self.obj = secp256k1.PublicKey(pubkey, raw, flags, ctx)
		else:
			if not raw:
				raise Exception("Non raw init unsupported")
			pubkey = pubkey[1:]
			x = int.from_bytes(pubkey[0:32], 'big')
			y = int.from_bytes(pubkey[32:], 'big')
			self.obj = ECPublicKey(Point(x, y, CURVE_SECP256K1))
Exemplo n.º 2
0
 def tweak_add(self, scalar):
     if USE_SECP:
         self.obj = self.obj.tweak_add(scalar)
     else:
         scalar = int.from_bytes(scalar, 'big')
         privKey = ECPrivateKey(scalar, CURVE_SECP256K1)
         self.obj = ECPublicKey(self.obj.W + privKey.get_public_key().W)
Exemplo n.º 3
0
	def __init__(self, pubkey=None, raw=False):
		if USE_SECP:
			self.obj = secp256k1.PublicKey(pubkey, raw)
		else:
			if not raw:
				raise Exception("Non raw init unsupported")
			pubkey = pubkey[1:]
			x = int.from_bytes(pubkey[0:32], 'big')
			y = int.from_bytes(pubkey[32:], 'big')
			self.obj = ECPublicKey(Point(x, y, CURVE_SECP256K1))
Exemplo n.º 4
0
def gen_random_tx(curve):
    n = curve.order
    P = curve.generator
    sA = random.randint(0, n)
    sk = ECPrivateKey(sA, curve)
    QA = sA * P
    pk = ECPublicKey(QA)

    payee_sA = random.randint(0, n)
    payee_sk = ECPrivateKey(payee_sA, curve)
    payee_QA = sA * P
    payee_pk = ECPublicKey(payee_QA)

    sum_string = "*** Bitcoin transaction ***\n"

    serial = random.getrandbits(128)
    sum_string += "Serial number: " + str(serial) + "\n"

    sum_string += "Payer Public key - x: " + str(QA.x) + "\n"

    sum_string += "Payer Public key - y: " + str(QA.y) + "\n"

    sum_string += "Payee Public key - x: " + str(payee_QA.x) + "\n"

    sum_string += "Payee Public key - y: " + str(payee_QA.y) + "\n"

    amount = random.randint(1, 1000000)
    sum_string += "Amount: " + str(amount) + " Satoshi" + "\n"

    signer = ECDSA()

    sig = signer.sign(sum_string.encode('UTF-8'), sk)

    (r, s) = decode_sig(sig)

    # k = random.randint(1, n - 1)
    # R = k * P
    # r = R.x % n
    # #r = str(r).encode('UTF-8')
    # h = hashlib.sha3_256()
    # h.update(sum_string.encode('UTF-8'))
    # # h.update(str(r).encode('UTF-8'))
    # #h.update(r)  # m + r
    # s = (modinv(k, n) * ((int(h.hexdigest(), 16)) + (sA * r))) % n
    # #h = int(h.hexdigest(), 16)

    sum_string += "Signature - r: " + str(r) + "\n"

    sum_string += "Signature - s: " + str(s) + "\n"

    return sum_string
Exemplo n.º 5
0
	def tweak_add(self, scalar):
		if USE_SECP:
			self.obj = self.obj.tweak_add(scalar)
		else:
			scalar = int.from_bytes(scalar, 'big')
			privKey = ECPrivateKey(scalar, CURVE_SECP256K1)
			self.obj = ECPublicKey(self.obj.W + privKey.get_public_key().W)
Exemplo n.º 6
0
 def pub_key_from_bytes_with_zeroth(self, pub_key_bytes, zeroth):
     try:
         point_bytes = zeroth + pub_key_bytes
         point = bytes_to_payment_point(point_bytes)
         return ECPublicKey(point)
     except ECPyException:
         raise InvalidPublicKeyError()
Exemplo n.º 7
0
def verify(pub_key,
           data,
           signature,
           hashfunc=sha256,
           curve=curve.P256,
           sign_fmt='DER',
           sign_size=32,
           pub_key_fmt='RAW'):
    if sign_fmt in ['RAW', 'DER']:
        pass
    else:
        raise UnknownSignatureFormatError("fmt: '%s'" % sign_fmt)

    if pub_key_fmt == 'RAW':
        pub_key_encoded = pub_key
    elif pub_key_fmt == '04':
        pub_key_encoded = pub_key[2:]
    else:
        raise UnknownPublicKeyFormatError("fmt: '%s'" % pub_key_fmt)
    x, y = split_str_to_halves(pub_key_encoded)
    x, y = int(x, 16), int(y, 16)
    pub_key_point = ECPublicKey(Point(x, y, curve))

    signature = bytes.fromhex(signature)
    signer = ECDSAWithSize(fmt=sign_fmt, size=sign_size)
    msg = hashfunc(data.encode()).digest()
    return signer.verify(msg, signature, pub_key_point)
def CheckBlock(filename, curve):
    if os.path.isfile(filename):
        f = open(filename, "r")
        block = f.readlines()
        if len(block)%9 != 0:
            print("Incorrect file format")
            f.close()
            return -10000
        block_count = len(block)//9
        for i in range(0, block_count):
            # coordinates of the public key point
            x1 = int(block[i*9+2][22:-1])
            y1 = int(block[i*9+3][22:-1])
            r = int(block[i*9+7][15:-1])
            s = int(block[i*9+8][15:-1])
            tx = "".join(block[i*9: i*9+7])
            # For the signature verfication
            payer = ECDSA()
            payer_pk = ECPublicKey(Point(x1, y1, curve))
            signature = encode_sig(r, s)
            try:
                assert(payer.verify(tx.encode('UTF-8'), signature, payer_pk))
                ver = 0
                f.close()
                return ver
            except:
                ver = -i-1
                f.close()
                return ver
        return 0
    else:
        print("File does not exist")
        return -10000
Exemplo n.º 9
0
    def __init__(self) -> None:

        cv = Curve.get_curve('secp256k1')

        pu_key = ECPublicKey()
        pv_key = ECPrivateKey()

        print(pu_key)
        print(pv_key)
Exemplo n.º 10
0
def _():
    cv = Curve.get_curve('secp256k1'); pu_key = ECPublicKey(
        Point(0x65d5b8bf9ab1801c9f168d4815994ad35f1dcb6ae6c7a1a303966b677b813b00,
              0xe6b865e529b8ecbf71cf966e900477d49ced5846d7662dd2dd11ccd55c0aff7f,
              cv))
    pv_key = ECPrivateKey(
        0xfb26a4e75eec75544c0f44e937dcf5ee6355c7176600b9688c667e5c283b43c5,
        cv) ; signer = ECDSA(fmt="ITUPLE")
    sig = signer.sign(b'01234567890123456789012345678912', pv_key) ;return sig
Exemplo n.º 11
0
def gen_random_tx(curve):
    # get a random 128 BIT integer for serial number
    serial_num = Num.getRandomNBitInteger(128)

    # create the public key for sender
    n = curve.order
    P = curve.generator
    sA = Num.getRandomRange(0, n + 1)
    sK = ECPrivateKey(sA, curve)
    QA = sA * P
    pk = ECPublicKey(QA)

    signer = ECDSA()

    # create the public key for sendee
    sA_2 = Num.getRandomRange(0, n + 1)
    sK_2 = ECPrivateKey(sA_2, curve)
    P2 = curve.generator
    QA_2 = sA_2 * P2
    pk_2 = ECPublicKey(QA_2)

    # header for the block
    temp = "*** Bitcoin transaction ***\n"

    # add the serial number to the block
    temp = temp + "Serial number: " + str(serial_num) + "\n"
    # write payers public keys
    temp = temp + "Payer public key - x: " + str(QA.x) + "\n"
    temp = temp + "Payer public key - y: " + str(QA.y) + "\n"
    # write payees public keys
    temp = temp + "Payee public key - x: " + str(QA_2.x) + "\n"
    temp = temp + "Payee public key - y: " + str(QA_2.y) + "\n"

    # get random transaction val
    amount = Num.getRandomRange(0, 1000001)
    temp = temp + "Amount: " + str(amount) + "\n"

    sig = signer.sign(temp.encode("utf-8"), sK)
    (r, s) = decode_sig(sig)
    temp = temp + "Signature (r): " + str(r) + "\n"
    temp = temp + "Signature (s): " + str(s) + "\n"

    return temp
Exemplo n.º 12
0
 def from_bytes(cls, pub_key_bytes):
     if len(pub_key_bytes) != PUB_KEY_LENGTH:
         raise InvalidPublicKeyError()
     try:
         point_bytes = b'\x02' + pub_key_bytes
         point = bytes_to_payment_point(point_bytes)
         pub_key = ECPublicKey(point)
         return cls(pub_key)
     except ECPyException:
         raise InvalidPublicKeyError()
Exemplo n.º 13
0
 def _derive_final_pair(
     cls: Type[SECP256K1],
     root_public: ECPublicKey,
     root_private: ECPrivateKey,
     mid_public: ECPublicKey,
     mid_private: ECPrivateKey,
 ) -> Tuple[ECPublicKey, ECPrivateKey]:
     raw_private = (root_private.d + mid_private.d) % _GROUP_ORDER
     wrapped_private = ECPrivateKey(raw_private, _CURVE)
     wrapped_public = ECPublicKey(
         _CURVE.add_point(root_public.W, mid_public.W))
     return wrapped_public, wrapped_private
    def __verifyUsingPublicKey(self, signature, api_key, params, timestamp,
                               public_key):
        signer = ECDSA()
        pu_bytes = base64.b64decode(public_key)
        # int(pu_bytes[1:33].encode('hex'), 16)
        x = int(binascii.hexlify(pu_bytes[1:33]), 16)
        y = int(binascii.hexlify(pu_bytes[33:]), 16)
        pu_key = ECPublicKey(Point(x, y, cv))
        hashed = hashlib.sha256("{}.{}.{}".format(
            api_key, params, timestamp).encode("UTF-8")).hexdigest()

        return signer.verify(bytearray.fromhex(hashed),
                             bytearray.fromhex(signature), pu_key)
def gen_random_tx(curve):
    serial = random.randint(0,
                            2**128 - 1)  # creates 128 bit random serial number
    n = curve.order
    P = curve.generator
    sA = random.randint(0, n)
    sk = ECPrivateKey(sA, curve)
    QA = sA * P
    pk = ECPublicKey(QA)

    sB = random.randint(0, n)
    skB = ECPrivateKey(sB, curve)
    QB = sB * P
    pkB = ECPublicKey(QB)

    amount = random.randint(1, 1000000)  # create a random int for amount

    transaction = "**** Bitcoin transaction ****\n"
    transaction += "Serial number: " + str(serial) + "\n"
    transaction += "Payer public key - x: " + str(QA.x) + "\n"
    transaction += "Payer public key - y: " + str(QA.y) + "\n"
    transaction += "Payee public key - x: " + str(QB.x) + "\n"
    transaction += "Payee public key - y: " + str(QB.y) + "\n"
    transaction += "Amount: " + str(amount) + "\n"

    signer = ECDSA()

    message = transaction
    message = message.encode('UTF-8')
    sig = signer.sign(message, sk)

    (r, s) = decode_sig(sig)

    transaction += "Signature (r): " + str(r) + "\n"
    transaction += "Signature (s): " + str(s) + "\n"
    return transaction
Exemplo n.º 16
0
def gen_random_tx(curve):
    serial = random.randrange(pow(2, 127), pow(2, 128))
    amount = random.randrange(1, 1000001)

    n = curve.order
    P = curve.generator

    sA = random.randint(0, n)
    sB = random.randint(0, n)

    skA = ECPrivateKey(sA, curve)
    skB = ECPrivateKey(sB, curve)
    QA = sA * P
    QB = sB * P

    pkA = ECPublicKey(QA)
    pkB = ECPublicKey(QB)

    signer = ECDSA()

    trans = "**** Bitcoin transaction ****" + \
        "\nSerial number: " + str(serial) + \
        "\nPayer public key - x: " + str(QA.x) + \
        "\nPayer public key - y: " + str(QA.y) + \
        "\nPayee public key - x: " + str(QB.x) + \
        "\nPayee public key - y: " + str(QB.y) + \
        "\nAmount: " + str(amount) + "\n"
    t = trans.encode("UTF-8")
    sig = signer.sign(t, skA)

    (r, s) = decode_sig(sig)

    trans += "Signature (r): " + str(r) + "\n" + "Signature (s): " + str(
        s) + "\n"

    return trans
Exemplo n.º 17
0
    def get_public_key(pv_key, hasher = hashlib.sha512, hash_len=None) :
        """ Returns the public key corresponding to this private key 
        
        This method compute the public key according to draft-irtf-cfrg-eddsa-05.
        
        The hash parameter shall be the same as the one used for signing and
        verifying.
        
        Args:
            hasher (hashlib): callable constructor returning an object with update(), digest() interface. Example: hashlib.sha256,  hashlib.sha512...
            pv_key (ecpy.keys.ECPrivateKey): key to use for signing

        Returns:
           ECPublicKey : public key
        """
        a,A,h = EDDSA._get_materials(pv_key, hasher, hash_len)
        return ECPublicKey(A)
Exemplo n.º 18
0
    def is_valid_message(
        cls: Type[ED25519], message: bytes, signature: bytes, public_key: str
    ) -> bool:
        """
        Verifies the signature on a given message.

        Args:
            message: The message to validate.
            signature: The signature of the message.
            public_key: The public key to use to verify the message and
                signature.

        Returns:
            Whether the message is valid for the given signature and public key.
        """
        raw_public = public_key[len(PREFIX) :]
        public_key_point = _CURVE.decode_point(bytes.fromhex(raw_public))
        wrapped_public = ECPublicKey(public_key_point)
        return cast(bool, _SIGNER.verify(message, signature, wrapped_public))
Exemplo n.º 19
0
    def is_valid_message(
        cls: Type[ED25519], message: bytes, signature: bytes, public_key: str
    ) -> bool:
        """
        Checks whether or not a message is valid.

        Args:
            message: Message to check against signature
            signature: Signature of message to to verify
            public_key: Public key corresponding to private key used to
                generate signature

        Returns:
            Whether message is valid given signature and public_key

        """
        raw_public = public_key[len(PREFIX) :]
        public_key_point = _CURVE.decode_point(bytes.fromhex(raw_public))
        wrapped_public = ECPublicKey(public_key_point)
        return cast(bool, _SIGNER.verify(message, signature, wrapped_public))
Exemplo n.º 20
0
    def is_valid_message(cls: Type[SECP256K1], message: bytes,
                         signature: bytes, public_key: str) -> bool:
        """
        Verifies that message matches signature given public_key.

        Args:
            message: The message to validate.
            signature: The signature of the message.
            public_key: The public_key to use to verify the message.

        Returns:
            Whether the message matches the signature given the public key.
        """
        public_key_point = _CURVE.decode_point(bytes.fromhex(public_key))
        wrapped_public = ECPublicKey(public_key_point)
        return cast(
            bool,
            _SIGNER.verify(sha512_first_half(message), signature,
                           wrapped_public),
        )
Exemplo n.º 21
0
def SignVer(message, s, r, E, QA):
    curve = QA.curve
    n = curve.order
    G = curve.generator
    if (r == None or r > n or s > n):
        return False

    h = int.from_bytes(SHA3_256.new(message).digest(), 'big')

    c = pow(h, n - 2, n)
    u1 = (s * c) % n
    u2 = (r * c) % n
    u1G = (n - u1)
    if type(QA) == Point:
        QA = ECPublicKey(QA)
    u2Q = u2 * QA.W
    V = u1G * G + u2Q
    x = V.x % n

    return not (x == r)
Exemplo n.º 22
0
        return left == right


    
if __name__ == "__main__":
    try:
        ### EDDSA
        cv     = Curve.get_curve('Ed25519')

        # public key
        # x: 74ad28205b4f384bc0813e6585864e528085f91fb6a5096f244ae01e57de43ae
        # y: 0c66f42af155cdc08c96c42ecf2c989cbc7e1b4da70ab7925a8943e8c317403d


        pu_key = ECPublicKey(Point(0x74ad28205b4f384bc0813e6585864e528085f91fb6a5096f244ae01e57de43ae,
                                   0x0c66f42af155cdc08c96c42ecf2c989cbc7e1b4da70ab7925a8943e8c317403d,
                                   cv))
        # private key
        # s: 0x4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb
        pv_key = ECPrivateKey(0x4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb,
                              cv)

        pu = EDDSA.get_public_key(pv_key)
        assert(pu.W == pu_key.W);
        

        # sig:
        # 0x92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da
        # 0x085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00
        expected_sig = int(0x92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00)
        expected_sig  = expected_sig.to_bytes(64,'big')
Exemplo n.º 23
0
import string
from ecpy.curves import Curve,Point
from ecpy.keys import ECPublicKey, ECPrivateKey
from ecpy.ecdsa import ECDSA
from ecpy.formatters import decode_sig, encode_sig

if sys.version_info < (3, 6):
    import sha3

curve = Curve.get_curve('secp256k1')
n = curve.order
P = curve.generator
sA = random.randint(0,n)
sk = ECPrivateKey(sA, curve)
QA = sA*P
pk = ECPublicKey(QA)

signer = ECDSA()

message = b'Anything goes here'

sig = signer.sign(message, sk)

(r, s) = decode_sig(sig)

f = open("deneme.txt", "w")
f.write("Public key - x: " + str(QA.x)+"\n")
f.write("Public key - y: " + str(QA.y)+"\n")
f.write("Signature - r: " + str(r)+"\n")
f.write("Signature - s: " + str(s)+"\n")
f.close()
Exemplo n.º 24
0
class PublicKey(object):
	def __init__(self, pubkey=None, raw=False, flags=None, ctx=None):
		if USE_SECP:
			if flags == None:
				flags = secp256k1.FLAG_VERIFY
			self.obj = secp256k1.PublicKey(pubkey, raw, flags, ctx)
		else:
			if not raw:
				raise Exception("Non raw init unsupported")
			pubkey = pubkey[1:]
			x = int.from_bytes(pubkey[0:32], 'big')
			y = int.from_bytes(pubkey[32:], 'big')
			self.obj = ECPublicKey(Point(x, y, CURVE_SECP256K1))
					
	def ecdsa_deserialize(self, ser_sig):
		if USE_SECP:
			return self.obj.ecdsa_deserialize(ser_sig)
		else:
			return ser_sig

	def serialize(self, compressed=True):
		if USE_SECP:
			return self.obj.serialize(compressed)
		else:
			if not compressed:
				out = b"\x04"
				out += self.obj.W.x.to_bytes(32, 'big')
				out += self.obj.W.y.to_bytes(32, 'big')
			else:
				out = b"\x03" if ((self.obj.W.y & 1) != 0) else "\x02"
				out += self.obj.W.x.to_bytes(32, 'big')
			return out

	def ecdh(self, scalar):
		if USE_SECP:
			return self.obj.ecdh(scalar)
		else:
			scalar = int.from_bytes(scalar, 'big')
			point = self.obj.W * scalar
			# libsecp256k1 style secret
			out = b"\x03" if ((point.y & 1) != 0) else b"\x02"
			out += point.x.to_bytes(32, 'big')
			hash = hashlib.sha256()
			hash.update(out)
			return hash.digest()

	def tweak_add(self, scalar):
		if USE_SECP:
			self.obj = self.obj.tweak_add(scalar)
		else:
			scalar = int.from_bytes(scalar, 'big')
			privKey = ECPrivateKey(scalar, CURVE_SECP256K1)
			self.obj = ECPublicKey(self.obj.W + privKey.get_public_key().W)

	def ecdsa_verify(self, msg, raw_sig, raw=False, digest=hashlib.sha256):
		if USE_SECP:
			return self.obj.ecdsa_verify(msg, raw_sig, raw, digest)
		else:
			if not raw:
				h = digest()
				h.update(msg)
				msg = h.digest()
			raw_sig = bytearray(raw_sig)
			return SIGNER.verify(msg, raw_sig, self.obj)
Exemplo n.º 25
0
        return left == right


if __name__ == "__main__":
    try:
        ### EDDSA
        cv = Curve.get_curve('Ed25519')

        # public key
        # x: 74ad28205b4f384bc0813e6585864e528085f91fb6a5096f244ae01e57de43ae
        # y: 0c66f42af155cdc08c96c42ecf2c989cbc7e1b4da70ab7925a8943e8c317403d

        pu_key = ECPublicKey(
            Point(
                0x74ad28205b4f384bc0813e6585864e528085f91fb6a5096f244ae01e57de43ae,
                0x0c66f42af155cdc08c96c42ecf2c989cbc7e1b4da70ab7925a8943e8c317403d,
                cv))
        # private key
        # s: 0x4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb
        pv_key = ECPrivateKey(
            0x4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb,
            cv)

        # sig:
        # 0x92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da
        # 0x085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00
        expected_sig = int(
            0x92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00
        )
        expected_sig = expected_sig.to_bytes(64, 'big')
Exemplo n.º 26
0
#Hash:
#  8c7632afe967e2e16ae7f39dc32c252b3d751fa6e01daa0efc3c174e230f4617
#Signer's public: 04
#  81bc1f9486564d3d57a305e8f9067df2a7e1f007d4af4fed085aca139c6b9c7a
#  8e3f35e4d7fb27a56a3f35d34c8c2b27cd1d266d5294df131bf3c1cbc39f5a91
#App signature:
#  304402203a329589dbc6f3bb88bf90b45b5d4935a18e13e2cb8fcee0b94b3102ec19645702202f61af55df0e56e71d40a9f5f111faeb2f831c1fd314c55227ac44110fb33049



### ECS
# test key
cv     = Curve.get_curve('secp256k1')
pv_key = ECPrivateKey(0xf028458b39af92fea938486ecc49562d0e7731b53d9b25e2701183e4f2adc991,cv)
pu_key = ECPublicKey(Point(0x81bc1f9486564d3d57a305e8f9067df2a7e1f007d4af4fed085aca139c6b9c7a,
                           0x8e3f35e4d7fb27a56a3f35d34c8c2b27cd1d266d5294df131bf3c1cbc39f5a91,
                           cv))


k = pv_key.get_public_key()
assert(k.W.x == pu_key.W.x)
assert(k.W.y == pu_key.W.y)

print("Public key ok")

msg = 0x8c7632afe967e2e16ae7f39dc32c252b3d751fa6e01daa0efc3c174e230f4617
msg = msg.to_bytes(32,'big')

sig = 0x304402203a329589dbc6f3bb88bf90b45b5d4935a18e13e2cb8fcee0b94b3102ec19645702202f61af55df0e56e71d40a9f5f111faeb2f831c1fd314c55227ac44110fb33049
sig = sig.to_bytes(70,'big')
Exemplo n.º 27
0
                xPub = b'\x03'+pu_key.W.x.to_bytes(size,'big')
            else :
                xPub = b'\x02'+pu_key.W.x.to_bytes(size,'big')
            hasher.update(xQ+xPub+msg)
            v = hasher.digest()
            v = int.from_bytes(v,'big')
            v = v%n

        return v == r

if __name__ == "__main__":
    import sys,random
    try:
        cv     = Curve.get_curve('NIST-P256')
        pu_key = ECPublicKey(Point(0x09b58b88323c52d1080aa525c89e8e12c6f40fcb014640fa88081ed9e9352de7,
                                   0x5ccbbd189538516238b0b0b28acb5f0b5e27217c3a9872421219de0aeebf1080,
                                   cv))
        pv_key = ECPrivateKey(0x5202a3d8acaf6909d12c9a774cd886f9fba61137ffd3e8e76aed363fb47ac492,
                              cv)

        msg = int(0x616263)
        msg  = msg.to_bytes(3,'big')

        k = int(0xde7e0e5e663f24183414b7c72f24546b81e9e5f410bebf26f3ca5fa82f5192c8)

        ## ISO
        R=0x5A79A0AA9B241E381A594B220554D096A5F09FA628AD9A33C3CE4393ADE1DEF7
        S=0x5C0EB78B67A513C3E53B2619F96855E291D5141C7CD0915E1D04B347457C9601

        signer = ECSchnorr(hashlib.sha256,"ISO","ITUPLE")
        sig = signer.sign_k(msg,pv_key,k)
Exemplo n.º 28
0
import hashlib
from ecpy.curves     import Curve,Point
from ecpy.keys       import ECPublicKey, ECPrivateKey
from ecpy.ecdsa  import ECDSA


### ECS
cv     = Curve.get_curve('secp256k1')

pu1_key = ECPublicKey(Point(0x506d1f7347b29aebc45ac079f0f3bc1ee7aa4b0afe8410810fcda3d046dd40d8, 
	                        0x561f37bd6af046807f739e72c53bdf970552d479e241ce1a05370d8c506f47c0,
                            cv))

d = 0x89be3842bf556d2dd47fd16dd3569e4661b33fd58f3d91eab653a7261d442d84

print("%s"%(d*pu1_key.W))
print("%s"%(d*cv.generator))
Exemplo n.º 29
0
class PublicKey(object):
    def __init__(self, pubkey=None, raw=False, flags=None, ctx=None):
        if USE_SECP:
            if flags == None:
                flags = secp256k1.FLAG_VERIFY
            self.obj = secp256k1.PublicKey(pubkey, raw, flags, ctx)
        else:
            if not raw:
                raise Exception("Non raw init unsupported")
            pubkey = pubkey[1:]
            x = int.from_bytes(pubkey[0:32], 'big')
            y = int.from_bytes(pubkey[32:], 'big')
            self.obj = ECPublicKey(Point(x, y, CURVE_SECP256K1))

    def ecdsa_deserialize(self, ser_sig):
        if USE_SECP:
            return self.obj.ecdsa_deserialize(ser_sig)
        else:
            return ser_sig

    def serialize(self, compressed=True):
        if USE_SECP:
            return self.obj.serialize(compressed)
        else:
            if not compressed:
                out = b"\x04"
                out += self.obj.W.x.to_bytes(32, 'big')
                out += self.obj.W.y.to_bytes(32, 'big')
            else:
                out = b"\x03" if ((self.obj.W.y & 1) != 0) else "\x02"
                out += self.obj.W.x.to_bytes(32, 'big')
            return out

    def ecdh(self, scalar):
        if USE_SECP:
            return self.obj.ecdh(scalar)
        else:
            scalar = int.from_bytes(scalar, 'big')
            point = self.obj.W * scalar
            # libsecp256k1 style secret
            out = b"\x03" if ((point.y & 1) != 0) else b"\x02"
            out += point.x.to_bytes(32, 'big')
            hash = hashlib.sha256()
            hash.update(out)
            return hash.digest()

    def tweak_add(self, scalar):
        if USE_SECP:
            self.obj = self.obj.tweak_add(scalar)
        else:
            scalar = int.from_bytes(scalar, 'big')
            privKey = ECPrivateKey(scalar, CURVE_SECP256K1)
            self.obj = ECPublicKey(self.obj.W + privKey.get_public_key().W)

    def ecdsa_verify(self, msg, raw_sig, raw=False, digest=hashlib.sha256):
        if USE_SECP:
            return self.obj.ecdsa_verify(msg, raw_sig, raw, digest)
        else:
            if not raw:
                h = digest()
                h.update(msg)
                msg = h.digest()
            raw_sig = bytearray(raw_sig)
            return SIGNER.verify(msg, raw_sig, self.obj)
Exemplo n.º 30
0
Arquivo: ecdsa.py Projeto: ntzwq/ECPy
        if GQ.is_infinity:
            return False
        x   = GQ.x % n

        return x == r


if __name__ == "__main__":
    import binascii
    try:
        signer = ECDSA()

        ### ECDSA secp256k1
        cv     = Curve.get_curve('secp256k1')
        pu_key = ECPublicKey(Point(0x65d5b8bf9ab1801c9f168d4815994ad35f1dcb6ae6c7a1a303966b677b813b00,

                                   0xe6b865e529b8ecbf71cf966e900477d49ced5846d7662dd2dd11ccd55c0aff7f,
                                   cv))
        pv_key = ECPrivateKey(0xfb26a4e75eec75544c0f44e937dcf5ee6355c7176600b9688c667e5c283b43c5,
                              cv)

        #sha256("abc")
        #  c:  0xC03DDDA6174963AD10224BADDBCF7ED9EA5E3DAE91941CB428D2EC060B4F290A
        # u1:  0x113BE17918E856E4D6EC2EE04F5E9B3CB599B82AC879C8E32A0140C290D32659
        # u2:  0x2976F786AE6333E125C0DFFD6C16D37E8CED5ABEDB491BCCA21C75B307D0B318
        # u1G: 0x51e4e6ed6f4b1db33b0d21b8bd30fb732f1d999c4e27bb1800eba20813ad3e86
        #      0x93101a9fa0d5c7c680400b03d3becb9130dd8f9f4d9b034360a74829dc1201ab
        # u2Q: 0xeaca8440897333e259d0f99165611b085d6e10a9bfd371c451bc0aea1aeb99c3
        #      0x57c5c95ea9f491c0fd9029a4089a2e6df47313f915f3e39e9f12e03ab16521c2
        #  + : 0x0623b4159c7112125be51716d1e706d68e52f5b321da68d8b86b3c7c7019a9da
        #    : 0x1029094ccc466a534df3dbb7f588b283c9bef213633750aeff021c4c131b7ce5
        # SIG: 3045
Exemplo n.º 31
0
from ecpy.curves import Curve, Point
from ecpy.keys import ECPublicKey, ECPrivateKey
from ecpy.ecdsa import ECDSA
from ecpy.formatters import decode_sig, encode_sig

if sys.version_info < (3, 6):
    import sha3

# You can keep this part (i.e., curve setting and key generation)
curve = Curve.get_curve('secp256k1')
n = curve.order
P = curve.generator
sA = random.randint(0, n)
sk = ECPrivateKey(sA, curve)
QA = sA * P
pk = ECPublicKey(QA)

# You need to change sign and verify methods below
signer = ECDSA()  # this line can be removed
message = b'Anything goes here'
sig = signer.sign(message, sk)  # new sign method here

verifier = ECDSA()  # this line can be removed

message = b'Anything goes here'
try:
    assert (verifier.verify(message, sig, pk))  # new sign method here
    print("Signature verifies")
except:
    print("Signature does not verify")
Exemplo n.º 32
0
def _validate_rrsig(rrset, rrsig, keys, origin=None, now=None):
    """Validate an RRset against a single signature rdata

    :param rrset: The RRset to validate
    :type rrset: :py:data:`dns.rrset.RRset` or
    (:py:data:`dns.name.Name`, :py:data:`dns.rdataset.Rdataset`)
    :param rrsig: Signature to validate
    :type rrsig: :py:data:`dns.rdata.Rdata`
    :param keys: Key dictionary, used to find the DNSKEY associated
    with a given name.  The dictionary is keyed by a
    :py:data:`dns.name.Name`, and has :py:data:`dns.node.Node` or
    :py:data:`dns.rdataset.Rdataset` values.
    :type keys: dictionary
    :param origin: Origin to use for relative name, defaults to None
    :type origin: :py:data:`dns.name.Name`, optional
    :param now: time to use when validating the signatures, in seconds
    since the UNIX epoch, defaults to current time
    :type now: integer, optional
    :raises ValidationFailure: RRSig expired
    :raises ValidationFailure: RRSig not yet valid
    :raises ValidationFailure: Invalid public key
    :raises ValidationFailure: Invalid ECDSA key
    :raises ValidationFailure: Unknown algorithm
    :raises ValueError: Generic Value Error
    :raises ValidationFailure: Verify failure
    :raises UnsupportedAlgorithm: Algorithm isn't supported by dnspython
    :return: none
    :rtype: none

    .. todo:: Fill in missing infos

    """

    if isinstance(origin, str):
        origin = dns.name.from_text(origin, dns.name.root)

    candidate_keys = _find_candidate_keys(keys, rrsig)
    if candidate_keys is None:
        raise ValidationFailure('unknown key')

    for candidate_key in candidate_keys:
        # For convenience, allow the rrset to be specified as a (name,
        # rdataset) tuple as well as a proper rrset
        if isinstance(rrset, tuple):
            rrname = rrset[0]
            rdataset = rrset[1]
        else:
            rrname = rrset.name
            rdataset = rrset

        if now is None:
            now = time.time()
        if rrsig.expiration < now:
            raise ValidationFailure('expired')
        if rrsig.inception > now:
            raise ValidationFailure('not yet valid')

        if _is_rsa(rrsig.algorithm):
            keyptr = candidate_key.key
            (bytes_, ) = struct.unpack('!B', keyptr[0:1])
            keyptr = keyptr[1:]
            if bytes_ == 0:
                (bytes_, ) = struct.unpack('!H', keyptr[0:2])
                keyptr = keyptr[2:]
            rsa_e = keyptr[0:bytes_]
            rsa_n = keyptr[bytes_:]
            try:
                pubkey = CryptoRSA.construct(
                    (number.bytes_to_long(rsa_n), number.bytes_to_long(rsa_e)))
            except ValueError:
                raise ValidationFailure('invalid public key')
            sig = rrsig.signature
        elif _is_dsa(rrsig.algorithm):
            keyptr = candidate_key.key
            (t, ) = struct.unpack('!B', keyptr[0:1])
            keyptr = keyptr[1:]
            octets = 64 + t * 8
            dsa_q = keyptr[0:20]
            keyptr = keyptr[20:]
            dsa_p = keyptr[0:octets]
            keyptr = keyptr[octets:]
            dsa_g = keyptr[0:octets]
            keyptr = keyptr[octets:]
            dsa_y = keyptr[0:octets]
            pubkey = CryptoDSA.construct(
                (number.bytes_to_long(dsa_y), number.bytes_to_long(dsa_g),
                 number.bytes_to_long(dsa_p), number.bytes_to_long(dsa_q)))
            sig = rrsig.signature[1:]
        elif _is_ecdsa(rrsig.algorithm):
            keyptr = candidate_key.key
            if rrsig.algorithm == ECDSAP256SHA256:
                curve = 'secp256r1'
                octets = 32
            else:
                curve = 'secp384r1'
                octets = 48
            ecdsa_x = keyptr[0:octets]
            ecdsa_y = keyptr[octets:octets * 2]
            pubkey = CryptoECC.construct(curve=curve,
                                         point_x=number.bytes_to_long(ecdsa_x),
                                         point_y=number.bytes_to_long(ecdsa_y))
            sig = rrsig.signature

        elif _is_eddsa(rrsig.algorithm):
            keyptr = candidate_key.key
            if not (_have_ecpy and sys.version_info >= (3, 6)):
                #pylint: disable=line-too-long
                raise ImportError(
                    'DNSSEC validation for algorithm %u requires ecpy library and Python 3.6 or newer'
                    % rrsig.algorithm)
            if rrsig.algorithm == ED25519:
                curve = 'Ed25519'
            else:
                curve = 'Ed448'
            point = Curve.get_curve(curve).decode_point(keyptr)
            pubkey = ECPublicKey(point)
            sig = rrsig.signature
        elif _is_gost(rrsig.algorithm):
            raise UnsupportedAlgorithm(
                'algorithm "%s" not supported by dnspython' %
                algorithm_to_text(rrsig.algorithm))
        else:
            raise ValidationFailure('unknown algorithm %u' % rrsig.algorithm)

        hash = _make_hash(rrsig.algorithm)
        hash.update(_to_rdata(rrsig, origin)[:18])
        hash.update(rrsig.signer.to_digestable(origin))

        if rrsig.labels < len(rrname) - 1:
            suffix = rrname.split(rrsig.labels + 1)[1]
            rrname = dns.name.from_text('*', suffix)
        rrnamebuf = rrname.to_digestable(origin)
        rrfixed = struct.pack('!HHI', rdataset.rdtype, rdataset.rdclass,
                              rrsig.original_ttl)
        rrlist = sorted(rdataset)
        for rr in rrlist:
            hash.update(rrnamebuf)
            hash.update(rrfixed)
            rrdata = rr.to_digestable(origin)
            rrlen = struct.pack('!H', len(rrdata))
            hash.update(rrlen)
            hash.update(rrdata)

        try:
            if _is_rsa(rrsig.algorithm):
                verifier = pkcs1_15.new(pubkey)
                # will raise ValueError if verify fails:
                verifier.verify(hash, sig)
            elif _is_dsa(rrsig.algorithm) or _is_ecdsa(rrsig.algorithm):
                verifier = DSS.new(pubkey, 'fips-186-3')
                verifier.verify(hash, sig)
            elif _is_eddsa(rrsig.algorithm):
                if rrsig.algorithm == ED25519:
                    verifier = EDDSA(hashlib.sha512)
                else:
                    verifier = EDDSA(hashlib.shake_256, 114)
                if not verifier.verify(hash.value, sig, pubkey):
                    raise ValueError
            else:
                # Raise here for code clarity; this won't actually ever happen
                # since if the algorithm is really unknown we'd already have
                # raised an exception above
                raise ValidationFailure('unknown algorithm %u' %
                                        rrsig.algorithm)
            # If we got here, we successfully verified so we can return without error
            return
        except ValueError:
            # this happens on an individual validation failure
            continue
    # nothing verified -- raise failure:
    raise ValidationFailure('verify failure')
Exemplo n.º 33
0
 def generate_pu_key_with_point(self, x, y):
     return ECPublicKey(Point(x, y, self.curve))