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/obj_mac.h>
9 #include <openssl/ssl.h>
10 #include <openssl/ecdh.h>
16 // Generate a private key from just the secret parameter
17 int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
21 EC_POINT *pub_key = NULL;
25 const EC_GROUP *group = EC_KEY_get0_group(eckey);
27 if ((ctx = BN_CTX_new()) == NULL)
30 pub_key = EC_POINT_new(group);
35 if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
38 EC_KEY_set_private_key(eckey,priv_key);
39 EC_KEY_set_public_key(eckey,pub_key);
46 EC_POINT_free(pub_key);
53 // Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
54 // recid selects which key is recovered
55 // if check is non-zero, additional checks are performed
56 int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
77 const EC_GROUP *group = EC_KEY_get0_group(eckey);
78 if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
80 order = BN_CTX_get(ctx);
81 if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
83 if (!BN_copy(x, order)) { ret=-1; goto err; }
84 if (!BN_mul_word(x, i)) { ret=-1; goto err; }
85 if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
86 field = BN_CTX_get(ctx);
87 if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
88 if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
89 if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
90 if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
93 if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
94 if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
95 if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
97 if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
98 n = EC_GROUP_get_degree(group);
100 if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
101 if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
102 zero = BN_CTX_get(ctx);
103 if (!BN_zero(zero)) { ret=-1; goto err; }
104 if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
105 rr = BN_CTX_get(ctx);
106 if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
107 sor = BN_CTX_get(ctx);
108 if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
109 eor = BN_CTX_get(ctx);
110 if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
111 if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
112 if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
121 if (R != NULL) EC_POINT_free(R);
122 if (O != NULL) EC_POINT_free(O);
123 if (Q != NULL) EC_POINT_free(Q);
127 int CompareBigEndian(const unsigned char *c1, size_t c1len, const unsigned char *c2, size_t c2len) {
128 while (c1len > c2len) {
134 while (c2len > c1len) {
152 // Order of secp256k1's generator minus 1.
153 const unsigned char vchMaxModOrder[32] = {
154 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
155 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
156 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,
157 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40
160 // Half of the order of secp256k1's generator minus 1.
161 const unsigned char vchMaxModHalfOrder[32] = {
162 0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
163 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
164 0x5D,0x57,0x6E,0x73,0x57,0xA4,0x50,0x1D,
165 0xDF,0xE9,0x2F,0x46,0x68,0x1B,0x20,0xA0
168 const unsigned char *vchZero = NULL;
172 void CKey::SetCompressedPubKey()
174 EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
175 fCompressedPubKey = true;
180 fCompressedPubKey = false;
183 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
185 throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
195 CKey::CKey(const CKey& b)
197 pkey = EC_KEY_dup(b.pkey);
199 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
201 fCompressedPubKey = b.fCompressedPubKey;
204 CKey& CKey::operator=(const CKey& b)
206 if (!EC_KEY_copy(pkey, b.pkey))
207 throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
209 fCompressedPubKey = b.fCompressedPubKey;
218 bool CKey::IsNull() const
223 bool CKey::IsCompressed() const
225 return fCompressedPubKey;
228 bool CKey::CheckSignatureElement(const unsigned char *vch, int len, bool half) {
229 return CompareBigEndian(vch, len, vchZero, 0) > 0 &&
230 CompareBigEndian(vch, len, half ? vchMaxModHalfOrder : vchMaxModOrder, 32) <= 0;
233 bool CKey::ReserealizeSignature(std::vector<unsigned char>& vchSig)
238 unsigned char *pos = &vchSig[0];
239 ECDSA_SIG *sig = d2i_ECDSA_SIG(NULL, (const unsigned char **)&pos, vchSig.size());
244 int nSize = i2d_ECDSA_SIG(sig, NULL);
246 vchSig.resize(nSize); // grow or shrink as needed
249 i2d_ECDSA_SIG(sig, &pos);
259 void CKey::MakeNewKey(bool fCompressed)
261 if (!EC_KEY_generate_key(pkey))
262 throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
264 SetCompressedPubKey();
268 bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
270 const unsigned char* pbegin = &vchPrivKey[0];
271 if (d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
273 // In testing, d2i_ECPrivateKey can return true
274 // but fill in pkey with a key that fails
275 // EC_KEY_check_key, so:
276 if (EC_KEY_check_key(pkey))
282 // If vchPrivKey data is bad d2i_ECPrivateKey() can
283 // leave pkey in a state where calling EC_KEY_free()
284 // crashes. To avoid that, set pkey to NULL and
285 // leak the memory (a leak is better than a crash)
291 bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
294 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
296 throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
297 if (vchSecret.size() != 32)
298 throw key_error("CKey::SetSecret() : secret must be 32 bytes");
299 BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
301 throw key_error("CKey::SetSecret() : BN_bin2bn failed");
302 if (!EC_KEY_regenerate_key(pkey,bn))
305 throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
309 if (fCompressed || fCompressedPubKey)
310 SetCompressedPubKey();
314 CSecret CKey::GetSecret(bool &fCompressed) const
318 const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
319 int nBytes = BN_num_bytes(bn);
321 throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
322 int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
324 throw key_error("CKey::GetSecret(): BN_bn2bin failed");
325 fCompressed = fCompressedPubKey;
329 CPrivKey CKey::GetPrivKey() const
331 int nSize = i2d_ECPrivateKey(pkey, NULL);
333 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
334 CPrivKey vchPrivKey(nSize, 0);
335 unsigned char* pbegin = &vchPrivKey[0];
336 if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
337 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
341 bool CKey::SetPubKey(const CPubKey& vchPubKey)
343 const unsigned char* pbegin = &vchPubKey.vchPubKey[0];
344 if (o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.vchPubKey.size()))
347 if (vchPubKey.vchPubKey.size() == 33)
348 SetCompressedPubKey();
356 CPubKey CKey::GetPubKey() const
358 int nSize = i2o_ECPublicKey(pkey, NULL);
360 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
361 std::vector<unsigned char> vchPubKey(nSize, 0);
362 unsigned char* pbegin = &vchPubKey[0];
363 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
364 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
365 return CPubKey(vchPubKey);
368 bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
371 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
374 const EC_GROUP *group = EC_KEY_get0_group(pkey);
375 CBigNum order, halforder;
376 EC_GROUP_get_order(group, &order, NULL);
377 BN_rshift1(&halforder, &order);
378 // enforce low S values, by negating the value (modulo the order) if above order/2.
379 if (BN_cmp(sig->s, &halforder) > 0) {
380 BN_sub(sig->s, &order, sig->s);
382 unsigned int nSize = ECDSA_size(pkey);
383 vchSig.resize(nSize); // Make sure it is big enough
384 unsigned char *pos = &vchSig[0];
385 nSize = i2d_ECDSA_SIG(sig, &pos);
387 vchSig.resize(nSize); // Shrink to fit actual size
388 // Testing our new signature
389 if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) {
396 // create a compact signature (65 bytes), which allows reconstructing the used public key
397 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
398 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
399 // 0x1D = second key with even y, 0x1E = second key with odd y
400 bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
403 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
406 const EC_GROUP *group = EC_KEY_get0_group(pkey);
407 CBigNum order, halforder;
408 EC_GROUP_get_order(group, &order, NULL);
409 BN_rshift1(&halforder, &order);
410 // enforce low S values, by negating the value (modulo the order) if above order/2.
411 if (BN_cmp(sig->s, &halforder) > 0) {
412 BN_sub(sig->s, &order, sig->s);
416 int nBitsR = BN_num_bits(sig->r);
417 int nBitsS = BN_num_bits(sig->s);
418 if (nBitsR <= 256 && nBitsS <= 256)
421 for (int8_t i=0; i<4; i++)
425 if (fCompressedPubKey)
426 keyRec.SetCompressedPubKey();
427 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
428 if (keyRec.GetPubKey() == this->GetPubKey())
438 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
441 vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
442 BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
443 BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
450 // reconstruct public key from a compact signature
451 // This is only slightly more CPU intensive than just verifying it.
452 // If this function succeeds, the recovered public key is guaranteed to be valid
453 // (the signature is a valid signature of the given data for that key)
454 bool CKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
456 if (vchSig.size() != 65)
461 ECDSA_SIG *sig = ECDSA_SIG_new();
462 BN_bin2bn(&vchSig[1],32,sig->r);
463 BN_bin2bn(&vchSig[33],32,sig->s);
466 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
469 SetCompressedPubKey();
472 if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)
482 bool CKey::Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
487 // New versions of OpenSSL will reject non-canonical DER signatures. de/re-serialize first.
488 unsigned char *norm_der = NULL;
489 ECDSA_SIG *norm_sig = ECDSA_SIG_new();
490 const unsigned char* sigptr = &vchSig[0];
492 if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL)
494 /* As of OpenSSL 1.0.0p d2i_ECDSA_SIG frees and nulls the pointer on
495 * error. But OpenSSL's own use of this function redundantly frees the
496 * result. As ECDSA_SIG_free(NULL) is a no-op, and in the absence of a
497 * clear contract for the function behaving the same way is more
500 ECDSA_SIG_free(norm_sig);
503 int derlen = i2d_ECDSA_SIG(norm_sig, &norm_der);
504 ECDSA_SIG_free(norm_sig);
508 // -1 = error, 0 = bad sig, 1 = good
509 bool ret = ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
510 OPENSSL_free(norm_der);
514 bool CKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
517 if (!key.SetCompactSignature(hash, vchSig))
519 if (GetPubKey() != key.GetPubKey())
530 if (!EC_KEY_check_key(pkey))
534 CSecret secret = GetSecret(fCompr);
536 key2.SetSecret(secret, fCompr);
537 return GetPubKey() == key2.GetPubKey();
547 group = EC_GROUP_new_by_curve_name(NID_secp256k1);
549 err = "EC_KEY_new_by_curve_name failed.";
553 point = EC_POINT_new(group);
555 err = "EC_POINT_new failed.";
561 err = "BN_CTX_new failed.";
568 if (group) EC_GROUP_free(group);
569 if (point) EC_POINT_free(point);
570 throw std::runtime_error(std::string("CPoint::CPoint() : - ") + err);
573 bool CPoint::operator!=(const CPoint &a)
575 if (EC_POINT_cmp(group, point, a.point, ctx) != 0)
581 if (point) EC_POINT_free(point);
582 if (group) EC_GROUP_free(group);
583 if (ctx) BN_CTX_free(ctx);
586 // Initialize from octets stream
587 bool CPoint::setBytes(const std::vector<unsigned char> &vchBytes)
589 if (!EC_POINT_oct2point(group, point, &vchBytes[0], vchBytes.size(), ctx)) {
595 // Serialize to octets stream
596 bool CPoint::getBytes(std::vector<unsigned char> &vchBytes)
598 unsigned int nSize = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, ctx);
599 vchBytes.resize(nSize);
600 if (!(nSize == EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, &vchBytes[0], nSize, ctx))) {
606 // ECC multiplication by specified multiplier
607 bool CPoint::ECMUL(const CBigNum &bnMultiplier)
609 if (!EC_POINT_mul(group, point, NULL, point, &bnMultiplier, NULL)) {
610 printf("CPoint::ECMUL() : EC_POINT_mul failed");
618 bool CPoint::ECMULGEN(const CBigNum &bnMultiplier, const CPoint &qPoint)
620 if (!EC_POINT_mul(group, point, &bnMultiplier, qPoint.point, BN_value_one(), NULL)) {
621 printf("CPoint::ECMULGEN() : EC_POINT_mul failed.");
630 void CMalleablePubKey::GetVariant(CPubKey &R, CPubKey &vchPubKeyVariant)
632 EC_KEY *eckey = NULL;
633 eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
635 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_new_by_curve_name failed");
638 // Use standard key generation function to get r and R values.
640 // r will be presented by private key;
641 // R is ECDSA public key which calculated as G*r
642 if (!EC_KEY_generate_key(eckey)) {
643 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_generate_key failed");
646 EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
648 int nSize = i2o_ECPublicKey(eckey, NULL);
650 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey failed");
653 std::vector<unsigned char> vchPubKey(nSize, 0);
654 unsigned char* pbegin_R = &vchPubKey[0];
656 if (i2o_ECPublicKey(eckey, &pbegin_R) != nSize) {
657 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey returned unexpected size");
661 R = CPubKey(vchPubKey);
663 // OpenSSL BIGNUM representation of r value
665 bnr = *(CBigNum*) EC_KEY_get0_private_key(eckey);
669 if (!point.setBytes(pubKeyL.Raw())) {
670 throw key_error("CMalleablePubKey::GetVariant() : Unable to decode L value");
676 std::vector<unsigned char> vchLr;
677 if (!point.getBytes(vchLr)) {
678 throw key_error("CMalleablePubKey::GetVariant() : Unable to convert Lr value");
681 // Calculate Hash(L*r) and then get a BIGNUM representation of hash value.
683 bnHash.setuint160(Hash160(vchLr));
686 pointH.setBytes(pubKeyH.Raw());
689 // Calculate P = Hash(L*r)*G + H
690 P.ECMULGEN(bnHash, pointH);
692 if (P.IsInfinity()) {
693 throw key_error("CMalleablePubKey::GetVariant() : P is infinity");
696 std::vector<unsigned char> vchResult;
697 P.getBytes(vchResult);
699 vchPubKeyVariant = CPubKey(vchResult);
702 std::string CMalleablePubKey::ToString()
704 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
706 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
708 return EncodeBase58Check(vch);
711 bool CMalleablePubKey::SetString(const std::string& strMalleablePubKey)
713 std::vector<unsigned char> vchTemp;
714 if (!DecodeBase58Check(strMalleablePubKey, vchTemp)) {
715 throw key_error("CMalleablePubKey::SetString() : Provided key data seems corrupted.");
718 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
724 bool CMalleablePubKey::operator==(const CMalleablePubKey &b)
726 return (nVersion == b.nVersion &&
727 pubKeyL == b.pubKeyL &&
728 pubKeyH == b.pubKeyH);
734 void CMalleableKey::Reset()
742 void CMalleableKey::MakeNewKeys()
745 bool fCompressed = true;
750 vchSecretL = L.GetSecret(fCompressed);
751 vchSecretH = H.GetSecret(fCompressed);
753 nVersion = CURRENT_VERSION;
756 CMalleableKey::CMalleableKey()
761 CMalleableKey::CMalleableKey(const CMalleableKey &b)
763 SetSecrets(b.vchSecretL, b.vchSecretH);
766 CMalleableKey::CMalleableKey(const CSecret &L, const CSecret &H)
771 CMalleableKey& CMalleableKey::operator=(const CMalleableKey &b)
773 SetSecrets(b.vchSecretL, b.vchSecretH);
778 CMalleableKey::~CMalleableKey()
782 bool CMalleableKey::IsNull() const
784 return nVersion != CURRENT_VERSION;
787 bool CMalleableKey::SetSecrets(const CSecret &pvchSecretL, const CSecret &pvchSecretH)
792 if (!L.SetSecret(pvchSecretL, true) || !H.SetSecret(pvchSecretH, true))
798 vchSecretL = pvchSecretL;
799 vchSecretH = pvchSecretH;
800 nVersion = CURRENT_VERSION;
805 void CMalleableKey::GetSecrets(CSecret &pvchSecretL, CSecret &pvchSecretH) const
807 pvchSecretL = vchSecretL;
808 pvchSecretH = vchSecretH;
811 CMalleablePubKey CMalleableKey::GetMalleablePubKey() const
814 L.SetSecret(vchSecretL, true);
815 H.SetSecret(vchSecretH, true);
817 std::vector<unsigned char> vchPubKeyL = L.GetPubKey().Raw();
818 std::vector<unsigned char> vchPubKeyH = H.GetPubKey().Raw();
820 return CMalleablePubKey(vchPubKeyL, vchPubKeyH);
824 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant)
827 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
831 throw key_error("CMalleableKey::CheckKeyVariant() : R is invalid");
834 if (!vchPubKeyVariant.IsValid()) {
835 throw key_error("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
839 if (!point_R.setBytes(R.Raw())) {
840 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
844 H.SetSecret(vchSecretH, true);
845 std::vector<unsigned char> vchPubKeyH = H.GetPubKey().Raw();
848 if (!point_H.setBytes(vchPubKeyH)) {
849 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
853 if (!point_P.setBytes(vchPubKeyVariant.Raw())) {
854 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
857 // Infinity points are senseless
858 if (point_P.IsInfinity()) {
859 throw key_error("CMalleableKey::CheckKeyVariant() : P is infinity");
863 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
867 std::vector<unsigned char> vchRl;
868 if (!point_R.getBytes(vchRl)) {
869 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
872 // Calculate Hash(R*l)
874 bnHash.setuint160(Hash160(vchRl));
877 // Calculate Ps = Hash(L*r)*G + H
878 point_Ps.ECMULGEN(bnHash, point_H);
880 // Infinity points are senseless
881 if (point_Ps.IsInfinity()) {
882 throw key_error("CMalleableKey::CheckKeyVariant() : Ps is infinity");
886 if (point_Ps != point_P) {
893 // Check ownership and restore private key
894 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant, CKey &privKeyVariant)
897 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
901 throw key_error("CMalleableKey::CheckKeyVariant() : R is invalid");
904 if (!vchPubKeyVariant.IsValid()) {
905 throw key_error("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
909 if (!point_R.setBytes(R.Raw())) {
910 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
914 H.SetSecret(vchSecretH, true);
915 std::vector<unsigned char> vchPubKeyH = H.GetPubKey().Raw();
918 if (!point_H.setBytes(vchPubKeyH)) {
919 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
923 if (!point_P.setBytes(vchPubKeyVariant.Raw())) {
924 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
927 // Infinity points are senseless
928 if (point_P.IsInfinity()) {
929 throw key_error("CMalleableKey::CheckKeyVariant() : P is infinity");
933 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
937 std::vector<unsigned char> vchRl;
938 if (!point_R.getBytes(vchRl)) {
939 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
942 // Calculate Hash(R*l)
944 bnHash.setuint160(Hash160(vchRl));
947 // Calculate Ps = Hash(L*r)*G + H
948 point_Ps.ECMULGEN(bnHash, point_H);
950 // Infinity points are senseless
951 if (point_Ps.IsInfinity()) {
952 throw key_error("CMalleableKey::CheckKeyVariant() : Ps is infinity");
956 if (point_Ps != point_P) {
960 // OpenSSL BIGNUM representation of the second private key from (l, h) pair
962 bnh.setBytes(std::vector<unsigned char>(vchSecretH.begin(), vchSecretH.end()));
964 // Calculate p = Hash(R*l) + h
965 CBigNum bnp = bnHash + bnh;
967 std::vector<unsigned char> vchp = bnp.getBytes();
968 privKeyVariant.SetSecret(CSecret(vchp.begin(), vchp.end()), true);
973 std::string CMalleableKey::ToString()
975 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
977 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
979 return EncodeBase58Check(vch);
982 bool CMalleableKey::SetString(const std::string& strMutableKey)
984 std::vector<unsigned char> vchTemp;
985 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
986 throw key_error("CMalleableKey::SetString() : Provided key data seems corrupted.");
989 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
997 CMalleableKeyView::CMalleableKeyView(const CMalleableKey &b)
999 vchSecretL = b.vchSecretL;
1002 H.SetSecret(b.vchSecretH, true);
1003 vchPubKeyH = H.GetPubKey().Raw();
1004 nVersion = b.nVersion;
1007 CMalleableKeyView::CMalleableKeyView(const CMalleableKeyView &b)
1009 vchSecretL = b.vchSecretL;
1010 vchPubKeyH = b.vchPubKeyH;
1011 nVersion = CURRENT_VERSION;
1014 CMalleableKeyView::CMalleableKeyView(const CSecret &L, const CPubKey &pvchPubKeyH)
1017 vchPubKeyH = pvchPubKeyH.Raw();
1018 nVersion = CURRENT_VERSION;
1021 CMalleableKeyView& CMalleableKeyView::operator=(const CMalleableKey &b)
1023 vchSecretL = b.vchSecretL;
1026 H.SetSecret(b.vchSecretH, true);
1027 vchPubKeyH = H.GetPubKey().Raw();
1028 nVersion = b.nVersion;
1033 CMalleableKeyView::~CMalleableKeyView()
1037 CMalleablePubKey CMalleableKeyView::GetMalleablePubKey() const
1040 keyL.SetSecret(vchSecretL, true);
1041 return CMalleablePubKey(keyL.GetPubKey(), vchPubKeyH);
1045 bool CMalleableKeyView::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant)
1048 throw key_error("CMalleableKeyView::CheckKeyVariant() : R is invalid");
1051 if (!vchPubKeyVariant.IsValid()) {
1052 throw key_error("CMalleableKeyView::CheckKeyVariant() : public key variant is invalid");
1056 if (!point_R.setBytes(R.Raw())) {
1057 throw key_error("CMalleableKeyView::CheckKeyVariant() : Unable to decode R value");
1061 if (!point_H.setBytes(vchPubKeyH)) {
1062 throw key_error("CMalleableKeyView::CheckKeyVariant() : Unable to decode H value");
1066 if (!point_P.setBytes(vchPubKeyVariant.Raw())) {
1067 throw key_error("CMalleableKeyView::CheckKeyVariant() : Unable to decode P value");
1070 // Infinity points are senseless
1071 if (point_P.IsInfinity()) {
1072 throw key_error("CMalleableKeyView::CheckKeyVariant() : P is infinity");
1076 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
1080 std::vector<unsigned char> vchRl;
1081 if (!point_R.getBytes(vchRl)) {
1082 throw key_error("CMalleableKeyView::CheckKeyVariant() : Unable to convert Rl value");
1085 // Calculate Hash(R*l)
1087 bnHash.setuint160(Hash160(vchRl));
1090 // Calculate Ps = Hash(L*r)*G + H
1091 point_Ps.ECMULGEN(bnHash, point_H);
1093 // Infinity points are senseless
1094 if (point_Ps.IsInfinity()) {
1095 throw key_error("CMalleableKeyView::CheckKeyVariant() : Ps is infinity");
1099 if (point_Ps != point_P) {
1106 std::string CMalleableKeyView::ToString()
1108 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1110 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1112 return EncodeBase58Check(vch);
1115 bool CMalleableKeyView::SetString(const std::string& strMutableKey)
1117 std::vector<unsigned char> vchTemp;
1118 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1119 throw key_error("CMalleableKeyView::SetString() : Provided key data seems corrupted.");
1122 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1128 bool CMalleableKeyView::IsNull() const
1130 return nVersion != CURRENT_VERSION;
1133 //// Asymmetric encryption
1135 void CPubKey::EncryptData(const std::vector<unsigned char>& data, std::vector<unsigned char>& encrypted)
1138 key.SetPubKey(*this);
1140 key.EncryptData(data, encrypted);
1143 void CKey::EncryptData(const std::vector<unsigned char>& data, std::vector<unsigned char>& encrypted)
1146 char error[1024] = "Unknown error";
1147 cryptogram_t *cryptogram;
1149 ctx = create_context(pkey);
1150 if (!EC_KEY_get0_public_key(ctx->user_key))
1151 throw key_error("Given EC key is not public key");
1153 cryptogram = ecies_encrypt(ctx, (unsigned char*)&data[0], data.size(), error);
1154 if (cryptogram == NULL) {
1157 throw key_error(std::string("Error in encryption: %s") + error);
1160 encrypted.resize(cryptogram_data_sum_length(cryptogram));
1161 unsigned char *key_data = cryptogram_key_data(cryptogram);
1162 memcpy(&encrypted[0], key_data, encrypted.size());
1163 cryptogram_free(cryptogram);
1167 void CKey::DecryptData(const std::vector<unsigned char>& encrypted, std::vector<unsigned char>& data)
1170 char error[1024] = "Unknown error";
1171 cryptogram_t *cryptogram;
1173 unsigned char *decrypted;
1175 ctx = create_context(pkey);
1176 if (!EC_KEY_get0_private_key(ctx->user_key))
1177 throw key_error("Given EC key is not private key");
1179 size_t key_length = ctx->stored_key_length;
1180 size_t mac_length = EVP_MD_size(ctx->md);
1181 cryptogram = cryptogram_alloc(key_length, mac_length, encrypted.size() - key_length - mac_length);
1183 memcpy(cryptogram_key_data(cryptogram), &encrypted[0], encrypted.size());
1185 decrypted = ecies_decrypt(ctx, cryptogram, &length, error);
1186 cryptogram_free(cryptogram);
1189 if (decrypted == NULL) {
1190 throw key_error(std::string("Error in decryption: %s") + error);
1193 data.resize(length);
1194 memcpy(&data[0], decrypted, length);