You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ecwrapper.cpp 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. // Copyright (c) 2009-2014 The Bitcoin developers
  2. // Distributed under the MIT software license, see the accompanying
  3. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  4. #include "ecwrapper.h"
  5. #include "serialize.h"
  6. #include "uint256.h"
  7. #include <openssl/bn.h>
  8. #include <openssl/ecdsa.h>
  9. #include <openssl/obj_mac.h>
  10. namespace {
  11. // Generate a private key from just the secret parameter
  12. int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
  13. {
  14. int ok = 0;
  15. BN_CTX *ctx = NULL;
  16. EC_POINT *pub_key = NULL;
  17. if (!eckey) return 0;
  18. const EC_GROUP *group = EC_KEY_get0_group(eckey);
  19. if ((ctx = BN_CTX_new()) == NULL)
  20. goto err;
  21. pub_key = EC_POINT_new(group);
  22. if (pub_key == NULL)
  23. goto err;
  24. if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
  25. goto err;
  26. EC_KEY_set_private_key(eckey,priv_key);
  27. EC_KEY_set_public_key(eckey,pub_key);
  28. ok = 1;
  29. err:
  30. if (pub_key)
  31. EC_POINT_free(pub_key);
  32. if (ctx != NULL)
  33. BN_CTX_free(ctx);
  34. return(ok);
  35. }
  36. // Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
  37. // recid selects which key is recovered
  38. // if check is non-zero, additional checks are performed
  39. int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
  40. {
  41. if (!eckey) return 0;
  42. int ret = 0;
  43. BN_CTX *ctx = NULL;
  44. BIGNUM *x = NULL;
  45. BIGNUM *e = NULL;
  46. BIGNUM *order = NULL;
  47. BIGNUM *sor = NULL;
  48. BIGNUM *eor = NULL;
  49. BIGNUM *field = NULL;
  50. EC_POINT *R = NULL;
  51. EC_POINT *O = NULL;
  52. EC_POINT *Q = NULL;
  53. BIGNUM *rr = NULL;
  54. BIGNUM *zero = NULL;
  55. int n = 0;
  56. int i = recid / 2;
  57. const EC_GROUP *group = EC_KEY_get0_group(eckey);
  58. if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
  59. BN_CTX_start(ctx);
  60. order = BN_CTX_get(ctx);
  61. if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
  62. x = BN_CTX_get(ctx);
  63. if (!BN_copy(x, order)) { ret=-1; goto err; }
  64. if (!BN_mul_word(x, i)) { ret=-1; goto err; }
  65. if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
  66. field = BN_CTX_get(ctx);
  67. if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
  68. if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
  69. if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
  70. if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
  71. if (check)
  72. {
  73. if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
  74. if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
  75. if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
  76. }
  77. if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
  78. n = EC_GROUP_get_degree(group);
  79. e = BN_CTX_get(ctx);
  80. if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
  81. if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
  82. zero = BN_CTX_get(ctx);
  83. if (!BN_zero(zero)) { ret=-1; goto err; }
  84. if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
  85. rr = BN_CTX_get(ctx);
  86. if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
  87. sor = BN_CTX_get(ctx);
  88. if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
  89. eor = BN_CTX_get(ctx);
  90. if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
  91. if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
  92. if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
  93. ret = 1;
  94. err:
  95. if (ctx) {
  96. BN_CTX_end(ctx);
  97. BN_CTX_free(ctx);
  98. }
  99. if (R != NULL) EC_POINT_free(R);
  100. if (O != NULL) EC_POINT_free(O);
  101. if (Q != NULL) EC_POINT_free(Q);
  102. return ret;
  103. }
  104. } // anon namespace
  105. CECKey::CECKey() {
  106. pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
  107. assert(pkey != NULL);
  108. }
  109. CECKey::~CECKey() {
  110. EC_KEY_free(pkey);
  111. }
  112. void CECKey::GetSecretBytes(unsigned char vch[32]) const {
  113. const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
  114. assert(bn);
  115. int nBytes = BN_num_bytes(bn);
  116. int n=BN_bn2bin(bn,&vch[32 - nBytes]);
  117. assert(n == nBytes);
  118. memset(vch, 0, 32 - nBytes);
  119. }
  120. void CECKey::SetSecretBytes(const unsigned char vch[32]) {
  121. bool ret;
  122. BIGNUM bn;
  123. BN_init(&bn);
  124. ret = BN_bin2bn(vch, 32, &bn) != NULL;
  125. assert(ret);
  126. ret = EC_KEY_regenerate_key(pkey, &bn) != 0;
  127. assert(ret);
  128. BN_clear_free(&bn);
  129. }
  130. int CECKey::GetPrivKeySize(bool fCompressed) {
  131. EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
  132. return i2d_ECPrivateKey(pkey, NULL);
  133. }
  134. int CECKey::GetPrivKey(unsigned char* privkey, bool fCompressed) {
  135. EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
  136. return i2d_ECPrivateKey(pkey, &privkey);
  137. }
  138. bool CECKey::SetPrivKey(const unsigned char* privkey, size_t size, bool fSkipCheck) {
  139. if (d2i_ECPrivateKey(&pkey, &privkey, size)) {
  140. if(fSkipCheck)
  141. return true;
  142. // d2i_ECPrivateKey returns true if parsing succeeds.
  143. // This doesn't necessarily mean the key is valid.
  144. if (EC_KEY_check_key(pkey))
  145. return true;
  146. }
  147. return false;
  148. }
  149. void CECKey::GetPubKey(std::vector<unsigned char> &pubkey, bool fCompressed) {
  150. EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
  151. int nSize = i2o_ECPublicKey(pkey, NULL);
  152. assert(nSize);
  153. assert(nSize <= 65);
  154. pubkey.clear();
  155. pubkey.resize(nSize);
  156. unsigned char *pbegin(begin_ptr(pubkey));
  157. int nSize2 = i2o_ECPublicKey(pkey, &pbegin);
  158. assert(nSize == nSize2);
  159. }
  160. bool CECKey::SetPubKey(const unsigned char* pubkey, size_t size) {
  161. return o2i_ECPublicKey(&pkey, &pubkey, size) != NULL;
  162. }
  163. bool CECKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig, bool lowS) {
  164. vchSig.clear();
  165. ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
  166. if (sig == NULL)
  167. return false;
  168. BN_CTX *ctx = BN_CTX_new();
  169. BN_CTX_start(ctx);
  170. const EC_GROUP *group = EC_KEY_get0_group(pkey);
  171. BIGNUM *order = BN_CTX_get(ctx);
  172. BIGNUM *halforder = BN_CTX_get(ctx);
  173. EC_GROUP_get_order(group, order, ctx);
  174. BN_rshift1(halforder, order);
  175. if (lowS && BN_cmp(sig->s, halforder) > 0) {
  176. // enforce low S values, by negating the value (modulo the order) if above order/2.
  177. BN_sub(sig->s, order, sig->s);
  178. }
  179. BN_CTX_end(ctx);
  180. BN_CTX_free(ctx);
  181. unsigned int nSize = ECDSA_size(pkey);
  182. vchSig.resize(nSize); // Make sure it is big enough
  183. unsigned char *pos = &vchSig[0];
  184. nSize = i2d_ECDSA_SIG(sig, &pos);
  185. ECDSA_SIG_free(sig);
  186. vchSig.resize(nSize); // Shrink to fit actual size
  187. return true;
  188. }
  189. bool CECKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) {
  190. // -1 = error, 0 = bad sig, 1 = good
  191. if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
  192. return false;
  193. return true;
  194. }
  195. bool CECKey::SignCompact(const uint256 &hash, unsigned char *p64, int &rec) {
  196. bool fOk = false;
  197. ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
  198. if (sig==NULL)
  199. return false;
  200. memset(p64, 0, 64);
  201. int nBitsR = BN_num_bits(sig->r);
  202. int nBitsS = BN_num_bits(sig->s);
  203. if (nBitsR <= 256 && nBitsS <= 256) {
  204. std::vector<unsigned char> pubkey;
  205. GetPubKey(pubkey, true);
  206. for (int i=0; i<4; i++) {
  207. CECKey keyRec;
  208. if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1) {
  209. std::vector<unsigned char> pubkeyRec;
  210. keyRec.GetPubKey(pubkeyRec, true);
  211. if (pubkeyRec == pubkey) {
  212. rec = i;
  213. fOk = true;
  214. break;
  215. }
  216. }
  217. }
  218. assert(fOk);
  219. BN_bn2bin(sig->r,&p64[32-(nBitsR+7)/8]);
  220. BN_bn2bin(sig->s,&p64[64-(nBitsS+7)/8]);
  221. }
  222. ECDSA_SIG_free(sig);
  223. return fOk;
  224. }
  225. bool CECKey::Recover(const uint256 &hash, const unsigned char *p64, int rec)
  226. {
  227. if (rec<0 || rec>=3)
  228. return false;
  229. ECDSA_SIG *sig = ECDSA_SIG_new();
  230. BN_bin2bn(&p64[0], 32, sig->r);
  231. BN_bin2bn(&p64[32], 32, sig->s);
  232. bool ret = ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), rec, 0) == 1;
  233. ECDSA_SIG_free(sig);
  234. return ret;
  235. }
  236. bool CECKey::TweakSecret(unsigned char vchSecretOut[32], const unsigned char vchSecretIn[32], const unsigned char vchTweak[32])
  237. {
  238. bool ret = true;
  239. BN_CTX *ctx = BN_CTX_new();
  240. BN_CTX_start(ctx);
  241. BIGNUM *bnSecret = BN_CTX_get(ctx);
  242. BIGNUM *bnTweak = BN_CTX_get(ctx);
  243. BIGNUM *bnOrder = BN_CTX_get(ctx);
  244. EC_GROUP *group = EC_GROUP_new_by_curve_name(NID_secp256k1);
  245. EC_GROUP_get_order(group, bnOrder, ctx); // what a grossly inefficient way to get the (constant) group order...
  246. BN_bin2bn(vchTweak, 32, bnTweak);
  247. if (BN_cmp(bnTweak, bnOrder) >= 0)
  248. ret = false; // extremely unlikely
  249. BN_bin2bn(vchSecretIn, 32, bnSecret);
  250. BN_add(bnSecret, bnSecret, bnTweak);
  251. BN_nnmod(bnSecret, bnSecret, bnOrder, ctx);
  252. if (BN_is_zero(bnSecret))
  253. ret = false; // ridiculously unlikely
  254. int nBits = BN_num_bits(bnSecret);
  255. memset(vchSecretOut, 0, 32);
  256. BN_bn2bin(bnSecret, &vchSecretOut[32-(nBits+7)/8]);
  257. EC_GROUP_free(group);
  258. BN_CTX_end(ctx);
  259. BN_CTX_free(ctx);
  260. return ret;
  261. }
  262. bool CECKey::TweakPublic(const unsigned char vchTweak[32]) {
  263. bool ret = true;
  264. BN_CTX *ctx = BN_CTX_new();
  265. BN_CTX_start(ctx);
  266. BIGNUM *bnTweak = BN_CTX_get(ctx);
  267. BIGNUM *bnOrder = BN_CTX_get(ctx);
  268. BIGNUM *bnOne = BN_CTX_get(ctx);
  269. const EC_GROUP *group = EC_KEY_get0_group(pkey);
  270. EC_GROUP_get_order(group, bnOrder, ctx); // what a grossly inefficient way to get the (constant) group order...
  271. BN_bin2bn(vchTweak, 32, bnTweak);
  272. if (BN_cmp(bnTweak, bnOrder) >= 0)
  273. ret = false; // extremely unlikely
  274. EC_POINT *point = EC_POINT_dup(EC_KEY_get0_public_key(pkey), group);
  275. BN_one(bnOne);
  276. EC_POINT_mul(group, point, bnTweak, point, bnOne, ctx);
  277. if (EC_POINT_is_at_infinity(group, point))
  278. ret = false; // ridiculously unlikely
  279. EC_KEY_set_public_key(pkey, point);
  280. EC_POINT_free(point);
  281. BN_CTX_end(ctx);
  282. BN_CTX_free(ctx);
  283. return ret;
  284. }
  285. bool CECKey::SanityCheck()
  286. {
  287. EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
  288. if(pkey == NULL)
  289. return false;
  290. EC_KEY_free(pkey);
  291. // TODO Is there more EC functionality that could be missing?
  292. return true;
  293. }