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>
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;
170 void CKey::SetCompressedPubKey()
172 EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
173 fCompressedPubKey = true;
178 fCompressedPubKey = false;
181 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
183 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");
199 fCompressedPubKey = b.fCompressedPubKey;
202 CKey& CKey::operator=(const CKey& b)
204 if (!EC_KEY_copy(pkey, b.pkey))
205 throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
207 fCompressedPubKey = b.fCompressedPubKey;
216 bool CKey::IsNull() const
221 bool CKey::IsCompressed() const
223 return fCompressedPubKey;
226 bool CKey::CheckSignatureElement(const unsigned char *vch, int len, bool half) {
227 return CompareBigEndian(vch, len, vchZero, 0) > 0 &&
228 CompareBigEndian(vch, len, half ? vchMaxModHalfOrder : vchMaxModOrder, 32) <= 0;
231 bool CKey::ReserealizeSignature(std::vector<unsigned char>& vchSig)
236 unsigned char *pos = &vchSig[0];
237 ECDSA_SIG *sig = d2i_ECDSA_SIG(NULL, (const unsigned char **)&pos, vchSig.size());
242 int nSize = i2d_ECDSA_SIG(sig, NULL);
244 vchSig.resize(nSize); // grow or shrink as needed
247 i2d_ECDSA_SIG(sig, &pos);
257 void CKey::MakeNewKey(bool fCompressed)
259 if (!EC_KEY_generate_key(pkey))
260 throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
262 SetCompressedPubKey();
266 bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
268 const unsigned char* pbegin = &vchPrivKey[0];
269 if (d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
271 // In testing, d2i_ECPrivateKey can return true
272 // but fill in pkey with a key that fails
273 // EC_KEY_check_key, so:
274 if (EC_KEY_check_key(pkey))
280 // If vchPrivKey data is bad d2i_ECPrivateKey() can
281 // leave pkey in a state where calling EC_KEY_free()
282 // crashes. To avoid that, set pkey to NULL and
283 // leak the memory (a leak is better than a crash)
289 bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
292 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
294 throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
295 if (vchSecret.size() != 32)
296 throw key_error("CKey::SetSecret() : secret must be 32 bytes");
297 BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
299 throw key_error("CKey::SetSecret() : BN_bin2bn failed");
300 if (!EC_KEY_regenerate_key(pkey,bn))
303 throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
307 if (fCompressed || fCompressedPubKey)
308 SetCompressedPubKey();
312 CSecret CKey::GetSecret(bool &fCompressed) const
316 const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
317 int nBytes = BN_num_bytes(bn);
319 throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
320 int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
322 throw key_error("CKey::GetSecret(): BN_bn2bin failed");
323 fCompressed = fCompressedPubKey;
327 CPrivKey CKey::GetPrivKey() const
329 int nSize = i2d_ECPrivateKey(pkey, NULL);
331 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
332 CPrivKey vchPrivKey(nSize, 0);
333 unsigned char* pbegin = &vchPrivKey[0];
334 if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
335 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
339 bool CKey::SetPubKey(const CPubKey& vchPubKey)
341 const unsigned char* pbegin = &vchPubKey.vchPubKey[0];
342 if (o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.vchPubKey.size()))
345 if (vchPubKey.vchPubKey.size() == 33)
346 SetCompressedPubKey();
354 CPubKey CKey::GetPubKey() const
356 int nSize = i2o_ECPublicKey(pkey, NULL);
358 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
359 std::vector<unsigned char> vchPubKey(nSize, 0);
360 unsigned char* pbegin = &vchPubKey[0];
361 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
362 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
363 return CPubKey(vchPubKey);
366 bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
369 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
372 const EC_GROUP *group = EC_KEY_get0_group(pkey);
373 CBigNum order, halforder;
374 EC_GROUP_get_order(group, &order, NULL);
375 BN_rshift1(&halforder, &order);
376 // enforce low S values, by negating the value (modulo the order) if above order/2.
377 if (BN_cmp(sig->s, &halforder) > 0) {
378 BN_sub(sig->s, &order, sig->s);
380 unsigned int nSize = ECDSA_size(pkey);
381 vchSig.resize(nSize); // Make sure it is big enough
382 unsigned char *pos = &vchSig[0];
383 nSize = i2d_ECDSA_SIG(sig, &pos);
385 vchSig.resize(nSize); // Shrink to fit actual size
386 // Testing our new signature
387 if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) {
394 // create a compact signature (65 bytes), which allows reconstructing the used public key
395 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
396 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
397 // 0x1D = second key with even y, 0x1E = second key with odd y
398 bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
401 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
404 const EC_GROUP *group = EC_KEY_get0_group(pkey);
405 CBigNum order, halforder;
406 EC_GROUP_get_order(group, &order, NULL);
407 BN_rshift1(&halforder, &order);
408 // enforce low S values, by negating the value (modulo the order) if above order/2.
409 if (BN_cmp(sig->s, &halforder) > 0) {
410 BN_sub(sig->s, &order, sig->s);
414 int nBitsR = BN_num_bits(sig->r);
415 int nBitsS = BN_num_bits(sig->s);
416 if (nBitsR <= 256 && nBitsS <= 256)
419 for (int8_t i=0; i<4; i++)
423 if (fCompressedPubKey)
424 keyRec.SetCompressedPubKey();
425 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
426 if (keyRec.GetPubKey() == this->GetPubKey())
436 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
439 vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
440 BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
441 BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
448 // reconstruct public key from a compact signature
449 // This is only slightly more CPU intensive than just verifying it.
450 // If this function succeeds, the recovered public key is guaranteed to be valid
451 // (the signature is a valid signature of the given data for that key)
452 bool CKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
454 if (vchSig.size() != 65)
459 ECDSA_SIG *sig = ECDSA_SIG_new();
460 BN_bin2bn(&vchSig[1],32,sig->r);
461 BN_bin2bn(&vchSig[33],32,sig->s);
464 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
467 SetCompressedPubKey();
470 if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)
480 bool CKey::Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
485 // New versions of OpenSSL will reject non-canonical DER signatures. de/re-serialize first.
486 unsigned char *norm_der = NULL;
487 ECDSA_SIG *norm_sig = ECDSA_SIG_new();
488 const unsigned char* sigptr = &vchSig[0];
490 if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL)
492 /* As of OpenSSL 1.0.0p d2i_ECDSA_SIG frees and nulls the pointer on
493 * error. But OpenSSL's own use of this function redundantly frees the
494 * result. As ECDSA_SIG_free(NULL) is a no-op, and in the absence of a
495 * clear contract for the function behaving the same way is more
498 ECDSA_SIG_free(norm_sig);
501 int derlen = i2d_ECDSA_SIG(norm_sig, &norm_der);
502 ECDSA_SIG_free(norm_sig);
506 // -1 = error, 0 = bad sig, 1 = good
507 bool ret = ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
508 OPENSSL_free(norm_der);
512 bool CKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
515 if (!key.SetCompactSignature(hash, vchSig))
517 if (GetPubKey() != key.GetPubKey())
528 if (!EC_KEY_check_key(pkey))
532 CSecret secret = GetSecret(fCompr);
534 key2.SetSecret(secret, fCompr);
535 return GetPubKey() == key2.GetPubKey();
545 group = EC_GROUP_new_by_curve_name(NID_secp256k1);
547 err = "EC_KEY_new_by_curve_name failed.";
551 point = EC_POINT_new(group);
553 err = "EC_POINT_new failed.";
559 err = "BN_CTX_new failed.";
566 if (group) EC_GROUP_free(group);
567 if (point) EC_POINT_free(point);
568 throw std::runtime_error(std::string("CPoint::CPoint() : - ") + err);
571 bool CPoint::operator!=(const CPoint &a)
573 if (EC_POINT_cmp(group, point, a.point, ctx) != 0)
579 if (point) EC_POINT_free(point);
580 if (group) EC_GROUP_free(group);
581 if (ctx) BN_CTX_free(ctx);
584 // Initialize from octets stream
585 bool CPoint::setBytes(const std::vector<unsigned char> &vchBytes)
587 if (!EC_POINT_oct2point(group, point, &vchBytes[0], vchBytes.size(), ctx)) {
593 // Serialize to octets stream
594 bool CPoint::getBytes(std::vector<unsigned char> &vchBytes)
596 unsigned int nSize = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, ctx);
597 vchBytes.resize(nSize);
598 if (!(nSize == EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, &vchBytes[0], nSize, ctx))) {
604 // ECC multiplication by specified multiplier
605 bool CPoint::ECMUL(const CBigNum &bnMultiplier)
607 if (!EC_POINT_mul(group, point, NULL, point, &bnMultiplier, NULL)) {
608 printf("CPoint::ECMUL() : EC_POINT_mul failed");
616 bool CPoint::ECMULGEN(const CBigNum &bnMultiplier, const CPoint &qPoint)
618 if (!EC_POINT_mul(group, point, &bnMultiplier, qPoint.point, BN_value_one(), NULL)) {
619 printf("CPoint::ECMULGEN() : EC_POINT_mul failed.");
628 void CMalleablePubKey::GetVariant(CPubKey &R, CPubKey &vchPubKeyVariant)
630 EC_KEY *eckey = NULL;
631 eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
633 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_new_by_curve_name failed");
636 // Use standard key generation function to get r and R values.
638 // r will be presented by private key;
639 // R is ECDSA public key which calculated as G*r
640 if (!EC_KEY_generate_key(eckey)) {
641 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_generate_key failed");
644 EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
646 int nSize = i2o_ECPublicKey(eckey, NULL);
648 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey failed");
651 std::vector<unsigned char> vchPubKey(nSize, 0);
652 unsigned char* pbegin_R = &vchPubKey[0];
654 if (i2o_ECPublicKey(eckey, &pbegin_R) != nSize) {
655 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey returned unexpected size");
659 R = CPubKey(vchPubKey);
661 // OpenSSL BIGNUM representation of r value
663 bnr = *(CBigNum*) EC_KEY_get0_private_key(eckey);
667 if (!point.setBytes(pubKeyL.Raw())) {
668 throw key_error("CMalleablePubKey::GetVariant() : Unable to decode L value");
674 std::vector<unsigned char> vchLr;
675 if (!point.getBytes(vchLr)) {
676 throw key_error("CMalleablePubKey::GetVariant() : Unable to convert Lr value");
679 // Calculate Hash(L*r) and then get a BIGNUM representation of hash value.
681 bnHash.setuint160(Hash160(vchLr));
684 pointH.setBytes(pubKeyH.Raw());
687 // Calculate P = Hash(L*r)*G + H
688 P.ECMULGEN(bnHash, pointH);
690 if (P.IsInfinity()) {
691 throw key_error("CMalleablePubKey::GetVariant() : P is infinity");
694 std::vector<unsigned char> vchResult;
695 P.getBytes(vchResult);
697 vchPubKeyVariant = CPubKey(vchResult);
700 std::string CMalleablePubKey::ToString()
702 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
704 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
706 return EncodeBase58Check(vch);
709 bool CMalleablePubKey::SetString(const std::string& strMalleablePubKey)
711 std::vector<unsigned char> vchTemp;
712 if (!DecodeBase58Check(strMalleablePubKey, vchTemp)) {
713 throw key_error("CMalleablePubKey::SetString() : Provided key data seems corrupted.");
716 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
722 bool CMalleablePubKey::operator==(const CMalleablePubKey &b)
724 return (nVersion == b.nVersion &&
725 pubKeyL == b.pubKeyL &&
726 pubKeyH == b.pubKeyH);
732 void CMalleableKey::Reset()
740 void CMalleableKey::MakeNewKeys()
743 bool fCompressed = true;
748 vchSecretL = L.GetSecret(fCompressed);
749 vchSecretH = H.GetSecret(fCompressed);
751 nVersion = CURRENT_VERSION;
754 CMalleableKey::CMalleableKey()
759 CMalleableKey::CMalleableKey(const CMalleableKey &b)
761 SetSecrets(b.vchSecretL, b.vchSecretH);
764 CMalleableKey::CMalleableKey(const CSecret &L, const CSecret &H)
769 CMalleableKey& CMalleableKey::operator=(const CMalleableKey &b)
771 SetSecrets(b.vchSecretL, b.vchSecretH);
776 CMalleableKey::~CMalleableKey()
780 bool CMalleableKey::IsNull() const
782 return nVersion != CURRENT_VERSION;
785 bool CMalleableKey::SetSecrets(const CSecret &pvchSecretL, const CSecret &pvchSecretH)
790 if (!L.SetSecret(pvchSecretL, true) || !H.SetSecret(pvchSecretH, true))
796 vchSecretL = pvchSecretL;
797 vchSecretH = pvchSecretH;
798 nVersion = CURRENT_VERSION;
803 void CMalleableKey::GetSecrets(CSecret &pvchSecretL, CSecret &pvchSecretH) const
805 pvchSecretL = vchSecretL;
806 pvchSecretH = vchSecretH;
809 CMalleablePubKey CMalleableKey::GetMalleablePubKey() const
812 L.SetSecret(vchSecretL, true);
813 H.SetSecret(vchSecretH, true);
815 std::vector<unsigned char> vchPubKeyL = L.GetPubKey().Raw();
816 std::vector<unsigned char> vchPubKeyH = H.GetPubKey().Raw();
818 return CMalleablePubKey(vchPubKeyL, vchPubKeyH);
822 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant)
825 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
829 throw key_error("CMalleableKey::CheckKeyVariant() : R is invalid");
832 if (!vchPubKeyVariant.IsValid()) {
833 throw key_error("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
837 if (!point_R.setBytes(R.Raw())) {
838 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
842 H.SetSecret(vchSecretH, true);
843 std::vector<unsigned char> vchPubKeyH = H.GetPubKey().Raw();
846 if (!point_H.setBytes(vchPubKeyH)) {
847 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
851 if (!point_P.setBytes(vchPubKeyVariant.Raw())) {
852 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
855 // Infinity points are senseless
856 if (point_P.IsInfinity()) {
857 throw key_error("CMalleableKey::CheckKeyVariant() : P is infinity");
861 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
865 std::vector<unsigned char> vchRl;
866 if (!point_R.getBytes(vchRl)) {
867 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
870 // Calculate Hash(R*l)
872 bnHash.setuint160(Hash160(vchRl));
875 // Calculate Ps = Hash(L*r)*G + H
876 point_Ps.ECMULGEN(bnHash, point_H);
878 // Infinity points are senseless
879 if (point_Ps.IsInfinity()) {
880 throw key_error("CMalleableKey::CheckKeyVariant() : Ps is infinity");
884 if (point_Ps != point_P) {
891 // Check ownership and restore private key
892 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant, CKey &privKeyVariant)
895 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
899 throw key_error("CMalleableKey::CheckKeyVariant() : R is invalid");
902 if (!vchPubKeyVariant.IsValid()) {
903 throw key_error("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
907 if (!point_R.setBytes(R.Raw())) {
908 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
912 H.SetSecret(vchSecretH, true);
913 std::vector<unsigned char> vchPubKeyH = H.GetPubKey().Raw();
916 if (!point_H.setBytes(vchPubKeyH)) {
917 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
921 if (!point_P.setBytes(vchPubKeyVariant.Raw())) {
922 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
925 // Infinity points are senseless
926 if (point_P.IsInfinity()) {
927 throw key_error("CMalleableKey::CheckKeyVariant() : P is infinity");
931 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
935 std::vector<unsigned char> vchRl;
936 if (!point_R.getBytes(vchRl)) {
937 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
940 // Calculate Hash(R*l)
942 bnHash.setuint160(Hash160(vchRl));
945 // Calculate Ps = Hash(L*r)*G + H
946 point_Ps.ECMULGEN(bnHash, point_H);
948 // Infinity points are senseless
949 if (point_Ps.IsInfinity()) {
950 throw key_error("CMalleableKey::CheckKeyVariant() : Ps is infinity");
954 if (point_Ps != point_P) {
958 // OpenSSL BIGNUM representation of the second private key from (l, h) pair
960 bnh.setBytes(std::vector<unsigned char>(vchSecretH.begin(), vchSecretH.end()));
962 // Calculate p = Hash(R*l) + h
963 CBigNum bnp = bnHash + bnh;
965 std::vector<unsigned char> vchp = bnp.getBytes();
966 privKeyVariant.SetSecret(CSecret(vchp.begin(), vchp.end()), true);
971 std::string CMalleableKey::ToString()
973 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
975 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
977 return EncodeBase58Check(vch);
980 bool CMalleableKey::SetString(const std::string& strMutableKey)
982 std::vector<unsigned char> vchTemp;
983 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
984 throw key_error("CMalleableKey::SetString() : Provided key data seems corrupted.");
987 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
995 CMalleableKeyView::CMalleableKeyView(const CMalleableKey &b)
997 assert(b.nVersion == CURRENT_VERSION);
998 vchSecretL = b.vchSecretL;
1001 H.SetSecret(b.vchSecretH, true);
1002 vchPubKeyH = H.GetPubKey().Raw();
1005 CMalleableKeyView::CMalleableKeyView(const CSecret &L, const CPubKey &pvchPubKeyH)
1008 vchPubKeyH = pvchPubKeyH.Raw();
1011 CMalleableKeyView& CMalleableKeyView::operator=(const CMalleableKey &b)
1013 assert(b.nVersion == CURRENT_VERSION);
1014 vchSecretL = b.vchSecretL;
1017 H.SetSecret(b.vchSecretH, true);
1018 vchPubKeyH = H.GetPubKey().Raw();
1023 CMalleableKeyView::~CMalleableKeyView()
1027 CMalleablePubKey CMalleableKeyView::GetMalleablePubKey() const
1030 keyL.SetSecret(vchSecretL, true);
1031 return CMalleablePubKey(keyL.GetPubKey(), vchPubKeyH);
1035 bool CMalleableKeyView::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant)
1038 throw key_error("CMalleableKeyView::CheckKeyVariant() : R is invalid");
1041 if (!vchPubKeyVariant.IsValid()) {
1042 throw key_error("CMalleableKeyView::CheckKeyVariant() : public key variant is invalid");
1046 if (!point_R.setBytes(R.Raw())) {
1047 throw key_error("CMalleableKeyView::CheckKeyVariant() : Unable to decode R value");
1051 if (!point_H.setBytes(vchPubKeyH)) {
1052 throw key_error("CMalleableKeyView::CheckKeyVariant() : Unable to decode H value");
1056 if (!point_P.setBytes(vchPubKeyVariant.Raw())) {
1057 throw key_error("CMalleableKeyView::CheckKeyVariant() : Unable to decode P value");
1060 // Infinity points are senseless
1061 if (point_P.IsInfinity()) {
1062 throw key_error("CMalleableKeyView::CheckKeyVariant() : P is infinity");
1066 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
1070 std::vector<unsigned char> vchRl;
1071 if (!point_R.getBytes(vchRl)) {
1072 throw key_error("CMalleableKeyView::CheckKeyVariant() : Unable to convert Rl value");
1075 // Calculate Hash(R*l)
1077 bnHash.setuint160(Hash160(vchRl));
1080 // Calculate Ps = Hash(L*r)*G + H
1081 point_Ps.ECMULGEN(bnHash, point_H);
1083 // Infinity points are senseless
1084 if (point_Ps.IsInfinity()) {
1085 throw key_error("CMalleableKeyView::CheckKeyVariant() : Ps is infinity");
1089 if (point_Ps != point_P) {
1096 //// Asymmetric encryption
1098 bool CPubKey::EncryptData(const std::vector<unsigned char>& data, std::vector<unsigned char>& encrypted)
1105 bool CKey::DecryptData(const std::vector<unsigned char>& encrypted, std::vector<unsigned char>& data)