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/evp.h>
9 #include <openssl/obj_mac.h>
14 // Generate a private key from just the secret parameter
15 int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
19 EC_POINT *pub_key = NULL;
23 const EC_GROUP *group = EC_KEY_get0_group(eckey);
25 if ((ctx = BN_CTX_new()) == NULL)
28 pub_key = EC_POINT_new(group);
33 if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
36 EC_KEY_set_private_key(eckey,priv_key);
37 EC_KEY_set_public_key(eckey,pub_key);
44 EC_POINT_free(pub_key);
51 // Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
52 // recid selects which key is recovered
53 // if check is non-zero, additional checks are performed
54 int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
75 const EC_GROUP *group = EC_KEY_get0_group(eckey);
76 if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
78 order = BN_CTX_get(ctx);
79 if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
81 if (!BN_copy(x, order)) { ret=-1; goto err; }
82 if (!BN_mul_word(x, i)) { ret=-1; goto err; }
84 // Get internal R and S pointers
85 const BIGNUM *ecsig_r, *ecsig_s;
86 ECDSA_SIG_get0(ecsig, &ecsig_r, &ecsig_s);
88 if (!BN_add(x, x, ecsig_r)) { ret=-1; goto err; }
89 field = BN_CTX_get(ctx);
90 if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
91 if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
92 if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
93 if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
96 if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
97 if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
98 if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
100 if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
101 n = EC_GROUP_get_degree(group);
103 if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
104 if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
105 zero = BN_CTX_get(ctx);
107 if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
108 rr = BN_CTX_get(ctx);
109 if (!BN_mod_inverse(rr, ecsig_r, order, ctx)) { ret=-1; goto err; }
110 sor = BN_CTX_get(ctx);
111 if (!BN_mod_mul(sor, ecsig_s, rr, order, ctx)) { ret=-1; goto err; }
112 eor = BN_CTX_get(ctx);
113 if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
114 if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
115 if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
124 if (R != NULL) EC_POINT_free(R);
125 if (O != NULL) EC_POINT_free(O);
126 if (Q != NULL) EC_POINT_free(Q);
130 int CompareBigEndian(const unsigned char *c1, size_t c1len, const unsigned char *c2, size_t c2len) {
131 while (c1len > c2len) {
137 while (c2len > c1len) {
155 // Order of secp256k1's generator minus 1.
156 const unsigned char vchMaxModOrder[32] = {
157 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
158 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
159 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,
160 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40
163 // Half of the order of secp256k1's generator minus 1.
164 const unsigned char vchMaxModHalfOrder[32] = {
165 0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
166 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
167 0x5D,0x57,0x6E,0x73,0x57,0xA4,0x50,0x1D,
168 0xDF,0xE9,0x2F,0x46,0x68,0x1B,0x20,0xA0
171 const unsigned char *vchZero = NULL;
173 void CKey::SetCompressedPubKey(bool fCompressed)
175 EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
183 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
185 throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
194 CKey::CKey(const CKey& b)
196 pkey = EC_KEY_dup(b.pkey);
198 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
202 CKey::CKey(const CSecret& b, bool fCompressed)
204 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
206 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
207 SetSecret(b, fCompressed);
210 CKey& CKey::operator=(const CKey& b)
212 if (!EC_KEY_copy(pkey, b.pkey))
213 throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
224 bool CKey::IsNull() const
229 bool CKey::IsCompressed() const
231 return (EC_KEY_get_conv_form(pkey) == POINT_CONVERSION_COMPRESSED);
234 bool CKey::CheckSignatureElement(const unsigned char *vch, int len, bool half) {
235 return CompareBigEndian(vch, len, vchZero, 0) > 0 &&
236 CompareBigEndian(vch, len, half ? vchMaxModHalfOrder : vchMaxModOrder, 32) <= 0;
239 bool CPubKey::ReserealizeSignature(std::vector<unsigned char>& vchSig)
244 unsigned char *pos = &vchSig[0];
245 ECDSA_SIG *sig = d2i_ECDSA_SIG(NULL, (const unsigned char **)&pos, vchSig.size());
250 int nSize = i2d_ECDSA_SIG(sig, NULL);
252 vchSig.resize(nSize); // grow or shrink as needed
255 i2d_ECDSA_SIG(sig, &pos);
265 void CKey::MakeNewKey(bool fCompressed)
267 if (!EC_KEY_generate_key(pkey))
268 throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
269 SetCompressedPubKey(fCompressed);
273 bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
275 const unsigned char* pbegin = &vchPrivKey[0];
276 if (d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
278 // In testing, d2i_ECPrivateKey can return true
279 // but fill in pkey with a key that fails
280 // EC_KEY_check_key, so:
281 if (EC_KEY_check_key(pkey))
287 // If vchPrivKey data is bad d2i_ECPrivateKey() can
288 // leave pkey in a state where calling EC_KEY_free()
289 // crashes. To avoid that, set pkey to NULL and
290 // leak the memory (a leak is better than a crash)
296 bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
299 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
301 throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
303 if (vchSecret.size() != 32)
304 throw key_error("CKey::SetSecret() : secret must be 32 bytes");
305 BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
307 throw key_error("CKey::SetSecret() : BN_bin2bn failed");
308 if (!EC_KEY_regenerate_key(pkey,bn))
311 throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
315 SetCompressedPubKey(fCompressed);
319 CSecret CKey::GetSecret(bool &fCompressed) const
323 const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
324 int nBytes = BN_num_bytes(bn);
326 throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
327 int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
329 throw key_error("CKey::GetSecret(): BN_bn2bin failed");
330 fCompressed = IsCompressed();
334 bool CKey::WritePEM(BIO *streamObj, const SecureString &strPassKey) const // dumppem 4KJLA99FyqMMhjjDe7KnRXK4sjtv9cCtNS /tmp/test.pem 123
336 EVP_PKEY *evpKey = EVP_PKEY_new();
337 if (!EVP_PKEY_assign_EC_KEY(evpKey, pkey))
338 return error("CKey::WritePEM() : Error initializing EVP_PKEY instance.");
339 if(!PEM_write_bio_PKCS8PrivateKey(streamObj, evpKey, EVP_aes_256_cbc(), (char *)&strPassKey[0], strPassKey.size(), NULL, NULL))
340 return error("CKey::WritePEM() : Error writing private key data to stream object");
345 CSecret CKey::GetSecret() const
348 return GetSecret(fCompressed);
351 CPrivKey CKey::GetPrivKey() const
353 int nSize = i2d_ECPrivateKey(pkey, NULL);
355 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
356 CPrivKey vchPrivKey(nSize, 0);
357 unsigned char* pbegin = &vchPrivKey[0];
358 if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
359 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
363 CPubKey CKey::GetPubKey() const
365 int nSize = i2o_ECPublicKey(pkey, NULL);
367 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
368 std::vector<unsigned char> vchPubKey(nSize, 0);
369 unsigned char* pbegin = &vchPubKey[0];
370 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
371 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
372 return CPubKey(vchPubKey);
375 bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
378 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
381 const EC_GROUP *group = EC_KEY_get0_group(pkey);
382 CBigNum order, halforder;
383 EC_GROUP_get_order(group, order.get(), NULL);
384 BN_rshift1(halforder.get(), order.get());
386 // Get internal R and S pointers
387 const BIGNUM *current_s = ECDSA_SIG_get0_s(sig);
389 // enforce low S values, by negating the value (modulo the order) if above order/2.
390 if (BN_cmp(current_s, halforder.get()) > 0) {
391 BIGNUM *updated_s = BN_new();
392 BN_copy(updated_s, current_s);
393 BN_sub(updated_s, order.get(), updated_s);
394 ECDSA_SIG_set0(sig, NULL, updated_s);
397 unsigned int nSize = ECDSA_size(pkey);
398 vchSig.resize(nSize); // Make sure it is big enough
399 unsigned char *pos = &vchSig[0];
400 nSize = i2d_ECDSA_SIG(sig, &pos);
402 vchSig.resize(nSize); // Shrink to fit actual size
403 // Testing our new signature
404 if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) {
411 // create a compact signature (65 bytes), which allows reconstructing the used public key
412 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
413 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
414 // 0x1D = second key with even y, 0x1E = second key with odd y
415 bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
418 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
421 const EC_GROUP *group = EC_KEY_get0_group(pkey);
422 CBigNum order, halforder;
423 EC_GROUP_get_order(group, order.get(), NULL);
424 BN_rshift1(halforder.get(), order.get());
426 // Get internal R and S pointers
427 const BIGNUM *current_s = ECDSA_SIG_get0_s(sig);
429 // enforce low S values, by negating the value (modulo the order) if above order/2.
430 if (BN_cmp(current_s, halforder.get()) > 0) {
431 BIGNUM *updated_s = BN_new();
432 BN_copy(updated_s, current_s);
433 BN_sub(updated_s, order.get(), updated_s);
434 ECDSA_SIG_set0(sig, NULL, updated_s);
439 int nBitsR = BN_num_bits(ECDSA_SIG_get0_r(sig));
440 int nBitsS = BN_num_bits(ECDSA_SIG_get0_s(sig));
441 bool fCompressedPubKey = IsCompressed();
442 if (nBitsR <= 256 && nBitsS <= 256)
445 for (int8_t i=0; i<4; i++)
449 keyRec.SetCompressedPubKey(fCompressedPubKey);
450 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
451 if (keyRec.GetPubKey() == this->GetPubKey())
461 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
464 vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
465 BN_bn2bin(ECDSA_SIG_get0_r(sig),&vchSig[33-(nBitsR+7)/8]);
466 BN_bn2bin(ECDSA_SIG_get0_s(sig),&vchSig[65-(nBitsS+7)/8]);
473 // reconstruct public key from a compact signature
474 // This is only slightly more CPU intensive than just verifying it.
475 // If this function succeeds, the recovered public key is guaranteed to be valid
476 // (the signature is a valid signature of the given data for that key)
477 bool CPubKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
479 if (vchSig.size() != 65)
484 ECDSA_SIG *sig = ECDSA_SIG_new();
485 BIGNUM *sig_r, *sig_s;
486 BN_bin2bn(&vchSig[1],32,sig_r);
487 BN_bin2bn(&vchSig[33],32,sig_s);
488 ECDSA_SIG_set0(sig, sig_r, sig_s);
489 bool fSuccessful = false;
490 EC_KEY* pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
494 EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
498 if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) != 1)
500 int nSize = i2o_ECPublicKey(pkey, NULL);
503 std::vector<unsigned char> vchPubKey(nSize, 0);
504 unsigned char* pbegin = &vchPubKey[0];
505 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
507 Set(vchPubKey.begin(), vchPubKey.end());
508 fSuccessful = IsValid();
518 bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const
520 if (vchSig.empty() || !IsValid())
523 EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
524 ECDSA_SIG *norm_sig = ECDSA_SIG_new();
533 uint8_t *norm_der = NULL;
534 const uint8_t* pbegin = &vbytes[0];
535 const uint8_t* sigptr = &vchSig[0];
537 // Trying to parse public key
538 if (!o2i_ECPublicKey(&pkey, &pbegin, size()))
540 // New versions of OpenSSL are rejecting a non-canonical DER signatures, de/re-serialize first.
541 if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL)
543 if ((derlen = i2d_ECDSA_SIG(norm_sig, &norm_der)) <= 0)
546 // -1 = error, 0 = bad sig, 1 = good
547 ret = ECDSA_verify(0, (const unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
548 OPENSSL_free(norm_der);
551 ECDSA_SIG_free(norm_sig);
557 bool CPubKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
560 if (!key.SetCompactSignature(hash, vchSig))
570 if (!EC_KEY_check_key(pkey))
574 CSecret secret = GetSecret(fCompr);
576 key2.SetSecret(secret, fCompr);
578 return GetPubKey() == key2.GetPubKey();
588 group = EC_GROUP_new_by_curve_name(NID_secp256k1);
590 err = "EC_KEY_new_by_curve_name failed.";
594 point = EC_POINT_new(group);
596 err = "EC_POINT_new failed.";
602 err = "BN_CTX_new failed.";
609 if (group) EC_GROUP_free(group);
610 if (point) EC_POINT_free(point);
611 throw std::runtime_error(std::string("CPoint::CPoint() : - ") + err);
614 bool CPoint::operator!=(const CPoint &a)
616 if (EC_POINT_cmp(group, point, a.point, ctx) != 0)
622 if (point) EC_POINT_free(point);
623 if (group) EC_GROUP_free(group);
624 if (ctx) BN_CTX_free(ctx);
627 // Initialize from octets stream
628 bool CPoint::setBytes(const std::vector<unsigned char> &vchBytes)
630 if (!EC_POINT_oct2point(group, point, &vchBytes[0], vchBytes.size(), ctx)) {
636 // Initialize from octets stream
637 bool CPoint::setPubKey(const CPubKey &key)
639 std::vector<uint8_t> vchPubKey(key.begin(), key.end());
640 return setBytes(vchPubKey);
643 // Serialize to octets stream
644 bool CPoint::getBytes(std::vector<unsigned char> &vchBytes)
646 size_t nSize = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, ctx);
647 vchBytes.resize(nSize);
648 if (!(nSize == EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, &vchBytes[0], nSize, ctx))) {
654 // ECC multiplication by specified multiplier
655 bool CPoint::ECMUL(const CBigNum &bnMultiplier)
657 if (!EC_POINT_mul(group, point, NULL, point, bnMultiplier.get(), NULL)) {
658 printf("CPoint::ECMUL() : EC_POINT_mul failed");
666 bool CPoint::ECMULGEN(const CBigNum &bnMultiplier, const CPoint &qPoint)
668 if (!EC_POINT_mul(group, point, bnMultiplier.get(), qPoint.point, BN_value_one(), NULL)) {
669 printf("CPoint::ECMULGEN() : EC_POINT_mul failed.");
678 void CMalleablePubKey::GetVariant(CPubKey &R, CPubKey &vchPubKeyVariant)
680 EC_KEY *eckey = NULL;
681 eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
683 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_new_by_curve_name failed");
686 // Use standard key generation function to get r and R values.
688 // r will be presented by private key;
689 // R is ECDSA public key which calculated as G*r
690 if (!EC_KEY_generate_key(eckey)) {
691 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_generate_key failed");
694 EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
696 int nSize = i2o_ECPublicKey(eckey, NULL);
698 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey failed");
701 std::vector<unsigned char> vchPubKey(nSize, 0);
702 unsigned char* pbegin_R = &vchPubKey[0];
704 if (i2o_ECPublicKey(eckey, &pbegin_R) != nSize) {
705 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey returned unexpected size");
709 R = CPubKey(vchPubKey);
711 // OpenSSL BIGNUM representation of r value
713 bnr = *(CBigNum*) EC_KEY_get0_private_key(eckey);
717 if (!point.setPubKey(pubKeyL)) {
718 throw key_error("CMalleablePubKey::GetVariant() : Unable to decode L value");
724 std::vector<unsigned char> vchLr;
725 if (!point.getBytes(vchLr)) {
726 throw key_error("CMalleablePubKey::GetVariant() : Unable to convert Lr value");
729 // Calculate Hash(L*r) and then get a BIGNUM representation of hash value.
731 bnHash.setuint160(Hash160(vchLr));
734 pointH.setPubKey(pubKeyH);
737 // Calculate P = Hash(L*r)*G + H
738 P.ECMULGEN(bnHash, pointH);
740 if (P.IsInfinity()) {
741 throw key_error("CMalleablePubKey::GetVariant() : P is infinity");
744 std::vector<unsigned char> vchResult;
745 P.getBytes(vchResult);
747 vchPubKeyVariant = CPubKey(vchResult);
750 std::string CMalleablePubKey::ToString() const
752 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
754 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
756 return EncodeBase58Check(vch);
759 bool CMalleablePubKey::setvch(const std::vector<unsigned char> &vchPubKeyPair)
761 CDataStream ssKey(vchPubKeyPair, SER_NETWORK, PROTOCOL_VERSION);
767 std::vector<unsigned char> CMalleablePubKey::Raw() const
769 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
771 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
776 bool CMalleablePubKey::SetString(const std::string& strMalleablePubKey)
778 std::vector<unsigned char> vchTemp;
779 if (!DecodeBase58Check(strMalleablePubKey, vchTemp)) {
780 throw key_error("CMalleablePubKey::SetString() : Provided key data seems corrupted.");
782 if (vchTemp.size() != 68)
785 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
791 bool CMalleablePubKey::operator==(const CMalleablePubKey &b)
793 return pubKeyL == b.pubKeyL && pubKeyH == b.pubKeyH;
799 void CMalleableKey::Reset()
805 void CMalleableKey::MakeNewKeys()
813 vchSecretL = keyL.GetSecret();
814 vchSecretH = keyH.GetSecret();
817 CMalleableKey::CMalleableKey()
822 CMalleableKey::CMalleableKey(const CMalleableKey &b)
824 SetSecrets(b.vchSecretL, b.vchSecretH);
827 CMalleableKey::CMalleableKey(const CSecret &L, const CSecret &H)
832 CMalleableKey::~CMalleableKey()
836 bool CMalleableKey::IsNull() const
838 return vchSecretL.size() != 32 || vchSecretH.size() != 32;
841 bool CMalleableKey::SetSecrets(const CSecret &pvchSecretL, const CSecret &pvchSecretH)
845 CKey keyL(pvchSecretL);
846 CKey keyH(pvchSecretH);
848 if (!keyL.IsValid() || !keyH.IsValid())
851 vchSecretL = pvchSecretL;
852 vchSecretH = pvchSecretH;
857 CMalleablePubKey CMalleableKey::GetMalleablePubKey() const
859 CKey L(vchSecretL), H(vchSecretH);
860 return CMalleablePubKey(L.GetPubKey(), H.GetPubKey());
864 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
867 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
871 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
875 if (!vchPubKeyVariant.IsValid()) {
876 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
881 if (!point_R.setPubKey(R)) {
882 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
887 CPubKey vchPubKeyH = H.GetPubKey();
890 if (!point_H.setPubKey(vchPubKeyH)) {
891 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
896 if (!point_P.setPubKey(vchPubKeyVariant)) {
897 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
901 // Infinity points are senseless
902 if (point_P.IsInfinity()) {
903 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
908 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
912 std::vector<unsigned char> vchRl;
913 if (!point_R.getBytes(vchRl)) {
914 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
918 // Calculate Hash(R*l)
920 bnHash.setuint160(Hash160(vchRl));
923 // Calculate Ps = Hash(L*r)*G + H
924 point_Ps.ECMULGEN(bnHash, point_H);
926 // Infinity points are senseless
927 if (point_Ps.IsInfinity()) {
928 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
933 if (point_Ps != point_P) {
940 // Check ownership and restore private key
941 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant, CKey &privKeyVariant) const
944 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
948 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
952 if (!vchPubKeyVariant.IsValid()) {
953 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
958 if (!point_R.setPubKey(R)) {
959 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
964 CPubKey vchPubKeyH = H.GetPubKey();
967 if (!point_H.setPubKey(vchPubKeyH)) {
968 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
973 if (!point_P.setPubKey(vchPubKeyVariant)) {
974 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
978 // Infinity points are senseless
979 if (point_P.IsInfinity()) {
980 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
985 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
989 std::vector<unsigned char> vchRl;
990 if (!point_R.getBytes(vchRl)) {
991 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
995 // Calculate Hash(R*l)
997 bnHash.setuint160(Hash160(vchRl));
1000 // Calculate Ps = Hash(L*r)*G + H
1001 point_Ps.ECMULGEN(bnHash, point_H);
1003 // Infinity points are senseless
1004 if (point_Ps.IsInfinity()) {
1005 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
1010 if (point_Ps != point_P) {
1014 // OpenSSL BIGNUM representation of the second private key from (l, h) pair
1016 bnh.setBytes(std::vector<unsigned char>(vchSecretH.begin(), vchSecretH.end()));
1018 // Calculate p = Hash(R*l) + h
1019 CBigNum bnp = bnHash + bnh;
1021 std::vector<unsigned char> vchp = bnp.getBytes();
1022 privKeyVariant.SetSecret(CSecret(vchp.begin(), vchp.end()));
1027 std::string CMalleableKey::ToString() const
1029 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1031 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1033 return EncodeBase58Check(vch);
1036 std::vector<unsigned char> CMalleableKey::Raw() const
1038 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1040 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1045 bool CMalleableKey::SetString(const std::string& strMutableKey)
1047 std::vector<unsigned char> vchTemp;
1048 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1049 throw key_error("CMalleableKey::SetString() : Provided key data seems corrupted.");
1051 if (vchTemp.size() != 66)
1053 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1059 // CMalleableKeyView
1061 CMalleableKeyView::CMalleableKeyView(const std::string &strMalleableKey)
1063 SetString(strMalleableKey);
1066 CMalleableKeyView::CMalleableKeyView(const CMalleableKey &b)
1068 if (b.vchSecretL.size() != 32)
1069 throw key_error("CMalleableKeyView::CMalleableKeyView() : L size must be 32 bytes");
1071 if (b.vchSecretH.size() != 32)
1072 throw key_error("CMalleableKeyView::CMalleableKeyView() : H size must be 32 bytes");
1074 vchSecretL = b.vchSecretL;
1076 CKey H(b.vchSecretH);
1077 vchPubKeyH = H.GetPubKey();
1080 CMalleableKeyView::CMalleableKeyView(const CMalleableKeyView &b)
1082 vchSecretL = b.vchSecretL;
1083 vchPubKeyH = b.vchPubKeyH;
1086 CMalleableKeyView& CMalleableKeyView::operator=(const CMalleableKey &b)
1088 vchSecretL = b.vchSecretL;
1090 CKey H(b.vchSecretH);
1091 vchPubKeyH = H.GetPubKey();
1096 CMalleableKeyView::~CMalleableKeyView()
1100 CMalleablePubKey CMalleableKeyView::GetMalleablePubKey() const
1102 CKey keyL(vchSecretL);
1103 return CMalleablePubKey(keyL.GetPubKey(), vchPubKeyH);
1107 bool CMalleableKeyView::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
1110 throw key_error("CMalleableKeyView::CheckKeyVariant() : Attempting to run on invalid view object.");
1114 printf("CMalleableKeyView::CheckKeyVariant() : R is invalid");
1118 if (!vchPubKeyVariant.IsValid()) {
1119 printf("CMalleableKeyView::CheckKeyVariant() : public key variant is invalid");
1124 if (!point_R.setPubKey(R)) {
1125 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode R value");
1130 if (!point_H.setPubKey(vchPubKeyH)) {
1131 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode H value");
1136 if (!point_P.setPubKey(vchPubKeyVariant)) {
1137 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode P value");
1141 // Infinity points are senseless
1142 if (point_P.IsInfinity()) {
1143 printf("CMalleableKeyView::CheckKeyVariant() : P is infinity");
1148 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
1152 std::vector<unsigned char> vchRl;
1153 if (!point_R.getBytes(vchRl)) {
1154 printf("CMalleableKeyView::CheckKeyVariant() : Unable to convert Rl value");
1158 // Calculate Hash(R*l)
1160 bnHash.setuint160(Hash160(vchRl));
1163 // Calculate Ps = Hash(L*r)*G + H
1164 point_Ps.ECMULGEN(bnHash, point_H);
1166 // Infinity points are senseless
1167 if (point_Ps.IsInfinity()) {
1168 printf("CMalleableKeyView::CheckKeyVariant() : Ps is infinity");
1173 if (point_Ps != point_P) {
1180 std::string CMalleableKeyView::ToString() const
1182 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1184 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1186 return EncodeBase58Check(vch);
1189 bool CMalleableKeyView::SetString(const std::string& strMutableKey)
1191 std::vector<unsigned char> vchTemp;
1192 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1193 throw key_error("CMalleableKeyView::SetString() : Provided key data seems corrupted.");
1196 if (vchTemp.size() != 67)
1199 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1205 std::vector<unsigned char> CMalleableKeyView::Raw() const
1207 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1209 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1215 bool CMalleableKeyView::IsValid() const
1217 return vchSecretL.size() == 32 && GetMalleablePubKey().IsValid();
1220 //// Asymmetric encryption
1222 void CPubKey::EncryptData(const std::vector<unsigned char>& data, std::vector<unsigned char>& encrypted)
1225 char error[1024] = "Unknown error";
1226 cryptogram_t *cryptogram;
1228 const unsigned char* pbegin = &vbytes[0];
1229 EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
1230 if (!o2i_ECPublicKey(&pkey, &pbegin, size()))
1231 throw key_error("Unable to parse EC key");
1233 ctx = create_context(pkey);
1234 if (!EC_KEY_get0_public_key(ctx->user_key))
1235 throw key_error("Given EC key is not public key");
1237 cryptogram = ecies_encrypt(ctx, (unsigned char*)&data[0], data.size(), error);
1238 if (cryptogram == NULL) {
1241 throw key_error(std::string("Error in encryption: %s") + error);
1244 encrypted.resize(cryptogram_data_sum_length(cryptogram));
1245 unsigned char *key_data = cryptogram_key_data(cryptogram);
1246 memcpy(&encrypted[0], key_data, encrypted.size());
1247 cryptogram_free(cryptogram);
1251 void CKey::DecryptData(const std::vector<unsigned char>& encrypted, std::vector<unsigned char>& data)
1254 char error[1024] = "Unknown error";
1255 cryptogram_t *cryptogram;
1257 unsigned char *decrypted;
1259 ctx = create_context(pkey);
1260 if (!EC_KEY_get0_private_key(ctx->user_key))
1261 throw key_error("Given EC key is not private key");
1263 size_t key_length = ctx->stored_key_length;
1264 size_t mac_length = EVP_MD_size(ctx->md);
1265 cryptogram = cryptogram_alloc(key_length, mac_length, encrypted.size() - key_length - mac_length);
1267 memcpy(cryptogram_key_data(cryptogram), &encrypted[0], encrypted.size());
1269 decrypted = ecies_decrypt(ctx, cryptogram, &length, error);
1270 cryptogram_free(cryptogram);
1273 if (decrypted == NULL) {
1274 throw key_error(std::string("Error in decryption: %s") + error);
1277 data.resize(length);
1278 memcpy(&data[0], decrypted, length);