Пример #1
0
 def pub2vkey(pub):
     key = pub[2:]
     l = len(key)
     assert l == 128, "key length wrong: %i" % l
     x = int(key[:int(l / 2)], 16)
     y = int(key[int(l / 2):], 16)
     return fpoint.Point(x, y, curve=fcurve.secp256k1)
Пример #2
0
 def verify(self, payload, user_id, r, s):
     canonical_payload = json.dumps(payload,
                                    sort_keys=True,
                                    separators=(',', ':'))
     pub_key_x = '0x' + user_id[2:]
     hex_int = int(pub_key_x, 16)
     return ecdsa.verify(
         (int(r, 16), int(s, 16)),
         canonical_payload,
         point.Point(hex_int, (self.uncompressed_keys[pub_key_x]),
                     curve.secp256k1),
         curve=curve.secp256k1)
Пример #3
0
def point_decode_from(curve, buffer):
    # https://github.com/cryptocoinjs/ecurve/blob/master/lib/point.js#L213
    typpe = int.from_bytes(bytes(buffer)[:1], byteorder='big', signed=False)
    compressed = typpe != 4
    byte_length = math.floor((curve.p.bit_length() + 7) / 8)
    x = buffer[1:1 + byte_length]
    int_x = int(x.hex(), 16)
    if compressed:
        if not len(buffer) == byte_length + 1:
            raise InvalidSignatureException('Invalid sequence length')
        if not (typpe == 0x02 or typpe == 0x03):
            raise InvalidSignatureException('Invalid sequence tag')
        is_odd = typpe == 0x03
        y = curve_point_from_x(curve, is_odd, int_x)
    else:
        if not len(buffer) == byte_length + byte_length + 1:
            raise InvalidSignatureException('Invalid sequence length')
        y = buffer[1 + byte_length:]
    return point.Point(int_x, y, curve)
Пример #4
0
def decode_public(pub_key: bytes) -> point.Point:
    try:
        if len(pub_key) == 33:
            # compressed format
            y_odd = pub_key[0:1] == SECP256K1_TAG_PUBKEY_ODD
            x = int.from_bytes(pub_key[1:], "big")

            y_y = pow(x, 3) + CURVE.a * x + CURVE.b
            y = mod_sqrt(y_y, CURVE.p, y_odd)

        elif len(pub_key) == 65:
            tag = pub_key[0:1]
            assert tag == SECP256K1_TAG_PUBKEY_UNCOMPRESSED

            x = int.from_bytes(pub_key[1:ENCODED_SIZE + 1], "big")
            y = int.from_bytes(pub_key[ENCODED_SIZE + 1:], "big")

        else:
            raise NotImplementedError

        return point.Point(x, y, CURVE)
    except:
        raise ValueError("The public key could not be parsed or is invalid")
Пример #5
0
def verified(args, ip):
    try:
        name = args['name']
        timestamp = long(args['timestamp'])
        max_nonce = get_max_nonce(name)
        if timestamp <= max_nonce:
            return False

        r = long(args['r'])
        s = long(args['s'])
        pub_key = get_pub_key(name)
        if pub_key == None:
            return False

        x, y, curvenum, _ = pub_key
        pub_key = None
        if curvenum == 256:
            pub_key = point.Point(x=long(x), y=long(y), curve=curve.P256)
        update_max_nonce(name, ip, timestamp)

        message = sha("I {} am verified to trade at {}".format(name, timestamp)).hexdigest()
        return ecdsa.verify((r, s), message, pub_key, hashfunc=sha)
    except Exception as e:
        return str(e)
Пример #6
0
#!/usr/bin/python

import hashlib, binascii, base64
from fastecdsa import keys, curve, point
from Crypto.Cipher import AES
import queue
import threading
import time
import sys

x = 0xc58966d17da18c7f019c881e187c608fcb5010ef36fba4a199e7b382a088072f
y = 0xd91b949eaf992c464d3e0d09c45b173b121d53097a9d47c25220c0b4beb943c

PUBLIC_KEY = point.Point(x, y, curve.P256)
PASSWORD_QUEUE = queue.Queue()

def tryPassword(pw):
    privKey = hashlib.sha256(pw).digest()
    pubKey = keys.get_public_key(int.from_bytes(privKey, "big"), curve.P256)
    if pubKey != PUBLIC_KEY:
        return False

    print("Found possible password:"******"Hy97Xwv97vpwGn21finVvZj5pK/BvBjscf6vffm1po0=")

    try:
        decrypted = cipher.decrypt(encrypted)
        print(decrypted.decode('utf-8'))
Пример #7
0
 def deserialize(self):
     self.digital_signature=(int(self.digital_signature[0]),int(self.digital_signature[1]))
     self.public_key=point.Point(int(self.public_key[0]),int(self.public_key[1]))
Пример #8
0
 def extract_points_from_str(self, strPoint):
     x = strPoint.split('\n')[0][3:]
     y = strPoint.split('\n')[1][3:]
     return point.Point(int(x, 16), int(y, 16))
Пример #9
0
h = int(res, 16)
hh = q + h
p.sendline("1")
p.recvuntil("hash (hex): ")
p.sendline(hex(hh)[2:])

res = p.recvuntil("4- Exit").decode().split(")")[0].split("(")[1].split(", ")
r = int(res[0])
s = int(res[1])

print(r, s, h)

rx = r
ry = sympy.sqrt_mod((rx * rx + E.a) * rx + E.b, E.p)

R1 = point.Point(rx, ry, curve=E)
R2 = point.Point(rx, -ry % E.p, curve=E)

P1 = int(gmpy2.invert(r, q)) * (s * R1 - h * E.G)
P2 = int(gmpy2.invert(r, q)) * (s * R2 - h * E.G)
keys = [P1, P2]

print("Searching...")
flag = None
for i in tqdm(range(m)):
    for j in range(len(keys)):
        if keys[j].x in table:
            d = None
            e = gmpy2.powmod(base, i * m + table[keys[j].x], q)
            eG = int(e) * E.G
            if P1 == eG or P2 == eG:
Пример #10
0
def do_some_work(p):
    res = p.recvline()
    p2 = process(res, shell=True)
    token = p2.recvline().split(b" ")[2]
    p.sendline(token)

    E = curve.P256

    q1 = 2 * 2 * 2 * 2 * 3 * 71 * 131 * 373 * 3407
    q2 = 17449 * 38189 * 187019741 * 622491383 * 1002328039319 * 2624747550333869278416773953
    q = q1 * q2 + 1

    # Solver with baby step giant step:
    m = math.ceil(math.sqrt(q1))
    table = {}
    base = pow(7, q2, q)

    if os.path.isfile('/app/ec_table'):
        with open("/app/ec_table", "rb") as f:
            table = pickle.load(f)
    else:
        t = 1
        print("Creating table...")
        for j in range(m):
            table[(t * E.G).x] = j
            t = t * base % q
        with open("/app/ec_table", "wb") as f:
            pickle.dump(table, f)

    v = gmpy2.powmod(base, -m, q)

    res = p.recvuntil("4- Exit")
    p.sendline("3")
    p.recvuntil("password: "******"123")
    res = p.recvuntil("4- Exit").decode().split("...")[0].split("Signing ")[1]
    h = int(res, 16)
    hh = q + h
    p.sendline("1")
    p.recvuntil("hash (hex): ")
    p.sendline(hex(hh)[2:])

    res = p.recvuntil("4- Exit").decode().split(")")[0].split("(")[1].split(
        ", ")
    r = int(res[0])
    s = int(res[1])

    print(r, s, h)

    rx = r
    ry = sympy.sqrt_mod((rx * rx + E.a) * rx + E.b, E.p)

    R1 = point.Point(rx, ry, curve=E)
    R2 = point.Point(rx, -ry % E.p, curve=E)

    P1 = int(gmpy2.invert(r, q)) * (s * R1 - h * E.G)
    P2 = int(gmpy2.invert(r, q)) * (s * R2 - h * E.G)
    keys = [P1, P2]

    print("Searching...")
    flag = None
    for i in range(m):
        print('progress: {}/{}'.format(i, m))
        for j in range(len(keys)):
            if keys[j].x in table:
                d = None
                e = gmpy2.powmod(base, i * m + table[keys[j].x], q)
                eG = int(e) * E.G
                if P1 == eG or P2 == eG:
                    print("Found", e)
                    d = e
                else:
                    if -P1 == eG or -P2 == eG:
                        f = -e % q
                        print("Found", f)
                        d = f
                if d:
                    u = gmpy2.invert(s, q) * (r * d + h) % q
                    sol1 = gmpy2.invert(u, q)
                    sol2 = -sol1 % q
                    print(sol1, sol2)
                    for sol in [sol1, sol2]:
                        p.sendline("3")
                        p.recvuntil("password: "******"OK!")
    p.sendline("4")
    res = p.recvuntil("Bye!")
    return flag.decode()