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 unsigned int 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 std::vector<unsigned char> CMalleablePubKey::Raw() const
730 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
732 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
737 bool CMalleablePubKey::SetString(const std::string& strMalleablePubKey)
739 std::vector<unsigned char> vchTemp;
740 if (!DecodeBase58Check(strMalleablePubKey, vchTemp)) {
741 throw key_error("CMalleablePubKey::SetString() : Provided key data seems corrupted.");
744 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
750 bool CMalleablePubKey::operator==(const CMalleablePubKey &b)
752 return pubKeyL == b.pubKeyL && pubKeyH == b.pubKeyH;
758 void CMalleableKey::Reset()
764 void CMalleableKey::MakeNewKeys()
772 vchSecretL = keyL.GetSecret();
773 vchSecretH = keyH.GetSecret();
776 CMalleableKey::CMalleableKey()
781 CMalleableKey::CMalleableKey(const CMalleableKey &b)
783 SetSecrets(b.vchSecretL, b.vchSecretH);
786 CMalleableKey::CMalleableKey(const CSecret &L, const CSecret &H)
791 CMalleableKey::~CMalleableKey()
795 bool CMalleableKey::IsNull() const
797 return vchSecretL.size() != 32 || vchSecretH.size() != 32;
800 bool CMalleableKey::SetSecrets(const CSecret &pvchSecretL, const CSecret &pvchSecretH)
804 CKey keyL(pvchSecretL);
805 CKey keyH(pvchSecretH);
807 if (!keyL.IsValid() || !keyL.IsValid())
810 vchSecretL = pvchSecretL;
811 vchSecretH = pvchSecretH;
816 CMalleablePubKey CMalleableKey::GetMalleablePubKey() const
819 L.SetSecret(vchSecretL, true);
820 H.SetSecret(vchSecretH, true);
822 std::vector<unsigned char> vchPubKeyL = L.GetPubKey().Raw();
823 std::vector<unsigned char> vchPubKeyH = H.GetPubKey().Raw();
825 return CMalleablePubKey(vchPubKeyL, vchPubKeyH);
829 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
832 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
836 throw key_error("CMalleableKey::CheckKeyVariant() : R is invalid");
839 if (!vchPubKeyVariant.IsValid()) {
840 throw key_error("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
844 if (!point_R.setPubKey(R)) {
845 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
849 H.SetSecret(vchSecretH, true);
850 std::vector<unsigned char> vchPubKeyH = H.GetPubKey().Raw();
853 if (!point_H.setPubKey(vchPubKeyH)) {
854 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
858 if (!point_P.setPubKey(vchPubKeyVariant)) {
859 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
862 // Infinity points are senseless
863 if (point_P.IsInfinity()) {
864 throw key_error("CMalleableKey::CheckKeyVariant() : P is infinity");
868 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
872 std::vector<unsigned char> vchRl;
873 if (!point_R.getBytes(vchRl)) {
874 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
877 // Calculate Hash(R*l)
879 bnHash.setuint160(Hash160(vchRl));
882 // Calculate Ps = Hash(L*r)*G + H
883 point_Ps.ECMULGEN(bnHash, point_H);
885 // Infinity points are senseless
886 if (point_Ps.IsInfinity()) {
887 throw key_error("CMalleableKey::CheckKeyVariant() : Ps is infinity");
891 if (point_Ps != point_P) {
898 // Check ownership and restore private key
899 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant, CKey &privKeyVariant) const
902 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
906 throw key_error("CMalleableKey::CheckKeyVariant() : R is invalid");
909 if (!vchPubKeyVariant.IsValid()) {
910 throw key_error("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
914 if (!point_R.setPubKey(R)) {
915 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
919 H.SetSecret(vchSecretH, true);
920 std::vector<unsigned char> vchPubKeyH = H.GetPubKey().Raw();
923 if (!point_H.setPubKey(vchPubKeyH)) {
924 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
928 if (!point_P.setPubKey(vchPubKeyVariant)) {
929 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
932 // Infinity points are senseless
933 if (point_P.IsInfinity()) {
934 throw key_error("CMalleableKey::CheckKeyVariant() : P is infinity");
938 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
942 std::vector<unsigned char> vchRl;
943 if (!point_R.getBytes(vchRl)) {
944 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
947 // Calculate Hash(R*l)
949 bnHash.setuint160(Hash160(vchRl));
952 // Calculate Ps = Hash(L*r)*G + H
953 point_Ps.ECMULGEN(bnHash, point_H);
955 // Infinity points are senseless
956 if (point_Ps.IsInfinity()) {
957 throw key_error("CMalleableKey::CheckKeyVariant() : Ps is infinity");
961 if (point_Ps != point_P) {
965 // OpenSSL BIGNUM representation of the second private key from (l, h) pair
967 bnh.setBytes(std::vector<unsigned char>(vchSecretH.begin(), vchSecretH.end()));
969 // Calculate p = Hash(R*l) + h
970 CBigNum bnp = bnHash + bnh;
972 std::vector<unsigned char> vchp = bnp.getBytes();
973 privKeyVariant.SetSecret(CSecret(vchp.begin(), vchp.end()), true);
978 std::string CMalleableKey::ToString() const
980 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
982 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
984 return EncodeBase58Check(vch);
987 std::vector<unsigned char> CMalleableKey::Raw() const
989 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
991 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
996 bool CMalleableKey::SetString(const std::string& strMutableKey)
998 std::vector<unsigned char> vchTemp;
999 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1000 throw key_error("CMalleableKey::SetString() : Provided key data seems corrupted.");
1003 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1009 // CMalleableKeyView
1011 CMalleableKeyView::CMalleableKeyView(const std::string &strMalleableKey)
1013 SetString(strMalleableKey);
1016 CMalleableKeyView::CMalleableKeyView(const CMalleableKey &b)
1018 if (b.vchSecretL.size() != 32)
1019 throw key_error("CMalleableKeyView::CMalleableKeyView() : L size must be 32 bytes");
1021 if (b.vchSecretH.size() != 32)
1022 throw key_error("CMalleableKeyView::CMalleableKeyView() : L size must be 32 bytes");
1024 vchSecretL = b.vchSecretL;
1027 H.SetSecret(b.vchSecretH, true);
1029 vchPubKeyH = H.GetPubKey().Raw();
1032 CMalleableKeyView::CMalleableKeyView(const CMalleableKeyView &b)
1034 vchSecretL = b.vchSecretL;
1035 vchPubKeyH = b.vchPubKeyH;
1038 CMalleableKeyView& CMalleableKeyView::operator=(const CMalleableKey &b)
1040 vchSecretL = b.vchSecretL;
1043 H.SetSecret(b.vchSecretH, true);
1044 vchPubKeyH = H.GetPubKey().Raw();
1049 CMalleableKeyView::~CMalleableKeyView()
1053 CMalleablePubKey CMalleableKeyView::GetMalleablePubKey() const
1056 keyL.SetSecret(vchSecretL, true);
1057 return CMalleablePubKey(keyL.GetPubKey(), vchPubKeyH);
1061 bool CMalleableKeyView::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
1064 throw key_error("CMalleableKeyView::CheckKeyVariant() : R is invalid");
1067 if (!vchPubKeyVariant.IsValid()) {
1068 throw key_error("CMalleableKeyView::CheckKeyVariant() : public key variant is invalid");
1072 if (!point_R.setPubKey(R)) {
1073 throw key_error("CMalleableKeyView::CheckKeyVariant() : Unable to decode R value");
1077 if (!point_H.setPubKey(vchPubKeyH)) {
1078 throw key_error("CMalleableKeyView::CheckKeyVariant() : Unable to decode H value");
1082 if (!point_P.setPubKey(vchPubKeyVariant)) {
1083 throw key_error("CMalleableKeyView::CheckKeyVariant() : Unable to decode P value");
1086 // Infinity points are senseless
1087 if (point_P.IsInfinity()) {
1088 throw key_error("CMalleableKeyView::CheckKeyVariant() : P is infinity");
1092 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
1096 std::vector<unsigned char> vchRl;
1097 if (!point_R.getBytes(vchRl)) {
1098 throw key_error("CMalleableKeyView::CheckKeyVariant() : Unable to convert Rl value");
1101 // Calculate Hash(R*l)
1103 bnHash.setuint160(Hash160(vchRl));
1106 // Calculate Ps = Hash(L*r)*G + H
1107 point_Ps.ECMULGEN(bnHash, point_H);
1109 // Infinity points are senseless
1110 if (point_Ps.IsInfinity()) {
1111 throw key_error("CMalleableKeyView::CheckKeyVariant() : Ps is infinity");
1115 if (point_Ps != point_P) {
1122 std::string CMalleableKeyView::ToString() const
1124 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1126 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1128 return EncodeBase58Check(vch);
1131 bool CMalleableKeyView::SetString(const std::string& strMutableKey)
1133 std::vector<unsigned char> vchTemp;
1134 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1135 throw key_error("CMalleableKeyView::SetString() : Provided key data seems corrupted.");
1138 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1144 std::vector<unsigned char> CMalleableKeyView::Raw() const
1146 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1148 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1154 bool CMalleableKeyView::IsValid() const
1156 return vchSecretL.size() == 32 && GetMalleablePubKey().IsValid();
1159 //// Asymmetric encryption
1161 void CPubKey::EncryptData(const std::vector<unsigned char>& data, std::vector<unsigned char>& encrypted)
1164 key.SetPubKey(*this);
1166 key.EncryptData(data, encrypted);
1169 void CKey::EncryptData(const std::vector<unsigned char>& data, std::vector<unsigned char>& encrypted)
1172 char error[1024] = "Unknown error";
1173 cryptogram_t *cryptogram;
1175 ctx = create_context(pkey);
1176 if (!EC_KEY_get0_public_key(ctx->user_key))
1177 throw key_error("Given EC key is not public key");
1179 cryptogram = ecies_encrypt(ctx, (unsigned char*)&data[0], data.size(), error);
1180 if (cryptogram == NULL) {
1183 throw key_error(std::string("Error in encryption: %s") + error);
1186 encrypted.resize(cryptogram_data_sum_length(cryptogram));
1187 unsigned char *key_data = cryptogram_key_data(cryptogram);
1188 memcpy(&encrypted[0], key_data, encrypted.size());
1189 cryptogram_free(cryptogram);
1193 void CKey::DecryptData(const std::vector<unsigned char>& encrypted, std::vector<unsigned char>& data)
1196 char error[1024] = "Unknown error";
1197 cryptogram_t *cryptogram;
1199 unsigned char *decrypted;
1201 ctx = create_context(pkey);
1202 if (!EC_KEY_get0_private_key(ctx->user_key))
1203 throw key_error("Given EC key is not private key");
1205 size_t key_length = ctx->stored_key_length;
1206 size_t mac_length = EVP_MD_size(ctx->md);
1207 cryptogram = cryptogram_alloc(key_length, mac_length, encrypted.size() - key_length - mac_length);
1209 memcpy(cryptogram_key_data(cryptogram), &encrypted[0], encrypted.size());
1211 decrypted = ecies_decrypt(ctx, cryptogram, &length, error);
1212 cryptogram_free(cryptogram);
1215 if (decrypted == NULL) {
1216 throw key_error(std::string("Error in decryption: %s") + error);
1219 data.resize(length);
1220 memcpy(&data[0], decrypted, length);