示例#1
0
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
    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)
示例#2
0
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)
示例#3
0
def create_ed_public_key(sk_human):
    v, sk = Base58.decode_version(sk_human)
    check_secret_key(v, sk)

    pk = ed25519.publickey(sk)
    pk_human = Base58.encode_version(Base58.VER_NODE_PUBLIC, ED25519_BYTE + pk)
    return pk_human
示例#4
0
文件: Sign.py 项目: yunsite/rippled
def create_ed_public_key(private_key_human):
    v, private_key = Base58.decode_version(private_key_human)
    check_master_secret(v, private_key)

    public_key = ed25519.publickey(private_key)
    public_key_human = Base58.encode_version(Base58.VER_NODE_PUBLIC, ED25519_BYTE + public_key)
    return public_key_human
示例#5
0
def create_ed_public_key(private_key_human):
    v, private_key = Base58.decode_version(private_key_human)
    check_master_secret(v, private_key)

    public_key = ed25519.publickey(private_key)
    public_key_human = Base58.encode_version(Base58.VER_NODE_PUBLIC,
                                             ED25519_BYTE + public_key)
    return public_key_human
示例#6
0
def create_ed_public_key(sk_human):
    v, sk = Base58.decode_version(sk_human)
    check_secret_key(v, sk)

    pk = ed25519.publickey(sk)
    pk_human = Base58.encode_version(
        Base58.VER_NODE_PUBLIC, ED25519_BYTE + pk)
    return pk_human
 def ed25519_public_key(self):
     """
     33-byte Ed25519 public key (bytes)—really a 32-byte key
     prefixed with the byte 0xED to indicate that it's an Ed25519 key.
     """
     if self._ed25519_pub is None:
         self._ed25519_pub = (ED_PREFIX +
                              ed25519.publickey(self.ed25519_secret_key))
     return self._ed25519_pub
示例#8
0
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)
示例#9
0
def get_signature(seq, validator_public_key_human, private_key_human):
    v, validator_public_key = Base58.decode_version(validator_public_key_human)
    check_validator_public(v, validator_public_key)

    v, private_key = Base58.decode_version(private_key_human)
    check_master_secret(v, private_key)

    pk = ed25519.publickey(private_key)
    apk = ED25519_BYTE + pk
    m = make_manifest(apk, validator_public_key, seq)
    m1 = sign_manifest(m, private_key, pk)
    return base64.b64encode(m1)
示例#10
0
def genKeys(id):
    keystore = open("keystore", "a")
    # génération de la clé publique et de la clé privée

    sk = urandom(256 / 8).encode('hex')
    pk = ed25519.publickey(sk).encode('hex')

    # impression de la clé publique
    keystore.write("[pub]\n" + id + ":DSA-Ed25519-SHA-512:" + pk + "\n")

    # imporession de la clé privée
    keystore.write("[sec]\n" + id + ":DSA-Ed25519-SHA-512:" + sk + "\n")
示例#11
0
文件: Sign.py 项目: yunsite/rippled
def get_signature(seq, validator_public_key_human, private_key_human):
    v, validator_public_key = Base58.decode_version(validator_public_key_human)
    check_validator_public(v, validator_public_key)

    v, private_key = Base58.decode_version(private_key_human)
    check_master_secret(v, private_key)

    pk = ed25519.publickey(private_key)
    apk = ED25519_BYTE + pk
    m = make_manifest(apk, validator_public_key, seq)
    m1 = sign_manifest(m, private_key, pk)
    return base64.b64encode(m1)
示例#12
0
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)
示例#13
0
def get_signature(seq, validation_pk_human, validation_sk_human, master_sk_human):
    v, validation_pk = Base58.decode_version(validation_pk_human)
    check_validation_public_key(v, validation_pk)

    v, validation_sk_str = Base58.decode_version(validation_sk_human)
    check_secret_key(v, validation_sk_str)
    validation_sk = ecdsa.SigningKey.from_string(validation_sk_str, curve=ecdsa.SECP256k1)

    v, master_sk = Base58.decode_version(master_sk_human)
    check_secret_key(v, master_sk)

    pk = ed25519.publickey(master_sk)
    apk = ED25519_BYTE + pk
    m = make_manifest(apk, validation_pk, seq)
    m1 = sign_manifest(m, validation_sk, master_sk, pk)
    return base64.b64encode(m1)
示例#14
0
def get_signature(seq, validation_pk_human, validation_sk_human,
                  master_sk_human):
    v, validation_pk = Base58.decode_version(validation_pk_human)
    check_validation_public_key(v, validation_pk)

    v, validation_sk_str = Base58.decode_version(validation_sk_human)
    check_secret_key(v, validation_sk_str)
    validation_sk = ecdsa.SigningKey.from_string(validation_sk_str,
                                                 curve=ecdsa.SECP256k1)

    v, master_sk = Base58.decode_version(master_sk_human)
    check_secret_key(v, master_sk)

    pk = ed25519.publickey(master_sk)
    apk = ED25519_BYTE + pk
    m = make_manifest(apk, validation_pk, seq)
    m1 = sign_manifest(m, validation_sk, master_sk, pk)
    return base64.b64encode(m1)
示例#15
0
def generationKey(nomUser):
    if exists("keystore") == False:
        print("creation du keystore")
        init_fichier()

    user = urandom(256 / 8)
    print user
    fichier = open("keystore", "r")
    pub = 0
    sec = 0
    toWrite = ""
    for ligne in fichier:
        nom = ligne.split(":")
        if nom[0] == nomUser:
            print("[ERREUR] Le nom existe deja ! ")
            return -1  #oui cest degue mais si quelque veux faire le projet qu'il le fasse

        if ligne == "[PUB]\n":
            pub = 1
            sec = 0

        if ligne == "[SEC]\n":
            pub = 0
            sec = 1

        if ligne == "[/PUB]\n" and pub == 1:
            toWrite = toWrite + nomUser + ":DSA-Ed25519-SHA-512:" + ed25519.publickey(
                user).encode('hex') + "\n"
            pub = 0
            toWrite = toWrite + ligne
        elif ligne == "[/SEC]\n" and sec == 1:
            toWrite = toWrite + nomUser + ":DSA-Ed25519-SHA-512:" + user.encode(
                'hex') + "\n"
            sec = 0
            toWrite = toWrite + ligne
        else:
            toWrite = toWrite + ligne
    fichier.close()
    fichier = open("keystore", "w")
    fichier.write(toWrite)
    fichier.close()
    return
示例#16
0
# should produce no output: python sign.py < sign.input

# warning: currently 37 seconds/line on a fast machine

# 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.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.checkvalid(s,forgedm,pk)
    forgedsuccess = 1
  except:
    pass
  assert not forgedsuccess
示例#17
0
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()
示例#18
0
def HexSigningPubKey(s):
  return binascii.hexlify(ed25519.publickey(ed25519.encodeint(MiniNero.hexToInt(s))))
示例#19
0
def Signature(m, sk):
  sk2 = ed25519.encodeint(MiniNero.hexToInt(sk))
  pk = ed25519.publickey(sk2)
  return binascii.hexlify(ed25519.signature(m, sk2, pk))
示例#20
0
文件: XMR.py 项目: lapwat/cryptowall
# generate random private spend key
r = random.SystemRandom()
hex = '0123456789abcdef'
private_spend_key = ''.join([r.choice(hex) for _ in range(64)])
private_spend_key = unhexlify(private_spend_key)

# reduce private spend key
private_spend_key = sc_reduce32(private_spend_key)

# compute and reduce private view key
private_view_key = keccak(private_spend_key)
private_view_key = sc_reduce32(private_view_key)

# compute public keys
public_spend_key = publickey(private_spend_key)
public_view_key = publickey(private_view_key)

# compute address
bytes65 = unhexlify(b'12') + public_spend_key + public_view_key
cs = checksum(bytes65)
bytes69 = bytes65 + cs
address = b''
for i in range(0, 64, 8):
    block = bytes69[i:i + 8]
    address += base58.b58encode(block).rjust(11, b'1')
last_block = bytes69[64:69]
address += base58.b58encode(last_block).rjust(7, b'1')

# convert from bytes to hex
private_spend_key = hexlify(private_spend_key)
示例#21
0
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)
示例#22
0
 def verify_key(self):
     return ed25519.publickey(self)
示例#23
0
def Signature(m, sk):
  #note this seems to return nicely sized version of the signature
  #contrast with, i.e. tweetnacl..
  sk2 = ed25519.encodeint(MiniNero.hexToInt(sk))
  pk = ed25519.publickey(sk2)
  return binascii.hexlify(ed25519.signature(m, sk2, pk))
示例#24
0
def ed25519_key_pair():
  secret_key = ''.join(chr(randint(0, 255)) for _ in range(0,32))
  public_key = ed25519.publickey(secret_key)
  return (secret_key, public_key)
示例#25
0
 def sign(self, msg, key):
     pk = ed25519.publickey(key)
     return ed25519.signature(msg, key, pk)
示例#26
0
def genPkBrut(id):
    sk = getkey(id, 'sec')
    pk = ed25519.publickey(sk)
    return pk
示例#27
0
output_fn = sys.argv[1]
privkey_fn = sys.argv[2]
vmlinuz_fn = sys.argv[3]
cmdline_fn = sys.argv[4]
initrd_fns = sys.argv[5:]


def read_file(fn):
    with open(fn, 'rb') as f:
        return f.read()


vmlinuz_data = read_file(vmlinuz_fn)
cmdline_data = read_file(cmdline_fn)
initrd_datas = [read_file(fn) for fn in initrd_fns]

buf = bytearray(
    struct.pack("=3Q", len(vmlinuz_data), sum(map(len, initrd_datas)),
                len(cmdline_data)))
buf += vmlinuz_data
for initrd_data in initrd_datas:
    buf += initrd_data
buf += cmdline_data

privkey = read_file(privkey_fn)
buf += ed25519.signature(buf, privkey, ed25519.publickey(privkey))

with open(output_fn, 'wb') as f:
    f.write(buf)
示例#28
0
# warning: currently 37 seconds/line on a fast machine

# 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])
    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
示例#29
0
def make_ed25519_keypair(urandom=os.urandom):
    sk = urandom(32)
    return sk, ed25519.publickey(sk)
示例#30
0
文件: profile.py 项目: Ivoz/ed25519
profile.py [case] [loops]

Run profiling of ed25519 functions

case - must be one of:
       pub -- generating a public key
       sig -- generating a signature
       val -- validating a signature

loop - how many times to repeat test
"""

seed = os.urandom(32)
data = b"The quick brown fox jumps over the lazy dog"
private_key = seed
public_key = ed25519.publickey(seed)
signature = ed25519.signature(data, private_key, public_key)

gen_public_key = 'ed25519.publickey(seed)'
gen_signature = 'ed25519.signature(data, private_key, public_key)'
do_validation = 'ed25519.checkvalid(signature, data, public_key)'

case = {
    'pub': gen_public_key,
    'sig': gen_signature,
    'val': do_validation,
}

length = 300
choice = ''
示例#31
0
def HexSigningPubKey(s):
  return binascii.hexlify(ed25519.publickey(ed25519.encodeint(MiniNero.hexToInt(s))))
def Signature(m, sk):
    sk2 = ed25519.encodeint(MiniNero.hexToInt(sk))
    pk = ed25519.publickey(sk2)
    return binascii.hexlify(ed25519.signature(m, sk2, pk))
示例#33
0
文件: test.py 项目: zeroegg/roll_up
    R_x = []
    R_y = []
    S = []
    old_leaf = []
    new_leaf = []
    rhs_leaf = []  # Message
    address = []
    public_key = []
    sk = []
    fee = 0

    # Generate random private key
    sk.append(genSalt(64))

    # Public key from private key
    public_key.append(ed.publickey(sk[0]))

    # Empty right handside of first leaf
    rhs_leaf.append(hashPadded("0" * 64, "0" * 64)[2:])

    # Iterate over transactions on the merkle tree
    for j in range(1, noTx + 1):

        leaves.append([])

        # create a random pub key from priv key
        sk.append(genSalt(64))
        public_key.append(ed.publickey(sk[j]))

        # create a random new leaf
        # This is just a filler message for test purpose (e.g. 11111111... , 22222211111...)
示例#34
0
def Signature(m, sk):
  #note this seems to return nicely sized version of the signature
  #contrast with, i.e. tweetnacl..
  sk2 = ed25519.encodeint(MiniNero.hexToInt(sk))
  pk = ed25519.publickey(sk2)
  return binascii.hexlify(ed25519.signature(m, sk2, pk))
示例#35
0
def make_ed25519_keypair(urandom=os.urandom):
    sk = urandom(32)
    return sk, ed25519.publickey(sk)
示例#36
0
def gen_key():
    sk = os.urandom(32)
    pk = ed25519.publickey(sk)
    print 'sk', [ord(c) for c in sk]
    print 'pk', [ord(c) for c in pk]
示例#37
0
文件: Sign.py 项目: yunsite/rippled
def make_ed25519_keypair(urandom=os.urandom):
    private_key = urandom(32)
    return private_key, ed25519.publickey(private_key)
示例#38
0
def ed25519_key_pair():
    secret_key = ''.join(chr(randint(0, 255)) for _ in range(0, 32))
    public_key = ed25519.publickey(secret_key)
    return (secret_key, public_key)
示例#39
0
def make_ed25519_keypair(urandom=os.urandom):
    private_key = urandom(32)
    return private_key, ed25519.publickey(private_key)
示例#40
0
文件: createfw.py 项目: iqyx/plumcore
fw_signature = ""
if args.signfile:

    if not args.check:
        print "Firmware check hash required for signing, use --check"
        exit(1)

    priv_key = ""
    try:
        with open(args.signfile, "r") as f:
            priv_key = f.read()
    except:
        print "Cannot read key file '%s'" % args.signfile
        exit(1)

    pub_key = ed25519.publickey(priv_key)

    fw_signature = ed25519.signature(fw_hash, priv_key, pub_key)
    fw_verification += build_section(section_magic.ed25519, fw_signature)

    # Append pubkey fingerprint.
    pub_key_fp = hashlib.sha512(pub_key).digest()
    pub_key_fp = pub_key_fp[:4]
    fw_verification += build_section(section_magic.fp, pub_key_fp)

# This variable contains full firmware image with all required parts
# Verified and verification sections are always present. Verification
# section can be empty.
fw_image = build_section(section_magic.verified, fw_verified) + build_section(
    section_magic.verification, fw_verification)