1 // Copyright (c) 2009-2012 The Bitcoin developers
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
7 #include <openssl/ecdsa.h>
8 #include <openssl/obj_mac.h>
13 // Generate a private key from just the secret parameter
14 int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
18 EC_POINT *pub_key = NULL;
22 const EC_GROUP *group = EC_KEY_get0_group(eckey);
24 if ((ctx = BN_CTX_new()) == NULL)
27 pub_key = EC_POINT_new(group);
32 if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
35 EC_KEY_set_private_key(eckey,priv_key);
36 EC_KEY_set_public_key(eckey,pub_key);
43 EC_POINT_free(pub_key);
50 // Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
51 // recid selects which key is recovered
52 // if check is nonzero, additional checks are performed
53 int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
74 const EC_GROUP *group = EC_KEY_get0_group(eckey);
75 if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
77 order = BN_CTX_get(ctx);
78 if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
80 if (!BN_copy(x, order)) { ret=-1; goto err; }
81 if (!BN_mul_word(x, i)) { ret=-1; goto err; }
82 if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
83 field = BN_CTX_get(ctx);
84 if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
85 if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
86 if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
87 if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
90 if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
91 if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
92 if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
94 if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
95 n = EC_GROUP_get_degree(group);
97 if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
98 if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
99 zero = BN_CTX_get(ctx);
100 if (!BN_zero(zero)) { ret=-1; goto err; }
101 if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
102 rr = BN_CTX_get(ctx);
103 if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
104 sor = BN_CTX_get(ctx);
105 if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
106 eor = BN_CTX_get(ctx);
107 if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
108 if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
109 if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
118 if (R != NULL) EC_POINT_free(R);
119 if (O != NULL) EC_POINT_free(O);
120 if (Q != NULL) EC_POINT_free(Q);
124 void CKey::SetCompressedPubKey()
126 EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
127 fCompressedPubKey = true;
132 fCompressedPubKey = false;
133 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
135 throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
144 CKey::CKey(const CKey& b)
146 pkey = EC_KEY_dup(b.pkey);
148 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
152 CKey& CKey::operator=(const CKey& b)
154 if (!EC_KEY_copy(pkey, b.pkey))
155 throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
165 bool CKey::IsNull() const
170 bool CKey::IsCompressed() const
172 return fCompressedPubKey;
175 void CKey::MakeNewKey(bool fCompressed)
177 if (!EC_KEY_generate_key(pkey))
178 throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
180 SetCompressedPubKey();
184 bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
186 const unsigned char* pbegin = &vchPrivKey[0];
187 if (!d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
193 bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
196 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
198 throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
199 if (vchSecret.size() != 32)
200 throw key_error("CKey::SetSecret() : secret must be 32 bytes");
201 BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
203 throw key_error("CKey::SetSecret() : BN_bin2bn failed");
204 if (!EC_KEY_regenerate_key(pkey,bn))
207 throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
211 if (fCompressed || fCompressedPubKey)
212 SetCompressedPubKey();
216 CSecret CKey::GetSecret(bool &fCompressed) const
220 const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
221 int nBytes = BN_num_bytes(bn);
223 throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
224 int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
226 throw key_error("CKey::GetSecret(): BN_bn2bin failed");
227 fCompressed = fCompressedPubKey;
231 CPrivKey CKey::GetPrivKey() const
233 int nSize = i2d_ECPrivateKey(pkey, NULL);
235 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
236 CPrivKey vchPrivKey(nSize, 0);
237 unsigned char* pbegin = &vchPrivKey[0];
238 if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
239 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
243 bool CKey::SetPubKey(const std::vector<unsigned char>& vchPubKey)
245 const unsigned char* pbegin = &vchPubKey[0];
246 if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.size()))
249 if (vchPubKey.size() == 33)
250 SetCompressedPubKey();
254 std::vector<unsigned char> CKey::GetPubKey() const
256 int nSize = i2o_ECPublicKey(pkey, NULL);
258 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
259 std::vector<unsigned char> vchPubKey(nSize, 0);
260 unsigned char* pbegin = &vchPubKey[0];
261 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
262 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
266 bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
268 unsigned int nSize = ECDSA_size(pkey);
269 vchSig.resize(nSize); // Make sure it is big enough
270 if (!ECDSA_sign(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], &nSize, pkey))
275 vchSig.resize(nSize); // Shrink to fit actual size
279 // create a compact signature (65 bytes), which allows reconstructing the used public key
280 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
281 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
282 // 0x1D = second key with even y, 0x1E = second key with odd y
283 bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
286 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
291 int nBitsR = BN_num_bits(sig->r);
292 int nBitsS = BN_num_bits(sig->s);
293 if (nBitsR <= 256 && nBitsS <= 256)
296 for (int i=0; i<4; i++)
300 if (fCompressedPubKey)
301 keyRec.SetCompressedPubKey();
302 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
303 if (keyRec.GetPubKey() == this->GetPubKey())
311 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
313 vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
314 BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
315 BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
322 // reconstruct public key from a compact signature
323 // This is only slightly more CPU intensive than just verifying it.
324 // If this function succeeds, the recovered public key is guaranteed to be valid
325 // (the signature is a valid signature of the given data for that key)
326 bool CKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
328 if (vchSig.size() != 65)
333 ECDSA_SIG *sig = ECDSA_SIG_new();
334 BN_bin2bn(&vchSig[1],32,sig->r);
335 BN_bin2bn(&vchSig[33],32,sig->s);
338 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
341 SetCompressedPubKey();
344 if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)
353 bool CKey::Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
355 // -1 = error, 0 = bad sig, 1 = good
356 if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
362 bool CKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
365 if (!key.SetCompactSignature(hash, vchSig))
367 if (GetPubKey() != key.GetPubKey())
379 CSecret secret = GetSecret(fCompr);
381 key2.SetSecret(secret, fCompr);
382 return GetPubKey() == key2.GetPubKey();