def test_outer_layer_creation(self): """ Outer layer creation. """ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey # minimal layer self.assertTrue(OuterLayer.content().startswith(b'desc-auth-type x25519\ndesc-auth-ephemeral-key ')) self.assertEqual('x25519', OuterLayer.create().auth_type) # specify the parameters desc = OuterLayer.create({ 'desc-auth-type': 'foo', 'desc-auth-ephemeral-key': 'bar', 'auth-client': [ 'JNil86N07AA epkaL79NtajmgME/egi8oA qosYH4rXisxda3X7p9b6fw', '1D8VBAh9hdM 6K/uO3sRqBp6URrKC7GB6Q ElwRj5+6SN9kb8bRhiiQvA', ], 'encrypted': '\n-----BEGIN MESSAGE-----\nmalformed block\n-----END MESSAGE-----', }) self.assertEqual('foo', desc.auth_type) self.assertEqual('bar', desc.ephemeral_key) self.assertEqual('-----BEGIN MESSAGE-----\nmalformed block\n-----END MESSAGE-----', desc.encrypted) self.assertEqual({ '1D8VBAh9hdM': AuthorizedClient(id = b'1D8VBAh9hdM', iv = b'6K/uO3sRqBp6URrKC7GB6Q', cookie = b'ElwRj5+6SN9kb8bRhiiQvA'), 'JNil86N07AA': AuthorizedClient(id = b'JNil86N07AA', iv = b'epkaL79NtajmgME/egi8oA', cookie = b'qosYH4rXisxda3X7p9b6fw'), }, desc.clients) self.assertEqual(EXPECTED_OUTER_LAYER, str(desc)) # create an inner layer then decrypt it revision_counter = 5 blinded_key = stem.util._pubkey_bytes(Ed25519PrivateKey.generate()) subcredential = HiddenServiceDescriptorV3._subcredential(Ed25519PrivateKey.generate(), blinded_key) outer_layer = OuterLayer.create( inner_layer = InnerLayer.create( introduction_points = [ IntroductionPointV3.create_for_address('1.1.1.1', 9001), ] ), revision_counter = revision_counter, subcredential = subcredential, blinded_key = blinded_key, ) inner_layer = InnerLayer._decrypt(outer_layer, revision_counter, subcredential, blinded_key) self.assertEqual(1, len(inner_layer.introduction_points)) self.assertEqual('1.1.1.1', inner_layer.introduction_points[0].link_specifiers[0].address)
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 generate(self) -> None: """ Generate an Ed25519 private key :returns: Ed25519PrivateKey """ self.secret = Ed25519PrivateKey.generate()
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 test_load_public_bytes(self, backend): public_key = Ed25519PrivateKey.generate().public_key() public_bytes = public_key.public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw) public_key2 = Ed25519PublicKey.from_public_bytes(public_bytes) assert public_bytes == public_key2.public_bytes( serialization.Encoding.Raw, serialization.PublicFormat.Raw)
def generate_private_key( options: dict ) -> typing.Union[str, ed25519.Ed25519PrivateKey, ed448.Ed448PrivateKey, rsa.RSAPrivateKey, dsa.DSAPrivateKey, ec.EllipticCurvePrivateKey, ]: # We should make sure to return in PEM format # Reason for using PKCS8 # https://stackoverflow.com/questions/48958304/pkcs1-and-pkcs8-format-for-rsa-private-key if options.get('type') == 'EC': if options['curve'] == 'ed25519': key = Ed25519PrivateKey.generate() else: key = ec.generate_private_key(getattr(ec, options.get('curve')), default_backend()) else: key = rsa.generate_private_key(public_exponent=65537, key_size=options.get('key_length'), backend=default_backend()) if options.get('serialize'): return key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption()).decode() else: return key
def create_keys(self): self.prv = X25519PrivateKey.generate() self.prv_bytes = self.prv.private_bytes( encoding=serialization.Encoding.Raw, format=serialization.PrivateFormat.Raw, encryption_algorithm=serialization.NoEncryption()) self.sig_prv = Ed25519PrivateKey.generate() self.sig_prv_bytes = self.sig_prv.private_bytes( encoding=serialization.Encoding.Raw, format=serialization.PrivateFormat.Raw, encryption_algorithm=serialization.NoEncryption()) 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() RNS.log("Identity keys created for " + RNS.prettyhexrep(self.hash), RNS.LOG_VERBOSE)
def main(): # connect to testnet client = testnet.create_client() # generate private key private_key = Ed25519PrivateKey.generate() # generate auth key auth_key = AuthKey.from_public_key(private_key.public_key()) print( f"Generated address: {utils.account_address_hex(auth_key.account_address())}" ) # create new account faucet = testnet.Faucet(client) testnet.Faucet.mint(faucet, auth_key.hex(), 100_000_000, CURRENCY) # get account events key account = client.get_account(auth_key.account_address()) events_key = account.received_events_key # start minter to demonstrates events creation start_minter(client, auth_key) # demonstrates events subscription subscribe(client, events_key)
def register(cls, password: bytes): """ Generate a new account. :param password The password for encrypting the keys. :return a Registration. """ reg = cls() # gen signature keypair sign_object = Ed25519PrivateKey.generate() reg.sign_pub = sign_object.public_key().public_bytes( serialization.Encoding.Raw, serialization.PublicFormat.Raw) sign = sign_object.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.Raw, serialization.NoEncryption()) reg.sign_sig = sign_object.sign(sign) # the private signature key's hash become the account's ID reg.identity = blake2b(sign).digest() # gen encryption keypair xchg_object = X25519PrivateKey.generate() reg.xchg_pub = xchg_object.public_key().public_bytes( serialization.Encoding.Raw, serialization.PublicFormat.Raw) xchg = xchg_object.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.Raw, serialization.NoEncryption()) reg.xchg_sig = sign_object.sign(xchg) # encrypt the private keys reg.set_passwd(sign, xchg, password) return reg
def generate_private_ed25519() -> Ed25519PrivateKey: """ Creates and returns a new Ed25519PrivateKey Returns: Ed25519PrivateKey: Private key of type Ed25519privateKey. """ return Ed25519PrivateKey.generate()
def __init__(self, private_key=None): """ Create a new keypair object with a public and private key as a Ed25519PrivateKey. It is better to use one of the following static methods to create an KeyPair object: * :meth:`import_from_bytes` * :meth:`import_from_file` * :meth:`import_from_mnemonic` * :meth:`import_from_text` :param Ed25519PrivateKey private_key: The public/private key as an Ed25519PrivateKey object The Convex KeyPair class, contains the public/private keys. To re-use the KeyPair again, you can import the keys. **Note** For security reasons all of the keys and password text displayed below in the documentation are only truncated ending with a **`...`** .. code-block:: python >>> # import convex-api >>> from convex_api import ConvexAPI >>> # setup the network connection >>> convex_api = ConvexAPI('https://convex.world') """ if private_key is None: private_key = Ed25519PrivateKey.generate() self._private_key = private_key self._public_key = private_key.public_key()
def test_descriptor_creation(self): """ HiddenServiceDescriptorV3 creation. """ # minimal descriptor self.assertTrue(HiddenServiceDescriptorV3.content().startswith( b'hs-descriptor 3\ndescriptor-lifetime 180\n')) self.assertEqual(180, HiddenServiceDescriptorV3.create().lifetime) # specify the parameters desc = HiddenServiceDescriptorV3.create( { 'hs-descriptor': '4', 'descriptor-lifetime': '123', 'descriptor-signing-key-cert': '\n-----BEGIN ED25519 CERT-----\nmalformed block\n-----END ED25519 CERT-----', 'revision-counter': '5', 'superencrypted': '\n-----BEGIN MESSAGE-----\nmalformed block\n-----END MESSAGE-----', 'signature': 'abcde', }, validate=False) self.assertEqual(4, desc.version) self.assertEqual(123, desc.lifetime) self.assertEqual( None, desc.signing_cert ) # malformed cert dropped because validation is disabled self.assertEqual(5, desc.revision_counter) self.assertEqual( '-----BEGIN MESSAGE-----\nmalformed block\n-----END MESSAGE-----', desc.superencrypted) self.assertEqual('abcde', desc.signature) # include introduction points from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey identity_key = Ed25519PrivateKey.generate() onion_address = HiddenServiceDescriptorV3.address_from_identity_key( identity_key) desc = HiddenServiceDescriptorV3.create( identity_key=identity_key, inner_layer=InnerLayer.create(introduction_points=[ IntroductionPointV3.create_for_address('1.1.1.1', 9001), IntroductionPointV3.create_for_address('2.2.2.2', 9001), IntroductionPointV3.create_for_address('3.3.3.3', 9001), ]), ) inner_layer = desc.decrypt(onion_address) self.assertEqual(3, len(inner_layer.introduction_points)) self.assertEqual( '1.1.1.1', inner_layer.introduction_points[0].link_specifiers[0].address)
def generate(cls, keytype='rsa', size=None, passphrase=None): """Returns an Asymmetric_Keypair object generated with the supplied parameters or defaults to an unencrypted RSA-2048 key :keytype: One of rsa, dsa, ecdsa, ed25519 :size: The key length for newly generated keys :passphrase: Secret of type Bytes used to encrypt the private key being generated """ if keytype not in _ALGORITHM_PARAMETERS.keys(): raise InvalidKeyTypeError( "%s is not a valid keytype. Valid keytypes are %s" % ( keytype, ", ".join(_ALGORITHM_PARAMETERS.keys()) ) ) if not size: size = _ALGORITHM_PARAMETERS[keytype]['default_size'] else: if size not in _ALGORITHM_PARAMETERS[keytype]['valid_sizes']: raise InvalidKeySizeError( "%s is not a valid key size for %s keys" % (size, keytype) ) if passphrase: encryption_algorithm = get_encryption_algorithm(passphrase) else: encryption_algorithm = serialization.NoEncryption() if keytype == 'rsa': privatekey = rsa.generate_private_key( # Public exponent should always be 65537 to prevent issues # if improper padding is used during signing public_exponent=65537, key_size=size, backend=backend, ) elif keytype == 'dsa': privatekey = dsa.generate_private_key( key_size=size, backend=backend, ) elif keytype == 'ed25519': privatekey = Ed25519PrivateKey.generate() elif keytype == 'ecdsa': privatekey = ec.generate_private_key( _ALGORITHM_PARAMETERS['ecdsa']['curves'][size], backend=backend, ) publickey = privatekey.public_key() return cls( keytype=keytype, size=size, privatekey=privatekey, publickey=publickey, encryption_algorithm=encryption_algorithm )
def create_signing_keypair(): """ Creates a new ed25519 keypair. :returns: 2-tuple of (private_key, public_key) """ private_key = Ed25519PrivateKey.generate() return private_key, private_key.public_key()
def test_invalid_signature(self, backend): key = Ed25519PrivateKey.generate() signature = key.sign(b"test data") with pytest.raises(InvalidSignature): key.public_key().verify(signature, b"wrong data") with pytest.raises(InvalidSignature): key.public_key().verify(b"0" * 64, b"test data")
def test_unsupported_key_type() -> None: key = Ed25519PrivateKey.generate() serialized_key = key.private_bytes( Encoding.PEM, PrivateFormat.PKCS8, NoEncryption() ) with pytest.raises(UnsupportedAlgorithm): RSAKeyPair.from_pem(serialized_key)
def test_invalid_signature(self, backend): key = Ed25519PrivateKey.generate() signature = key.sign(b"test data") with pytest.raises(InvalidSignature): key.public_key().verify(signature, b"wrong data") with pytest.raises(InvalidSignature): key.public_key().verify(b"0" * 64, b"test data")
def generate_test_keys(): private_key = Ed25519PrivateKey.generate() 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)) return private_key, public_address
def __init__(self): self.private_handshake_key = X25519PrivateKey.generate() self.public_handshake_key = self.private_handshake_key.public_key() self.private_key = Ed25519PrivateKey.generate() self.public_key = self.private_key.public_key() self.data = "data".encode('utf8')
def test_load_public_bytes(self, backend): public_key = Ed25519PrivateKey.generate().public_key() public_bytes = public_key.public_bytes( serialization.Encoding.Raw, serialization.PublicFormat.Raw ) public_key2 = Ed25519PublicKey.from_public_bytes(public_bytes) assert public_bytes == public_key2.public_bytes( serialization.Encoding.Raw, serialization.PublicFormat.Raw )
def _generate_keys(self): privkey = Ed25519PrivateKey.generate() pubkey = privkey.public_key() self.event.settings.ticket_secrets_pretix_sig1_privkey = base64.b64encode( privkey.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption())).decode() self.event.settings.ticket_secrets_pretix_sig1_pubkey = base64.b64encode( pubkey.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo)).decode()
def init_compliance_keys(self) -> jsonrpc.Transaction: self.compliance_key = Ed25519PrivateKey.generate() txn = self.create_transaction( self._parent_vasp, stdlib.encode_rotate_dual_attestation_info_script( new_url=b"http://helloworld.org", new_key=utils.public_key_bytes(self.compliance_key.public_key()) ), testnet.TEST_CURRENCY_CODE, ) return self.submit_and_wait(self._parent_vasp.sign(txn))
def create_private_key(private_key_filename='key.pem', passphrase=None): """ Create a new private key and store it in private_key_filename (defaults to 'key.pem', may be None for no file). Return public key """ private_key = PrivateKey.generate() if private_key_filename: write_private_key(private_key, private_key_filename, passphrase) return private_key
def main(): if len(sys.argv) != 2: print("usage: gen_key.py <secret filename>") sys.exit(1) pk = Ed25519PrivateKey.generate() pem = pk.private_bytes(encoding=Encoding.PEM, format=PrivateFormat.PKCS8, encryption_algorithm=NoEncryption()) with open(sys.argv[1], "wb") as f: f.write(pem)
def __init__(self, shop_id=None, priv_key=None): self._priv_key = priv_key if priv_key else Ed25519PrivateKey.generate() self._cup_signature = None self._signing_shop = Shop(shop_id) cup_id_digest = hashes.Hash(hashes.SHAKE128(16), backend=default_backend()) cup_id_digest.update( self.pub_key.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo)) self._cup_id: bytes = cup_id_digest.finalize()
def load_v3_master_key(self, master_key_path): if master_key_path: # load key from file return self._load_v3_master_key_from_file(master_key_path) else: # generate new v3 key master_private_key = Ed25519PrivateKey.generate() master_public_key = master_private_key.public_key() master_pub_key_bytes = master_public_key.public_bytes(encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw) master_onion_address = HiddenServiceDescriptorV3.address_from_identity_key(master_pub_key_bytes) # cut out the onion since that's what the rest of the code expects master_onion_address = master_onion_address.replace(".onion", "") return master_private_key, master_onion_address
def main(): # generate private key private_key = Ed25519PrivateKey.generate() # generate auth key auth_key = AuthKey.from_public_key(private_key.public_key()) print( f"Generated address: {utils.account_address_hex(auth_key.account_address())}" ) print(f"Auth Key (HEX): {auth_key.hex()}") print( f"Public key (HEX): {utils.public_key_bytes(private_key.public_key()).hex()}" )
def test_invalid_public_bytes(self, backend): key = Ed25519PrivateKey.generate().public_key() with pytest.raises(ValueError): key.public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.SubjectPublicKeyInfo) with pytest.raises(ValueError): key.public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.PKCS1) with pytest.raises(ValueError): key.public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.Raw)
def new_child_vasp( self, initial_balance: int, currency: str ) -> Tuple["LocalAccount", diem_types.TransactionPayload]: """Creates a new ChildVASP local account and script function""" child_vasp = replace(self, private_key=Ed25519PrivateKey.generate()) payload = stdlib.encode_create_child_vasp_account_script_function( coin_type=utils.currency_code(currency), child_address=child_vasp.account_address, auth_key_prefix=child_vasp.auth_key.prefix(), add_all_currencies=False, child_initial_balance=initial_balance, ) return (child_vasp, payload)
def test_invalid_private_bytes(self, backend): key = Ed25519PrivateKey.generate() with pytest.raises(ValueError): key.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.Raw, None) with pytest.raises(ValueError): key.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.PKCS8, None) with pytest.raises(ValueError): key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.Raw, serialization.NoEncryption())
def generate(index: int) -> typing.Tuple[LocalAccount, Config]: port = 5000 + index base_url = f"http://localhost:{port}/api/offchain" account = LocalAccount.generate() conf = Config( wallet_custody_account_name=f"wallet{index}", vasp_compliance_key=utils.private_key_bytes( Ed25519PrivateKey.generate()).hex(), vasp_address=account.account_address.to_hex(), base_url=base_url, json_rpc_url=testnet.JSON_RPC_URL, chain_id=testnet.CHAIN_ID.to_int(), gas_currency_code=testnet.TEST_CURRENCY_CODE, ) return (account, conf)
def test_cryptography_okp_public_key_ed25519(): ed25519_private_key = Ed25519PrivateKey.generate() ed25519_public_number = ed25519_private_key.public_key().public_bytes( Encoding.Raw, PublicFormat.Raw) okp_key = OKPCredentialPublicKey( kty=COSEKeyType.Value.OKP, crv=OKPKeyType.Value.ED25519, x=ed25519_public_number, ) converted_public_key = cryptography_okp_public_key(okp_key) converted_public_number = converted_public_key.public_bytes( Encoding.Raw, PublicFormat.Raw) assert ed25519_public_number == converted_public_number
def test_invalid_public_bytes(self, backend): key = Ed25519PrivateKey.generate().public_key() with pytest.raises(ValueError): key.public_bytes( serialization.Encoding.Raw, serialization.PublicFormat.SubjectPublicKeyInfo ) with pytest.raises(ValueError): key.public_bytes( serialization.Encoding.PEM, serialization.PublicFormat.PKCS1 ) with pytest.raises(ValueError): key.public_bytes( serialization.Encoding.PEM, serialization.PublicFormat.Raw )
def test_invalid_private_bytes(self, backend): key = Ed25519PrivateKey.generate() with pytest.raises(ValueError): key.private_bytes( serialization.Encoding.Raw, serialization.PrivateFormat.Raw, None ) with pytest.raises(ValueError): key.private_bytes( serialization.Encoding.Raw, serialization.PrivateFormat.PKCS8, None ) with pytest.raises(ValueError): key.private_bytes( serialization.Encoding.PEM, serialization.PrivateFormat.Raw, serialization.NoEncryption() )
def test_generate(self, backend): key = Ed25519PrivateKey.generate() assert key assert key.public_key()
)).decode('utf-8') def b64_from_public_key(key): """Get the base64 string from an Ed25519PublicKey.""" return base64.b64encode(key.public_bytes( encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw, )).decode('utf-8') prefix = "" if len(sys.argv) > 1: prefix = "{}_".format(sys.argv[1]) privkey = Ed25519PrivateKey.generate() pubkey = privkey.public_key() privkey_str = b64_from_private_key(privkey) pubkey_str = b64_from_public_key(pubkey) # test privkey2 = private_key_from_string(privkey_str) pubkey2 = public_key_from_string(pubkey_str) assert b64_from_private_key(privkey2) == privkey_str assert b64_from_public_key(pubkey2) == pubkey_str with open("{}private_key".format(prefix), "w") as fh: fh.write(privkey_str) with open("{}public_key".format(prefix), "w") as fh: fh.write(pubkey_str)
def test_round_trip_private_serialization(self, encoding, fmt, encryption, passwd, load_func, backend): key = Ed25519PrivateKey.generate() serialized = key.private_bytes(encoding, fmt, encryption) loaded_key = load_func(serialized, passwd, backend) assert isinstance(loaded_key, Ed25519PrivateKey)