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; }
83 if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
84 field = BN_CTX_get(ctx);
85 if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
86 if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
87 if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
88 if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
91 if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
92 if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
93 if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
95 if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
96 n = EC_GROUP_get_degree(group);
98 if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
99 if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
100 zero = BN_CTX_get(ctx);
101 if (!BN_zero(zero)) { ret=-1; goto err; }
102 if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
103 rr = BN_CTX_get(ctx);
104 if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
105 sor = BN_CTX_get(ctx);
106 if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
107 eor = BN_CTX_get(ctx);
108 if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
109 if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
110 if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
119 if (R != NULL) EC_POINT_free(R);
120 if (O != NULL) EC_POINT_free(O);
121 if (Q != NULL) EC_POINT_free(Q);
125 int CompareBigEndian(const unsigned char *c1, size_t c1len, const unsigned char *c2, size_t c2len) {
126 while (c1len > c2len) {
132 while (c2len > c1len) {
150 // Order of secp256k1's generator minus 1.
151 const unsigned char vchMaxModOrder[32] = {
152 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
153 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
154 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,
155 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40
158 // Half of the order of secp256k1's generator minus 1.
159 const unsigned char vchMaxModHalfOrder[32] = {
160 0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
161 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
162 0x5D,0x57,0x6E,0x73,0x57,0xA4,0x50,0x1D,
163 0xDF,0xE9,0x2F,0x46,0x68,0x1B,0x20,0xA0
166 const unsigned char *vchZero = NULL;
168 void CKey::SetCompressedPubKey()
170 EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
171 fCompressedPubKey = true;
176 fCompressedPubKey = fSet = false;
179 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
181 throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
190 CKey::CKey(const CKey& b)
192 pkey = EC_KEY_dup(b.pkey);
194 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
196 fCompressedPubKey = b.fCompressedPubKey;
199 CKey::CKey(const CSecret& b, bool fCompressed)
201 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
203 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
204 SetSecret(b, fCompressed);
207 CKey& CKey::operator=(const CKey& b)
209 if (!EC_KEY_copy(pkey, b.pkey))
210 throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
212 fCompressedPubKey = b.fCompressedPubKey;
222 bool CKey::IsNull() const
227 bool CKey::IsCompressed() const
229 return fCompressedPubKey;
232 bool CKey::CheckSignatureElement(const unsigned char *vch, int len, bool half) {
233 return CompareBigEndian(vch, len, vchZero, 0) > 0 &&
234 CompareBigEndian(vch, len, half ? vchMaxModHalfOrder : vchMaxModOrder, 32) <= 0;
237 bool CPubKey::ReserealizeSignature(std::vector<unsigned char>& vchSig)
242 unsigned char *pos = &vchSig[0];
243 ECDSA_SIG *sig = d2i_ECDSA_SIG(NULL, (const unsigned char **)&pos, vchSig.size());
248 int nSize = i2d_ECDSA_SIG(sig, NULL);
250 vchSig.resize(nSize); // grow or shrink as needed
253 i2d_ECDSA_SIG(sig, &pos);
263 void CKey::MakeNewKey(bool fCompressed)
265 if (!EC_KEY_generate_key(pkey))
266 throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
268 SetCompressedPubKey();
272 bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
274 const unsigned char* pbegin = &vchPrivKey[0];
275 if (d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
277 // In testing, d2i_ECPrivateKey can return true
278 // but fill in pkey with a key that fails
279 // EC_KEY_check_key, so:
280 if (EC_KEY_check_key(pkey))
286 // If vchPrivKey data is bad d2i_ECPrivateKey() can
287 // leave pkey in a state where calling EC_KEY_free()
288 // crashes. To avoid that, set pkey to NULL and
289 // leak the memory (a leak is better than a crash)
295 bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
298 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
300 throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
302 if (vchSecret.size() != 32)
303 throw key_error("CKey::SetSecret() : secret must be 32 bytes");
304 BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
306 throw key_error("CKey::SetSecret() : BN_bin2bn failed");
307 if (!EC_KEY_regenerate_key(pkey,bn))
310 throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
314 if (fCompressed || fCompressedPubKey)
315 SetCompressedPubKey();
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 = fCompressedPubKey;
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.");
340 if(!PEM_write_bio_PKCS8PrivateKey(streamObj, evpKey, EVP_aes_256_cbc(), (char *)&strPassKey[0], strPassKey.size(), NULL, NULL))
341 return error("CKey::WritePEM() : Error writing private key data to stream object");
343 if(!PEM_write_bio_PUBKEY(streamObj, evpKey))
344 return error("CKey::WritePEM() : Error writing public key data to stream object");
349 CSecret CKey::GetSecret() const
352 return GetSecret(fCompressed);
355 CPrivKey CKey::GetPrivKey() const
357 int nSize = i2d_ECPrivateKey(pkey, NULL);
359 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
360 CPrivKey vchPrivKey(nSize, 0);
361 unsigned char* pbegin = &vchPrivKey[0];
362 if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
363 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
367 CPubKey CKey::GetPubKey() const
369 int nSize = i2o_ECPublicKey(pkey, NULL);
371 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
372 std::vector<unsigned char> vchPubKey(nSize, 0);
373 unsigned char* pbegin = &vchPubKey[0];
374 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
375 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
376 return CPubKey(vchPubKey);
379 bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
382 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
385 const EC_GROUP *group = EC_KEY_get0_group(pkey);
386 CBigNum order, halforder;
387 EC_GROUP_get_order(group, &order, NULL);
388 BN_rshift1(&halforder, &order);
389 // enforce low S values, by negating the value (modulo the order) if above order/2.
390 if (BN_cmp(sig->s, &halforder) > 0) {
391 BN_sub(sig->s, &order, sig->s);
393 unsigned int nSize = ECDSA_size(pkey);
394 vchSig.resize(nSize); // Make sure it is big enough
395 unsigned char *pos = &vchSig[0];
396 nSize = i2d_ECDSA_SIG(sig, &pos);
398 vchSig.resize(nSize); // Shrink to fit actual size
399 // Testing our new signature
400 if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) {
407 // create a compact signature (65 bytes), which allows reconstructing the used public key
408 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
409 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
410 // 0x1D = second key with even y, 0x1E = second key with odd y
411 bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
414 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
417 const EC_GROUP *group = EC_KEY_get0_group(pkey);
418 CBigNum order, halforder;
419 EC_GROUP_get_order(group, &order, NULL);
420 BN_rshift1(&halforder, &order);
421 // enforce low S values, by negating the value (modulo the order) if above order/2.
422 if (BN_cmp(sig->s, &halforder) > 0) {
423 BN_sub(sig->s, &order, sig->s);
427 int nBitsR = BN_num_bits(sig->r);
428 int nBitsS = BN_num_bits(sig->s);
429 if (nBitsR <= 256 && nBitsS <= 256)
432 for (int8_t i=0; i<4; i++)
436 if (fCompressedPubKey)
437 keyRec.SetCompressedPubKey();
438 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
439 if (keyRec.GetPubKey() == this->GetPubKey())
449 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
452 vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
453 BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
454 BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
461 // reconstruct public key from a compact signature
462 // This is only slightly more CPU intensive than just verifying it.
463 // If this function succeeds, the recovered public key is guaranteed to be valid
464 // (the signature is a valid signature of the given data for that key)
465 bool CPubKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
467 if (vchSig.size() != 65)
472 ECDSA_SIG *sig = ECDSA_SIG_new();
473 BN_bin2bn(&vchSig[1],32,sig->r);
474 BN_bin2bn(&vchSig[33],32,sig->s);
476 EC_KEY* pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
480 EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
485 if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) != 1)
489 int nSize = i2o_ECPublicKey(pkey, NULL);
492 std::vector<unsigned char> vchPubKey(nSize, 0);
493 unsigned char* pbegin = &vchPubKey[0];
494 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
496 Set(vchPubKey.begin(), vchPubKey.end());
506 bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const
508 if (vchSig.empty() || !IsValid())
511 const unsigned char* pbegin = &vbytes[0];
512 EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
513 if (!o2i_ECPublicKey(&pkey, &pbegin, size()))
514 return false; // Unable to parse public key
516 // New versions of OpenSSL will reject non-canonical DER signatures. de/re-serialize first.
517 unsigned char *norm_der = NULL;
518 ECDSA_SIG *norm_sig = ECDSA_SIG_new();
519 const unsigned char* sigptr = &vchSig[0];
521 if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL)
523 /* As of OpenSSL 1.0.0p d2i_ECDSA_SIG frees and nulls the pointer on
524 * error. But OpenSSL's own use of this function redundantly frees the
525 * result. As ECDSA_SIG_free(NULL) is a no-op, and in the absence of a
526 * clear contract for the function behaving the same way is more
529 ECDSA_SIG_free(norm_sig);
532 int derlen = i2d_ECDSA_SIG(norm_sig, &norm_der);
533 ECDSA_SIG_free(norm_sig);
537 // -1 = error, 0 = bad sig, 1 = good
538 bool ret = ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
539 OPENSSL_free(norm_der);
543 bool CPubKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
546 if (!key.SetCompactSignature(hash, vchSig))
556 if (!EC_KEY_check_key(pkey))
560 CSecret secret = GetSecret(fCompr);
562 key2.SetSecret(secret, fCompr);
564 return GetPubKey() == key2.GetPubKey();
574 group = EC_GROUP_new_by_curve_name(NID_secp256k1);
576 err = "EC_KEY_new_by_curve_name failed.";
580 point = EC_POINT_new(group);
582 err = "EC_POINT_new failed.";
588 err = "BN_CTX_new failed.";
595 if (group) EC_GROUP_free(group);
596 if (point) EC_POINT_free(point);
597 throw std::runtime_error(std::string("CPoint::CPoint() : - ") + err);
600 bool CPoint::operator!=(const CPoint &a)
602 if (EC_POINT_cmp(group, point, a.point, ctx) != 0)
608 if (point) EC_POINT_free(point);
609 if (group) EC_GROUP_free(group);
610 if (ctx) BN_CTX_free(ctx);
613 // Initialize from octets stream
614 bool CPoint::setBytes(const std::vector<unsigned char> &vchBytes)
616 if (!EC_POINT_oct2point(group, point, &vchBytes[0], vchBytes.size(), ctx)) {
622 // Initialize from octets stream
623 bool CPoint::setPubKey(const CPubKey &key)
625 std::vector<uint8_t> vchPubKey(key.begin(), key.end());
626 return setBytes(vchPubKey);
629 // Serialize to octets stream
630 bool CPoint::getBytes(std::vector<unsigned char> &vchBytes)
632 size_t nSize = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, ctx);
633 vchBytes.resize(nSize);
634 if (!(nSize == EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, &vchBytes[0], nSize, ctx))) {
640 // ECC multiplication by specified multiplier
641 bool CPoint::ECMUL(const CBigNum &bnMultiplier)
643 if (!EC_POINT_mul(group, point, NULL, point, &bnMultiplier, NULL)) {
644 printf("CPoint::ECMUL() : EC_POINT_mul failed");
652 bool CPoint::ECMULGEN(const CBigNum &bnMultiplier, const CPoint &qPoint)
654 if (!EC_POINT_mul(group, point, &bnMultiplier, qPoint.point, BN_value_one(), NULL)) {
655 printf("CPoint::ECMULGEN() : EC_POINT_mul failed.");
664 void CMalleablePubKey::GetVariant(CPubKey &R, CPubKey &vchPubKeyVariant)
666 EC_KEY *eckey = NULL;
667 eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
669 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_new_by_curve_name failed");
672 // Use standard key generation function to get r and R values.
674 // r will be presented by private key;
675 // R is ECDSA public key which calculated as G*r
676 if (!EC_KEY_generate_key(eckey)) {
677 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_generate_key failed");
680 EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
682 int nSize = i2o_ECPublicKey(eckey, NULL);
684 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey failed");
687 std::vector<unsigned char> vchPubKey(nSize, 0);
688 unsigned char* pbegin_R = &vchPubKey[0];
690 if (i2o_ECPublicKey(eckey, &pbegin_R) != nSize) {
691 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey returned unexpected size");
695 R = CPubKey(vchPubKey);
697 // OpenSSL BIGNUM representation of r value
699 bnr = *(CBigNum*) EC_KEY_get0_private_key(eckey);
703 if (!point.setPubKey(pubKeyL)) {
704 throw key_error("CMalleablePubKey::GetVariant() : Unable to decode L value");
710 std::vector<unsigned char> vchLr;
711 if (!point.getBytes(vchLr)) {
712 throw key_error("CMalleablePubKey::GetVariant() : Unable to convert Lr value");
715 // Calculate Hash(L*r) and then get a BIGNUM representation of hash value.
717 bnHash.setuint160(Hash160(vchLr));
720 pointH.setPubKey(pubKeyH);
723 // Calculate P = Hash(L*r)*G + H
724 P.ECMULGEN(bnHash, pointH);
726 if (P.IsInfinity()) {
727 throw key_error("CMalleablePubKey::GetVariant() : P is infinity");
730 std::vector<unsigned char> vchResult;
731 P.getBytes(vchResult);
733 vchPubKeyVariant = CPubKey(vchResult);
736 std::string CMalleablePubKey::ToString() const
738 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
740 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
742 return EncodeBase58Check(vch);
745 bool CMalleablePubKey::setvch(const std::vector<unsigned char> &vchPubKeyPair)
747 CDataStream ssKey(vchPubKeyPair, SER_NETWORK, PROTOCOL_VERSION);
753 std::vector<unsigned char> CMalleablePubKey::Raw() const
755 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
757 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
762 bool CMalleablePubKey::SetString(const std::string& strMalleablePubKey)
764 std::vector<unsigned char> vchTemp;
765 if (!DecodeBase58Check(strMalleablePubKey, vchTemp)) {
766 throw key_error("CMalleablePubKey::SetString() : Provided key data seems corrupted.");
769 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
775 bool CMalleablePubKey::operator==(const CMalleablePubKey &b)
777 return pubKeyL == b.pubKeyL && pubKeyH == b.pubKeyH;
783 void CMalleableKey::Reset()
789 void CMalleableKey::MakeNewKeys()
797 vchSecretL = keyL.GetSecret();
798 vchSecretH = keyH.GetSecret();
801 CMalleableKey::CMalleableKey()
806 CMalleableKey::CMalleableKey(const CMalleableKey &b)
808 SetSecrets(b.vchSecretL, b.vchSecretH);
811 CMalleableKey::CMalleableKey(const CSecret &L, const CSecret &H)
816 CMalleableKey::~CMalleableKey()
820 bool CMalleableKey::IsNull() const
822 return vchSecretL.size() != 32 || vchSecretH.size() != 32;
825 bool CMalleableKey::SetSecrets(const CSecret &pvchSecretL, const CSecret &pvchSecretH)
829 CKey keyL(pvchSecretL);
830 CKey keyH(pvchSecretH);
832 if (!keyL.IsValid() || !keyH.IsValid())
835 vchSecretL = pvchSecretL;
836 vchSecretH = pvchSecretH;
841 CMalleablePubKey CMalleableKey::GetMalleablePubKey() const
843 CKey L(vchSecretL), H(vchSecretH);
844 return CMalleablePubKey(L.GetPubKey(), H.GetPubKey());
848 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
851 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
855 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
859 if (!vchPubKeyVariant.IsValid()) {
860 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
865 if (!point_R.setPubKey(R)) {
866 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
871 CPubKey vchPubKeyH = H.GetPubKey();
874 if (!point_H.setPubKey(vchPubKeyH)) {
875 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
880 if (!point_P.setPubKey(vchPubKeyVariant)) {
881 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
885 // Infinity points are senseless
886 if (point_P.IsInfinity()) {
887 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
892 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
896 std::vector<unsigned char> vchRl;
897 if (!point_R.getBytes(vchRl)) {
898 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
902 // Calculate Hash(R*l)
904 bnHash.setuint160(Hash160(vchRl));
907 // Calculate Ps = Hash(L*r)*G + H
908 point_Ps.ECMULGEN(bnHash, point_H);
910 // Infinity points are senseless
911 if (point_Ps.IsInfinity()) {
912 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
917 if (point_Ps != point_P) {
924 // Check ownership and restore private key
925 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant, CKey &privKeyVariant) const
928 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
932 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
936 if (!vchPubKeyVariant.IsValid()) {
937 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
942 if (!point_R.setPubKey(R)) {
943 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
948 CPubKey vchPubKeyH = H.GetPubKey();
951 if (!point_H.setPubKey(vchPubKeyH)) {
952 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
957 if (!point_P.setPubKey(vchPubKeyVariant)) {
958 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
962 // Infinity points are senseless
963 if (point_P.IsInfinity()) {
964 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
969 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
973 std::vector<unsigned char> vchRl;
974 if (!point_R.getBytes(vchRl)) {
975 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
979 // Calculate Hash(R*l)
981 bnHash.setuint160(Hash160(vchRl));
984 // Calculate Ps = Hash(L*r)*G + H
985 point_Ps.ECMULGEN(bnHash, point_H);
987 // Infinity points are senseless
988 if (point_Ps.IsInfinity()) {
989 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
994 if (point_Ps != point_P) {
998 // OpenSSL BIGNUM representation of the second private key from (l, h) pair
1000 bnh.setBytes(std::vector<unsigned char>(vchSecretH.begin(), vchSecretH.end()));
1002 // Calculate p = Hash(R*l) + h
1003 CBigNum bnp = bnHash + bnh;
1005 std::vector<unsigned char> vchp = bnp.getBytes();
1006 privKeyVariant.SetSecret(CSecret(vchp.begin(), vchp.end()));
1011 std::string CMalleableKey::ToString() const
1013 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1015 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1017 return EncodeBase58Check(vch);
1020 std::vector<unsigned char> CMalleableKey::Raw() const
1022 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1024 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1029 bool CMalleableKey::SetString(const std::string& strMutableKey)
1031 std::vector<unsigned char> vchTemp;
1032 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1033 throw key_error("CMalleableKey::SetString() : Provided key data seems corrupted.");
1036 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1042 // CMalleableKeyView
1044 CMalleableKeyView::CMalleableKeyView(const std::string &strMalleableKey)
1046 SetString(strMalleableKey);
1049 CMalleableKeyView::CMalleableKeyView(const CMalleableKey &b)
1051 if (b.vchSecretL.size() != 32)
1052 throw key_error("CMalleableKeyView::CMalleableKeyView() : L size must be 32 bytes");
1054 if (b.vchSecretH.size() != 32)
1055 throw key_error("CMalleableKeyView::CMalleableKeyView() : H size must be 32 bytes");
1057 vchSecretL = b.vchSecretL;
1059 CKey H(b.vchSecretH);
1060 vchPubKeyH = H.GetPubKey();
1063 CMalleableKeyView::CMalleableKeyView(const CMalleableKeyView &b)
1065 vchSecretL = b.vchSecretL;
1066 vchPubKeyH = b.vchPubKeyH;
1069 CMalleableKeyView& CMalleableKeyView::operator=(const CMalleableKey &b)
1071 vchSecretL = b.vchSecretL;
1073 CKey H(b.vchSecretH);
1074 vchPubKeyH = H.GetPubKey();
1079 CMalleableKeyView::~CMalleableKeyView()
1083 CMalleablePubKey CMalleableKeyView::GetMalleablePubKey() const
1085 CKey keyL(vchSecretL);
1086 return CMalleablePubKey(keyL.GetPubKey(), vchPubKeyH);
1090 bool CMalleableKeyView::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
1093 throw key_error("CMalleableKeyView::CheckKeyVariant() : Attempting to run on invalid view object.");
1097 printf("CMalleableKeyView::CheckKeyVariant() : R is invalid");
1101 if (!vchPubKeyVariant.IsValid()) {
1102 printf("CMalleableKeyView::CheckKeyVariant() : public key variant is invalid");
1107 if (!point_R.setPubKey(R)) {
1108 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode R value");
1113 if (!point_H.setPubKey(vchPubKeyH)) {
1114 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode H value");
1119 if (!point_P.setPubKey(vchPubKeyVariant)) {
1120 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode P value");
1124 // Infinity points are senseless
1125 if (point_P.IsInfinity()) {
1126 printf("CMalleableKeyView::CheckKeyVariant() : P is infinity");
1131 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
1135 std::vector<unsigned char> vchRl;
1136 if (!point_R.getBytes(vchRl)) {
1137 printf("CMalleableKeyView::CheckKeyVariant() : Unable to convert Rl value");
1141 // Calculate Hash(R*l)
1143 bnHash.setuint160(Hash160(vchRl));
1146 // Calculate Ps = Hash(L*r)*G + H
1147 point_Ps.ECMULGEN(bnHash, point_H);
1149 // Infinity points are senseless
1150 if (point_Ps.IsInfinity()) {
1151 printf("CMalleableKeyView::CheckKeyVariant() : Ps is infinity");
1156 if (point_Ps != point_P) {
1163 std::string CMalleableKeyView::ToString() const
1165 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1167 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1169 return EncodeBase58Check(vch);
1172 bool CMalleableKeyView::SetString(const std::string& strMutableKey)
1174 std::vector<unsigned char> vchTemp;
1175 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1176 throw key_error("CMalleableKeyView::SetString() : Provided key data seems corrupted.");
1179 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1185 std::vector<unsigned char> CMalleableKeyView::Raw() const
1187 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1189 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1195 bool CMalleableKeyView::IsValid() const
1197 return vchSecretL.size() == 32 && GetMalleablePubKey().IsValid();
1200 //// Asymmetric encryption
1202 void CPubKey::EncryptData(const std::vector<unsigned char>& data, std::vector<unsigned char>& encrypted)
1205 char error[1024] = "Unknown error";
1206 cryptogram_t *cryptogram;
1208 const unsigned char* pbegin = &vbytes[0];
1209 EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
1210 if (!o2i_ECPublicKey(&pkey, &pbegin, size()))
1211 throw key_error("Unable to parse EC key");
1213 ctx = create_context(pkey);
1214 if (!EC_KEY_get0_public_key(ctx->user_key))
1215 throw key_error("Given EC key is not public key");
1217 cryptogram = ecies_encrypt(ctx, (unsigned char*)&data[0], data.size(), error);
1218 if (cryptogram == NULL) {
1221 throw key_error(std::string("Error in encryption: %s") + error);
1224 encrypted.resize(cryptogram_data_sum_length(cryptogram));
1225 unsigned char *key_data = cryptogram_key_data(cryptogram);
1226 memcpy(&encrypted[0], key_data, encrypted.size());
1227 cryptogram_free(cryptogram);
1231 void CKey::DecryptData(const std::vector<unsigned char>& encrypted, std::vector<unsigned char>& data)
1234 char error[1024] = "Unknown error";
1235 cryptogram_t *cryptogram;
1237 unsigned char *decrypted;
1239 ctx = create_context(pkey);
1240 if (!EC_KEY_get0_private_key(ctx->user_key))
1241 throw key_error("Given EC key is not private key");
1243 size_t key_length = ctx->stored_key_length;
1244 size_t mac_length = EVP_MD_size(ctx->md);
1245 cryptogram = cryptogram_alloc(key_length, mac_length, encrypted.size() - key_length - mac_length);
1247 memcpy(cryptogram_key_data(cryptogram), &encrypted[0], encrypted.size());
1249 decrypted = ecies_decrypt(ctx, cryptogram, &length, error);
1250 cryptogram_free(cryptogram);
1253 if (decrypted == NULL) {
1254 throw key_error(std::string("Error in decryption: %s") + error);
1257 data.resize(length);
1258 memcpy(&data[0], decrypted, length);