ch4 priv keys

pull/2/head
Andreas M. Antonopoulos 10 years ago
parent 12e0c4fd8e
commit d8d12727f9

@ -1,13 +1,185 @@
[[ch04_wallets_keys]]
== Wallets, Keys and Addresses
Ownership of bitcoin is established through _digital keys_ and _digital signatures_. These keys are not actually stored in the network, but are instead created and stored by end-users, in a file called a _wallet_, or in a database. The keys within each user's wallet allow the user to sign transactions, thereby providing cryptographic proof of the ownership of the bitcoins sourced by the transaction. The keys themselves are completely independent of the bitcoin protocol and can be generated and managed by the end users. Keys can be generated without reference to the blockchain or access to the network. Keys enable many of the interesting properties of bitcoin, including de-centralized trust and control, ownership attestation and the cryptographic-proof security model. Keys can also be converted into unique and public addresses (eg. bitcoin addresses, those that start with a "1"), allowing anyone to create transactions that transfer ownership of bitcoin to our keys.
In this chapter we will introduce wallets, which contain cryptographic keys. We will look at how keys are generated, stored and managed. We will review the various encoding formats used to represent private and public keys, addresses and script addresses. Finally we will look at special uses of keys to sign messages, prove ownerhsip and special addresses uses such as vanity addresses and paper wallets.
[TIP]
====
Wallets contain keys, not coins. The coins are stored on the blockchain, in the form of transaction-outputs (often noted as vout or txout). Each user has a wallet containing keys. Wallets are really keychains containing pairs of private/publice keys (See <<public key>>). Users sign transactions with the keys, thereby proving they own the transaction outputs (their coins).
====
[[wallets]]
=== Wallets
=== Keys
Your bitcoin wallet contains a collection of key pairs, each consisting of a private key and a public key.
In the most simple form, the private key is a 256-bit number picked at random. The private key be used to create a corresponding public key. The public key can then be converted into a +bitcoin address+, which is shared with anyone who we want to send us bitcoin. Ownerhsip and control over the private key is the root of user control over all funds associated with the corresponding bitcoin address.
==== A Private Key
A private key is a 256-bit number. To create one, we just pick a 256-bit random number. In programming terms, this is usually achieved by feeding a larger string of random numbers, collected from a cryptographically-secure source of randomness, into the SHA-256 hash algorithm which will conveniently produce a 256-bit number.
[TIP]
====
Do not try and design your own random number generator (RNG). Use a cryptographically-secure RNG with a seed from a source of sufficient entropy. A good source of entropy is operating-system dependent. Correct implementation of the RNG is critical to the security of the keys. DIY is highly discouraged unless you are a professional cryptographer.
====
Below, is a randomly generated private key shown in hexadecimal format (256 binary digits, or bits is shown as 64 hexadecimal digits, each 4-bits):
----
1E 99 42 3A 4E D2 76 08 A1 5A 26 16 A2 B0 E9 E5 2C ED 33 0A C5 30 ED CC 32 C8 FF C6 A5 26 AE DD
----
The private key can be represented in a number of different formats, all of which correspond to the same 256-bit number. These formats include:
.Private Key Representations (Encoding Formats)
[options="header"]
|=======
|Type|Prefix|Description
| Hex | None | 64 hexadecimal digits
| WIF | 5 | Base-58 encoding with version prefix of 128 and 32-bit checksum
| WIF-compressed | K or L | As above, with added suffix 0x01 before encoding
|=======
The key above, for example can be represented as:
.Example: Same Key, Different Formats
[options="header"]
|=======
|Format | Private Key
| Hex | 1e99423a4ed27608a15a2616a2b0e9e52ced330ac530edcc32c8ffc6a526aedd
| WIF | 5J3mBbAH58CpQ3Y5RNJpUKPE62SQ5tfcvU2JpbnkeyhfsYB1Jcn
| WIF-compressed | KxFC1jmwwCoACiCAWZ3eXa96mBM6tb3TYzGmf6YwgdGWZgawvrtJ
|=======
All of the above representations are different ways of showing the same number, the same private key. They look different, but any one format can easily be converted to any other format.
To generate a new key with bitcoind, use the +getnewaddress+ command. For security reasons it displays the public key only, not the private key. To ask bitcoind to expose the private key, use the +dumpprivkey+ command. Here's an example of both commands:
----
$ bitcoind getnewaddress
16EVkC8zXLEJ1NHp1a7gPMS5b8SRyARrWi
$ bitcoind dumpprivkey 16EVkC8zXLEJ1NHp1a7gPMS5b8SRyARrWi
KxL8r7Y9KexgvToiEJfWu6brrQw797MtvKUdKJRRqnqRh2cFu9Md
----
The +dumpprivkey+ command is opening the wallet and extracting the private key that was generated by the +getnewaddress+ command. It is not otherwise possible for bitcoind to know the private key from the public key, unless they are both stored in the wallet. In the example above, we see that the private key has a "K" prefix, indicating it is encoded as a WIF-compressed format. This means it that the key-pair is stored in the wallet with both keys compressed, saving 31 bytes of space. If the prefix had been "5", indicating the WIF format, we would know that the key-pair is uncompressed.
You can also use +sx tools+ to generate keys and convert them between formats:
===== New key
----
$ sx newkey
5HsAnnceKqSFpTE1gnbB1aY5VcG1skmVF1gsNvjH5kLw4sqgf41
----
===== Decoded from the Base58Check encoding to Hex
----
$ sx base58check-decode 5HsAnnceKqSFpTE1gnbB1aY5VcG1skmVF1gsNvjH5kLw4sqgf41
068bc683aaf37e8078c65c396e33377194476cbf77000e2a454edc8afeca67c4 128
----
===== Encode from Hex back to Base58Check encoding, with the version prefix "128"
----
$ sx base58check-encode 068bc683aaf37e8078c65c396e33377194476cbf77000e2a454edc8afeca67c4 128
5HsAnnceKqSFpTE1gnbB1aY5VcG1skmVF1gsNvjH5kLw4sqgf41
----
===== Encode from Hex with a suffix of "01" to Base58Check encoding, with the version prefix "128"
----
$ sx base58check-encode 068bc683aaf37e8078c65c396e33377194476cbf77000e2a454edc8afeca67c401 128
KwSSD6LKk8nUQSkS2cDqBZ2AqGdGs2BMer2yMn9byxJydor5GWJX
----
==== From Private Key to Public Key
The public key is calculated from the private key using elliptic curve multiplication, which is irreversible: +latexmath:[\(\K = k * G\)]+ where +k+ is the private key, +G+ is a constant and +K+ is the resulting public key. The reverse (division), or calculating +k+ if you know +K+ is as difficult as trying all possible values of +k+, ie a brute-force search.
[TIP]
====
A private key can be converted into a public key, but a public key cannot be converted back into a private key because the math only works one way.
====
==== From Public Key to Address
An address is a string of digits and characters that can be shared with anyone who wants to send you money. In bitcoin, addresses begin with the digit "1". An address made by hashing the public key twice, through two different hashing algorithms.
==== Generating keys
There are many ways to generate keys for use in bitcoin. The simplest is to pick a large random number and turn it into a key pair (See <<key_derivation>>). A random key can generated with very simple hardware or even manually with pen, paper and dice. The disadvantage of random keys is that if you generate many of them you must keep copies of all of them. Another method for making keys is _deterministic key generation_. Here you generate each new key as a function of the previous key, linking them in a sequence. As long as you can re-create that sequence, you only need the first key to generate them all. In this section we will examine the different methods for key generation.
[TIP]
====
The private key is just a number. A public key can be generated from any private key. Therefore, a public key can be generated from any number, up to 256-bits long. You can pick your keys randomly using a method as simple as tossing a coin, pencil and paper. Toss a coin 256 times and you have the binary digits of a random private key you can use in a bitcoin wallet. Keys really are just a pair of numbers, one calculated from the other.
====
===== Type-0 or non-deterministic (random) keys
The first and most important step in generating keys is to find a secure source of entropy, or randomness. The private key is a 256-bit number, which must be selected at random. Creating a bitcoin key is essentially the same as "Pick a number between 1 and 2^256^". The exact method you use to pick that number does not matter, as long as it is not predictable or repeatable. Bitcoin software will use the underlying operating system's random number generators to produce 256-bits of entropy. Usually, the OS random number generator is initialized by a human source of randomness, which is why you may be asked to wiggle your mouse around for a few seconds. For the trully paranoid, nothing beats dice, pencil and paper.
[[Type0_keygen]]
.Private key generation: From random mouse movements to a 256-bit number used as the private key
image::images/Type-0 keygen.png["Private key generation"]
[TIP]
====
The bitcoin private key is just a number. A public key can be generated from any private key. Therefore, a public key can be generated from any number, up to 256-bits long. You can pick your keys randomly using a method as simple as dice, pencil and paper.
====
Once a private key has been generated, the public key equivalent can be derived from it using the elliptic curve multiplication function. Many software implementations of bitcoin use the OpenSSL library, specifically the https://www.openssl.org/docs/crypto/ec.html[Elliptic Curve library].
[TIP]
====
The size of bitcoin's private key, 2^256^ is a truly unfathomable number. It is equal to approximately 10^77^ in decimal. The visible universe contains approximately 10^80^ atoms.
====
This most basic form of key generation, generates what are known as _Type-0_ or _Non-Deterministic_ (ie. random) keys. When a sequence of keys is generated for a single user's wallet, each key is randomly generated when needed
[[Type0_chain]]
.Type-0 or Non-Deterministic Keys are randomly generated as needed
image::images/type0_chain.png["Key generation"]
===== Type-1 deterministic (non-random) key chains
[[Type1_chain]]
.Type-1 Deterministic Keys are generated from a phrase and index number
image::images/type1_chain.png["Key generation"]
===== Type-2 chained deterministic keys
[[Type2_chain]]
.Type-2 Chained Deterministic Keys are generated from a binary seed and index number
image::images/type2_chain.png["Key generation"]
===== Type-2 hierarchical deterministic keys
[[Type2_tree]]
.Type-2 Hierarchical Deterministic Keys are derived from a master seed using a tree structure
image::images/BIP32-derivation.png["Key generation"]
[[public_key]]
==== Public key cryptography and crypto-currency
((("public key")))
Public-key cryptography, or assymetric cryptography, is a key part of a crypto-currency. Surprisingly, the cryptographic keys are not actually stored inside the bitcoin blockchain or the network. Instead, the blockchain only records transactions with digital signatures (hashes) of keys. The keys themselves are completely independent and can be generated and managed by the end users. This enables many of the interesting properties of bitcoin, including de-centralized trust and control.
Public-key cryptography, is like a digital padlock, which can only be opened by the owner of a secret, also known as a private key. The owner of that key can hand out as many copies of the padlock, as they want, and others can use it to "lock" bitcoins inside transactions recorded on the blockchain. Only the owner of the private key can then create a signature to unlock and "redeem" these transactions, as only they can open the digital padlock.
In a nutshell, public-key cryptography is like a digital padlock, which can only be opened by the owner of a secret key. The owner of that key can hand out as many copies of the padlock as they want, and others can use it to "lock" bitcoins inside transactions recorded on the blockchain. Only the owner of the key can then unlock and "redeem" these transactions, as only they can open the digital padlock.
When Alice pays Bob 15 millibits (0.015 BTC), she is unlocking a set of unspent outputs with _digital signatures_ made with her _private keys_. Like signing a check, she signs a transaction to authorize spending her coins. Then she "locks" a certain amount of bitcoin with Bob's address (made from his _public key_ and freely shared), thereby making a transaction output encumbered by Bob's address and spendable only with Bob's signature.
Spending can be visualized as unlocking my coins and then locking some of them with someone else's padlock so they now own them.
==== Public Key Cryptography
((("public key", "private key")))
@ -30,12 +202,12 @@ In most implementations, the private and public keys are stored together as a _k
((("elliptic curve cryptography", "ECC")))
Elliptic Curve Cryptography is a type of assymetric or public-key cryptography based on the discrete logarithm problem as expressed by addition and multiplication on the points of an elliptic curve.
Starting with a private key in the form of a randomly generator number +k+, we multiply it with a predetermined point on the curve called the _generator point_ to produce another point somewhere else on the curve, which is the corresponding public key.
Starting with a private key in the form of a randomly generator number +k+, we multiply it with a predetermined point on the curve called the _generator point_ +G+ to produce another point somewhere else on the curve, which is the corresponding public key +K+.
[latexmath]
++++
\begin{equation}
{K = k G}
{K = k * G}
\end{equation}
++++
@ -65,7 +237,7 @@ or
\end{equation}
++++
where +p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F+, a very large prime.
where +latexmath:[\(\p = 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1\)]+, a very large prime number.
The +mod p+ indicates that this curve is over a finite field of prime order +p+, also written as latexmath:[\(\mathbb{F}_p\)]. The curve looks like a pattern of dots scattered in two dimensions, which makes it difficult to visualize. However, the math is identical as that of an elliptic curve over the real numbers shown above.
@ -74,25 +246,6 @@ The +mod p+ indicates that this curve is over a finite field of prime order +p+,
image::images/ecc-over-F37-math.png["Addition operator on points of an elliptic curve over F(p)"]
==== Generating bitcoin keys
There are many ways to generate keys for use in bitcoin. The simplest is to pick a large random number and turn it into a key pair (See <<key_derivation>>). A random key can generated with very simple hardware or even manually with pen, paper and dice. The disadvantage of random keys is that if you generate many of them you must keep copies of all of them. Another method for making keys is _deterministic key generation_. Here you generate each new key as a function of the previous key, linking them in a sequence. As long as you can re-create that sequence, you only need the first key to generate them all. In this section we will examine the different methods for key generation.
===== Type-0 or non-deterministic (random) keys
The first and most important step in generating keys is to find a secure source of entropy, or randomness. The private key is a 256-bit number, which must be selected at random. Creating a bitcoin key is essentially the same as "Pick a number between 1 and 2^256^". The exact method you use to pick that number does not matter, as long as it is not predictable or repeatable. Bitcoin software will use the underlying operating system's random number generators to produce 256-bits of entropy. Usually, the OS random number generator is initialized by a human source of randomness, which is why you may be asked to wiggle your mouse around for a few seconds. For the trully paranoid, nothing beats dice, pencil and paper.
[[Type0_keygen]]
.Private key generation: From random mouse movements to a 256-bit number used as the private key
image::images/Type-0 keygen.png["Private key generation"]
[TIP]
====
The bitcoin private key is just a number. A public key can be generated from any private key. Therefore, a public key can be generated from any number, up to 256-bits long. You can pick your keys randomly using a method as simple as dice, pencil and paper.
====
Once a private key has been generated, the public key equivalent can be derived from it using the elliptic curve multiplication function. Many software implementations of bitcoin use the OpenSSL library, specifically the https://www.openssl.org/docs/crypto/ec.html[Elliptic Curve library].
Here's an example from the reference implementation, generating a public key from an existing private key
@ -125,26 +278,4 @@ int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
The size of bitcoin's private key, 2^256^ is a truly unfathomable number. It is equal to approximately 10^77^ in decimal. The visible universe contains approximately 10^80^ atoms.
====
This most basic form of key generation, generates what are known as _Type-0_ or _Non-Deterministic_ (ie. random) keys. When a sequence of keys is generated for a single user's wallet, each key is randomly generated when needed
[[Type0_chain]]
.Type-0 or Non-Deterministic Keys are randomly generated as needed
image::images/type0_chain.png["Key generation"]
===== Type-1 deterministic (non-random) key chains
[[Type1_chain]]
.Type-1 Deterministic Keys are generated from a phrase and index number
image::images/type1_chain.png["Key generation"]
===== Type-2 chained deterministic keys
[[Type2_chain]]
.Type-2 Chained Deterministic Keys are generated from a binary seed and index number
image::images/type2_chain.png["Key generation"]
===== Type-2 hierarchical deterministic keys
[[Type2_tree]]
.Type-2 Hierarchical Deterministic Keys are derived from a master seed using a tree structure
image::images/BIP32-derivation.png["Key generation"]

Loading…
Cancel
Save