def test_ed25519_unsupported(backend): with raises_unsupported_algorithm( _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM): Ed25519PublicKey.from_public_bytes(b"0" * 32) with raises_unsupported_algorithm( _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM): Ed25519PrivateKey.from_private_bytes(b"0" * 32) with raises_unsupported_algorithm( _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM): Ed25519PrivateKey.generate()
def test_ed25519_unsupported(backend): with raises_unsupported_algorithm( _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM ): Ed25519PublicKey.from_public_bytes(b"0" * 32) with raises_unsupported_algorithm( _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM ): Ed25519PrivateKey.from_private_bytes(b"0" * 32) with raises_unsupported_algorithm( _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM ): Ed25519PrivateKey.generate()
def key_decrypt_prompt(key_file, retries=3): """ Try open an PEM encrypted private key, prompting the user for a passphrase if required. """ key_passphrase = None with open(key_file, 'rb') as handle: pem_key = handle.read() hsv3_tag = b"== ed25519v1-secret: type0 ==" if pem_key.startswith(hsv3_tag): return Ed25519PrivateKey.from_private_bytes(pem_key[32:64]) pem_key = pem_key.decode('utf-8') for retries in range(0, retries): if "Proc-Type: 4,ENCRYPTED" in pem_key: # Key looks encrypted key_passphrase = getpass.getpass( "Enter the password for the private key (%s): " % key_file) try: rsa_key = Crypto.PublicKey.RSA.importKey( pem_key, passphrase=key_passphrase) except ValueError: # Key not decrypted correctly, prompt for passphrase again continue else: # .. todo:: Check the loaded key size in a more reasonable way. if rsa_key.has_private() and rsa_key.size() in (1023, 1024): return rsa_key else: raise ValueError("The specified key was not a 1024 bit " "private key.") # No private key was imported raise ValueError("Could not import RSA key.")
def from_jwk(jwk): try: if isinstance(jwk, str): obj = json.loads(jwk) elif isinstance(jwk, dict): obj = jwk else: raise ValueError except ValueError: raise InvalidKeyError("Key is not valid JSON") if obj.get("kty") != "OKP": raise InvalidKeyError("Not an Octet Key Pair") curve = obj.get("crv") if curve != "Ed25519": raise InvalidKeyError(f"Invalid curve: {curve}") if "x" not in obj: raise InvalidKeyError('OKP should have "x" parameter') x = base64url_decode(obj.get("x")) try: if "d" not in obj: return Ed25519PublicKey.from_public_bytes(x) d = base64url_decode(obj.get("d")) return Ed25519PrivateKey.from_private_bytes(d) except ValueError as err: raise InvalidKeyError("Invalid key parameter") from err
def sign(self, to_be_signed: bytes, alg: Optional[CoseAlgorithms] = None, curve: CoseEllipticCurves = None) -> bytes: """ Computes a digital signature over 'to_be_signed'. The parameter 'alg' and 'curve' parameters are optional in case they are already provided by the key object self. :param to_be_signed: Data over which the signature is calculated. :param alg: An optional algorithm parameter. :param curve: An optional curve parameter. :return: the signature over the COSE object. """ self._check_key_conf(algorithm=alg, key_operation=KeyOps.SIGN, curve=curve) if self.crv == CoseEllipticCurves.ED25519: sk = Ed25519PrivateKey.from_private_bytes(self.d) elif self._crv == CoseEllipticCurves.ED448: sk = Ed448PrivateKey.from_private_bytes(self.d) else: raise CoseIllegalCurve( f"Illegal curve for OKP singing: {self.crv}") return sk.sign(to_be_signed)
def test_encode_example_jws(): example = "eyJhbGciOiJFZERTQSJ9.U2FtcGxlIHNpZ25lZCBwYXlsb2FkLg.dZvbycl2Jkl3H7NmQzL6P0_lDEW42s9FrZ8z-hXkLqYyxNq8yOlDjlP9wh3wyop5MU2sIOYvay-laBmpdW6OBQ" private_key = "bcbb56781ee4b7b7dc30f964d351a11a6a566131d8aa719165450def6013d4ae" key = Ed25519PrivateKey.from_private_bytes(bytes.fromhex(private_key)) msg = jws.encode("Sample signed payload.", key.sign) assert msg.decode("utf-8") == example
def register(self, account_name: str, private_key: typing.Union[Ed25519PrivateKey, str]): if isinstance(private_key, str): private_key = Ed25519PrivateKey.from_private_bytes( bytes.fromhex(private_key)) self._accounts[account_name] = private_key
def __init__(self, key: bytes): if not key: private = Ed25519PrivateKey.generate() else: private = Ed25519PrivateKey.from_private_bytes(key) self.private = private self.public: Ed25519PublicKey = self.private.public_key()
def load_private_key(self, prv_bytes): """ Load a private key into the instance. :param prv_bytes: The private key as *bytes*. :returns: True if the key was loaded, otherwise False. """ try: self.prv_bytes = prv_bytes[:Identity.KEYSIZE // 8 // 2] self.prv = X25519PrivateKey.from_private_bytes(self.prv_bytes) self.sig_prv_bytes = prv_bytes[Identity.KEYSIZE // 8 // 2:] self.sig_prv = Ed25519PrivateKey.from_private_bytes( self.sig_prv_bytes) self.pub = self.prv.public_key() self.pub_bytes = self.pub.public_bytes( encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw) self.sig_pub = self.sig_prv.public_key() self.sig_pub_bytes = self.sig_pub.public_bytes( encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw) self.update_hashes() return True except Exception as e: raise e RNS.log("Failed to load identity key", RNS.LOG_ERROR) RNS.log("The contained exception was: " + str(e), RNS.LOG_ERROR) return False
def test_buffer_protocol(self, backend): private_bytes = os.urandom(32) key = Ed25519PrivateKey.from_private_bytes(bytearray(private_bytes)) assert key.private_bytes( serialization.Encoding.Raw, serialization.PrivateFormat.Raw, serialization.NoEncryption() ) == private_bytes
def test_buffer_protocol(self, backend): private_bytes = os.urandom(32) key = Ed25519PrivateKey.from_private_bytes(bytearray(private_bytes)) assert (key.private_bytes( serialization.Encoding.Raw, serialization.PrivateFormat.Raw, serialization.NoEncryption(), ) == private_bytes)
def sign(cls, key: 'OKP', data: bytes) -> bytes: if key.crv.fullname == 'ED25519': sk = Ed25519PrivateKey.from_private_bytes(key.d) elif key.crv.fullname == 'ED448': sk = Ed448PrivateKey.from_private_bytes(key.d) else: raise CoseException(f"Illegal curve for OKP singing: {key.crv}") return sk.sign(data)
def loadKey(self, data): self.private_key = Ed25519PrivateKey.from_private_bytes( bytes.fromhex(data['private_key'])) self.public_key_bytes = bytes.fromhex(data['public_key']) self.public_key = Ed25519PublicKey.from_public_bytes( self.public_key_bytes) self.nid = bytes.fromhex(data['myNID']) self.rsa_private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
def get_test_account(): private_key = Ed25519PrivateKey.from_private_bytes( to_bytes(PRIVATE_TEST_KEY)) public_key = private_key.public_key() public_key_bytes = public_key.public_bytes( encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw) public_address = remove_0x_prefix(to_hex(public_key_bytes)) assert (public_address == PUBLIC_ADDRESS) return private_key, public_address
def loadKey(data): private_bytes = data['private'] private_key = Ed25519PrivateKey.from_private_bytes( bytes.fromhex(data['private'])) public_bytes = data['public'] public_key = Ed25519PublicKey.from_public_bytes( bytes.fromhex(data['public'])) nid = data['nid'] print('私钥', private_bytes) print('公钥', public_bytes) print('nid ', nid) return private_key, public_key, nid
def test_sign_verify_input(self, vector, backend): sk = binascii.unhexlify(vector["secret_key"]) pk = binascii.unhexlify(vector["public_key"]) message = binascii.unhexlify(vector["message"]) signature = binascii.unhexlify(vector["signature"]) private_key = Ed25519PrivateKey.from_private_bytes(sk) computed_sig = private_key.sign(message) assert computed_sig == signature public_key = private_key.public_key() assert (public_key.public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw) == pk) public_key.verify(signature, message)
def test_sign_verify_input(self, vector, backend): sk = binascii.unhexlify(vector["secret_key"]) pk = binascii.unhexlify(vector["public_key"]) message = binascii.unhexlify(vector["message"]) signature = binascii.unhexlify(vector["signature"]) private_key = Ed25519PrivateKey.from_private_bytes(sk) computed_sig = private_key.sign(message) assert computed_sig == signature public_key = private_key.public_key() assert public_key.public_bytes( serialization.Encoding.Raw, serialization.PublicFormat.Raw ) == pk public_key.verify(signature, message)
def from_dict(dic: Dict[str, str]) -> "LocalAccount": """from a dict that is created by LocalAccount#to_dict The private_key and compliance_key values are hex-encoded bytes; they will be loaded by `Ed25519PrivateKey.from_private_bytes`. """ dic = copy(dic) for name in ["private_key", "compliance_key"]: if name not in dic: continue key = dic[name] dic[name] = Ed25519PrivateKey.from_private_bytes(bytes.fromhex(key)) return LocalAccount(**dic) # pyre-ignore
def ed25519_private_key_from_string(string): """Create an ed25519 private key from ``string``, which is a seed. Args: string (str): the string to use as a seed. Returns: Ed25519PrivateKey: the private key """ try: return Ed25519PrivateKey.from_private_bytes(base64.b64decode(string)) except (UnsupportedAlgorithm, Base64Error) as exc: raise ScriptWorkerEd25519Error("Can't create Ed25519PrivateKey: {}!".format(str(exc)))
def signing_keypair_from_string(private_key_bytes): """ Load a signing keypair from a string of bytes (which includes the PRIVATE_KEY_PREFIX) :returns: a 2-tuple of (private_key, public_key) """ if not isinstance(private_key_bytes, six.binary_type): raise ValueError('private_key_bytes must be bytes') private_key = Ed25519PrivateKey.from_private_bytes( a2b(remove_prefix(private_key_bytes, PRIVATE_KEY_PREFIX))) return private_key, private_key.public_key()
def import_from_bytes(value): """ Import an keypair from a private key in bytes. :returns: KeyPair object with the private/public key :rtype: KeyPair .. code-block:: python >>> # create an KeyPair object from a raw private key >>> key_pair = KeyPair.import_from_bytes(0x0x973f69bcd654b26475917072...) """ return KeyPair(Ed25519PrivateKey.from_private_bytes(value))
def ed25519_private_key_from_string(string): """Create an ed25519 private key from ``string``, which is a seed. Args: string (str): the string to use as a seed. Returns: Ed25519PrivateKey: the private key """ try: return Ed25519PrivateKey.from_private_bytes( base64.b64decode(string) ) except (UnsupportedAlgorithm, Base64Error) as exc: raise ScriptWorkerEd25519Error("Can't create Ed25519PrivateKey: {}!".format(str(exc)))
def test_blinding(self): """ Create a descriptor with key blinding. """ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey expected_blinded_key = b'\xb5\xefEA\xfaI\x1a\xd8*p\xcd\x97\x01\x90O\xa8p\xd3\x10\x16\x8e-\x19\xab+\x92\xbc\xf6\xe7\x92\xc2k' desc = HiddenServiceDescriptorV3.create( identity_key = Ed25519PrivateKey.from_private_bytes(b'a' * 32), blinding_nonce = b'a' * 32, ) self.assertEqual(64, len(desc.signing_cert.signature)) self.assertEqual(expected_blinded_key, desc.signing_cert.signing_key())
def generate_keys(seed): """Generate server encryption keys from seed.""" signing_key = Ed25519PrivateKey.from_private_bytes(seed) verify_private = X25519PrivateKey.from_private_bytes(seed) return ServerKeys( sign=signing_key, auth=signing_key.private_bytes( encoding=serialization.Encoding.Raw, format=serialization.PrivateFormat.Raw, encryption_algorithm=serialization.NoEncryption(), ), auth_pub=signing_key.public_key().public_bytes( encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw), verify=verify_private, verify_pub=verify_private.public_key(), )
def initialize(self): """Initialize operation by generating new keys.""" self._signing_key = Ed25519PrivateKey.from_private_bytes(os.urandom(32)) self._auth_private = self._signing_key.private_bytes( encoding=serialization.Encoding.Raw, format=serialization.PrivateFormat.Raw, encryption_algorithm=serialization.NoEncryption(), ) self._auth_public = self._signing_key.public_key().public_bytes( encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw ) self._verify_private = X25519PrivateKey.from_private_bytes(os.urandom(32)) self._verify_public = self._verify_private.public_key() self._public_bytes = self._verify_public.public_bytes( encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw ) return self._auth_public, self._public_bytes
def initialize(self): """Initialize handler operation.""" signing_key = Ed25519PrivateKey.from_private_bytes(self.credentials.seed) verifying_key = signing_key.public_key() self._auth_private = signing_key.private_bytes( encoding=serialization.Encoding.Raw, format=serialization.PrivateFormat.Raw, encryption_algorithm=serialization.NoEncryption(), ) self._auth_public = verifying_key.public_bytes( encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw ) log_binary( _LOGGER, "Authentication keys", Private=self._auth_private, Public=self._auth_public, )
def createUNL(validators_names_list: list, validator_gen_keys: dict, version: int, keys_path: str): """Creates a properly signed UNL that contains only the validators in the validators_names_list Arguments: validators_names_list {list} -- [description] master_keys {dict} -- [description] ephemeral_keys {dict} -- [description] version {int} -- [description] keys_path {str} -- the root path for the validators keys """ munl = {} mblob_data = {} mblob_data['validators'] = createValidatorsList(validators_names_list, keys_path) mblob_data['sequence'] = version td = time.mktime(time.strptime("19710101000000", "%Y%m%d%H%M%S")) ripple_epoch = time.mktime(time.strptime("20000101000000", "%Y%m%d%H%M%S")) mblob_data['expiration'] = time.time() + td - ripple_epoch # print(mblob_data, type(mblob_data)) mblob_bin = base64.b64encode(json.dumps(mblob_data).encode('ascii')) munl['blob'] = mblob_bin.decode('ascii') # mSecK=Ed25519PrivateKey.from_private_bytes(base58ToBytes(validator_gen_keys['secret_key'])) # mPubK=Ed25519PublicKey.from_public_bytes(base58ToBytes(validator_gen_keys['public_key'])) # man_master_signature=mSecK.sign(munl['blob'])#createManifestForSigning(sequence,public_key,signing_public_key)) # munl['signature']=mSecK.sign(munl['blob']) signing_public_key = decodeManifest( validator_gen_keys['manifest'])['signing_public_key'] mSignK = Ed25519PrivateKey.from_private_bytes( binascii.unhexlify(validator_gen_keys['validation_secret_key'])) # base58ToBytes(binascii.unhexlify(validator_gen_keys['validation_secret_key']))) # mSignPubK=Ed25519PublicKey.from_public_bytes(base58ToBytes(signing_public_key)) # man_signature=mSignK.sign(munl)#createManifestForSigning(sequence,public_key,signing_public_key)) munl['signature'] = binascii.hexlify( mSignK.sign(mblob_bin)).decode('ascii') munl['manifest'] = validator_gen_keys['manifest'] munl['version'] = 1 munl['public_key'] = validator_gen_keys['public_key'].decode('ascii') return munl
def verify1(self, credentials, session_pub_key, encrypted): """First verification step.""" self._shared = self._verify_private.exchange( X25519PublicKey.from_public_bytes(session_pub_key) ) session_key = hkdf_expand( "Pair-Verify-Encrypt-Salt", "Pair-Verify-Encrypt-Info", self._shared ) chacha = chacha20.Chacha20Cipher(session_key, session_key) decrypted_tlv = hap_tlv8.read_tlv( chacha.decrypt(encrypted, nounce="PV-Msg02".encode()) ) identifier = decrypted_tlv[TlvValue.Identifier] signature = decrypted_tlv[TlvValue.Signature] if identifier != credentials.atv_id: raise exceptions.AuthenticationError("incorrect device response") info = session_pub_key + bytes(identifier) + self._public_bytes ltpk = Ed25519PublicKey.from_public_bytes(bytes(credentials.ltpk)) try: ltpk.verify(bytes(signature), bytes(info)) except InvalidSignature as ex: raise exceptions.AuthenticationError("signature error") from ex device_info = self._public_bytes + credentials.client_id + session_pub_key device_signature = Ed25519PrivateKey.from_private_bytes(credentials.ltsk).sign( device_info ) tlv = hap_tlv8.write_tlv( { TlvValue.Identifier: credentials.client_id, TlvValue.Signature: device_signature, } ) return chacha.encrypt(tlv, nounce="PV-Msg03".encode())
def test_sign_verify_input(self, backend, subtests): vectors = load_vectors_from_file( os.path.join("asymmetric", "Ed25519", "sign.input"), load_ed25519_vectors, ) for vector in vectors: with subtests.test(): sk = binascii.unhexlify(vector["secret_key"]) pk = binascii.unhexlify(vector["public_key"]) message = binascii.unhexlify(vector["message"]) signature = binascii.unhexlify(vector["signature"]) private_key = Ed25519PrivateKey.from_private_bytes(sk) computed_sig = private_key.sign(message) assert computed_sig == signature public_key = private_key.public_key() assert (public_key.public_bytes( serialization.Encoding.Raw, serialization.PublicFormat.Raw, ) == pk) public_key.verify(signature, message)
def import_from_mnemonic(words): """ Creates a new KeyPair object using a list of words. These words contain the private key and must be kept secret. :param str words: List of mnemonic words to read :returns: KeyPair object with the public/private key :rtype: KeyPair .. code-block:: python >>> # create an KeyPair object from a mnemonic word list >>> key_pair = KeyPair.import_from_text('my word list that is the private key ..', 42) """ mnemonic = Mnemonic('english') value = mnemonic.to_entropy(words) return KeyPair(Ed25519PrivateKey.from_private_bytes(value))
def verify2(self, atv_public_key, data): """Last device verification step.""" log_binary(_LOGGER, "Verify", PublicSecret=atv_public_key, Data=data) # Generate a shared secret key shared = self._verify_private.exchange( X25519PublicKey.from_public_bytes(atv_public_key)) log_binary(_LOGGER, "Shared secret", Secret=shared) # Derive new AES key and IV from shared key aes_key = hash_sha512("Pair-Verify-AES-Key", shared)[0:16] aes_iv = hash_sha512("Pair-Verify-AES-IV", shared)[0:16] log_binary(_LOGGER, "Pair-Verify-AES", Key=aes_key, IV=aes_iv) # Sign public keys and encrypt with AES signer = Ed25519PrivateKey.from_private_bytes(self._auth_private) signed = signer.sign(self._public_bytes + atv_public_key) signature, _ = aes_encrypt(modes.CTR, aes_key, aes_iv, data, signed) log_binary(_LOGGER, "Signature", Signature=signature) # Signature is prepended with 0x00000000 (alignment?) return b"\x00\x00\x00\x00" + signature
def authenticate(self, password: bytes): """ Decrypt the secret keys and test if it is identical to identity. :param password The password used to encrypt the keys. :return A tuple containing an X25519PrivateKey and an Ed25519PrivateKey, or None if the results does not match. """ # Attempt to decrypt signature key session = _gen_login_key(password, self.identity) context = Cipher(algorithms.ChaCha20(session, self.sign_iv), None, default_backend()).decryptor() sign = context.update(self.sign_priv) + context.finalize() # Verification identity = blake2b(sign).digest() if identity != self.identity: return None # Decrypt the encryption key context = Cipher(algorithms.ChaCha20(session, self.xchg_iv), None, default_backend()).decryptor() xchg = context.update(self.xchg_priv) + context.finalize() return (Ed25519PrivateKey.from_private_bytes(sign), X25519PrivateKey.from_private_bytes(xchg))
def initialize(self, seed=None): """Initialize handler operation. This method will generate new encryption keys and must be called prior to doing authentication or verification. """ self.seed = seed or os.urandom(32) # Generate new seed if not provided signing_key = Ed25519PrivateKey.from_private_bytes(self.seed) verifying_key = signing_key.public_key() self._auth_private = signing_key.private_bytes( encoding=serialization.Encoding.Raw, format=serialization.PrivateFormat.Raw, encryption_algorithm=serialization.NoEncryption(), ) self._auth_public = verifying_key.public_bytes( encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw) log_binary( _LOGGER, "Authentication keys", Private=self._auth_private, Public=self._auth_public, )
def private_load_enc(self): return str(Ed25519PrivateKey.from_private_bytes(self.privateKey_gen()))
def test_invalid_length_from_private_bytes(self, backend): with pytest.raises(ValueError): Ed25519PrivateKey.from_private_bytes(b"a" * 31) with pytest.raises(ValueError): Ed25519PrivateKey.from_private_bytes(b"a" * 33)
def test_invalid_type_private_bytes(self, backend): with pytest.raises(TypeError): Ed25519PrivateKey.from_private_bytes(object())
def private_key_from_string(key_str): """Create an Ed25519PrivateKey from a base64-encoded string.""" return Ed25519PrivateKey.from_private_bytes( base64.b64decode(key_str) )