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::operator=(const CKey& b)
203 if (!EC_KEY_copy(pkey, b.pkey))
204 throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
206 fCompressedPubKey = b.fCompressedPubKey;
215 bool CKey::IsNull() const
220 bool CKey::IsCompressed() const
222 return fCompressedPubKey;
225 bool CKey::CheckSignatureElement(const unsigned char *vch, int len, bool half) {
226 return CompareBigEndian(vch, len, vchZero, 0) > 0 &&
227 CompareBigEndian(vch, len, half ? vchMaxModHalfOrder : vchMaxModOrder, 32) <= 0;
230 bool CKey::ReserealizeSignature(std::vector<unsigned char>& vchSig)
235 unsigned char *pos = &vchSig[0];
236 ECDSA_SIG *sig = d2i_ECDSA_SIG(NULL, (const unsigned char **)&pos, vchSig.size());
241 int nSize = i2d_ECDSA_SIG(sig, NULL);
243 vchSig.resize(nSize); // grow or shrink as needed
246 i2d_ECDSA_SIG(sig, &pos);
256 void CKey::MakeNewKey(bool fCompressed)
258 if (!EC_KEY_generate_key(pkey))
259 throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
261 SetCompressedPubKey();
265 bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
267 const unsigned char* pbegin = &vchPrivKey[0];
268 if (d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
270 // In testing, d2i_ECPrivateKey can return true
271 // but fill in pkey with a key that fails
272 // EC_KEY_check_key, so:
273 if (EC_KEY_check_key(pkey))
279 // If vchPrivKey data is bad d2i_ECPrivateKey() can
280 // leave pkey in a state where calling EC_KEY_free()
281 // crashes. To avoid that, set pkey to NULL and
282 // leak the memory (a leak is better than a crash)
288 bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
291 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
293 throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
294 if (vchSecret.size() != 32)
295 throw key_error("CKey::SetSecret() : secret must be 32 bytes");
296 BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
298 throw key_error("CKey::SetSecret() : BN_bin2bn failed");
299 if (!EC_KEY_regenerate_key(pkey,bn))
302 throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
306 if (fCompressed || fCompressedPubKey)
307 SetCompressedPubKey();
311 CSecret CKey::GetSecret(bool &fCompressed) const
315 const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
316 int nBytes = BN_num_bytes(bn);
318 throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
319 int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
321 throw key_error("CKey::GetSecret(): BN_bn2bin failed");
322 fCompressed = fCompressedPubKey;
326 CPrivKey CKey::GetPrivKey() const
328 int nSize = i2d_ECPrivateKey(pkey, NULL);
330 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
331 CPrivKey vchPrivKey(nSize, 0);
332 unsigned char* pbegin = &vchPrivKey[0];
333 if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
334 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
338 bool CKey::SetPubKey(const CPubKey& vchPubKey)
340 const unsigned char* pbegin = &vchPubKey.vchPubKey[0];
341 if (o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.vchPubKey.size()))
344 if (vchPubKey.vchPubKey.size() == 33)
345 SetCompressedPubKey();
353 CPubKey CKey::GetPubKey() const
355 int nSize = i2o_ECPublicKey(pkey, NULL);
357 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
358 std::vector<unsigned char> vchPubKey(nSize, 0);
359 unsigned char* pbegin = &vchPubKey[0];
360 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
361 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
362 return CPubKey(vchPubKey);
365 bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
368 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
371 const EC_GROUP *group = EC_KEY_get0_group(pkey);
372 CBigNum order, halforder;
373 EC_GROUP_get_order(group, &order, NULL);
374 BN_rshift1(&halforder, &order);
375 // enforce low S values, by negating the value (modulo the order) if above order/2.
376 if (BN_cmp(sig->s, &halforder) > 0) {
377 BN_sub(sig->s, &order, sig->s);
379 unsigned int nSize = ECDSA_size(pkey);
380 vchSig.resize(nSize); // Make sure it is big enough
381 unsigned char *pos = &vchSig[0];
382 nSize = i2d_ECDSA_SIG(sig, &pos);
384 vchSig.resize(nSize); // Shrink to fit actual size
385 // Testing our new signature
386 if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) {
393 // create a compact signature (65 bytes), which allows reconstructing the used public key
394 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
395 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
396 // 0x1D = second key with even y, 0x1E = second key with odd y
397 bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
400 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
403 const EC_GROUP *group = EC_KEY_get0_group(pkey);
404 CBigNum order, halforder;
405 EC_GROUP_get_order(group, &order, NULL);
406 BN_rshift1(&halforder, &order);
407 // enforce low S values, by negating the value (modulo the order) if above order/2.
408 if (BN_cmp(sig->s, &halforder) > 0) {
409 BN_sub(sig->s, &order, sig->s);
413 int nBitsR = BN_num_bits(sig->r);
414 int nBitsS = BN_num_bits(sig->s);
415 if (nBitsR <= 256 && nBitsS <= 256)
418 for (int8_t i=0; i<4; i++)
422 if (fCompressedPubKey)
423 keyRec.SetCompressedPubKey();
424 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
425 if (keyRec.GetPubKey() == this->GetPubKey())
435 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
438 vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
439 BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
440 BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
447 // reconstruct public key from a compact signature
448 // This is only slightly more CPU intensive than just verifying it.
449 // If this function succeeds, the recovered public key is guaranteed to be valid
450 // (the signature is a valid signature of the given data for that key)
451 bool CKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
453 if (vchSig.size() != 65)
458 ECDSA_SIG *sig = ECDSA_SIG_new();
459 BN_bin2bn(&vchSig[1],32,sig->r);
460 BN_bin2bn(&vchSig[33],32,sig->s);
463 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
466 SetCompressedPubKey();
469 if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)
479 bool CKey::Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
484 // New versions of OpenSSL will reject non-canonical DER signatures. de/re-serialize first.
485 unsigned char *norm_der = NULL;
486 ECDSA_SIG *norm_sig = ECDSA_SIG_new();
487 const unsigned char* sigptr = &vchSig[0];
489 if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL)
491 /* As of OpenSSL 1.0.0p d2i_ECDSA_SIG frees and nulls the pointer on
492 * error. But OpenSSL's own use of this function redundantly frees the
493 * result. As ECDSA_SIG_free(NULL) is a no-op, and in the absence of a
494 * clear contract for the function behaving the same way is more
497 ECDSA_SIG_free(norm_sig);
500 int derlen = i2d_ECDSA_SIG(norm_sig, &norm_der);
501 ECDSA_SIG_free(norm_sig);
505 // -1 = error, 0 = bad sig, 1 = good
506 bool ret = ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
507 OPENSSL_free(norm_der);
511 bool CKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
514 if (!key.SetCompactSignature(hash, vchSig))
516 if (GetPubKey() != key.GetPubKey())
527 if (!EC_KEY_check_key(pkey))
531 CSecret secret = GetSecret(fCompr);
533 key2.SetSecret(secret, fCompr);
534 return GetPubKey() == key2.GetPubKey();
544 group = EC_GROUP_new_by_curve_name(NID_secp256k1);
546 err = "EC_KEY_new_by_curve_name failed.";
550 point = EC_POINT_new(group);
552 err = "EC_POINT_new failed.";
558 err = "BN_CTX_new failed.";
565 if (group) EC_GROUP_free(group);
566 if (point) EC_POINT_free(point);
567 throw std::runtime_error(std::string("CPoint::CPoint() : - ") + err);
570 bool CPoint::operator!=(const CPoint &a)
572 if (EC_POINT_cmp(group, point, a.point, ctx) != 0)
578 if (point) EC_POINT_free(point);
579 if (group) EC_GROUP_free(group);
580 if (ctx) BN_CTX_free(ctx);
583 // Initialize from octets stream
584 bool CPoint::setBytes(const std::vector<unsigned char> &vchBytes)
586 if (!EC_POINT_oct2point(group, point, &vchBytes[0], vchBytes.size(), ctx)) {
592 // Initialize from octets stream
593 bool CPoint::setPubKey(const CPubKey &vchPubKey)
595 return setBytes(vchPubKey.Raw());
598 // Serialize to octets stream
599 bool CPoint::getBytes(std::vector<unsigned char> &vchBytes)
601 unsigned int nSize = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, ctx);
602 vchBytes.resize(nSize);
603 if (!(nSize == EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, &vchBytes[0], nSize, ctx))) {
609 // ECC multiplication by specified multiplier
610 bool CPoint::ECMUL(const CBigNum &bnMultiplier)
612 if (!EC_POINT_mul(group, point, NULL, point, &bnMultiplier, NULL)) {
613 printf("CPoint::ECMUL() : EC_POINT_mul failed");
621 bool CPoint::ECMULGEN(const CBigNum &bnMultiplier, const CPoint &qPoint)
623 if (!EC_POINT_mul(group, point, &bnMultiplier, qPoint.point, BN_value_one(), NULL)) {
624 printf("CPoint::ECMULGEN() : EC_POINT_mul failed.");
633 void CMalleablePubKey::GetVariant(CPubKey &R, CPubKey &vchPubKeyVariant)
635 EC_KEY *eckey = NULL;
636 eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
638 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_new_by_curve_name failed");
641 // Use standard key generation function to get r and R values.
643 // r will be presented by private key;
644 // R is ECDSA public key which calculated as G*r
645 if (!EC_KEY_generate_key(eckey)) {
646 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_generate_key failed");
649 EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
651 int nSize = i2o_ECPublicKey(eckey, NULL);
653 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey failed");
656 std::vector<unsigned char> vchPubKey(nSize, 0);
657 unsigned char* pbegin_R = &vchPubKey[0];
659 if (i2o_ECPublicKey(eckey, &pbegin_R) != nSize) {
660 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey returned unexpected size");
664 R = CPubKey(vchPubKey);
666 // OpenSSL BIGNUM representation of r value
668 bnr = *(CBigNum*) EC_KEY_get0_private_key(eckey);
672 if (!point.setPubKey(pubKeyL)) {
673 throw key_error("CMalleablePubKey::GetVariant() : Unable to decode L value");
679 std::vector<unsigned char> vchLr;
680 if (!point.getBytes(vchLr)) {
681 throw key_error("CMalleablePubKey::GetVariant() : Unable to convert Lr value");
684 // Calculate Hash(L*r) and then get a BIGNUM representation of hash value.
686 bnHash.setuint160(Hash160(vchLr));
689 pointH.setPubKey(pubKeyH);
692 // Calculate P = Hash(L*r)*G + H
693 P.ECMULGEN(bnHash, pointH);
695 if (P.IsInfinity()) {
696 throw key_error("CMalleablePubKey::GetVariant() : P is infinity");
699 std::vector<unsigned char> vchResult;
700 P.getBytes(vchResult);
702 vchPubKeyVariant = CPubKey(vchResult);
705 std::string CMalleablePubKey::ToString() const
707 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
709 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
711 return EncodeBase58Check(vch);
714 std::vector<unsigned char> CMalleablePubKey::Raw() const
716 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
718 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
723 bool CMalleablePubKey::SetString(const std::string& strMalleablePubKey)
725 std::vector<unsigned char> vchTemp;
726 if (!DecodeBase58Check(strMalleablePubKey, vchTemp)) {
727 throw key_error("CMalleablePubKey::SetString() : Provided key data seems corrupted.");
730 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
736 bool CMalleablePubKey::operator==(const CMalleablePubKey &b)
738 return (nVersion == b.nVersion &&
739 pubKeyL == b.pubKeyL &&
740 pubKeyH == b.pubKeyH);
746 void CMalleableKey::Reset()
754 void CMalleableKey::MakeNewKeys()
757 bool fCompressed = true;
762 vchSecretL = L.GetSecret(fCompressed);
763 vchSecretH = H.GetSecret(fCompressed);
765 nVersion = CURRENT_VERSION;
768 CMalleableKey::CMalleableKey()
773 CMalleableKey::CMalleableKey(const CMalleableKey &b)
775 SetSecrets(b.vchSecretL, b.vchSecretH);
778 CMalleableKey::CMalleableKey(const CSecret &L, const CSecret &H)
784 CMalleableKey& CMalleableKey::operator=(const CMalleableKey &b)
786 SetSecrets(b.vchSecretL, b.vchSecretH);
792 CMalleableKey::~CMalleableKey()
796 bool CMalleableKey::IsNull() const
798 return nVersion != CURRENT_VERSION;
801 bool CMalleableKey::SetSecrets(const CSecret &pvchSecretL, const CSecret &pvchSecretH)
806 if (pvchSecretL.size() != 32 || pvchSecretH.size() != 32 || !L.SetSecret(pvchSecretL, true) || !H.SetSecret(pvchSecretH, true))
812 vchSecretL = pvchSecretL;
813 vchSecretH = pvchSecretH;
814 nVersion = CURRENT_VERSION;
819 void CMalleableKey::GetSecrets(CSecret &pvchSecretL, CSecret &pvchSecretH) const
821 pvchSecretL = vchSecretL;
822 pvchSecretH = vchSecretH;
825 CMalleablePubKey CMalleableKey::GetMalleablePubKey() const
828 L.SetSecret(vchSecretL, true);
829 H.SetSecret(vchSecretH, true);
831 std::vector<unsigned char> vchPubKeyL = L.GetPubKey().Raw();
832 std::vector<unsigned char> vchPubKeyH = H.GetPubKey().Raw();
834 return CMalleablePubKey(vchPubKeyL, vchPubKeyH);
838 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
841 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
845 throw key_error("CMalleableKey::CheckKeyVariant() : R is invalid");
848 if (!vchPubKeyVariant.IsValid()) {
849 throw key_error("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
853 if (!point_R.setPubKey(R)) {
854 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
858 H.SetSecret(vchSecretH, true);
859 std::vector<unsigned char> vchPubKeyH = H.GetPubKey().Raw();
862 if (!point_H.setPubKey(vchPubKeyH)) {
863 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
867 if (!point_P.setPubKey(vchPubKeyVariant)) {
868 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
871 // Infinity points are senseless
872 if (point_P.IsInfinity()) {
873 throw key_error("CMalleableKey::CheckKeyVariant() : P is infinity");
877 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
881 std::vector<unsigned char> vchRl;
882 if (!point_R.getBytes(vchRl)) {
883 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
886 // Calculate Hash(R*l)
888 bnHash.setuint160(Hash160(vchRl));
891 // Calculate Ps = Hash(L*r)*G + H
892 point_Ps.ECMULGEN(bnHash, point_H);
894 // Infinity points are senseless
895 if (point_Ps.IsInfinity()) {
896 throw key_error("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 throw key_error("CMalleableKey::CheckKeyVariant() : R is invalid");
918 if (!vchPubKeyVariant.IsValid()) {
919 throw key_error("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
923 if (!point_R.setPubKey(R)) {
924 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
928 H.SetSecret(vchSecretH, true);
929 std::vector<unsigned char> vchPubKeyH = H.GetPubKey().Raw();
932 if (!point_H.setPubKey(vchPubKeyH)) {
933 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
937 if (!point_P.setPubKey(vchPubKeyVariant)) {
938 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
941 // Infinity points are senseless
942 if (point_P.IsInfinity()) {
943 throw key_error("CMalleableKey::CheckKeyVariant() : P is infinity");
947 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
951 std::vector<unsigned char> vchRl;
952 if (!point_R.getBytes(vchRl)) {
953 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
956 // Calculate Hash(R*l)
958 bnHash.setuint160(Hash160(vchRl));
961 // Calculate Ps = Hash(L*r)*G + H
962 point_Ps.ECMULGEN(bnHash, point_H);
964 // Infinity points are senseless
965 if (point_Ps.IsInfinity()) {
966 throw key_error("CMalleableKey::CheckKeyVariant() : Ps is infinity");
970 if (point_Ps != point_P) {
974 // OpenSSL BIGNUM representation of the second private key from (l, h) pair
976 bnh.setBytes(std::vector<unsigned char>(vchSecretH.begin(), vchSecretH.end()));
978 // Calculate p = Hash(R*l) + h
979 CBigNum bnp = bnHash + bnh;
981 std::vector<unsigned char> vchp = bnp.getBytes();
982 privKeyVariant.SetSecret(CSecret(vchp.begin(), vchp.end()), true);
987 std::string CMalleableKey::ToString() const
989 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
991 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
993 return EncodeBase58Check(vch);
996 std::vector<unsigned char> CMalleableKey::Raw() const
998 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1000 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1005 bool CMalleableKey::SetString(const std::string& strMutableKey)
1007 std::vector<unsigned char> vchTemp;
1008 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1009 throw key_error("CMalleableKey::SetString() : Provided key data seems corrupted.");
1012 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1018 // CMalleableKeyView
1020 CMalleableKeyView::CMalleableKeyView(const CMalleableKey &b)
1022 if (b.vchSecretL.size() != 32)
1023 throw key_error("CMalleableKeyView::CMalleableKeyView() : L size must be 32 bytes");
1025 if (b.vchSecretH.size() != 32)
1026 throw key_error("CMalleableKeyView::CMalleableKeyView() : L size must be 32 bytes");
1028 vchSecretL = b.vchSecretL;
1031 H.SetSecret(b.vchSecretH, true);
1033 vchPubKeyH = H.GetPubKey().Raw();
1034 nVersion = b.nVersion;
1037 CMalleableKeyView::CMalleableKeyView(const CMalleableKeyView &b)
1039 vchSecretL = b.vchSecretL;
1040 vchPubKeyH = b.vchPubKeyH;
1041 nVersion = CURRENT_VERSION;
1044 CMalleableKeyView::CMalleableKeyView(const CSecret &L, const CPubKey &pvchPubKeyH)
1047 vchPubKeyH = pvchPubKeyH.Raw();
1048 nVersion = CURRENT_VERSION;
1051 CMalleableKeyView& CMalleableKeyView::operator=(const CMalleableKey &b)
1053 vchSecretL = b.vchSecretL;
1056 H.SetSecret(b.vchSecretH, true);
1057 vchPubKeyH = H.GetPubKey().Raw();
1058 nVersion = b.nVersion;
1063 CMalleableKeyView::~CMalleableKeyView()
1067 CMalleablePubKey CMalleableKeyView::GetMalleablePubKey() const
1070 keyL.SetSecret(vchSecretL, true);
1071 return CMalleablePubKey(keyL.GetPubKey(), vchPubKeyH);
1075 bool CMalleableKeyView::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
1078 throw key_error("CMalleableKeyView::CheckKeyVariant() : R is invalid");
1081 if (!vchPubKeyVariant.IsValid()) {
1082 throw key_error("CMalleableKeyView::CheckKeyVariant() : public key variant is invalid");
1086 if (!point_R.setPubKey(R)) {
1087 throw key_error("CMalleableKeyView::CheckKeyVariant() : Unable to decode R value");
1091 if (!point_H.setPubKey(vchPubKeyH)) {
1092 throw key_error("CMalleableKeyView::CheckKeyVariant() : Unable to decode H value");
1096 if (!point_P.setPubKey(vchPubKeyVariant)) {
1097 throw key_error("CMalleableKeyView::CheckKeyVariant() : Unable to decode P value");
1100 // Infinity points are senseless
1101 if (point_P.IsInfinity()) {
1102 throw key_error("CMalleableKeyView::CheckKeyVariant() : P is infinity");
1106 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
1110 std::vector<unsigned char> vchRl;
1111 if (!point_R.getBytes(vchRl)) {
1112 throw key_error("CMalleableKeyView::CheckKeyVariant() : Unable to convert Rl value");
1115 // Calculate Hash(R*l)
1117 bnHash.setuint160(Hash160(vchRl));
1120 // Calculate Ps = Hash(L*r)*G + H
1121 point_Ps.ECMULGEN(bnHash, point_H);
1123 // Infinity points are senseless
1124 if (point_Ps.IsInfinity()) {
1125 throw key_error("CMalleableKeyView::CheckKeyVariant() : Ps is infinity");
1129 if (point_Ps != point_P) {
1136 std::string CMalleableKeyView::ToString() const
1138 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1140 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1142 return EncodeBase58Check(vch);
1145 bool CMalleableKeyView::SetString(const std::string& strMutableKey)
1147 std::vector<unsigned char> vchTemp;
1148 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1149 throw key_error("CMalleableKeyView::SetString() : Provided key data seems corrupted.");
1152 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1158 std::vector<unsigned char> CMalleableKeyView::Raw() const
1160 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1162 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1168 bool CMalleableKeyView::IsNull() const
1170 return nVersion != CURRENT_VERSION;
1173 //// Asymmetric encryption
1175 void CPubKey::EncryptData(const std::vector<unsigned char>& data, std::vector<unsigned char>& encrypted)
1178 key.SetPubKey(*this);
1180 key.EncryptData(data, encrypted);
1183 void CKey::EncryptData(const std::vector<unsigned char>& data, std::vector<unsigned char>& encrypted)
1186 char error[1024] = "Unknown error";
1187 cryptogram_t *cryptogram;
1189 ctx = create_context(pkey);
1190 if (!EC_KEY_get0_public_key(ctx->user_key))
1191 throw key_error("Given EC key is not public key");
1193 cryptogram = ecies_encrypt(ctx, (unsigned char*)&data[0], data.size(), error);
1194 if (cryptogram == NULL) {
1197 throw key_error(std::string("Error in encryption: %s") + error);
1200 encrypted.resize(cryptogram_data_sum_length(cryptogram));
1201 unsigned char *key_data = cryptogram_key_data(cryptogram);
1202 memcpy(&encrypted[0], key_data, encrypted.size());
1203 cryptogram_free(cryptogram);
1207 void CKey::DecryptData(const std::vector<unsigned char>& encrypted, std::vector<unsigned char>& data)
1210 char error[1024] = "Unknown error";
1211 cryptogram_t *cryptogram;
1213 unsigned char *decrypted;
1215 ctx = create_context(pkey);
1216 if (!EC_KEY_get0_private_key(ctx->user_key))
1217 throw key_error("Given EC key is not private key");
1219 size_t key_length = ctx->stored_key_length;
1220 size_t mac_length = EVP_MD_size(ctx->md);
1221 cryptogram = cryptogram_alloc(key_length, mac_length, encrypted.size() - key_length - mac_length);
1223 memcpy(cryptogram_key_data(cryptogram), &encrypted[0], encrypted.size());
1225 decrypted = ecies_decrypt(ctx, cryptogram, &length, error);
1226 cryptogram_free(cryptogram);
1229 if (decrypted == NULL) {
1230 throw key_error(std::string("Error in decryption: %s") + error);
1233 data.resize(length);
1234 memcpy(&data[0], decrypted, length);