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.");
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, NULL);
384 BN_rshift1(&halforder, &order);
385 // enforce low S values, by negating the value (modulo the order) if above order/2.
386 if (BN_cmp(sig->s, &halforder) > 0) {
387 BN_sub(sig->s, &order, sig->s);
389 unsigned int nSize = ECDSA_size(pkey);
390 vchSig.resize(nSize); // Make sure it is big enough
391 unsigned char *pos = &vchSig[0];
392 nSize = i2d_ECDSA_SIG(sig, &pos);
394 vchSig.resize(nSize); // Shrink to fit actual size
395 // Testing our new signature
396 if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) {
403 // create a compact signature (65 bytes), which allows reconstructing the used public key
404 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
405 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
406 // 0x1D = second key with even y, 0x1E = second key with odd y
407 bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
410 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
413 const EC_GROUP *group = EC_KEY_get0_group(pkey);
414 CBigNum order, halforder;
415 EC_GROUP_get_order(group, &order, NULL);
416 BN_rshift1(&halforder, &order);
417 // enforce low S values, by negating the value (modulo the order) if above order/2.
418 if (BN_cmp(sig->s, &halforder) > 0) {
419 BN_sub(sig->s, &order, sig->s);
423 int nBitsR = BN_num_bits(sig->r);
424 int nBitsS = BN_num_bits(sig->s);
425 if (nBitsR <= 256 && nBitsS <= 256)
428 for (int8_t i=0; i<4; i++)
432 if (fCompressedPubKey)
433 keyRec.SetCompressedPubKey();
434 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
435 if (keyRec.GetPubKey() == this->GetPubKey())
445 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
448 vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
449 BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
450 BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
457 // reconstruct public key from a compact signature
458 // This is only slightly more CPU intensive than just verifying it.
459 // If this function succeeds, the recovered public key is guaranteed to be valid
460 // (the signature is a valid signature of the given data for that key)
461 bool CPubKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
463 if (vchSig.size() != 65)
468 ECDSA_SIG *sig = ECDSA_SIG_new();
469 BN_bin2bn(&vchSig[1],32,sig->r);
470 BN_bin2bn(&vchSig[33],32,sig->s);
472 EC_KEY* pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
476 EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
481 if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) != 1)
485 int nSize = i2o_ECPublicKey(pkey, NULL);
488 std::vector<unsigned char> vchPubKey(nSize, 0);
489 unsigned char* pbegin = &vchPubKey[0];
490 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
492 Set(vchPubKey.begin(), vchPubKey.end());
502 bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const
504 if (vchSig.empty() || !IsValid())
507 const unsigned char* pbegin = &vbytes[0];
508 EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
509 if (!o2i_ECPublicKey(&pkey, &pbegin, size()))
510 return false; // Unable to parse public key
512 // New versions of OpenSSL will reject non-canonical DER signatures. de/re-serialize first.
513 unsigned char *norm_der = NULL;
514 ECDSA_SIG *norm_sig = ECDSA_SIG_new();
515 const unsigned char* sigptr = &vchSig[0];
517 if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL)
519 /* As of OpenSSL 1.0.0p d2i_ECDSA_SIG frees and nulls the pointer on
520 * error. But OpenSSL's own use of this function redundantly frees the
521 * result. As ECDSA_SIG_free(NULL) is a no-op, and in the absence of a
522 * clear contract for the function behaving the same way is more
525 ECDSA_SIG_free(norm_sig);
528 int derlen = i2d_ECDSA_SIG(norm_sig, &norm_der);
529 ECDSA_SIG_free(norm_sig);
533 // -1 = error, 0 = bad sig, 1 = good
534 bool ret = ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
535 OPENSSL_free(norm_der);
539 bool CPubKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
542 if (!key.SetCompactSignature(hash, vchSig))
552 if (!EC_KEY_check_key(pkey))
556 CSecret secret = GetSecret(fCompr);
558 key2.SetSecret(secret, fCompr);
560 return GetPubKey() == key2.GetPubKey();
570 group = EC_GROUP_new_by_curve_name(NID_secp256k1);
572 err = "EC_KEY_new_by_curve_name failed.";
576 point = EC_POINT_new(group);
578 err = "EC_POINT_new failed.";
584 err = "BN_CTX_new failed.";
591 if (group) EC_GROUP_free(group);
592 if (point) EC_POINT_free(point);
593 throw std::runtime_error(std::string("CPoint::CPoint() : - ") + err);
596 bool CPoint::operator!=(const CPoint &a)
598 if (EC_POINT_cmp(group, point, a.point, ctx) != 0)
604 if (point) EC_POINT_free(point);
605 if (group) EC_GROUP_free(group);
606 if (ctx) BN_CTX_free(ctx);
609 // Initialize from octets stream
610 bool CPoint::setBytes(const std::vector<unsigned char> &vchBytes)
612 if (!EC_POINT_oct2point(group, point, &vchBytes[0], vchBytes.size(), ctx)) {
618 // Initialize from octets stream
619 bool CPoint::setPubKey(const CPubKey &key)
621 std::vector<uint8_t> vchPubKey(key.begin(), key.end());
622 return setBytes(vchPubKey);
625 // Serialize to octets stream
626 bool CPoint::getBytes(std::vector<unsigned char> &vchBytes)
628 size_t nSize = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, ctx);
629 vchBytes.resize(nSize);
630 if (!(nSize == EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, &vchBytes[0], nSize, ctx))) {
636 // ECC multiplication by specified multiplier
637 bool CPoint::ECMUL(const CBigNum &bnMultiplier)
639 if (!EC_POINT_mul(group, point, NULL, point, &bnMultiplier, NULL)) {
640 printf("CPoint::ECMUL() : EC_POINT_mul failed");
648 bool CPoint::ECMULGEN(const CBigNum &bnMultiplier, const CPoint &qPoint)
650 if (!EC_POINT_mul(group, point, &bnMultiplier, qPoint.point, BN_value_one(), NULL)) {
651 printf("CPoint::ECMULGEN() : EC_POINT_mul failed.");
660 void CMalleablePubKey::GetVariant(CPubKey &R, CPubKey &vchPubKeyVariant)
662 EC_KEY *eckey = NULL;
663 eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
665 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_new_by_curve_name failed");
668 // Use standard key generation function to get r and R values.
670 // r will be presented by private key;
671 // R is ECDSA public key which calculated as G*r
672 if (!EC_KEY_generate_key(eckey)) {
673 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_generate_key failed");
676 EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
678 int nSize = i2o_ECPublicKey(eckey, NULL);
680 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey failed");
683 std::vector<unsigned char> vchPubKey(nSize, 0);
684 unsigned char* pbegin_R = &vchPubKey[0];
686 if (i2o_ECPublicKey(eckey, &pbegin_R) != nSize) {
687 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey returned unexpected size");
691 R = CPubKey(vchPubKey);
693 // OpenSSL BIGNUM representation of r value
695 bnr = *(CBigNum*) EC_KEY_get0_private_key(eckey);
699 if (!point.setPubKey(pubKeyL)) {
700 throw key_error("CMalleablePubKey::GetVariant() : Unable to decode L value");
706 std::vector<unsigned char> vchLr;
707 if (!point.getBytes(vchLr)) {
708 throw key_error("CMalleablePubKey::GetVariant() : Unable to convert Lr value");
711 // Calculate Hash(L*r) and then get a BIGNUM representation of hash value.
713 bnHash.setuint160(Hash160(vchLr));
716 pointH.setPubKey(pubKeyH);
719 // Calculate P = Hash(L*r)*G + H
720 P.ECMULGEN(bnHash, pointH);
722 if (P.IsInfinity()) {
723 throw key_error("CMalleablePubKey::GetVariant() : P is infinity");
726 std::vector<unsigned char> vchResult;
727 P.getBytes(vchResult);
729 vchPubKeyVariant = CPubKey(vchResult);
732 std::string CMalleablePubKey::ToString() const
734 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
736 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
738 return EncodeBase58Check(vch);
741 bool CMalleablePubKey::setvch(const std::vector<unsigned char> &vchPubKeyPair)
743 CDataStream ssKey(vchPubKeyPair, SER_NETWORK, PROTOCOL_VERSION);
749 std::vector<unsigned char> CMalleablePubKey::Raw() const
751 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
753 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
758 bool CMalleablePubKey::SetString(const std::string& strMalleablePubKey)
760 std::vector<unsigned char> vchTemp;
761 if (!DecodeBase58Check(strMalleablePubKey, vchTemp)) {
762 throw key_error("CMalleablePubKey::SetString() : Provided key data seems corrupted.");
765 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
771 bool CMalleablePubKey::operator==(const CMalleablePubKey &b)
773 return pubKeyL == b.pubKeyL && pubKeyH == b.pubKeyH;
779 void CMalleableKey::Reset()
785 void CMalleableKey::MakeNewKeys()
793 vchSecretL = keyL.GetSecret();
794 vchSecretH = keyH.GetSecret();
797 CMalleableKey::CMalleableKey()
802 CMalleableKey::CMalleableKey(const CMalleableKey &b)
804 SetSecrets(b.vchSecretL, b.vchSecretH);
807 CMalleableKey::CMalleableKey(const CSecret &L, const CSecret &H)
812 CMalleableKey::~CMalleableKey()
816 bool CMalleableKey::IsNull() const
818 return vchSecretL.size() != 32 || vchSecretH.size() != 32;
821 bool CMalleableKey::SetSecrets(const CSecret &pvchSecretL, const CSecret &pvchSecretH)
825 CKey keyL(pvchSecretL);
826 CKey keyH(pvchSecretH);
828 if (!keyL.IsValid() || !keyH.IsValid())
831 vchSecretL = pvchSecretL;
832 vchSecretH = pvchSecretH;
837 CMalleablePubKey CMalleableKey::GetMalleablePubKey() const
839 CKey L(vchSecretL), H(vchSecretH);
840 return CMalleablePubKey(L.GetPubKey(), H.GetPubKey());
844 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
847 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
851 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
855 if (!vchPubKeyVariant.IsValid()) {
856 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
861 if (!point_R.setPubKey(R)) {
862 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
867 CPubKey vchPubKeyH = H.GetPubKey();
870 if (!point_H.setPubKey(vchPubKeyH)) {
871 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
876 if (!point_P.setPubKey(vchPubKeyVariant)) {
877 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
881 // Infinity points are senseless
882 if (point_P.IsInfinity()) {
883 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
888 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
892 std::vector<unsigned char> vchRl;
893 if (!point_R.getBytes(vchRl)) {
894 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
898 // Calculate Hash(R*l)
900 bnHash.setuint160(Hash160(vchRl));
903 // Calculate Ps = Hash(L*r)*G + H
904 point_Ps.ECMULGEN(bnHash, point_H);
906 // Infinity points are senseless
907 if (point_Ps.IsInfinity()) {
908 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
913 if (point_Ps != point_P) {
920 // Check ownership and restore private key
921 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant, CKey &privKeyVariant) const
924 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
928 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
932 if (!vchPubKeyVariant.IsValid()) {
933 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
938 if (!point_R.setPubKey(R)) {
939 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
944 CPubKey vchPubKeyH = H.GetPubKey();
947 if (!point_H.setPubKey(vchPubKeyH)) {
948 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
953 if (!point_P.setPubKey(vchPubKeyVariant)) {
954 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
958 // Infinity points are senseless
959 if (point_P.IsInfinity()) {
960 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
965 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
969 std::vector<unsigned char> vchRl;
970 if (!point_R.getBytes(vchRl)) {
971 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
975 // Calculate Hash(R*l)
977 bnHash.setuint160(Hash160(vchRl));
980 // Calculate Ps = Hash(L*r)*G + H
981 point_Ps.ECMULGEN(bnHash, point_H);
983 // Infinity points are senseless
984 if (point_Ps.IsInfinity()) {
985 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
990 if (point_Ps != point_P) {
994 // OpenSSL BIGNUM representation of the second private key from (l, h) pair
996 bnh.setBytes(std::vector<unsigned char>(vchSecretH.begin(), vchSecretH.end()));
998 // Calculate p = Hash(R*l) + h
999 CBigNum bnp = bnHash + bnh;
1001 std::vector<unsigned char> vchp = bnp.getBytes();
1002 privKeyVariant.SetSecret(CSecret(vchp.begin(), vchp.end()));
1007 std::string CMalleableKey::ToString() const
1009 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1011 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1013 return EncodeBase58Check(vch);
1016 std::vector<unsigned char> CMalleableKey::Raw() const
1018 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1020 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1025 bool CMalleableKey::SetString(const std::string& strMutableKey)
1027 std::vector<unsigned char> vchTemp;
1028 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1029 throw key_error("CMalleableKey::SetString() : Provided key data seems corrupted.");
1032 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1038 // CMalleableKeyView
1040 CMalleableKeyView::CMalleableKeyView(const std::string &strMalleableKey)
1042 SetString(strMalleableKey);
1045 CMalleableKeyView::CMalleableKeyView(const CMalleableKey &b)
1047 if (b.vchSecretL.size() != 32)
1048 throw key_error("CMalleableKeyView::CMalleableKeyView() : L size must be 32 bytes");
1050 if (b.vchSecretH.size() != 32)
1051 throw key_error("CMalleableKeyView::CMalleableKeyView() : H size must be 32 bytes");
1053 vchSecretL = b.vchSecretL;
1055 CKey H(b.vchSecretH);
1056 vchPubKeyH = H.GetPubKey();
1059 CMalleableKeyView::CMalleableKeyView(const CMalleableKeyView &b)
1061 vchSecretL = b.vchSecretL;
1062 vchPubKeyH = b.vchPubKeyH;
1065 CMalleableKeyView& CMalleableKeyView::operator=(const CMalleableKey &b)
1067 vchSecretL = b.vchSecretL;
1069 CKey H(b.vchSecretH);
1070 vchPubKeyH = H.GetPubKey();
1075 CMalleableKeyView::~CMalleableKeyView()
1079 CMalleablePubKey CMalleableKeyView::GetMalleablePubKey() const
1081 CKey keyL(vchSecretL);
1082 return CMalleablePubKey(keyL.GetPubKey(), vchPubKeyH);
1086 bool CMalleableKeyView::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
1089 throw key_error("CMalleableKeyView::CheckKeyVariant() : Attempting to run on invalid view object.");
1093 printf("CMalleableKeyView::CheckKeyVariant() : R is invalid");
1097 if (!vchPubKeyVariant.IsValid()) {
1098 printf("CMalleableKeyView::CheckKeyVariant() : public key variant is invalid");
1103 if (!point_R.setPubKey(R)) {
1104 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode R value");
1109 if (!point_H.setPubKey(vchPubKeyH)) {
1110 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode H value");
1115 if (!point_P.setPubKey(vchPubKeyVariant)) {
1116 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode P value");
1120 // Infinity points are senseless
1121 if (point_P.IsInfinity()) {
1122 printf("CMalleableKeyView::CheckKeyVariant() : P is infinity");
1127 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
1131 std::vector<unsigned char> vchRl;
1132 if (!point_R.getBytes(vchRl)) {
1133 printf("CMalleableKeyView::CheckKeyVariant() : Unable to convert Rl value");
1137 // Calculate Hash(R*l)
1139 bnHash.setuint160(Hash160(vchRl));
1142 // Calculate Ps = Hash(L*r)*G + H
1143 point_Ps.ECMULGEN(bnHash, point_H);
1145 // Infinity points are senseless
1146 if (point_Ps.IsInfinity()) {
1147 printf("CMalleableKeyView::CheckKeyVariant() : Ps is infinity");
1152 if (point_Ps != point_P) {
1159 std::string CMalleableKeyView::ToString() const
1161 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1163 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1165 return EncodeBase58Check(vch);
1168 bool CMalleableKeyView::SetString(const std::string& strMutableKey)
1170 std::vector<unsigned char> vchTemp;
1171 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1172 throw key_error("CMalleableKeyView::SetString() : Provided key data seems corrupted.");
1175 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1181 std::vector<unsigned char> CMalleableKeyView::Raw() const
1183 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1185 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1191 bool CMalleableKeyView::IsValid() const
1193 return vchSecretL.size() == 32 && GetMalleablePubKey().IsValid();
1196 //// Asymmetric encryption
1198 void CPubKey::EncryptData(const std::vector<unsigned char>& data, std::vector<unsigned char>& encrypted)
1201 char error[1024] = "Unknown error";
1202 cryptogram_t *cryptogram;
1204 const unsigned char* pbegin = &vbytes[0];
1205 EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
1206 if (!o2i_ECPublicKey(&pkey, &pbegin, size()))
1207 throw key_error("Unable to parse EC key");
1209 ctx = create_context(pkey);
1210 if (!EC_KEY_get0_public_key(ctx->user_key))
1211 throw key_error("Given EC key is not public key");
1213 cryptogram = ecies_encrypt(ctx, (unsigned char*)&data[0], data.size(), error);
1214 if (cryptogram == NULL) {
1217 throw key_error(std::string("Error in encryption: %s") + error);
1220 encrypted.resize(cryptogram_data_sum_length(cryptogram));
1221 unsigned char *key_data = cryptogram_key_data(cryptogram);
1222 memcpy(&encrypted[0], key_data, encrypted.size());
1223 cryptogram_free(cryptogram);
1227 void CKey::DecryptData(const std::vector<unsigned char>& encrypted, std::vector<unsigned char>& data)
1230 char error[1024] = "Unknown error";
1231 cryptogram_t *cryptogram;
1233 unsigned char *decrypted;
1235 ctx = create_context(pkey);
1236 if (!EC_KEY_get0_private_key(ctx->user_key))
1237 throw key_error("Given EC key is not private key");
1239 size_t key_length = ctx->stored_key_length;
1240 size_t mac_length = EVP_MD_size(ctx->md);
1241 cryptogram = cryptogram_alloc(key_length, mac_length, encrypted.size() - key_length - mac_length);
1243 memcpy(cryptogram_key_data(cryptogram), &encrypted[0], encrypted.size());
1245 decrypted = ecies_decrypt(ctx, cryptogram, &length, error);
1246 cryptogram_free(cryptogram);
1249 if (decrypted == NULL) {
1250 throw key_error(std::string("Error in decryption: %s") + error);
1253 data.resize(length);
1254 memcpy(&data[0], decrypted, length);