def borromean_verify(pubkeys, rings_size, ring_count, msg, sig): tell("*** BORROMEAN VERIFY ***") curve = Curve.get_curve('secp256k1') G = curve.generator order = curve.order e0 = sig[0] s = sig[1] sha256_e0 = hashlib.sha256() r0 = 0 for i in range(0, ring_count): tell("\nstep2-3 / ring %d" % i) e_ij = borromean_hash(m, e0, i, 0) for j in range(0, rings_size[i]): tell("\n step2-3 / ring %d / sec %d" % (i, j)) e_ij = int.from_bytes(e_ij, 'big') s_ij = int.from_bytes(s[r0 + j], 'big') tell(" index : %d" % (r0 + j)) tell(" pubkeys[]: %s" % pubkeys[r0 + j]) tell(" s[] : %x" % s_ij) tell(" e_ij : %x" % e_ij) sG_eP = s_ij * G + e_ij * pubkeys[r0 + j].W tell(" sG_eP :\n %s" % sG_eP) e_ij = point_to_bytes(sG_eP) if j != rings_size[i] - 1: e_ij = borromean_hash(m, e_ij, i, j + 1) else: tell(" e_ij0 : %s" % h(e_ij)) sha256_e0.update(e_ij) r0 += rings_size[i] sha256_e0.update(m) e0x = sha256_e0.digest() return e0 == e0x
def init_key(): cv = Curve.get_curve('secp256k1') pv_key = ECPrivateKey( int(hashlib.md5(settings.PRIVATE_KEY.encode()).hexdigest(), 16), cv) settings.PUBLIC_KEY = hex( int.from_bytes(cv.encode_point(pv_key.get_public_key().W), "big")) print(settings.PUBLIC_KEY)
def createPriKey(wifKey): wif_encoding_private_key = wifKey wifUNCompressed = bitcoin.decode_privkey(wif_encoding_private_key, 'wif_compressed') decimalToHex = bitcoin.encode(wifUNCompressed, 16) # return str cv = Curve.get_curve('secp256k1') pv_key = ECPrivateKey(int("0x" + decimalToHex, 16), cv) # 16进制str 转为 int return pv_key
def __init__(self) -> None: cv = Curve.get_curve('secp256k1') pu_key = ECPublicKey() pv_key = ECPrivateKey() print(pu_key) print(pv_key)
def __init__(self, params: ZKParameters): """ Initialize the ZKProof """ self._curve: Curve = Curve.get_curve(params.curve) if self._curve is None: raise NotImplementedError(f"Invalid Curve '{params.curve}'") self._ecc: ECPrivateKey = ECPrivateKey(params.d, self._curve) self._g0: int = convert.point_to_int(self._ecc.get_public_key().W)
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
def public_child_key_not_hardened(self, node, i): """ INPUT: A : 32 bytes public key (y coordinatte only) c : 32 bytes chain code i : child index to compute (must not be hardened < 0x80000000) OUTPUT: A_i : 32 bytes ith-child public key, A_i = kR_i.G (y coordinatte only) c_i : 32 bytes ith-child chain code PROCESS: 1. encode i 4-bytes little endian, il = encode_U32LE(i) 2. if i is more than 2^31 this means it's a hardened path and it's no supported so None is returned - compute Z = HMAC-SHA512(key=c, Data=0x02 | A | il ) - compute c_ = HMAC-SHA512(key=c, Data=0x03 | A | il ) 3. ci = lowest_32bytes(c_) 4. set ZL = highest_28bytes(Z) 5. compute Ai Ai = A + ZL * 8 * G 6. return Ai, c """ trace("ENTER private_child_key") if not node: return None # unpack argument (AP, cP) = node assert 0 <= i < 2**32 trace("private_child_key/AP : %s" % binascii.hexlify(AP)) trace("private_child_key/cP : %s" % binascii.hexlify(cP)) trace("private_child_key/i : %.04x" % i) # compute Z,c if i > 2**31: #We only do none hardened paths return None i_bytes = i.to_bytes(4, 'little') # regular child trace("regular Z input : %s" % binascii.hexlify(b'\x02' + AP + i_bytes)) Z = _Fk(b'\x02' + AP + i_bytes, cP) trace("regular c input : %s" % binascii.hexlify(b'\x03' + AP + i_bytes)) c = _Fk(b'\x03' + AP + i_bytes, cP)[32:] cv25519 = Curve.get_curve("Ed25519") P = int.from_bytes(Z[:28], 'little' ) * 8 * cv25519.generator + cv25519.decode_point(AP) A = cv25519.encode_point(P) return (A, c)
def __init__(self, parameters: ZKParameters): """ Initialize the curve with the given parameters """ self._curve = Curve.get_curve(parameters.curve) if not self._curve: raise ValueError("The curve '{}' is invalid".format(parameters.curve)) self._params = parameters self._bits = self._curve.field.bit_length() self._mask = (1 << self._bits) - 1
def __init__(self): super().__init__() self._clksleeptime = 150 # need lots of idling time self.curve = Curve.get_curve('NIST-P256') self.pmul_cycles = 1124157 # Verilog defines file(s): self.default_verilog_defines = 'cw305_pmul_defines.v' self.default_verilog_defines_full_path = '../../hardware/victims/cw305_artixtarget/fpga/vivado_examples/ecc_p256_pmul/hdl/' + self.default_verilog_defines self.registers = 12 # number of registers we expect to find self.bytecount_size = 8 # pBYTECNT_SIZE in Verilog self.target_name = 'Cryptech ecdsa256-v1 pmul'
def root_key_slip10(self, master_secret): """ INPUT: S: 512 bits seed from BIP39/BIP32 seedkey:"ed25519 seed" OUTPUT: k = (kL,kR), c PROCESS: 1. compute c = HMAC-SHA256(key=seedkey,0x01 || Data = S) 2. compute I = HMAC-SHA512(key=seedkey, Data=S) 3. split I = into tow sequence of 32-bytes sequence kL,Kr 4. if the third highest bit of the last byte ok kL is not zero: S = I goto step 1 5. Set the bits in kL as follows: - the lowest 3 bits of the first byte of kL of are cleared - the highest bit of the last byte is cleared - the second highest bit of the last byte is set 6. return (kL,kR), c """ ENTER("root_key_slip10") key = b'ed25519 seed' # root chain code c = bytearray(_Fk256(b'\x01' + master_secret, key)) #KL:KR I = bytearray(_Fk(master_secret, key)) kL, kR = I[:32], I[32:] while _get_bit(kL[31], 0b00100000) != 0: master_secret = I I = bytearray(_Fk(master_secret, key)) kL, kR = I[:32], I[32:] # the lowest 3 bits of the first byte of kL of are cleared kL[0] = _clear_bit(kL[0], 0b00000111) # the highest bit of the last byte is cleared kL[31] = _clear_bit(kL[31], 0b10000000) # the second highest bit of the last byte is set kL[31] = _set_bit(kL[31], 0b01000000) # root public key #A = _crypto_scalarmult_curve25519_base(bytes(kL)) cv25519 = Curve.get_curve("Ed25519") k_scalar = int.from_bytes(bytes(kL), 'little') P = k_scalar * cv25519.generator A = cv25519.encode_point(P) trace("root key: ") trace("kL %s" % binascii.hexlify(kL)) trace("kR %s" % binascii.hexlify(kR)) trace("A %s" % binascii.hexlify(A)) trace("c %s" % binascii.hexlify(c)) LEAVE("root_key_slip10") return ((kL, kR), A, c)
def new(curve_name: str = "secp256k1", hash_alg: str = "sha256", bits: int = None): curve = Curve.get_curve(curve_name) if curve is None: raise ValueError("Invalid Curve") return ZK( ZKParameters(alg=hash_alg, curve=curve_name, s=random.getrandbits(bits or curve.field.bit_length())))
def new(bits: int = 256, curve_name="secp256k1"): """ Create a new ZKProof using the elliptic curve `curve` and a `bits`-sized scalar """ if Curve.get_curve(curve_name) is None: raise NotImplementedError( f"The curve '{curve_name}' is not implemented") return ZKProof( ZKParameters( curve=curve_name, d=crypto.get_prime(bits), ))
def resetEphemeral(): API_URL = 'http://cryptlygos.pythonanywhere.com' stuID = 25388 # 24198,19872, 23574, 25655 E = Curve.get_curve('secp256k1') n = E.order P = E.generator # long term keys s_l, Q_l = 13085853449963706822679688925724357385610122371856980557637515554534105534392, Point( 99706965781601861644488801678706331501908275461350155965248416002017363728845, 34959479883630730429995407912028272742489857511375877620317188275102881036203, E) h, s = signatureGeneration(str(stuID), P, n, s_l) mes = {'ID': stuID, 'S': s, 'H': h} response = requests.get('{}/{}'.format(API_URL, "RstEKey"), json=mes) print(response.json())
def register_long_term_key(stuID): ####Register Long Term Key curve = Curve.get_curve('secp256k1') P = curve.generator sL = randint(1, random_prime(256) - 1) qL = sL * P print("sL= ", sL) print("qL= ", qL) s, h = SignGen(str(stuID).encode(), curve, sL) mes = {'ID': stuID, 'H': h, 'S': s, 'LKEY.X': qL.x, 'LKEY.Y': qL.y} response = requests.put('{}/{}'.format(API_URL, "RegLongRqst"), json=mes) print(response.json()) code = int(input()) mes = {'ID': stuID, 'CODE': code} response = requests.put('{}/{}'.format(API_URL, "RegLong"), json=mes) print(response.json())
def scp_derive_key(self, ecdh_secret, keyindex): retry = 0 # di = sha256(i || retrycounter || ecdh secret) while True: sha256 = hashlib.new('sha256') sha256.update(struct.pack(">IB", keyindex, retry)) sha256.update(ecdh_secret) # compare di with order CURVE_SECP256K1 = Curve.get_curve('secp256k1') if int.from_bytes(sha256.digest(), 'big') < CURVE_SECP256K1.order: break #regenerate a new di satisfying order upper bound retry+=1 # Pi = di*G privkey = PrivateKey(bytes(sha256.digest())) pubkey = bytearray(privkey.pubkey.serialize(compressed=False)) # ki = sha256(Pi) sha256 = hashlib.new('sha256') sha256.update(pubkey) #print ("Key " + str (keyindex) + ": " + sha256.hexdigest()) return sha256.digest()
def scp_derive_key(self, ecdh_secret, keyindex): retry = 0 # di = sha256(i || retrycounter || ecdh secret) while True: sha256 = hashlib.new('sha256') sha256.update(struct.pack(">IB", keyindex, retry)) sha256.update(ecdh_secret) # compare di with order CURVE_SECP256K1 = Curve.get_curve('secp256k1') if int.from_bytes(sha256.digest(), 'big') < CURVE_SECP256K1.order: break #regenerate a new di satisfying order upper bound retry+=1 # Pi = di*G privkey = PrivateKey(bytes(sha256.digest())) pubkey = bytearray(privkey.pubkey.serialize(compressed=False)) # ki = sha256(Pi) sha256 = hashlib.new('sha256') sha256.update(pubkey) #print ("Key " + str (keyindex) + ": " + sha256.hexdigest()) return sha256.digest()
def _crypto_scalarmult_curve25519_base(k): cv25519 = Curve.get_curve("Ed25519") k = int.from_bytes(k, 'little') P = k * cv25519.generator return cv25519.encode_point(P)
from ecpy.curves import Curve, Point ed = Curve.get_curve('Ed25519') P = Point(0x3f14cc3324c79d9687f95c8f75af102eaebc1f7670a80b1f6a07959e3698afe9, 0x4a927deb79b86633dc86a0ea061ef34276dc20d736a7b47fc926e54cf4ea5e32, ed) Q = Point(0x34a511dbf0b36780d8c785ecc2857525bc990a6df9803c68b8af302be00c104c, 0x417587b30efdc587244a8609934a5ce39bf2986de45706810b0c0e314bc961f5, ed) print('-------------------------------------------------') y = int.from_bytes(ed.encode_point(P), 'big') print("P %s" % hex(y)) y = int.from_bytes(ed.encode_point(Q), 'big') print("Q %s" % hex(y)) print('-------------------------------------------------') Q_ = Point(ed.field - Q.x, Q.y, ed) Z = P + Q_ print(Z) y = int.from_bytes(ed.encode_point(Z), 'big') print(hex(y)) print('-------------------------------------------------') print('-------------------------------------------------')
from ecpy.curves import Curve from ecpy.keys import ECPrivateKey from ecpy.eddsa import EDDSA import secrets, hashlib, binascii curve = Curve.get_curve('Ed448') signer = EDDSA(hashlib.shake_256, hash_len=114) privKey = ECPrivateKey(secrets.randbits(57 * 8), curve) pubKey = signer.get_public_key(privKey, hashlib.shake_256, hash_len=114) print("Private key (57 bytes):", privKey) print("Public key (compressed, 57 bytes): ", binascii.hexlify(curve.encode_point(pubKey.W))) print("Public key (point): ", pubKey) msg = b'Message for Ed448 signing' signature = signer.sign(msg, privKey) print("Signature (114 bytes):", binascii.hexlify(signature)) valid = signer.verify(msg, signature, pubKey) print("Valid signature?", valid) valid = signer.verify(b'Tampered msg', signature, pubKey) print("Valid signature?", valid)
pub = pv_keyget_public_key() if pu_key.W & 1: xPub = b'\0x03' + pu_key.W.x.to_bytes(size, 'big') else: xPub = b'\0x02' + pu_key.W.x.to_bytes(size, 'big') hasher.update(xQ + xPub + msg) v = hasher.digest() v = int.from_bytes(v, 'big') return v == r if __name__ == "__main__": import sys 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)
u2Q = u2*pu_key.W GQ = u1G+u2Q 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
import hashlib from ecpy.curves import Curve, Point cv = Curve.get_curve('Curve25519') ed = Curve.get_curve('Ed25519') p = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed d = 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3 a = -1 x = 0x36ab384c9f5a046c3d043b7d1833e7ac080d8e4515d7a45f83c5a14e2843ce0e y = 0x2260cdf3092329c21da25ee8c9a21f5697390f51643851560e5f46ae6af8a3c9 P = Point(x, y, ed) B = 1 A = 486662 def inv(x): return pow(x % p, p - 2, p) def AB(a, d): A = (2 * (a + d) * inv(a - d)) % p B = (4 * inv(a - d)) % p print("A %x" % A) print("B %x" % B) def UV(x, y): u = ((1 + y) * inv((1 - y) % p)) % p v = ((1 + y) * inv(((1 - y) * x) % p)) % p
xQ = b'\x02'+Q.x.to_bytes(size,'big') if pu_key.W.y & 1: 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
h = int.from_bytes(h,'little') h = h%n A = pu_key.W left = R+h*A #right right = S*curve.generator 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)
def borromean_sign(pubkeys, privkeys, rings_size, private_keys_index, ring_count, msg): tell("*** BORROMEAN SIGN ***\n") enter("borromean_sign") curve = Curve.get_curve('secp256k1') G = curve.generator order = curve.order e0 = None s = [] k = [] #just declare for i in range(0, ring_count): k.append(None) for j in range(0, rings_size[i]): s.append(None) #step2-3 shuffle = random.randint r0 = 0 sha256_e0 = hashlib.sha256() for i in range(0, ring_count): tell("\nstep2-3 / ring %d" % i) k[i] = rrand(i) tell("ki : %x" % k[i]) kiG = k[i] * G tell("ki.G :\n %s" % kiG) j0 = private_keys_index[i] e_ij = point_to_bytes(kiG) tell("e_ij : %s" % h(e_ij)) for j in range(j0 + 1, rings_size[i]): tell("\n step2-3 / ring %d / sec %d" % (i, j)) s[r0 + j] = prand(r0 + j) e_ij = borromean_hash(m, e_ij, i, j) e_ij = int.from_bytes(e_ij, 'big') tell(" index : %d" % (r0 + j)) tell(" pubkeys[]: %s" % pubkeys[r0 + j]) tell(" s[] : %x" % s[r0 + j]) tell(" e_ij : %x" % e_ij) sG_eP = s[r0 + j] * G + e_ij * pubkeys[r0 + j].W tell(" sG_eP :\n %s" % sG_eP) e_ij = point_to_bytes(sG_eP) tell("\ne0ij :\n %s" % h(e_ij)) sha256_e0.update(e_ij) r0 += rings_size[i] sha256_e0.update(m) e0 = sha256_e0.digest() tell("\ne0: %s" % h(e0)) #step 4 tell("") r0 = 0 for i in range(0, ring_count): tell("\nstep 4 / ring %d" % i) j0 = private_keys_index[i] e_ij = borromean_hash(m, e0, i, 0) e_ij = int.from_bytes(e_ij, 'big') for j in range(0, j0): tell("\n step 4 / ring %d / sec %d" % (i, j)) s[r0 + j] = prand(r0 + j) tell(" index : %d" % (r0 + j)) tell(" pubkeys[]: %s" % pubkeys[r0 + j]) tell(" s[] : %x" % s[r0 + j]) tell(" e_ij : %x" % e_ij) sG_eP = s[r0 + j] * G + e_ij * pubkeys[r0 + j].W tell(" sG_eP :\n %s" % sG_eP) e_ij = borromean_hash(m, point_to_bytes(sG_eP), i, j + 1) e_ij = int.from_bytes(e_ij, 'big') tell("ki : %x" % k[i]) tell("xi : %x" % privkeys[i].d) tell("eij* : %x" % e_ij) s[r0 + j0] = (k[i] - privkeys[i].d * e_ij) % order tell("sij* : %x" % s[r0 + j0]) r0 += rings_size[i] leave("borromean_sign") s = [sij.to_bytes(32, 'big') for sij in s] return (e0, s)
""" import hashlib try: import secp256k1 USE_SECP = secp256k1.HAS_ECDH except ImportError: USE_SECP = False if not USE_SECP: import ecpy from builtins import int from ecpy.curves import Curve, Point from ecpy.keys import ECPublicKey, ECPrivateKey from ecpy.ecdsa import ECDSA CURVE_SECP256K1 = Curve.get_curve('secp256k1') SIGNER = ECDSA() 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))
import hashlib from ecpy.curves import Curve, Point from ecpy.keys import ECPublicKey, ECPrivateKey cv = Curve.get_curve("Ed25519") g = cv.generator p = cv.field l = cv.order #message as a string #pbkey as a point encoded as hexstring (32) #signature as hexstring def verify(message, pbkey, signature): # sign contains R i s (32 bytes each) # Verify: # R + hash(R+m)Pb == sG keybytes = bytes.fromhex(pbkey) sigbytes = bytes.fromhex(signature) R = sigbytes[:32] s = sigbytes[32:] #calculate the hash h = hashlib.sha256() h.update(R) h.update(message.encode("utf-8")) hint = int.from_bytes(h.digest(),"little") si = int.from_bytes(s, "little") S = cv.mul_point(si,g)
from ecpy.curves import Curve from ecpy.keys import ECPrivateKey from ecpy.ecdsa import ECDSA import sys import base64 import hashlib import time import binascii cv = Curve.get_curve('secp256r1') def sign(api_key, api_secret, params, timestamp=None): if timestamp is None: timestamp = __currentTimestamp() payload = __composePayload(api_key, params, timestamp) hashed_payload = hashlib.sha256(payload.encode("UTF-8")).hexdigest() pv_key = ECPrivateKey( int(binascii.hexlify(base64.b64decode(api_secret)), 16), cv) signature_bytes = ECDSA().sign(bytearray.fromhex(hashed_payload), pv_key) return binascii.hexlify(signature_bytes).decode("UTF-8"), timestamp def verify(api_key, api_secret, params, signature, timestamp): payload = __composePayload(api_key, params, timestamp) pv_key = ECPrivateKey( int(binascii.hexlify(base64.b64decode(api_secret)), 16), cv) hashed_payload = hashlib.sha256(payload.encode("UTF-8")).hexdigest() return ECDSA().verify(bytearray.fromhex(hashed_payload),
SHA3_256.new(hashTree[i] + hashTree[i + 1]).digest()) j += t t = t >> 1 H_r = hashTree[2 * TxCnt - 2] PrevPoW = Block[-2][14:-1] PrevPoW = PrevPoW.encode('UTF-8') nonce = int(Block[-1][7:-1]) digest = H_r + PrevPoW + nonce.to_bytes( (nonce.bit_length() + 7) // 8, byteorder='big') PoW = SHA3_256.new(digest).hexdigest() return PoW, Block[-2][14:-1] ############## E = Curve.get_curve('secp256k1') # We will always use this curve # Test I ######### # Testing our version of ECDSA; # Generate a signature and verify it sA, QA = ECDSA.KeyGen(E) # generate a secret/public key pair message = b"When you can't find the sunshine, be the sunshine" s, r = ECDSA.SignGen(message, E, sA) if ECDSA.SignVer(message, s, r, E, QA) == 0: print("Test I: The signature verifies") else: print("Test I: The signature DOES NOT verify") # Test II
Authors: Jacky Huynh & Jordan Cheung This file contains the neccessary functions to generate the keys for Elliptic-curve Diffie–Hellman Key Exchange References used: https://en.wikipedia.org/wiki/Signal_Protocol https://en.wikipedia.org/wiki/Elliptic-curve_Diffie%E2%80%93Hellman#:~:text=Elliptic%2Dcurve%20Diffie%E2%80%93Hellman%20(,secret%20over%20an%20insecure%20channel.&text=The%20key%2C%20or%20the%20derived,using%20a%20symmetric%2Dkey%20cipher. ''' import random from ecpy.curves import Curve, Point import math import secrets # Get the curve for Curve25519 cv = Curve.get_curve('Curve25519') # Generate private key def generate_private_key(): # Get a random point on the elliptic curve return secrets.randbelow(cv.field) # Generate public key from private key def generate_public_key(private_key): # Multiply the private key with a point on the elliptic curve return private_key * cv.generator
temp = m + r.to_bytes((r.bit_length() + 7) // 8,byteorder= 'big') h = SHA3_256.new(temp) h = int.from_bytes(h.digest(), byteorder='big') % n s = (sA*h + k) % n return(h,s) #testarray for id 18007 test=["The world is full of lonely people afraid to make the first move.", "I don’t like sand. It’s all coarse, and rough, and irritating. And it gets everywhere.", "Hate is baggage. Life’s too short to be pissed off all the time. It’s just not worth it.", "Well, sir, it’s this rug I have, it really tied the room together.", "Love is like taking a dump, Butters. Sometimes it works itself out. But sometimes, you need to give it a nice hard slimy push."] #create a long term key curve = Curve.get_curve('secp256k1') n = curve.order P = curve.generator #sA_l,QA_l=key_generation(n, P); sA_l = 47739507727097583103574014533029612368096643715089728534014772436197620809295 #long term key QA_l = sA_l*P lkey=QA_l lpkey=sA_l print('sA_l:',sA_l) print('QA_l:',QA_l) m = str(stuID) m = str.encode(m) h,s = signature_generation(n, m, P, sA_l) ####Register Long Term Key
def P256(self): return Curve.get_curve('secp256r1')