1 // Copyright (c) 2009-2012 The Bitcoin developers
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include <openssl/ecdsa.h>
8 #include <openssl/obj_mac.h>
12 // Generate a private key from just the secret parameter
13 int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
17 EC_POINT *pub_key = NULL;
21 const EC_GROUP *group = EC_KEY_get0_group(eckey);
23 if ((ctx = BN_CTX_new()) == NULL)
26 pub_key = EC_POINT_new(group);
31 if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
34 EC_KEY_set_private_key(eckey,priv_key);
35 EC_KEY_set_public_key(eckey,pub_key);
42 EC_POINT_free(pub_key);
49 // Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
50 // recid selects which key is recovered
51 // if check is non-zero, additional checks are performed
52 int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
73 const EC_GROUP *group = EC_KEY_get0_group(eckey);
74 if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
76 order = BN_CTX_get(ctx);
77 if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
79 if (!BN_copy(x, order)) { ret=-1; goto err; }
80 if (!BN_mul_word(x, i)) { ret=-1; goto err; }
81 if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
82 field = BN_CTX_get(ctx);
83 if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
84 if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
85 if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
86 if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
89 if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
90 if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
91 if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
93 if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
94 n = EC_GROUP_get_degree(group);
96 if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
97 if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
98 zero = BN_CTX_get(ctx);
99 if (!BN_zero(zero)) { ret=-1; goto err; }
100 if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
101 rr = BN_CTX_get(ctx);
102 if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
103 sor = BN_CTX_get(ctx);
104 if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
105 eor = BN_CTX_get(ctx);
106 if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
107 if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
108 if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
117 if (R != NULL) EC_POINT_free(R);
118 if (O != NULL) EC_POINT_free(O);
119 if (Q != NULL) EC_POINT_free(Q);
123 int CompareBigEndian(const unsigned char *c1, size_t c1len, const unsigned char *c2, size_t c2len) {
124 while (c1len > c2len) {
130 while (c2len > c1len) {
148 // Order of secp256k1's generator minus 1.
149 const unsigned char vchMaxModOrder[32] = {
150 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
151 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
152 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,
153 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40
156 // Half of the order of secp256k1's generator minus 1.
157 const unsigned char vchMaxModHalfOrder[32] = {
158 0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
159 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
160 0x5D,0x57,0x6E,0x73,0x57,0xA4,0x50,0x1D,
161 0xDF,0xE9,0x2F,0x46,0x68,0x1B,0x20,0xA0
164 const unsigned char *vchZero = NULL;
168 void CKey::SetCompressedPubKey()
170 EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
171 fCompressedPubKey = true;
176 fCompressedPubKey = false;
179 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
181 throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
191 CKey::CKey(const CKey& b)
193 pkey = EC_KEY_dup(b.pkey);
195 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
199 CKey& CKey::operator=(const CKey& b)
201 if (!EC_KEY_copy(pkey, b.pkey))
202 throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
212 bool CKey::IsNull() const
217 bool CKey::IsCompressed() const
219 return fCompressedPubKey;
222 bool CKey::CheckSignatureElement(const unsigned char *vch, int len, bool half) {
223 return CompareBigEndian(vch, len, vchZero, 0) > 0 &&
224 CompareBigEndian(vch, len, half ? vchMaxModHalfOrder : vchMaxModOrder, 32) <= 0;
227 void CKey::MakeNewKey(bool fCompressed)
229 if (!EC_KEY_generate_key(pkey))
230 throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
232 SetCompressedPubKey();
236 bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
238 const unsigned char* pbegin = &vchPrivKey[0];
239 if (d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
241 // In testing, d2i_ECPrivateKey can return true
242 // but fill in pkey with a key that fails
243 // EC_KEY_check_key, so:
244 if (EC_KEY_check_key(pkey))
250 // If vchPrivKey data is bad d2i_ECPrivateKey() can
251 // leave pkey in a state where calling EC_KEY_free()
252 // crashes. To avoid that, set pkey to NULL and
253 // leak the memory (a leak is better than a crash)
259 bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
262 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
264 throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
265 if (vchSecret.size() != 32)
266 throw key_error("CKey::SetSecret() : secret must be 32 bytes");
267 BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
269 throw key_error("CKey::SetSecret() : BN_bin2bn failed");
270 if (!EC_KEY_regenerate_key(pkey,bn))
273 throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
277 if (fCompressed || fCompressedPubKey)
278 SetCompressedPubKey();
282 CSecret CKey::GetSecret(bool &fCompressed) const
286 const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
287 int nBytes = BN_num_bytes(bn);
289 throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
290 int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
292 throw key_error("CKey::GetSecret(): BN_bn2bin failed");
293 fCompressed = fCompressedPubKey;
297 CPrivKey CKey::GetPrivKey() const
299 int nSize = i2d_ECPrivateKey(pkey, NULL);
301 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
302 CPrivKey vchPrivKey(nSize, 0);
303 unsigned char* pbegin = &vchPrivKey[0];
304 if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
305 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
309 bool CKey::SetPubKey(const CPubKey& vchPubKey)
311 const unsigned char* pbegin = &vchPubKey.vchPubKey[0];
312 if (o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.vchPubKey.size()))
315 if (vchPubKey.vchPubKey.size() == 33)
316 SetCompressedPubKey();
324 CPubKey CKey::GetPubKey() const
326 int nSize = i2o_ECPublicKey(pkey, NULL);
328 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
329 std::vector<unsigned char> vchPubKey(nSize, 0);
330 unsigned char* pbegin = &vchPubKey[0];
331 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
332 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
333 return CPubKey(vchPubKey);
336 bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
339 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
342 const EC_GROUP *group = EC_KEY_get0_group(pkey);
343 CBigNum order, halforder;
344 EC_GROUP_get_order(group, &order, NULL);
345 BN_rshift1(&halforder, &order);
346 // enforce low S values, by negating the value (modulo the order) if above order/2.
347 if (BN_cmp(sig->s, &halforder) > 0) {
348 BN_sub(sig->s, &order, sig->s);
350 unsigned int nSize = ECDSA_size(pkey);
351 vchSig.resize(nSize); // Make sure it is big enough
352 unsigned char *pos = &vchSig[0];
353 nSize = i2d_ECDSA_SIG(sig, &pos);
355 vchSig.resize(nSize); // Shrink to fit actual size
356 // Testing our new signature
357 if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) {
364 // create a compact signature (65 bytes), which allows reconstructing the used public key
365 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
366 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
367 // 0x1D = second key with even y, 0x1E = second key with odd y
368 bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
371 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
374 const EC_GROUP *group = EC_KEY_get0_group(pkey);
375 CBigNum order, halforder;
376 EC_GROUP_get_order(group, &order, NULL);
377 BN_rshift1(&halforder, &order);
378 // enforce low S values, by negating the value (modulo the order) if above order/2.
379 if (BN_cmp(sig->s, &halforder) > 0) {
380 BN_sub(sig->s, &order, sig->s);
384 int nBitsR = BN_num_bits(sig->r);
385 int nBitsS = BN_num_bits(sig->s);
386 if (nBitsR <= 256 && nBitsS <= 256)
389 for (int i=0; i<4; i++)
393 if (fCompressedPubKey)
394 keyRec.SetCompressedPubKey();
395 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
396 if (keyRec.GetPubKey() == this->GetPubKey())
406 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
409 vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
410 BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
411 BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
418 // reconstruct public key from a compact signature
419 // This is only slightly more CPU intensive than just verifying it.
420 // If this function succeeds, the recovered public key is guaranteed to be valid
421 // (the signature is a valid signature of the given data for that key)
422 bool CKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
424 if (vchSig.size() != 65)
429 ECDSA_SIG *sig = ECDSA_SIG_new();
430 BN_bin2bn(&vchSig[1],32,sig->r);
431 BN_bin2bn(&vchSig[33],32,sig->s);
434 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
437 SetCompressedPubKey();
440 if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)
450 bool CKey::Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
452 // -1 = error, 0 = bad sig, 1 = good
453 if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
459 bool CKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
462 if (!key.SetCompactSignature(hash, vchSig))
464 if (GetPubKey() != key.GetPubKey())
475 if (!EC_KEY_check_key(pkey))
479 CSecret secret = GetSecret(fCompr);
481 key2.SetSecret(secret, fCompr);
482 return GetPubKey() == key2.GetPubKey();