1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
11 #include <openssl/ec.h>
12 #include <openssl/ecdsa.h>
13 #include <openssl/obj_mac.h>
15 #include "serialize.h"
20 // const unsigned int PRIVATE_KEY_SIZE = 192;
21 // const unsigned int PUBLIC_KEY_SIZE = 41;
22 // const unsigned int SIGNATURE_SIZE = 48;
25 // const unsigned int PRIVATE_KEY_SIZE = 222;
26 // const unsigned int PUBLIC_KEY_SIZE = 49;
27 // const unsigned int SIGNATURE_SIZE = 57;
30 // const unsigned int PRIVATE_KEY_SIZE = 250;
31 // const unsigned int PUBLIC_KEY_SIZE = 57;
32 // const unsigned int SIGNATURE_SIZE = 66;
35 // const unsigned int PRIVATE_KEY_SIZE = 279;
36 // const unsigned int PUBLIC_KEY_SIZE = 65;
37 // const unsigned int SIGNATURE_SIZE = 72;
39 // see www.keylength.com
40 // script supports up to 75 for single byte push
42 // Generate a private key from just the secret parameter
43 int static inline EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
47 EC_POINT *pub_key = NULL;
51 const EC_GROUP *group = EC_KEY_get0_group(eckey);
53 if ((ctx = BN_CTX_new()) == NULL)
56 pub_key = EC_POINT_new(group);
61 if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
64 EC_KEY_set_private_key(eckey,priv_key);
65 EC_KEY_set_public_key(eckey,pub_key);
72 EC_POINT_free(pub_key);
79 // Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
80 // recid selects which key is recovered
81 // if check is nonzero, additional checks are performed
82 int static inline ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
103 const EC_GROUP *group = EC_KEY_get0_group(eckey);
104 if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
106 order = BN_CTX_get(ctx);
107 if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
109 if (!BN_copy(x, order)) { ret=-1; goto err; }
110 if (!BN_mul_word(x, i)) { ret=-1; goto err; }
111 if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
112 field = BN_CTX_get(ctx);
113 if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
114 if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
115 if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
116 if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
119 if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
120 if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
121 if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
123 if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
124 n = EC_GROUP_get_degree(group);
126 if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
127 if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
128 zero = BN_CTX_get(ctx);
129 if (!BN_zero(zero)) { ret=-1; goto err; }
130 if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
131 rr = BN_CTX_get(ctx);
132 if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
133 sor = BN_CTX_get(ctx);
134 if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
135 eor = BN_CTX_get(ctx);
136 if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
137 if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
138 if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
147 if (R != NULL) EC_POINT_free(R);
148 if (O != NULL) EC_POINT_free(O);
149 if (Q != NULL) EC_POINT_free(Q);
153 class key_error : public std::runtime_error
156 explicit key_error(const std::string& str) : std::runtime_error(str) {}
160 // secure_allocator is defined in serialize.h
161 // CPrivKey is a serialized private key, with all parameters included (279 bytes)
162 typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
163 // CSecret is a serialization of just the secret parameter (32 bytes)
164 typedef std::vector<unsigned char, secure_allocator<unsigned char> > CSecret;
175 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
177 throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
183 pkey = EC_KEY_dup(b.pkey);
185 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
189 CKey& operator=(const CKey& b)
191 if (!EC_KEY_copy(pkey, b.pkey))
192 throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
209 if (!EC_KEY_generate_key(pkey))
210 throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
214 bool SetPrivKey(const CPrivKey& vchPrivKey)
216 const unsigned char* pbegin = &vchPrivKey[0];
217 if (!d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
223 bool SetSecret(const CSecret& vchSecret)
226 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
228 throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
229 if (vchSecret.size() != 32)
230 throw key_error("CKey::SetSecret() : secret must be 32 bytes");
231 BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
233 throw key_error("CKey::SetSecret() : BN_bin2bn failed");
234 if (!EC_KEY_regenerate_key(pkey,bn))
235 throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
241 CSecret GetSecret() const
245 const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
246 int nBytes = BN_num_bytes(bn);
248 throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
249 int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
251 throw key_error("CKey::GetSecret(): BN_bn2bin failed");
255 CPrivKey GetPrivKey() const
257 unsigned int nSize = i2d_ECPrivateKey(pkey, NULL);
259 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
260 CPrivKey vchPrivKey(nSize, 0);
261 unsigned char* pbegin = &vchPrivKey[0];
262 if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
263 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
267 bool SetPubKey(const std::vector<unsigned char>& vchPubKey)
269 const unsigned char* pbegin = &vchPubKey[0];
270 if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.size()))
276 std::vector<unsigned char> GetPubKey() const
278 unsigned int nSize = i2o_ECPublicKey(pkey, NULL);
280 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
281 std::vector<unsigned char> vchPubKey(nSize, 0);
282 unsigned char* pbegin = &vchPubKey[0];
283 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
284 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
288 bool Sign(uint256 hash, std::vector<unsigned char>& vchSig)
291 unsigned char pchSig[10000];
292 unsigned int nSize = 0;
293 if (!ECDSA_sign(0, (unsigned char*)&hash, sizeof(hash), pchSig, &nSize, pkey))
295 vchSig.resize(nSize);
296 memcpy(&vchSig[0], pchSig, nSize);
300 // create a compact signature (65 bytes), which allows reconstructing the used public key
301 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
302 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
303 // 0x1D = second key with even y, 0x1E = second key with odd y
304 bool SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
307 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
312 int nBitsR = BN_num_bits(sig->r);
313 int nBitsS = BN_num_bits(sig->s);
314 if (nBitsR <= 256 && nBitsS <= 256)
317 for (int i=0; i<4; i++)
321 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
322 if (keyRec.GetPubKey() == this->GetPubKey())
330 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
332 vchSig[0] = nRecId+27;
333 BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
334 BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
341 // reconstruct public key from a compact signature
342 // This is only slightly more CPU intensive than just verifying it.
343 // If this function succeeds, the recovered public key is guaranteed to be valid
344 // (the signature is a valid signature of the given data for that key)
345 bool SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
347 if (vchSig.size() != 65)
349 if (vchSig[0]<27 || vchSig[0]>=31)
351 ECDSA_SIG *sig = ECDSA_SIG_new();
352 BN_bin2bn(&vchSig[1],32,sig->r);
353 BN_bin2bn(&vchSig[33],32,sig->s);
356 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
357 if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), vchSig[0] - 27, 0) == 1)
366 bool Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
368 // -1 = error, 0 = bad sig, 1 = good
369 if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
374 // Verify a compact signature
375 bool VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
378 if (!key.SetCompactSignature(hash, vchSig))
380 if (GetPubKey() != key.GetPubKey())
385 // Get the address corresponding to this key
386 CBitcoinAddress GetAddress() const
388 return CBitcoinAddress(GetPubKey());