Generate Bitcoin Address From Public Key Rating: 7,5/10 3573 votes

The process of generating a Bitcoin wallet address from a private key is not that difficult if you pay close attention to the aforementioned steps. If your private key is full or compressed, the resulting addresses will look different, but both of them are just as valid. Similarly, just like your house/flat number, anyone in the Bitcoin world can know your public address (Bitcoin address) to send you bitcoins. And to unlock (spend/send) those bitcoins, you would require your private address (or key) for which you need to take full responsibility, just like the keys of the mailbox. Generating a private key is only a first step. The next step is extracting a public key and a wallet address that you can use to receive payments. The process of generating a wallet differs for Bitcoin and Ethereum, and I plan to write two more articles on that topic. If you want to play with the code, I published it to this Github repository.

What is a Private Key?

Oct 31, 2015  libbtc – A fast, clean and small bitcoin C library. What is libbtc? Libbtc is a very portable C library for creating and manipulating bitcoin data structures and interacting with the p2p network. Current features. Generating and storing private and public keys; ECDSA secp256k1 signing and verification (through libsecp256k1 included as git. I'm writing simple code in C using OpenSSL to generate valid bitcoin address - private key pair. I'm using this snippet to generate public key from given hex-form private key: #include <stdi.

A private key is a secret 256-bit long number randomly selected when you create a Bitcoin wallet. This is the address which enables you to send the Bitcoins to a recipient’s address. You never share the private key to anyone.

The number and type of cryptographic functions implemented for security reasons defines just how random and unique the key is.

A private uncompressed key always begins with a 5 and it looks like this:

5Hwgr3u458GLafKBgxtssHSPqJnYoGrSzgQsPwLFhLNYskDPyyA

What is a Public Key?

A public key is another address consisting of numbers and letters which is a derivate from private keys after they have been encrypted via the use of mathematical functions. The encryption process cannot be reversed and thus no one can find out the original private key. This is the address that enables you to receive Bitcoins.

The hash of a public key is always 1:

1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2

This address you publicly make available in order to receive Bitcoins. There is no limit to how many public addresses a user can generate. In order to generate such a key and subsequently a wallet address, there have to be applied a number of conversions to the private key. These conversions are known as hash functions, which are un-reversible conversions.

Creating a Public Key with ECDSA

The first thing you have to do is apply to your private key an ECDSA, also know as Elliptic Curve Digital Signature Algorithm. An elliptic curve is defined by the equation y² = x³ + ax + b with selected value for a and b. There is an entire family of these curves which can be applied. Bitcoin makes use of the secp256k1 curve.

Applying an ECDSA to the private key will result in a 64-byte integer composed of two 32-byte integers put together which represent the X and Y of the point on the elliptic curve.

Below is the code you would require in Python language:

private_key_bytes = codecs.decode(private_key, ‘hex’)

# Get ECDSA public key

key = ecdsa.SigningKey.from_string(private_key_bytes, curve=ecdsa.SECP256k1).verifying_key

key_bytes = key.to_string()

key_hex = codecs.encode(key_bytes, ‘hex’)

In the code presented above the private keys were decoded with codecs. As in Python, there are at least two classes that can keep the private and public keys, “str”, a string array, and “bytes”- a byte array, things can get a little confusing.

This is because an X string array is not equal to an X byte array, but it equals the byte array with two elements, O<. The codecs.decode method converts a string into a byte array.

After applying ECDSA, we will have to add the bytes 0x04 (04 as a prefix) to the resulted public key. This will generate a Bitcoin full public key.

Compressing the public key

Instead of using the long version of the public key we can compress it to be shorter.

This is done by taking the X from the ECDSA public key and adding 0x02 if the last byte of Y is even, and the 0x03 byte if the last byte is odd.

Encrypting the Key with SHA-256 And RIPEMD-160

Now we move on to create our wallet address. Regardless of the method applied to the public key, the procedure is the same. Obviously, you will have different resulting addresses.

For this, we will need to apply two hash functions: first, we apply SHA-256 to the public key, and then encrypt the result using RIPEMD-160. It is very important that the algorithms are applied in this exact order.

At the end of this process, you will have a 160-bit integer which represents an encrypted public key.

Below is the code needed to encrypt the public key in Python:

public_key_bytes = codecs.decode(public_key, ‘hex’)

# Run SHA-256 for the public key

sha256_bpk = hashlib.sha256(public_key_bytes)

sha256_bpk_digest = sha256_bpk.digest()

# Run RIPEMD-160 for the SHA-256

ripemd160_bpk = hashlib.new(‘ripemd160’)

ripemd160_bpk.update(sha256_bpk_digest)

ripemd160_bpk_digest = ripemd160_bpk.digest()

ripemd160_bpk_hex = codecs.encode(ripemd160_bpk_digest, ‘hex’)

Adding the network byte

As Bitcoin has two networks, main and test, we will need to create an address which will be used on the mainnet. This means that we will have to add 0x00 bytes to the encrypted public key. For testnet use, you would have to add 0x6f bytes.

Calculating the Checksum

The next step is to calculate the checksum of the resulted mainnet key. A checksum ensures that the key has still maintained its integrity during the process. If the checksum does not match, the address will be marked as invalid.

In order to generate a key’s checksum, the SHA-256 hash function must be applied twice and then take the first 4 bytes from this result. Keep in mind that 4 bytes represent 8 hex digits.

The code required for calculating an address checksum is:

# Double SHA256 to get checksum

sha256_nbpk = hashlib.sha256(network_bitcoin_public_key_bytes)

sha256_nbpk_digest = sha256_nbpk.digest()

sha256_2_nbpk = hashlib.sha256(sha256_nbpk_digest)

sha256_2_nbpk_digest = sha256_2_nbpk.digest()

sha256_2_hex = codecs.encode(sha256_2_nbpk_digest, ‘hex’)

checksum = sha256_2_hex[:8]

Now the last step required to make an address is to merge the mainnet key and the checksum.

Encoding the Key with Base58

You will notice that the resulted key does not look like other BTC addresses. This is because most convert them to a Base58 address.

Below is the algorithm needed to convert a hex address to a Base58 address:

def base58(address_hex):

alphabet = ‘123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz’

b58_string = ‘’

# Get the number of leading zeros

leading_zeros = len(address_hex) — len(address_hex.lstrip(‘0’))

# Convert hex to decimal

address_int = int(address_hex, 16)

# Append digits to the start of string

while address_int > 0:

digit = address_int % 58

digit_char = alphabet[digit]

b58_string = digit_char + b58_string

address_int //= 58

# Add ‘1’ for each 2 leading zeros

ones = leading_zeros // 2

for one in range(ones):

b58_string = ‘1’ + b58_string

return b58_string

The resulted string will represent a compressed Bitcoin wallet address.

Conclusion

The process of generating a Bitcoin wallet address from a private key is not that difficult if you pay close attention to the aforementioned steps.

If your private key is full or compressed, the resulting addresses will look different, but both of them are just as valid.

In cryptocurrencies, a private key allows a user to gain access to their wallet. The person who holds the private key fully controls the coins in that wallet. For this reason, you should keep it secret. And if you really want to generate the key yourself, it makes sense to generate it in a secure way.

Here, I will provide an introduction to private keys and show you how you can generate your own key using various cryptographic functions. I will provide a description of the algorithm and the code in Python.

Do I need to generate a private key?

Most of the time you don’t. For example, if you use a web wallet like Coinbase or Blockchain.info, they create and manage the private key for you. It’s the same for exchanges.

Mobile and desktop wallets usually also generate a private key for you, although they might have the option to create a wallet from your own private key.

So why generate it anyway? Here are the reasons that I have:

  • You want to make sure that no one knows the key
  • You just want to learn more about cryptography and random number generation (RNG)

What exactly is a private key?

Formally, a private key for Bitcoin (and many other cryptocurrencies) is a series of 32 bytes. Now, there are many ways to record these bytes. It can be a string of 256 ones and zeros (32 * 8 = 256) or 100 dice rolls. It can be a binary string, Base64 string, a WIF key, mnemonic phrase, or finally, a hex string. For our purposes, we will use a 64 character long hex string.

Why exactly 32 bytes? Great question! You see, to create a public key from a private one, Bitcoin uses the ECDSA, or Elliptic Curve Digital Signature Algorithm. More specifically, it uses one particular curve called secp256k1.

Now, this curve has an order of 256 bits, takes 256 bits as input, and outputs 256-bit integers. And 256 bits is exactly 32 bytes. So, to put it another way, we need 32 bytes of data to feed to this curve algorithm.

There is an additional requirement for the private key. Because we use ECDSA, the key should be positive and should be less than the order of the curve. The order of secp256k1 is FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141, which is pretty big: almost any 32-byte number will be smaller than it.

Naive method

So, how do we generate a 32-byte integer? The first thing that comes to mind is to just use an RNG library in your language of choice. Python even provides a cute way of generating just enough bits:

Looks good, but actually, it’s not. You see, normal RNG libraries are not intended for cryptography, as they are not very secure. They generate numbers based on a seed, and by default, the seed is the current time. That way, if you know approximately when I generated the bits above, all you need to do is brute-force a few variants.

When you generate a private key, you want to be extremely secure. Remember, if anyone learns the private key, they can easily steal all the coins from the corresponding wallet, and you have no chance of ever getting them back.

So let’s try to do it more securely. Key generator final draft 8 mac.

Cryptographically strong RNG

Along with a standard RNG method, programming languages usually provide a RNG specifically designed for cryptographic operations. This method is usually much more secure, because it draws entropy straight from the operating system. The result of such RNG is much harder to reproduce. You can’t do it by knowing the time of generation or having the seed, because there is no seed. Well, at least the user doesn’t enter a seed — rather, it’s created by the program.

Generate public key file from secret key. In Python, cryptographically strong RNG is implemented in the secrets module. Let’s modify the code above to make the private key generation secure!

That is amazing. I bet you wouldn’t be able to reproduce this, even with access to my PC. But can we go deeper?

Specialized sites

There are sites that generate random numbers for you. We will consider just two here. One is random.org, a well-known general purpose random number generator. Another one is bitaddress.org, which is designed specifically for Bitcoin private key generation.

Can random.org help us generate a key? Definitely, as they have service for generating random bytes. But two problems arise here. Random.org claims to be a truly random generator, but can you trust it? Can you be sure that it is indeed random? Can you be sure that the owner doesn’t record all generation results, especially ones that look like private keys? The answer is up to you. Oh, and you can’t run it locally, which is an additional problem. This method is not 100% secure.

Now, bitaddress.org is a whole different story. It’s open source, so you can see what’s under its hood. It’s client-side, so you can download it and run it locally, even without an Internet connection.

So how does it work? It uses you — yes, you — as a source of entropy. It asks you to move your mouse or press random keys. You do it long enough to make it infeasible to reproduce the results.

Are you interested to see how bitaddress.org works? For educational purposes, we will look at its code and try to reproduce it in Python.

Generate Bitcoin Address From Public Key
Quick note: bitaddress.org gives you the private key in a compressed WIF format, which is close to the WIF format that we discussed before. For our purposes, we will make the algorithm return a hex string so that we can use it later for a public key generation.

Bitaddress: the specifics

Bitaddress creates the entropy in two forms: by mouse movement and by key pressure. We’ll talk about both, but we’ll focus on the key presses, as it’s hard to implement mouse tracking in the Python lib. We’ll expect the end user to type buttons until we have enough entropy, and then we’ll generate a key.

Bitaddress does three things. It initializes byte array, trying to get as much entropy as possible from your computer, it fills the array with the user input, and then it generates a private key.

Bitaddress uses the 256-byte array to store entropy. This array is rewritten in cycles, so when the array is filled for the first time, the pointer goes to zero, and the process of filling starts again.

The program initiates an array with 256 bytes from window.crypto. Then, it writes a timestamp to get an additional 4 bytes of entropy. Finally, it gets such data as the size of the screen, your time zone, information about browser plugins, your locale, and more. That gives it another 6 bytes.

Generate Bitcoin Public Key

After the initialization, the program continually waits for user input to rewrite initial bytes. When the user moves the cursor, the program writes the position of the cursor. When the user presses buttons, the program writes the char code of the button pressed.

Finally, bitaddress uses accumulated entropy to generate a private key. It needs to generate 32 bytes. For this task, bitaddress uses an RNG algorithm called ARC4. The program initializes ARC4 with the current time and collected entropy, then gets bytes one by one 32 times.

This is all an oversimplification of how the program works, but I hope that you get the idea. You can check out the algorithm in full detail on Github.

Doing it yourself

For our purposes, we’ll build a simpler version of bitaddress. First, we won’t collect data about the user’s machine and location. Second, we will input entropy only via text, as it’s quite challenging to continually receive mouse position with a Python script (check PyAutoGUI if you want to do that).

That brings us to the formal specification of our generator library. First, it will initialize a byte array with cryptographic RNG, then it will fill the timestamp, and finally it will fill the user-created string. After the seed pool is filled, the library will let the developer create a key. Actually, they will be able to create as many private keys as they want, all secured by the collected entropy.

Initializing the pool

Generate Bitcoin Address From Public Key Location

Here we put some bytes from cryptographic RNG and a timestamp. __seed_int and __seed_byte are two helper methods that insert the entropy into our pool array. Notice that we use secrets.

Seeding with input

Here we first put a timestamp and then the input string, character by character.

Generating the private key

This part might look hard, but it’s actually very simple.

First, we need to generate 32-byte number using our pool. Unfortunately, we can’t just create our own random object and use it only for the key generation. Instead, there is a shared object that is used by any code that is running in one script.

What does that mean for us? It means that at each moment, anywhere in the code, one simple random.seed(0) can destroy all our collected entropy. We don’t want that. Thankfully, Python provides getstate and setstate methods. So, to save our entropy each time we generate a key, we remember the state we stopped at and set it next time we want to make a key.

Generate Private Key From Bitcoin Address Online

Second, we just make sure that our key is in range (1, CURVE_ORDER). This is a requirement for all ECDSA private keys. The CURVE_ORDER is the order of the secp256k1 curve, which is FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141.

Finally, for convenience, we convert to hex, and strip the ‘0x’ part.

Generate Bitcoin Address From Public Key Largo

In action

Let’s try to use the library. Actually, it’s really simple: you can generate a private key in three lines of code!

You can see it yourself. The key is random and totally valid. Moreover, each time you run this code, you get different results.

Conclusion

As you can see, there are a lot of ways to generate private keys. They differ in simplicity and security.

Generating a private key is only a first step. The next step is extracting a public key and a wallet address that you can use to receive payments. The process of generating a wallet differs for Bitcoin and Ethereum, and I plan to write two more articles on that topic.

Bitcoin Private Key Generator

If you want to play with the code, I published it to this Github repository.

I am making a course on cryptocurrencies here on freeCodeCamp News. The first part is a detailed description of the blockchain.

I also post random thoughts about crypto on Twitter, so you might want to check it out.