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>
13 // Generate a private key from just the secret parameter
14 int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
18 EC_POINT *pub_key = NULL;
22 const EC_GROUP *group = EC_KEY_get0_group(eckey);
24 if ((ctx = BN_CTX_new()) == NULL)
27 pub_key = EC_POINT_new(group);
32 if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
35 EC_KEY_set_private_key(eckey,priv_key);
36 EC_KEY_set_public_key(eckey,pub_key);
43 EC_POINT_free(pub_key);
50 // Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
51 // recid selects which key is recovered
52 // if check is non-zero, additional checks are performed
53 int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
74 const EC_GROUP *group = EC_KEY_get0_group(eckey);
75 if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
77 order = BN_CTX_get(ctx);
78 if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
80 if (!BN_copy(x, order)) { ret=-1; goto err; }
81 if (!BN_mul_word(x, i)) { ret=-1; goto err; }
82 if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
83 field = BN_CTX_get(ctx);
84 if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
85 if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
86 if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
87 if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
90 if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
91 if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
92 if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
94 if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
95 n = EC_GROUP_get_degree(group);
97 if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
98 if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
99 zero = BN_CTX_get(ctx);
100 if (!BN_zero(zero)) { ret=-1; goto err; }
101 if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
102 rr = BN_CTX_get(ctx);
103 if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
104 sor = BN_CTX_get(ctx);
105 if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
106 eor = BN_CTX_get(ctx);
107 if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
108 if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
109 if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
118 if (R != NULL) EC_POINT_free(R);
119 if (O != NULL) EC_POINT_free(O);
120 if (Q != NULL) EC_POINT_free(Q);
124 int CompareBigEndian(const unsigned char *c1, size_t c1len, const unsigned char *c2, size_t c2len) {
125 while (c1len > c2len) {
131 while (c2len > c1len) {
149 // Order of secp256k1's generator minus 1.
150 const unsigned char vchMaxModOrder[32] = {
151 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
152 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
153 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,
154 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40
157 // Half of the order of secp256k1's generator minus 1.
158 const unsigned char vchMaxModHalfOrder[32] = {
159 0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
160 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
161 0x5D,0x57,0x6E,0x73,0x57,0xA4,0x50,0x1D,
162 0xDF,0xE9,0x2F,0x46,0x68,0x1B,0x20,0xA0
165 const unsigned char *vchZero = NULL;
169 void CKey::SetCompressedPubKey()
171 EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
172 fCompressedPubKey = true;
177 fCompressedPubKey = false;
180 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
182 throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
192 CKey::CKey(const CKey& b)
194 pkey = EC_KEY_dup(b.pkey);
196 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
198 fCompressedPubKey = b.fCompressedPubKey;
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");
214 fCompressedPubKey = b.fCompressedPubKey;
223 bool CKey::IsNull() const
228 bool CKey::IsCompressed() const
230 return fCompressedPubKey;
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 CKey::ReserealizeSignature(std::vector<unsigned char>& vchSig)
243 unsigned char *pos = &vchSig[0];
244 ECDSA_SIG *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");
269 SetCompressedPubKey();
273 bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
275 const unsigned char* pbegin = &vchPrivKey[0];
276 if (d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
278 // In testing, d2i_ECPrivateKey can return true
279 // but fill in pkey with a key that fails
280 // EC_KEY_check_key, so:
281 if (EC_KEY_check_key(pkey))
287 // If vchPrivKey data is bad d2i_ECPrivateKey() can
288 // leave pkey in a state where calling EC_KEY_free()
289 // crashes. To avoid that, set pkey to NULL and
290 // leak the memory (a leak is better than a crash)
296 bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
299 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
301 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 CSecret CKey::GetSecret() const
337 return GetSecret(fCompressed);
340 CPrivKey CKey::GetPrivKey() const
342 int nSize = i2d_ECPrivateKey(pkey, NULL);
344 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
345 CPrivKey vchPrivKey(nSize, 0);
346 unsigned char* pbegin = &vchPrivKey[0];
347 if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
348 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
352 bool CKey::SetPubKey(const CPubKey& vchPubKey)
354 const unsigned char* pbegin = &vchPubKey.vchPubKey[0];
355 if (o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.vchPubKey.size()))
358 if (vchPubKey.vchPubKey.size() == 33)
359 SetCompressedPubKey();
367 CPubKey CKey::GetPubKey() const
369 int nSize = i2o_ECPublicKey(pkey, NULL);
371 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
372 std::vector<unsigned char> vchPubKey(nSize, 0);
373 unsigned char* pbegin = &vchPubKey[0];
374 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
375 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
376 return CPubKey(vchPubKey);
379 bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
382 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
385 const EC_GROUP *group = EC_KEY_get0_group(pkey);
386 CBigNum order, halforder;
387 EC_GROUP_get_order(group, &order, NULL);
388 BN_rshift1(&halforder, &order);
389 // enforce low S values, by negating the value (modulo the order) if above order/2.
390 if (BN_cmp(sig->s, &halforder) > 0) {
391 BN_sub(sig->s, &order, sig->s);
393 unsigned int nSize = ECDSA_size(pkey);
394 vchSig.resize(nSize); // Make sure it is big enough
395 unsigned char *pos = &vchSig[0];
396 nSize = i2d_ECDSA_SIG(sig, &pos);
398 vchSig.resize(nSize); // Shrink to fit actual size
399 // Testing our new signature
400 if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) {
407 // create a compact signature (65 bytes), which allows reconstructing the used public key
408 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
409 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
410 // 0x1D = second key with even y, 0x1E = second key with odd y
411 bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
414 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
417 const EC_GROUP *group = EC_KEY_get0_group(pkey);
418 CBigNum order, halforder;
419 EC_GROUP_get_order(group, &order, NULL);
420 BN_rshift1(&halforder, &order);
421 // enforce low S values, by negating the value (modulo the order) if above order/2.
422 if (BN_cmp(sig->s, &halforder) > 0) {
423 BN_sub(sig->s, &order, sig->s);
427 int nBitsR = BN_num_bits(sig->r);
428 int nBitsS = BN_num_bits(sig->s);
429 if (nBitsR <= 256 && nBitsS <= 256)
432 for (int8_t i=0; i<4; i++)
436 if (fCompressedPubKey)
437 keyRec.SetCompressedPubKey();
438 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
439 if (keyRec.GetPubKey() == this->GetPubKey())
449 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
452 vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
453 BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
454 BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
461 // reconstruct public key from a compact signature
462 // This is only slightly more CPU intensive than just verifying it.
463 // If this function succeeds, the recovered public key is guaranteed to be valid
464 // (the signature is a valid signature of the given data for that key)
465 bool CKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
467 if (vchSig.size() != 65)
472 ECDSA_SIG *sig = ECDSA_SIG_new();
473 BN_bin2bn(&vchSig[1],32,sig->r);
474 BN_bin2bn(&vchSig[33],32,sig->s);
477 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
480 SetCompressedPubKey();
483 if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)
493 bool CKey::Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
498 // New versions of OpenSSL will reject non-canonical DER signatures. de/re-serialize first.
499 unsigned char *norm_der = NULL;
500 ECDSA_SIG *norm_sig = ECDSA_SIG_new();
501 const unsigned char* sigptr = &vchSig[0];
503 if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL)
505 /* As of OpenSSL 1.0.0p d2i_ECDSA_SIG frees and nulls the pointer on
506 * error. But OpenSSL's own use of this function redundantly frees the
507 * result. As ECDSA_SIG_free(NULL) is a no-op, and in the absence of a
508 * clear contract for the function behaving the same way is more
511 ECDSA_SIG_free(norm_sig);
514 int derlen = i2d_ECDSA_SIG(norm_sig, &norm_der);
515 ECDSA_SIG_free(norm_sig);
519 // -1 = error, 0 = bad sig, 1 = good
520 bool ret = ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
521 OPENSSL_free(norm_der);
525 bool CKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
528 if (!key.SetCompactSignature(hash, vchSig))
530 if (GetPubKey() != key.GetPubKey())
541 if (!EC_KEY_check_key(pkey))
545 CSecret secret = GetSecret(fCompr);
547 key2.SetSecret(secret, fCompr);
548 return GetPubKey() == key2.GetPubKey();
558 group = EC_GROUP_new_by_curve_name(NID_secp256k1);
560 err = "EC_KEY_new_by_curve_name failed.";
564 point = EC_POINT_new(group);
566 err = "EC_POINT_new failed.";
572 err = "BN_CTX_new failed.";
579 if (group) EC_GROUP_free(group);
580 if (point) EC_POINT_free(point);
581 throw std::runtime_error(std::string("CPoint::CPoint() : - ") + err);
584 bool CPoint::operator!=(const CPoint &a)
586 if (EC_POINT_cmp(group, point, a.point, ctx) != 0)
592 if (point) EC_POINT_free(point);
593 if (group) EC_GROUP_free(group);
594 if (ctx) BN_CTX_free(ctx);
597 // Initialize from octets stream
598 bool CPoint::setBytes(const std::vector<unsigned char> &vchBytes)
600 if (!EC_POINT_oct2point(group, point, &vchBytes[0], vchBytes.size(), ctx)) {
606 // Initialize from octets stream
607 bool CPoint::setPubKey(const CPubKey &vchPubKey)
609 return setBytes(vchPubKey.Raw());
612 // Serialize to octets stream
613 bool CPoint::getBytes(std::vector<unsigned char> &vchBytes)
615 size_t nSize = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, ctx);
616 vchBytes.resize(nSize);
617 if (!(nSize == EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, &vchBytes[0], nSize, ctx))) {
623 // ECC multiplication by specified multiplier
624 bool CPoint::ECMUL(const CBigNum &bnMultiplier)
626 if (!EC_POINT_mul(group, point, NULL, point, &bnMultiplier, NULL)) {
627 printf("CPoint::ECMUL() : EC_POINT_mul failed");
635 bool CPoint::ECMULGEN(const CBigNum &bnMultiplier, const CPoint &qPoint)
637 if (!EC_POINT_mul(group, point, &bnMultiplier, qPoint.point, BN_value_one(), NULL)) {
638 printf("CPoint::ECMULGEN() : EC_POINT_mul failed.");
647 void CMalleablePubKey::GetVariant(CPubKey &R, CPubKey &vchPubKeyVariant)
649 EC_KEY *eckey = NULL;
650 eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
652 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_new_by_curve_name failed");
655 // Use standard key generation function to get r and R values.
657 // r will be presented by private key;
658 // R is ECDSA public key which calculated as G*r
659 if (!EC_KEY_generate_key(eckey)) {
660 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_generate_key failed");
663 EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
665 int nSize = i2o_ECPublicKey(eckey, NULL);
667 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey failed");
670 std::vector<unsigned char> vchPubKey(nSize, 0);
671 unsigned char* pbegin_R = &vchPubKey[0];
673 if (i2o_ECPublicKey(eckey, &pbegin_R) != nSize) {
674 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey returned unexpected size");
678 R = CPubKey(vchPubKey);
680 // OpenSSL BIGNUM representation of r value
682 bnr = *(CBigNum*) EC_KEY_get0_private_key(eckey);
686 if (!point.setPubKey(pubKeyL)) {
687 throw key_error("CMalleablePubKey::GetVariant() : Unable to decode L value");
693 std::vector<unsigned char> vchLr;
694 if (!point.getBytes(vchLr)) {
695 throw key_error("CMalleablePubKey::GetVariant() : Unable to convert Lr value");
698 // Calculate Hash(L*r) and then get a BIGNUM representation of hash value.
700 bnHash.setuint160(Hash160(vchLr));
703 pointH.setPubKey(pubKeyH);
706 // Calculate P = Hash(L*r)*G + H
707 P.ECMULGEN(bnHash, pointH);
709 if (P.IsInfinity()) {
710 throw key_error("CMalleablePubKey::GetVariant() : P is infinity");
713 std::vector<unsigned char> vchResult;
714 P.getBytes(vchResult);
716 vchPubKeyVariant = CPubKey(vchResult);
719 std::string CMalleablePubKey::ToString() const
721 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
723 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
725 return EncodeBase58Check(vch);
728 bool CMalleablePubKey::setvch(const std::vector<unsigned char> &vchPubKeyPair)
730 CDataStream ssKey(vchPubKeyPair, SER_NETWORK, PROTOCOL_VERSION);
736 std::vector<unsigned char> CMalleablePubKey::Raw() const
738 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
740 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
745 bool CMalleablePubKey::SetString(const std::string& strMalleablePubKey)
747 std::vector<unsigned char> vchTemp;
748 if (!DecodeBase58Check(strMalleablePubKey, vchTemp)) {
749 throw key_error("CMalleablePubKey::SetString() : Provided key data seems corrupted.");
752 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
758 bool CMalleablePubKey::operator==(const CMalleablePubKey &b)
760 return pubKeyL == b.pubKeyL && pubKeyH == b.pubKeyH;
766 void CMalleableKey::Reset()
772 void CMalleableKey::MakeNewKeys()
780 vchSecretL = keyL.GetSecret();
781 vchSecretH = keyH.GetSecret();
784 CMalleableKey::CMalleableKey()
789 CMalleableKey::CMalleableKey(const CMalleableKey &b)
791 SetSecrets(b.vchSecretL, b.vchSecretH);
794 CMalleableKey::CMalleableKey(const CSecret &L, const CSecret &H)
799 CMalleableKey::~CMalleableKey()
803 bool CMalleableKey::IsNull() const
805 return vchSecretL.size() != 32 || vchSecretH.size() != 32;
808 bool CMalleableKey::SetSecrets(const CSecret &pvchSecretL, const CSecret &pvchSecretH)
812 CKey keyL(pvchSecretL);
813 CKey keyH(pvchSecretH);
815 if (!keyL.IsValid() || !keyH.IsValid())
818 vchSecretL = pvchSecretL;
819 vchSecretH = pvchSecretH;
824 CMalleablePubKey CMalleableKey::GetMalleablePubKey() const
826 CKey L(vchSecretL), H(vchSecretH);
827 return CMalleablePubKey(L.GetPubKey().Raw(), H.GetPubKey().Raw());
831 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
834 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
838 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
842 if (!vchPubKeyVariant.IsValid()) {
843 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
848 if (!point_R.setPubKey(R)) {
849 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
854 std::vector<unsigned char> vchPubKeyH = H.GetPubKey().Raw();
857 if (!point_H.setPubKey(vchPubKeyH)) {
858 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
863 if (!point_P.setPubKey(vchPubKeyVariant)) {
864 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
868 // Infinity points are senseless
869 if (point_P.IsInfinity()) {
870 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
875 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
879 std::vector<unsigned char> vchRl;
880 if (!point_R.getBytes(vchRl)) {
881 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
885 // Calculate Hash(R*l)
887 bnHash.setuint160(Hash160(vchRl));
890 // Calculate Ps = Hash(L*r)*G + H
891 point_Ps.ECMULGEN(bnHash, point_H);
893 // Infinity points are senseless
894 if (point_Ps.IsInfinity()) {
895 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
900 if (point_Ps != point_P) {
907 // Check ownership and restore private key
908 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant, CKey &privKeyVariant) const
911 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
915 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
919 if (!vchPubKeyVariant.IsValid()) {
920 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
925 if (!point_R.setPubKey(R)) {
926 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
931 std::vector<unsigned char> vchPubKeyH = H.GetPubKey().Raw();
934 if (!point_H.setPubKey(vchPubKeyH)) {
935 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
940 if (!point_P.setPubKey(vchPubKeyVariant)) {
941 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
945 // Infinity points are senseless
946 if (point_P.IsInfinity()) {
947 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
952 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
956 std::vector<unsigned char> vchRl;
957 if (!point_R.getBytes(vchRl)) {
958 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
962 // Calculate Hash(R*l)
964 bnHash.setuint160(Hash160(vchRl));
967 // Calculate Ps = Hash(L*r)*G + H
968 point_Ps.ECMULGEN(bnHash, point_H);
970 // Infinity points are senseless
971 if (point_Ps.IsInfinity()) {
972 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
977 if (point_Ps != point_P) {
981 // OpenSSL BIGNUM representation of the second private key from (l, h) pair
983 bnh.setBytes(std::vector<unsigned char>(vchSecretH.begin(), vchSecretH.end()));
985 // Calculate p = Hash(R*l) + h
986 CBigNum bnp = bnHash + bnh;
988 std::vector<unsigned char> vchp = bnp.getBytes();
989 privKeyVariant.SetSecret(CSecret(vchp.begin(), vchp.end()));
994 std::string CMalleableKey::ToString() const
996 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
998 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1000 return EncodeBase58Check(vch);
1003 std::vector<unsigned char> CMalleableKey::Raw() const
1005 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1007 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1012 bool CMalleableKey::SetString(const std::string& strMutableKey)
1014 std::vector<unsigned char> vchTemp;
1015 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1016 throw key_error("CMalleableKey::SetString() : Provided key data seems corrupted.");
1019 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1025 // CMalleableKeyView
1027 CMalleableKeyView::CMalleableKeyView(const std::string &strMalleableKey)
1029 SetString(strMalleableKey);
1032 CMalleableKeyView::CMalleableKeyView(const CMalleableKey &b)
1034 if (b.vchSecretL.size() != 32)
1035 throw key_error("CMalleableKeyView::CMalleableKeyView() : L size must be 32 bytes");
1037 if (b.vchSecretH.size() != 32)
1038 throw key_error("CMalleableKeyView::CMalleableKeyView() : H size must be 32 bytes");
1040 vchSecretL = b.vchSecretL;
1042 CKey H(b.vchSecretH);
1043 vchPubKeyH = H.GetPubKey().Raw();
1046 CMalleableKeyView::CMalleableKeyView(const CMalleableKeyView &b)
1048 vchSecretL = b.vchSecretL;
1049 vchPubKeyH = b.vchPubKeyH;
1052 CMalleableKeyView& CMalleableKeyView::operator=(const CMalleableKey &b)
1054 vchSecretL = b.vchSecretL;
1056 CKey H(b.vchSecretH);
1057 vchPubKeyH = H.GetPubKey().Raw();
1062 CMalleableKeyView::~CMalleableKeyView()
1066 CMalleablePubKey CMalleableKeyView::GetMalleablePubKey() const
1068 CKey keyL(vchSecretL);
1069 return CMalleablePubKey(keyL.GetPubKey(), vchPubKeyH);
1073 bool CMalleableKeyView::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
1076 throw key_error("CMalleableKeyView::CheckKeyVariant() : Attempting to run on invalid view object.");
1080 printf("CMalleableKeyView::CheckKeyVariant() : R is invalid");
1084 if (!vchPubKeyVariant.IsValid()) {
1085 printf("CMalleableKeyView::CheckKeyVariant() : public key variant is invalid");
1090 if (!point_R.setPubKey(R)) {
1091 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode R value");
1096 if (!point_H.setPubKey(vchPubKeyH)) {
1097 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode H value");
1102 if (!point_P.setPubKey(vchPubKeyVariant)) {
1103 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode P value");
1107 // Infinity points are senseless
1108 if (point_P.IsInfinity()) {
1109 printf("CMalleableKeyView::CheckKeyVariant() : P is infinity");
1114 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
1118 std::vector<unsigned char> vchRl;
1119 if (!point_R.getBytes(vchRl)) {
1120 printf("CMalleableKeyView::CheckKeyVariant() : Unable to convert Rl value");
1124 // Calculate Hash(R*l)
1126 bnHash.setuint160(Hash160(vchRl));
1129 // Calculate Ps = Hash(L*r)*G + H
1130 point_Ps.ECMULGEN(bnHash, point_H);
1132 // Infinity points are senseless
1133 if (point_Ps.IsInfinity()) {
1134 printf("CMalleableKeyView::CheckKeyVariant() : Ps is infinity");
1139 if (point_Ps != point_P) {
1146 std::string CMalleableKeyView::ToString() const
1148 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1150 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1152 return EncodeBase58Check(vch);
1155 bool CMalleableKeyView::SetString(const std::string& strMutableKey)
1157 std::vector<unsigned char> vchTemp;
1158 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1159 throw key_error("CMalleableKeyView::SetString() : Provided key data seems corrupted.");
1162 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1168 std::vector<unsigned char> CMalleableKeyView::Raw() const
1170 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1172 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1178 bool CMalleableKeyView::IsValid() const
1180 return vchSecretL.size() == 32 && GetMalleablePubKey().IsValid();
1183 //// Asymmetric encryption
1185 void CPubKey::EncryptData(const std::vector<unsigned char>& data, std::vector<unsigned char>& encrypted)
1188 key.SetPubKey(*this);
1190 key.EncryptData(data, encrypted);
1193 void CKey::EncryptData(const std::vector<unsigned char>& data, std::vector<unsigned char>& encrypted)
1196 char error[1024] = "Unknown error";
1197 cryptogram_t *cryptogram;
1199 ctx = create_context(pkey);
1200 if (!EC_KEY_get0_public_key(ctx->user_key))
1201 throw key_error("Given EC key is not public key");
1203 cryptogram = ecies_encrypt(ctx, (unsigned char*)&data[0], data.size(), error);
1204 if (cryptogram == NULL) {
1207 throw key_error(std::string("Error in encryption: %s") + error);
1210 encrypted.resize(cryptogram_data_sum_length(cryptogram));
1211 unsigned char *key_data = cryptogram_key_data(cryptogram);
1212 memcpy(&encrypted[0], key_data, encrypted.size());
1213 cryptogram_free(cryptogram);
1217 void CKey::DecryptData(const std::vector<unsigned char>& encrypted, std::vector<unsigned char>& data)
1220 char error[1024] = "Unknown error";
1221 cryptogram_t *cryptogram;
1223 unsigned char *decrypted;
1225 ctx = create_context(pkey);
1226 if (!EC_KEY_get0_private_key(ctx->user_key))
1227 throw key_error("Given EC key is not private key");
1229 size_t key_length = ctx->stored_key_length;
1230 size_t mac_length = EVP_MD_size(ctx->md);
1231 cryptogram = cryptogram_alloc(key_length, mac_length, encrypted.size() - key_length - mac_length);
1233 memcpy(cryptogram_key_data(cryptogram), &encrypted[0], encrypted.size());
1235 decrypted = ecies_decrypt(ctx, cryptogram, &length, error);
1236 cryptogram_free(cryptogram);
1239 if (decrypted == NULL) {
1240 throw key_error(std::string("Error in decryption: %s") + error);
1243 data.resize(length);
1244 memcpy(&data[0], decrypted, length);