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 auto 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 auto 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 CScriptID::CScriptID(const CScript& in) : uint160(Hash160(in.begin(), in.end()))
172 void CKey::SetCompressedPubKey(bool fCompressed)
174 EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
182 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
184 throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
193 CKey::CKey(const CKey& b)
195 pkey = EC_KEY_dup(b.pkey);
197 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
201 CKey::CKey(const CSecret& b, bool fCompressed)
203 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
205 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
206 SetSecret(b, fCompressed);
209 CKey& CKey::operator=(const CKey& b)
211 if (!EC_KEY_copy(pkey, b.pkey))
212 throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
223 bool CKey::IsNull() const
228 bool CKey::IsCompressed() const
230 return (EC_KEY_get_conv_form(pkey) == POINT_CONVERSION_COMPRESSED);
233 bool CKey::CheckSignatureElement(const unsigned char *vch, int len, bool half) {
234 return CompareBigEndian(vch, len, vchZero, 0) > 0 &&
235 CompareBigEndian(vch, len, half ? vchMaxModHalfOrder : vchMaxModOrder, 32) <= 0;
238 bool CPubKey::ReserealizeSignature(std::vector<unsigned char>& vchSig)
243 auto pos = &vchSig[0];
244 auto sig = d2i_ECDSA_SIG(NULL, (const unsigned char **)&pos, vchSig.size());
249 int nSize = i2d_ECDSA_SIG(sig, NULL);
251 vchSig.resize(nSize); // grow or shrink as needed
254 i2d_ECDSA_SIG(sig, &pos);
264 void CKey::MakeNewKey(bool fCompressed)
266 if (!EC_KEY_generate_key(pkey))
267 throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
268 SetCompressedPubKey(fCompressed);
272 bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
274 auto 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 auto 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 SetCompressedPubKey(fCompressed);
318 CSecret CKey::GetSecret(bool &fCompressed) const
322 auto bn = EC_KEY_get0_private_key(pkey);
323 int nBytes = BN_num_bytes(bn);
325 throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
326 int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
328 throw key_error("CKey::GetSecret(): BN_bn2bin failed");
329 fCompressed = IsCompressed();
333 bool CKey::WritePEM(BIO *streamObj, const SecureString &strPassKey) const // dumppem 4KJLA99FyqMMhjjDe7KnRXK4sjtv9cCtNS /tmp/test.pem 123
335 auto evpKey = EVP_PKEY_new();
336 if (!EVP_PKEY_assign_EC_KEY(evpKey, pkey))
337 return error("CKey::WritePEM() : Error initializing EVP_PKEY instance.");
338 if(!PEM_write_bio_PKCS8PrivateKey(streamObj, evpKey, EVP_aes_256_cbc(), (char *)&strPassKey[0], strPassKey.size(), NULL, NULL))
339 return error("CKey::WritePEM() : Error writing private key data to stream object");
344 CSecret CKey::GetSecret() const
347 return GetSecret(fCompressed);
350 CPrivKey CKey::GetPrivKey() const
352 int nSize = i2d_ECPrivateKey(pkey, NULL);
354 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
355 CPrivKey vchPrivKey(nSize, 0);
356 auto pbegin = &vchPrivKey[0];
357 if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
358 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
362 CPubKey CKey::GetPubKey() const
364 int nSize = i2o_ECPublicKey(pkey, NULL);
366 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
367 std::vector<unsigned char> vchPubKey(nSize, 0);
368 unsigned char* pbegin = &vchPubKey[0];
369 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
370 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
371 return CPubKey(vchPubKey);
374 bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
377 auto sig = ECDSA_do_sign(hash.begin(), hash.size(), pkey);
380 auto group = EC_KEY_get0_group(pkey);
381 CBigNum order, halforder;
382 EC_GROUP_get_order(group, &order, NULL);
383 BN_rshift1(&halforder, &order);
384 // enforce low S values, by negating the value (modulo the order) if above order/2.
385 if (BN_cmp(sig->s, &halforder) > 0) {
386 BN_sub(sig->s, &order, sig->s);
388 size_t nSize = ECDSA_size(pkey);
389 vchSig.resize(nSize); // Make sure it is big enough
390 auto pos = &vchSig[0];
391 nSize = i2d_ECDSA_SIG(sig, &pos);
393 vchSig.resize(nSize); // Shrink to fit actual size
394 // Testing our new signature
395 if (ECDSA_verify(0, hash.begin(), hash.size(), &vchSig[0], vchSig.size(), pkey) != 1) {
402 // create a compact signature (65 bytes), which allows reconstructing the used public key
403 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
404 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
405 // 0x1D = second key with even y, 0x1E = second key with odd y
406 bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig)
409 auto sig = ECDSA_do_sign(hash.begin(), hash.size(), pkey);
412 auto group = EC_KEY_get0_group(pkey);
413 CBigNum order, halforder;
414 EC_GROUP_get_order(group, &order, NULL);
415 BN_rshift1(&halforder, &order);
416 // enforce low S values, by negating the value (modulo the order) if above order/2.
417 if (BN_cmp(sig->s, &halforder) > 0) {
418 BN_sub(sig->s, &order, sig->s);
422 int nBitsR = BN_num_bits(sig->r);
423 int nBitsS = BN_num_bits(sig->s);
424 bool fCompressedPubKey = IsCompressed();
425 if (nBitsR <= 256 && nBitsS <= 256)
428 for (int8_t i=0; i<4; i++)
432 keyRec.SetCompressedPubKey(fCompressedPubKey);
433 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, hash.begin(), hash.size(), i, 1) == 1)
434 if (keyRec.GetPubKey() == this->GetPubKey())
444 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
447 vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
448 BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
449 BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
456 // reconstruct public key from a compact signature
457 // This is only slightly more CPU intensive than just verifying it.
458 // If this function succeeds, the recovered public key is guaranteed to be valid
459 // (the signature is a valid signature of the given data for that key)
460 bool CPubKey::SetCompactSignature(const uint256 &hash, const std::vector<unsigned char>& vchSig)
462 if (vchSig.size() != 65)
467 bool fSuccessful = false;
468 auto sig = ECDSA_SIG_new();
469 auto pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
470 BN_bin2bn(&vchSig[1],32,sig->r);
471 BN_bin2bn(&vchSig[33],32,sig->s);
475 EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
479 if (ECDSA_SIG_recover_key_GFp(pkey, sig, hash.begin(), hash.size(), nV - 27, 0) != 1)
481 int nSize = i2o_ECPublicKey(pkey, NULL);
484 std::vector<unsigned char> vchPubKey(nSize, 0);
485 auto pbegin = &vchPubKey[0];
486 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
488 Set(vchPubKey.begin(), vchPubKey.end());
489 fSuccessful = IsValid();
499 bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const
501 if (vchSig.empty() || !IsValid())
504 auto pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
505 auto norm_sig = ECDSA_SIG_new();
514 uint8_t *norm_der = NULL;
515 auto pbegin = &vbytes[0];
516 auto sigptr = &vchSig[0];
518 // Trying to parse public key
519 if (!o2i_ECPublicKey(&pkey, &pbegin, size()))
521 // New versions of OpenSSL are rejecting a non-canonical DER signatures, de/re-serialize first.
522 if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL)
524 if ((derlen = i2d_ECDSA_SIG(norm_sig, &norm_der)) <= 0)
527 // -1 = error, 0 = bad sig, 1 = good
528 ret = ECDSA_verify(0, hash.begin(), hash.size(), norm_der, derlen, pkey) == 1;
529 OPENSSL_free(norm_der);
532 ECDSA_SIG_free(norm_sig);
538 bool CPubKey::VerifyCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig)
541 if (!key.SetCompactSignature(hash, vchSig))
551 if (!EC_KEY_check_key(pkey))
555 auto secret = GetSecret(fCompr);
557 key2.SetSecret(secret, fCompr);
559 return GetPubKey() == key2.GetPubKey();
569 group = EC_GROUP_new_by_curve_name(NID_secp256k1);
571 err = "EC_KEY_new_by_curve_name failed.";
575 point = EC_POINT_new(group);
577 err = "EC_POINT_new failed.";
583 err = "BN_CTX_new failed.";
590 if (group) EC_GROUP_free(group);
591 if (point) EC_POINT_free(point);
592 throw std::runtime_error(std::string("CPoint::CPoint() : - ") + err);
595 bool CPoint::operator!=(const CPoint &a)
597 if (EC_POINT_cmp(group, point, a.point, ctx) != 0)
603 if (point) EC_POINT_free(point);
604 if (group) EC_GROUP_free(group);
605 if (ctx) BN_CTX_free(ctx);
608 // Initialize from octets stream
609 bool CPoint::setBytes(const std::vector<unsigned char> &vchBytes)
611 if (!EC_POINT_oct2point(group, point, &vchBytes[0], vchBytes.size(), ctx)) {
617 // Initialize from octets stream
618 bool CPoint::setPubKey(const CPubKey &key)
620 std::vector<uint8_t> vchPubKey(key.begin(), key.end());
621 return setBytes(vchPubKey);
624 // Serialize to octets stream
625 bool CPoint::getBytes(std::vector<unsigned char> &vchBytes)
627 size_t nSize = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, ctx);
628 vchBytes.resize(nSize);
629 if (!(nSize == EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, &vchBytes[0], nSize, ctx))) {
635 // ECC multiplication by specified multiplier
636 bool CPoint::ECMUL(const CBigNum &bnMultiplier)
638 if (!EC_POINT_mul(group, point, NULL, point, &bnMultiplier, NULL)) {
639 printf("CPoint::ECMUL() : EC_POINT_mul failed");
647 bool CPoint::ECMULGEN(const CBigNum &bnMultiplier, const CPoint &qPoint)
649 if (!EC_POINT_mul(group, point, &bnMultiplier, qPoint.point, BN_value_one(), NULL)) {
650 printf("CPoint::ECMULGEN() : EC_POINT_mul failed.");
659 void CMalleablePubKey::GetVariant(CPubKey &R, CPubKey &vchPubKeyVariant)
661 EC_KEY *eckey = NULL;
662 eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
664 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_new_by_curve_name failed");
667 // Use standard key generation function to get r and R values.
669 // r will be presented by private key;
670 // R is ECDSA public key which calculated as G*r
671 if (!EC_KEY_generate_key(eckey)) {
672 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_generate_key failed");
675 EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
677 int nSize = i2o_ECPublicKey(eckey, NULL);
679 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey failed");
682 std::vector<unsigned char> vchPubKey(nSize, 0);
683 unsigned char* pbegin_R = &vchPubKey[0];
685 if (i2o_ECPublicKey(eckey, &pbegin_R) != nSize) {
686 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey returned unexpected size");
690 R = CPubKey(vchPubKey);
692 // OpenSSL BIGNUM representation of r value
694 bnr = *(CBigNum*) EC_KEY_get0_private_key(eckey);
698 if (!point.setPubKey(pubKeyL)) {
699 throw key_error("CMalleablePubKey::GetVariant() : Unable to decode L value");
705 std::vector<unsigned char> vchLr;
706 if (!point.getBytes(vchLr)) {
707 throw key_error("CMalleablePubKey::GetVariant() : Unable to convert Lr value");
710 // Calculate Hash(L*r) and then get a BIGNUM representation of hash value.
712 bnHash.setuint160(Hash160(vchLr));
715 if (!pointH.setPubKey(pubKeyH)) {
716 throw key_error("CMalleablePubKey::GetVariant() : Unable to decode H value");
720 // Calculate P = Hash(L*r)*G + H
721 P.ECMULGEN(bnHash, pointH);
723 if (P.IsInfinity()) {
724 throw key_error("CMalleablePubKey::GetVariant() : P is infinity");
727 std::vector<unsigned char> vchResult;
728 if (!P.getBytes(vchResult)) {
729 throw key_error("CMalleablePubKey::GetVariant() : Unable to convert P value");
732 vchPubKeyVariant = CPubKey(vchResult);
735 std::string CMalleablePubKey::ToString() const
737 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
739 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
741 return EncodeBase58Check(vch);
744 bool CMalleablePubKey::setvch(const std::vector<unsigned char> &vchPubKeyPair)
746 CDataStream ssKey(vchPubKeyPair, SER_NETWORK, PROTOCOL_VERSION);
752 std::vector<unsigned char> CMalleablePubKey::Raw() const
754 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
756 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
761 bool CMalleablePubKey::SetString(const std::string& strMalleablePubKey)
763 std::vector<unsigned char> vchTemp;
764 if (!DecodeBase58Check(strMalleablePubKey, vchTemp)) {
765 throw key_error("CMalleablePubKey::SetString() : Provided key data seems corrupted.");
767 if (vchTemp.size() != 68)
770 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
776 bool CMalleablePubKey::operator==(const CMalleablePubKey &b)
778 return pubKeyL == b.pubKeyL && pubKeyH == b.pubKeyH;
784 void CMalleableKey::Reset()
790 void CMalleableKey::MakeNewKeys()
798 vchSecretL = keyL.GetSecret();
799 vchSecretH = keyH.GetSecret();
802 CMalleableKey::CMalleableKey()
807 CMalleableKey::CMalleableKey(const CMalleableKey &b)
809 SetSecrets(b.vchSecretL, b.vchSecretH);
812 CMalleableKey::CMalleableKey(const CSecret &L, const CSecret &H)
817 CMalleableKey::~CMalleableKey()
821 bool CMalleableKey::IsNull() const
823 return vchSecretL.size() != 32 || vchSecretH.size() != 32;
826 bool CMalleableKey::SetSecrets(const CSecret &pvchSecretL, const CSecret &pvchSecretH)
830 CKey keyL(pvchSecretL);
831 CKey keyH(pvchSecretH);
833 if (!keyL.IsValid() || !keyH.IsValid())
836 vchSecretL = pvchSecretL;
837 vchSecretH = pvchSecretH;
842 CMalleablePubKey CMalleableKey::GetMalleablePubKey() const
844 CKey L(vchSecretL), H(vchSecretH);
845 return CMalleablePubKey(L.GetPubKey(), H.GetPubKey());
849 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
852 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
856 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
860 if (!vchPubKeyVariant.IsValid()) {
861 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
866 if (!point_R.setPubKey(R)) {
867 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
872 CPubKey vchPubKeyH = H.GetPubKey();
875 if (!point_H.setPubKey(vchPubKeyH)) {
876 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
881 if (!point_P.setPubKey(vchPubKeyVariant)) {
882 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
886 // Infinity points are senseless
887 if (point_P.IsInfinity()) {
888 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
893 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
897 std::vector<unsigned char> vchRl;
898 if (!point_R.getBytes(vchRl)) {
899 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
903 // Calculate Hash(R*l)
905 bnHash.setuint160(Hash160(vchRl));
908 // Calculate Ps = Hash(L*r)*G + H
909 point_Ps.ECMULGEN(bnHash, point_H);
911 // Infinity points are senseless
912 if (point_Ps.IsInfinity()) {
913 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
918 if (point_Ps != point_P) {
925 // Check ownership and restore private key
926 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant, CKey &privKeyVariant) const
929 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
933 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
937 if (!vchPubKeyVariant.IsValid()) {
938 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
943 if (!point_R.setPubKey(R)) {
944 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
949 CPubKey vchPubKeyH = H.GetPubKey();
952 if (!point_H.setPubKey(vchPubKeyH)) {
953 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
958 if (!point_P.setPubKey(vchPubKeyVariant)) {
959 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
963 // Infinity points are senseless
964 if (point_P.IsInfinity()) {
965 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
970 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
974 std::vector<unsigned char> vchRl;
975 if (!point_R.getBytes(vchRl)) {
976 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
980 // Calculate Hash(R*l)
982 bnHash.setuint160(Hash160(vchRl));
985 // Calculate Ps = Hash(L*r)*G + H
986 point_Ps.ECMULGEN(bnHash, point_H);
988 // Infinity points are senseless
989 if (point_Ps.IsInfinity()) {
990 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
995 if (point_Ps != point_P) {
999 // OpenSSL BIGNUM representation of the second private key from (l, h) pair
1001 bnh.setBytes(std::vector<unsigned char>(vchSecretH.begin(), vchSecretH.end()));
1003 // Calculate p = Hash(R*l) + h
1004 CBigNum bnp = bnHash + bnh;
1006 std::vector<unsigned char> vchp = bnp.getBytes();
1007 privKeyVariant.SetSecret(CSecret(vchp.begin(), vchp.end()));
1012 std::string CMalleableKey::ToString() const
1014 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1016 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1018 return EncodeBase58Check(vch);
1021 std::vector<unsigned char> CMalleableKey::Raw() const
1023 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1025 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1030 bool CMalleableKey::SetString(const std::string& strMutableKey)
1032 std::vector<unsigned char> vchTemp;
1033 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1034 throw key_error("CMalleableKey::SetString() : Provided key data seems corrupted.");
1036 if (vchTemp.size() != 66)
1038 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1044 // CMalleableKeyView
1046 CMalleableKeyView::CMalleableKeyView(const std::string &strMalleableKey)
1048 SetString(strMalleableKey);
1051 CMalleableKeyView::CMalleableKeyView(const CMalleableKey &b)
1053 if (b.vchSecretL.size() != 32)
1054 throw key_error("CMalleableKeyView::CMalleableKeyView() : L size must be 32 bytes");
1056 if (b.vchSecretH.size() != 32)
1057 throw key_error("CMalleableKeyView::CMalleableKeyView() : H size must be 32 bytes");
1059 vchSecretL = b.vchSecretL;
1061 CKey H(b.vchSecretH);
1062 vchPubKeyH = H.GetPubKey();
1065 CMalleableKeyView::CMalleableKeyView(const CMalleableKeyView &b)
1067 vchSecretL = b.vchSecretL;
1068 vchPubKeyH = b.vchPubKeyH;
1071 CMalleableKeyView& CMalleableKeyView::operator=(const CMalleableKey &b)
1073 vchSecretL = b.vchSecretL;
1075 CKey H(b.vchSecretH);
1076 vchPubKeyH = H.GetPubKey();
1081 CMalleableKeyView::~CMalleableKeyView()
1085 CMalleablePubKey CMalleableKeyView::GetMalleablePubKey() const
1087 CKey keyL(vchSecretL);
1088 return CMalleablePubKey(keyL.GetPubKey(), vchPubKeyH);
1092 bool CMalleableKeyView::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
1095 throw key_error("CMalleableKeyView::CheckKeyVariant() : Attempting to run on invalid view object.");
1099 printf("CMalleableKeyView::CheckKeyVariant() : R is invalid");
1103 if (!vchPubKeyVariant.IsValid()) {
1104 printf("CMalleableKeyView::CheckKeyVariant() : public key variant is invalid");
1109 if (!point_R.setPubKey(R)) {
1110 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode R value");
1115 if (!point_H.setPubKey(vchPubKeyH)) {
1116 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode H value");
1121 if (!point_P.setPubKey(vchPubKeyVariant)) {
1122 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode P value");
1126 // Infinity points are senseless
1127 if (point_P.IsInfinity()) {
1128 printf("CMalleableKeyView::CheckKeyVariant() : P is infinity");
1133 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
1137 std::vector<unsigned char> vchRl;
1138 if (!point_R.getBytes(vchRl)) {
1139 printf("CMalleableKeyView::CheckKeyVariant() : Unable to convert Rl value");
1143 // Calculate Hash(R*l)
1145 bnHash.setuint160(Hash160(vchRl));
1148 // Calculate Ps = Hash(L*r)*G + H
1149 point_Ps.ECMULGEN(bnHash, point_H);
1151 // Infinity points are senseless
1152 if (point_Ps.IsInfinity()) {
1153 printf("CMalleableKeyView::CheckKeyVariant() : Ps is infinity");
1158 if (point_Ps != point_P) {
1165 std::string CMalleableKeyView::ToString() const
1167 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1169 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1171 return EncodeBase58Check(vch);
1174 bool CMalleableKeyView::SetString(const std::string& strMutableKey)
1176 std::vector<unsigned char> vchTemp;
1177 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1178 throw key_error("CMalleableKeyView::SetString() : Provided key data seems corrupted.");
1181 if (vchTemp.size() != 67)
1184 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1190 std::vector<unsigned char> CMalleableKeyView::Raw() const
1192 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1194 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1200 bool CMalleableKeyView::IsValid() const
1202 return vchSecretL.size() == 32 && GetMalleablePubKey().IsValid();
1205 //// Asymmetric encryption
1207 void CPubKey::EncryptData(const std::vector<unsigned char>& data, std::vector<unsigned char>& encrypted)
1210 char error[1024] = "Unknown error";
1211 cryptogram_t *cryptogram;
1213 const unsigned char* pbegin = &vbytes[0];
1214 EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
1215 if (!o2i_ECPublicKey(&pkey, &pbegin, size()))
1216 throw key_error("Unable to parse EC key");
1218 ctx = create_context(pkey);
1219 if (!EC_KEY_get0_public_key(ctx->user_key))
1220 throw key_error("Given EC key is not public key");
1222 cryptogram = ecies_encrypt(ctx, (unsigned char*)&data[0], data.size(), error);
1223 if (cryptogram == NULL) {
1226 throw key_error(std::string("Error in encryption: %s") + error);
1229 encrypted.resize(cryptogram_data_sum_length(cryptogram));
1230 unsigned char *key_data = cryptogram_key_data(cryptogram);
1231 memcpy(&encrypted[0], key_data, encrypted.size());
1232 cryptogram_free(cryptogram);
1236 void CKey::DecryptData(const std::vector<unsigned char>& encrypted, std::vector<unsigned char>& data)
1239 char error[1024] = "Unknown error";
1240 cryptogram_t *cryptogram;
1242 unsigned char *decrypted;
1244 ctx = create_context(pkey);
1245 if (!EC_KEY_get0_private_key(ctx->user_key))
1246 throw key_error("Given EC key is not private key");
1248 size_t key_length = ctx->stored_key_length;
1249 size_t mac_length = EVP_MD_size(ctx->md);
1250 cryptogram = cryptogram_alloc(key_length, mac_length, encrypted.size() - key_length - mac_length);
1252 memcpy(cryptogram_key_data(cryptogram), &encrypted[0], encrypted.size());
1254 decrypted = ecies_decrypt(ctx, cryptogram, &length, error);
1255 cryptogram_free(cryptogram);
1258 if (decrypted == NULL) {
1259 throw key_error(std::string("Error in decryption: %s") + error);
1262 data.resize(length);
1263 memcpy(&data[0], decrypted, length);