Generate Keypair

The Keypair object represents a key pair used to sign transactions in a Stellar network. The Keypair object can contain both a public and a private key, or only a public key.

If a Keypair object does not contain a private key it can’t be used to sign transactions. The most convenient method of creating a new keypair is by passing the account’s secret seed:

1from stellar_sdk import Keypair
2
3secret = "SBK2VIYYSVG76E7VC3QHYARNFLY2EAQXDHRC7BMXBBGIFG74ARPRMNQM"
4keypair = Keypair.from_secret(secret)
5
6# GDHMW6QZOL73SHKG2JA3YHXFDHM46SS5ZRWEYF5BCYHX2C5TVO6KZBYL
7public_key = keypair.public_key
8
9can_sign = keypair.can_sign()  # True

You can create a keypair from public key, but its function is limited:

1from stellar_sdk import Keypair
2
3public_key = "GDHMW6QZOL73SHKG2JA3YHXFDHM46SS5ZRWEYF5BCYHX2C5TVO6KZBYL"
4keypair = Keypair.from_public_key(public_key)
5can_sign = keypair.can_sign()  # False

You can create a randomly generated keypair:

1from stellar_sdk import Keypair
2
3keypair = Keypair.random()
4print("Public Key: " + keypair.public_key)
5print("Secret Seed: " + keypair.secret)

Vou can also generate a mnemonic phrase and later use it to generate a keypair:

1from stellar_sdk import Keypair
2
3mnemonic_phrase = Keypair.generate_mnemonic_phrase()
4print(f"Mnemonic phrase: {mnemonic_phrase}")
5keypair = Keypair.from_mnemonic_phrase(mnemonic_phrase)
6print(f"Public Key: {keypair.public_key}")
7print(f"Secret Seed: {keypair.secret}")

Lastly, you can also use the Shamir secret sharing method to split a mnemonic phrase into multiple phrases. In the following example, we need exactly 2 phrases in order to reconstruct the secret:

1from stellar_sdk import Keypair
2
3mnemonic_phrases = Keypair.generate_shamir_mnemonic_phrases(member_threshold=2, member_count=3)
4print(f"Mnemonic phrases: {mnemonic_phrases}")
5keypair = Keypair.from_shamir_mnemonic_phrases(mnemonic_phrases[:2])  # any combinations
6print(f"Public Key: {keypair.public_key}")
7print(f"Secret Seed: {keypair.secret}")

If you want to convert an existing mnemonic phrase to Shamir, you need to get the corresponding entropy. You can use these lower level functions:

 1import shamir_mnemonic
 2from stellar_sdk.sep.mnemonic import StellarMnemonic
 3
 4seed_raw = StellarMnemonic("english").to_entropy(mnemonic)
 5mnemonic_phrases = shamir_mnemonic.generate_mnemonics(
 6    group_threshold=1,
 7    groups=[(2, 3)],
 8    master_secret=seed_raw,
 9    passphrase=passphrase.encode(),
10)[0]
11print(f"Mnemonic phrases: {mnemonic_phrases}")