def test_ed25519_kat(secret_key, public_key, message, signed, signature): sk = binascii.unhexlify(secret_key) m = binascii.unhexlify(message) pk = ed25519.publickey(sk) sig = ed25519.signature(m, sk, pk) # Assert that the signature and public key are what we expected assert binascii.hexlify(pk) == public_key assert binascii.hexlify(sig) == signature # Validate the signature using the checkvalid routine ed25519.checkvalid(sig, m, pk) # Assert that we cannot forge a message # TODO: Yes this means that we "pass" a test if we can't generate a forged # message. This matches the original test suite. with pytest.raises(Exception): if len(m) == 0: forgedm = b"x" else: forgedm = b"".join( [chr(ord(m[i]) + (i == len(m) - 1)) for i in range(len(m))] ) ed25519.checkvalid(sig, forgedm, pk)
def test_ed25519_kat(secret_key, public_key, message, signed, signature): sk = binascii.unhexlify(secret_key) m = binascii.unhexlify(message) pk = ed25519.publickey_unsafe(sk) sig = ed25519.signature_unsafe(m, sk, pk) # Assert that the signature and public key are what we expected assert binascii.hexlify(pk) == public_key assert binascii.hexlify(sig) == signature # Validate the signature using the checkvalid routine ed25519.checkvalid(sig, m, pk) # Assert that we cannot forge a message try: if len(m) == 0: forgedm = b"x" else: forgedm = ed25519.intlist2bytes([ ed25519.indexbytes(m, i) + (i == len(m) - 1) for i in range(len(m)) ]) except ValueError: # TODO: Yes this means that we "pass" a test if we can't generate a # forged message. This matches the original test suite, it's # unclear if it was intentional there or not. pass else: with pytest.raises(ed25519.SignatureMismatch): ed25519.checkvalid(sig, forgedm, pk)
def verify_signature(seq, validator_public_key_human, public_key_human, signature): v, validator_public_key = Base58.decode_version(validator_public_key_human) check_validator_public(v, validator_public_key) v, public_key = Base58.decode_version(public_key_human) m = make_manifest(public_key, validator_public_key, seq) public_key = public_key[1:] # Remove ED25519_BYTE sig = signature.decode("hex") ed25519.checkvalid(sig, "MAN\0" + m, public_key)
def verify_signature(seq, validator_public_key_human, public_key_human, signature): v, validator_public_key = Base58.decode_version(validator_public_key_human) check_validator_public(v, validator_public_key) v, public_key = Base58.decode_version(public_key_human) m = make_manifest(public_key, validator_public_key, seq) public_key = public_key[1:] # Remove ED25519_BYTE sig = signature.decode('hex') ed25519.checkvalid(sig, 'MAN\0' + m, public_key)
def main(): default_key_file_absolute = os.path.join(script_dir, DEFAULT_KEY_FILE) parser = argparse.ArgumentParser( description="Generate tokens for enabling experimental APIs") parser.add_argument("origin", help="Origin for which to enable the API. This can be " "either a hostname (default scheme HTTPS, default " "port 443) or a URL.", type=OriginFromArg) parser.add_argument("trial_name", help="Feature to enable. The current list of " "experimental feature trials can be found in " "RuntimeFeatures.in") parser.add_argument("--key-file", help="Ed25519 private key file to sign the token with", default=default_key_file_absolute) expiry_group = parser.add_mutually_exclusive_group() expiry_group.add_argument( "--expire-days", help="Days from now when the token should exipire", type=int, default=42) expiry_group.add_argument("--expire-timestamp", help="Exact time (seconds since 1970-01-01 " "00:00:00 UTC) when the token should exipire", type=int) args = parser.parse_args() expiry = ExpiryFromArgs(args) key_file = open(os.path.expanduser(args.key_file), mode="rb") private_key = key_file.read(64) # Validate that the key file read was a proper Ed25519 key -- running the # publickey method on the first half of the key should return the second # half. if (len(private_key) < 64 or ed25519.publickey(private_key[:32]) != private_key[32:]): print("Unable to use the specified private key file.") sys.exit(1) token_data = GenerateTokenData(args.origin, args.trial_name, expiry) data_to_sign = GenerateDataToSign(VERSION, token_data) signature = Sign(private_key, data_to_sign) # Verify that that the signature is correct before printing it. try: ed25519.checkvalid(signature, data_to_sign, private_key[32:]) except Exception, exc: print "There was an error generating the signature." print "(The original error was: %s)" % exc sys.exit(1)
def main(): parser = argparse.ArgumentParser( description="Generate tokens for enabling experimental APIs") parser.add_argument("origin", help="Origin for which to enable the API. This can be " "either a hostname (default scheme HTTPS, default " "port 443) or a URL.", type=OriginFromArg) parser.add_argument("trial_name", help="Feature to enable. The current list of " "experimental feature trials can be found in " "RuntimeFeatures.in") parser.add_argument("--key-file", help="Ed25519 private key file to sign the token with", default="eftest.key") expiry_group = parser.add_mutually_exclusive_group() expiry_group.add_argument("--expire-days", help="Days from now when the token should exipire", type=int, default=42) expiry_group.add_argument("--expire-timestamp", help="Exact time (seconds since 1970-01-01 " "00:00:00 UTC) when the token should exipire", type=int) args = parser.parse_args() expiry = ExpiryFromArgs(args) key_file = open(os.path.expanduser(args.key_file), mode="rb") private_key = key_file.read(64) # Validate that the key file read was a proper Ed25519 key -- running the # publickey method on the first half of the key should return the second # half. if (len(private_key) < 64 or ed25519.publickey(private_key[:32]) != private_key[32:]): print("Unable to use the specified private key file.") sys.exit(1) token_data = GenerateTokenData(args.origin, args.trial_name, expiry) data_to_sign = GenerateDataToSign(VERSION, token_data) signature = Sign(private_key, data_to_sign) # Verify that that the signature is correct before printing it. try: ed25519.checkvalid(signature, data_to_sign, private_key[32:]) except Exception, exc: print "There was an error generating the signature." print "(The original error was: %s)" % exc sys.exit(1)
old_leaf.append(createLeaf(public_key[j - 1], rhs_leaf[j - 1])) # The new leaf is current pubkey with current message new_leaf.append(createLeaf(public_key[j], rhs_leaf[j])) # The message to sign is the previous leaf with the new leaf message = hashPadded(old_leaf[j - 1], new_leaf[j - 1]) # Remove '0x' from byte message = message[2:] # Obtain Signature r, s = getSignature(message, sk[j - 1], public_key[j - 1]) # check the signature is correct ed.checkvalid(r, s, message, public_key[j - 1]) # Now we reverse the puplic key by bit # we have to reverse the bits so that the # unpacker in libsnark will return us the # correct field element # To put into little-endian pub_key_x = hex( int( ''.join( str(e) for e in hexToBinary(hex(public_key[j - 1][0]))[::-1]), 2)) pub_key_y = hex( int( ''.join( str(e)
def main(): parser = argparse.ArgumentParser(description="Inspect origin trial tokens") parser.add_argument("token", help="Token to be checked (must be Base64 encoded)") key_group = parser.add_mutually_exclusive_group() key_group.add_argument( "--use-chrome-key", help="Validate token using the real Chrome public key", dest="use_chrome_key", action="store_true") key_group.add_argument("--use-test-key", help="Validate token using the eftest.key", dest="use_chrome_key", action="store_false") key_group.add_argument( "--key-file", help="Ed25519 private key file to validate the token", dest="key_file", action=OverrideKeyFileAction) parser.set_defaults(use_chrome_key=False) args = parser.parse_args() # Figure out which public key to use: Chrome, test key (default option), or # key file provided on command line. public_key = None private_key_file = None if (args.use_chrome_key is None): private_key_file = args.key_file else: if (args.use_chrome_key): public_key = "".join(chr(x) for x in CHROME_PUBLIC_KEY) else: # Use the test key, relative to this script. private_key_file = os.path.join(script_dir, DEFAULT_KEY_FILE) # If not using the Chrome public key, extract the public key from either the # test key file, or the private key file provided on the command line. if public_key is None: try: key_file = open(os.path.expanduser(private_key_file), mode="rb") except IOError as exc: print("Unable to open key file: %s" % private_key_file) print("(%s)" % exc) sys.exit(1) private_key = key_file.read(64) # Validate that the key file read was a proper Ed25519 key -- running the # publickey method on the first half of the key should return the second # half. if (len(private_key) < 64 or ed25519.publickey(private_key[:32]) != private_key[32:]): print("Unable to use the specified private key file.") sys.exit(1) public_key = private_key[32:] try: token_contents = base64.b64decode(args.token) except TypeError as exc: print("Error decoding the token (%s)" % exc) sys.exit(1) # Only version 2 and version 3 currently supported. if (len(token_contents) < (VERSION_OFFSET + VERSION_SIZE)): print("Token is malformed - too short.") sys.exit(1) version = token_contents[VERSION_OFFSET:(VERSION_OFFSET + VERSION_SIZE)] # Convert the version string to a number version_number = 0 for x in version: version_number <<= 8 version_number += ord(x) if (version != VERSION2 and version != VERSION3): print("Token has wrong version: %d" % version_number) sys.exit(1) # Token must be large enough to contain a version, signature, and payload # length. minimum_token_length = PAYLOAD_LENGTH_OFFSET + PAYLOAD_LENGTH_SIZE if (len(token_contents) < minimum_token_length): print("Token is malformed - too short: %d bytes, minimum is %d" % \ (len(token_contents), minimum_token_length)) sys.exit(1) # Extract the length of the signed data (Big-endian). # (unpack returns a tuple). payload_length = struct.unpack_from(">I", token_contents, PAYLOAD_LENGTH_OFFSET)[0] # Validate that the stated length matches the actual payload length. actual_payload_length = len(token_contents) - PAYLOAD_OFFSET if (payload_length != actual_payload_length): print("Token is %d bytes, expected %d" % (actual_payload_length, payload_length)) sys.exit(1) # Extract the version-specific contents of the token. # Contents are: version|signature|payload length|payload signature = token_contents[SIGNATURE_OFFSET:PAYLOAD_LENGTH_OFFSET] # The data which is covered by the signature is (version + length + payload). signed_data = version + token_contents[PAYLOAD_LENGTH_OFFSET:] # Validate the signature on the data. try: ed25519.checkvalid(signature, signed_data, public_key) except Exception as exc: print("Signature invalid (%s)" % exc) sys.exit(1) try: payload = token_contents[PAYLOAD_OFFSET:].decode('utf-8') except UnicodeError as exc: print("Unable to decode token contents (%s)" % exc) sys.exit(1) try: token_data = json.loads(payload) except Exception as exc: print("Unable to parse payload (%s)" % exc) print("Payload: %s" % payload) sys.exit(1) print() print("Token data: %s" % token_data) print() # Extract the required fields for field in ["origin", "feature", "expiry"]: if field not in token_data: print("Token is missing required field: %s" % field) sys.exit(1) origin = token_data["origin"] trial_name = token_data["feature"] expiry = token_data["expiry"] # Extract the optional fields is_subdomain = token_data.get("isSubdomain") is_third_party = token_data.get("isThirdParty") if (is_third_party is not None and version != VERSION3): print("The isThirdParty field can only be be set in Version 3 token.") sys.exit(1) usage_restriction = token_data.get("usage") if (usage_restriction is not None and version != VERSION3): print("The usage field can only be be set in Version 3 token.") sys.exit(1) if (usage_restriction is not None and usage_restriction not in USAGE_RESTRICTION): print( "Only empty string and \"subset\" are supported in the usage field." ) sys.exit(1) # Output the token details print("Token details:") print(" Version: %s" % version_number) print(" Origin: %s" % origin) print(" Is Subdomain: %s" % is_subdomain) if (version == VERSION3): print(" Is Third Party: %s" % is_third_party) print(" Usage Restriction: %s" % usage_restriction) print(" Feature: %s" % trial_name) print(" Expiry: %d (%s UTC)" % (expiry, datetime.utcfromtimestamp(expiry))) print(" Signature: %s" % ", ".join('0x%02x' % ord(x) for x in signature)) print(" Signature (Base64): %s" % base64.b64encode(signature)) print()
def Verify(sig, m, pk): return ed25519.checkvalid(binascii.unhexlify(sig), m, binascii.unhexlify(pk))
# Affiche de clés if args.typeKey and args.id: if args.typeKey == 'pub' or args.typeKey == 'sec': key = gk.getkey(args.id, args.typeKey) if key: print key else: print "Pas d'entrée trouvée pour " + args.id else: print args.typeKey + " est une mauvaise option pour l'argument -export" # Génére la signature if args.message and args.id and args.gensign: sk = gk.getkey(args.id, 'sec') pk = gk.genPkBrut(args.id) sign = ed.signature(args.message, sk, pk) if sign: print sign.encode('hex') # Vérifie si la signature est valide if args.sign and args.message and args.id: sk = gk.getkey(args.id, 'sec') pk = gk.genPkBrut(args.id) sign = str(args.sign).rstrip().decode('hex') try: ed.checkvalid(sign, args.message, pk) print "La signature est valide" except: print "La signature n'a pu être validée"
def main(): default_key_file_absolute = os.path.join(script_dir, DEFAULT_KEY_FILE) parser = argparse.ArgumentParser( description="Generate tokens for enabling experimental features") parser.add_argument("--version", help="Token version to use. Currently only version 2" "and version 3 are supported.", default='3', type=VersionFromArg) parser.add_argument( "origin", help="Origin for which to enable the feature. This can " "be either a hostname (default scheme HTTPS, " "default port 443) or a URL.", type=OriginFromArg) parser.add_argument("trial_name", help="Feature to enable. The current list of " "experimental feature trials can be found in " "RuntimeFeatures.in") parser.add_argument("--key-file", help="Ed25519 private key file to sign the token with", default=default_key_file_absolute) subdomain_group = parser.add_mutually_exclusive_group() subdomain_group.add_argument("--is-subdomain", help="Token will enable the feature for all " "subdomains that match the origin", dest="is_subdomain", action="store_true") subdomain_group.add_argument("--no-subdomain", help="Token will only match the specified " "origin (default behavior)", dest="is_subdomain", action="store_false") parser.set_defaults(is_subdomain=None) third_party_group = parser.add_mutually_exclusive_group() third_party_group.add_argument( "--is-third-party", help="Token will enable the feature for third " "party origins. This option is only available for token version 3", dest="is_third_party", action="store_true") third_party_group.add_argument( "--no-third-party", help="Token will only match first party origin. This option is only " "available for token version 3", dest="is_third_party", action="store_false") parser.set_defaults(is_third_party=None) parser.add_argument( "--usage-restriction", help="Alternative token usage resctriction. This option " "is only available for token version 3. Currently only " "subset exclusion is supported.") expiry_group = parser.add_mutually_exclusive_group() expiry_group.add_argument( "--expire-days", help="Days from now when the token should expire", type=int, default=42) expiry_group.add_argument("--expire-timestamp", help="Exact time (seconds since 1970-01-01 " "00:00:00 UTC) when the token should expire", type=int) args = parser.parse_args() expiry = ExpiryFromArgs(args) key_file = open(os.path.expanduser(args.key_file), mode="rb") private_key = key_file.read(64) # Validate that the key file read was a proper Ed25519 key -- running the # publickey method on the first half of the key should return the second # half. if (len(private_key) < 64 or ed25519.publickey(private_key[:32]) != private_key[32:]): print("Unable to use the specified private key file.") sys.exit(1) if (not args.version): print("Invalid token version. Only version 2 and 3 are supported.") sys.exit(1) if (args.is_third_party is not None and args.version[0] != 3): print("Only version 3 token supports is_third_party flag.") sys.exit(1) if (args.usage_restriction is not None): if (args.version[0] != 3): print( "Only version 3 token supports alternative usage restriction.") sys.exit(1) if (not args.is_third_party): print( "Only third party token supports alternative usage restriction." ) sys.exit(1) if (args.usage_restriction not in USAGE_RESTRICTION): print( "Only empty string and \"subset\" are supported in alternative usage " "restriction.") sys.exit(1) token_data = GenerateTokenData(args.version[0], args.origin, args.is_subdomain, args.is_third_party, args.usage_restriction, args.trial_name, expiry) data_to_sign = GenerateDataToSign(args.version[1], token_data) signature = Sign(private_key, data_to_sign) # Verify that that the signature is correct before printing it. try: ed25519.checkvalid(signature, data_to_sign, private_key[32:]) except Exception, exc: print("There was an error generating the signature.") print("(The original error was: %s)" % exc) sys.exit(1)
def verify(self, msg, key, sig): try: ed25519.checkvalid(sig, msg, key) except: return False return True
print "erreur id introuvable" else: userPK = info_pk[2] userSK = info_sk[2] userPK = str(userPK).rstrip().decode('hex') userSK = str(userSK).rstrip().decode('hex') fsig = open(args.sig, "r") signature = fsig.read() fsig.close() signature = str(signature).rstrip().decode('hex') try: ed25519.checkvalid(signature, msg, userPK) print "La signature est conforme" except: print "La signature est erornée" # ecctool -enc -dest bob -in message.txt -out message.crypt elif args.enc : action = 0 if action != -1 and args.dest : action = 1 else: print("[ERREUR] -dest manquant") errcommand() if action != -1 and args.in_info:
# fields on each input line: sk, pk, m, sm # each field hex # each field colon-terminated # sk includes pk at end # sm includes m at end while 1: line = sys.stdin.readline() if not line: break x = line.split(':') sk = binascii.unhexlify(x[0][0:64]) pk = ed25519.publickey(sk) m = binascii.unhexlify(x[2]) s = ed25519.signature(m, sk, pk) ed25519.checkvalid(s, m, pk) forgedsuccess = 0 try: if len(m) == 0: forgedm = "x" else: forgedmlen = len(m) forgedm = ''.join([ chr(ord(m[i]) + (i == forgedmlen - 1)) for i in range(forgedmlen) ]) ed25519.checkvalid(s, forgedm, pk) forgedsuccess = 1 except: pass assert not forgedsuccess
def generate_transfer_proof(self, transactions): return 42 pub_x = [] pub_y = [] leaves = [] R_x = [] R_y = [] S = [] previous_owners = [] new_owners = [] address = [] public_key = [] # Public key of sender from first tx public_key.append(tx.senderPubKey) # Iterate over transactions. each tx is an object from classes.py for j in range(1, len(transactions) + 1): tx = transactions[i] leaves.append([]) # Append sender pubkey public_key.append(tx.senderPubKey) # The old owner is previous pubkey + RHS # TODO add rhs_leaf / # replace with stub previous_owners.append(createLeaf(tx.senderPubKey, rhs_leaf)) # The new leaf is current pubkey with RHS new_owners.append(createLeaf(tx.receiverPubKey, rhs_leaf)) # The message to sign is the previous leaf with the new leaf message = hashPadded(previous_owners[j - 1], new_owners[j - 1]) # Remove '0x' from byte message = message[2:] # Check the signer is correct ed.checkvalid(tx.R, tx.S, message, tx.senderPubKey) # Now we reverse the puplic key by bit # we have to reverse the bits so that the # unpacker in libsnark will return us the # correct field element # To put into little-endian pub_key_x = hex( int( ''.join( str(e) for e in hexToBinary(hex(public_key[j - 1][0]))[::-1]), 2)) pub_key_y = hex( int( ''.join( str(e) for e in hexToBinary(hex(public_key[j - 1][1]))[::-1]), 2)) tx.R[0] = hex( int(''.join(str(e) for e in hexToBinary(hex(tx.R[0]))[::-1]), 2)) tx.R[1] = hex( int(''.join(str(e) for e in hexToBinary(hex(tx.R[1]))[::-1]), 2)) # Two r on x and y axis of curve R_x.append(tx.R[0]) R_y.append(tx.R[1]) # Store s S.append(s) # Store public key pub_x.append(pub_key_x) pub_y.append(pub_key_y) # leaves[j - 1].append(previous_owners[j - 1]) # address.append(0) # Get zk proof and Merkle root proof, root = generate_witness(leaves, pub_x, pub_y, address, tree_depth, rhs_leaf, new_owners, R_x, R_y, S) #Build proof for contract proof["a"] = hex2int(proof["a"]) proof["a_p"] = hex2int(proof["a_p"]) proof["b"] = [hex2int(proof["b"][0]), hex2int(proof["b"][1])] proof["b_p"] = hex2int(proof["b_p"]) proof["c"] = hex2int(proof["c"]) proof["c_p"] = hex2int(proof["c_p"]) proof["h"] = hex2int(proof["h"]) proof["k"] = hex2int(proof["k"]) proof["input"] = hex2int(proof["input"]) return proof
# sk includes pk at end # sm includes m at end while 1: line = sys.stdin.readline() if not line: break x = line.split(':') sk = binascii.unhexlify(x[0][0:64]) print "sk:" + binascii.b2a_hex(sk) pk = ed25519.publickey(sk) #print "pk:" + binascii.b2a_hex(pk) m = binascii.unhexlify(x[2]) s = ed25519.signature(m, sk, pk) ed25519.checkvalid(s, m, pk) """ forgedsuccess = 0 try: if len(m) == 0: forgedm = "x" else: forgedmlen = len(m) forgedm = ''.join([chr(ord(m[i])+(i==forgedmlen-1)) for i in range(forgedmlen)]) ed25519.checkvalid(s,forgedm,pk) forgedsuccess = 1 except: pass assert not forgedsuccess assert x[0] == binascii.hexlify(sk + pk)
apdu += struct.pack("B", p2) apdu += struct.pack("B", len(thischunk)) apdu += thischunk signature = dongle.exchange(apdu) tosend = tosend[len(thischunk):] p1 = 0x80 if len(signature) > 64: raise Exception("Error: %s" % signature[65:]) print "signature " + str(signature).encode('hex') ed25519.checkvalid(str(signature), 'TX' + txbytes, str(publicKey)) print "Verified signature" foundMsig = False msig = instx.get('msig') if msig is not None: if msig.get('v') != 1: print "Unknown multisig version %d, not filling in multisig" % msig[ 'v'] for sub in msig['subsig']: if sub['pk'] == publicKey: sub['s'] = signature foundMsig = True if not foundMsig: instx['sig'] = signature
import ed25519 sk = 32 * chr(0) pk = ed25519.publickey(sk) print "publickey for 0 is", pk.encode('hex') for i in [0, 1, 10]: print "encodeint %d = %s" % (i, ed25519.encodeint(i).encode('hex')) for p in [ (0, 0), (1, 1), (10, 0), (1, 10), (9639205628789703341510410801487549615560488670885798085067615194958049462616, 18930617471878267742194159801949745215346600387277955685031939302387136031291 ) ]: print "encodepoint %s = %s" % (repr(p), ed25519.encodepoint(p).encode('hex')) msg = "This is a secret message" sig = ed25519.signature(msg, sk, pk) print 'signature("%s") = %s' % (msg, sig.encode('hex')) try: ed25519.checkvalid(sig, msg, pk) print 'check signature result: true' except: print 'check signature result: false'