aboutsummaryrefslogtreecommitdiff
path: root/src/key.cpp
diff options
context:
space:
mode:
authorPieter Wuille <pieter.wuille@gmail.com>2012-12-26 21:10:49 +0100
committerPieter Wuille <pieterw@google.com>2013-08-16 00:17:50 +0200
commita81cd96805ce6b65cca3a40ebbd3b2eb428abb7b (patch)
tree6bd44b6534c2041f0728f8b985d7c766f85c41cb /src/key.cpp
parent4323bfeafda4a5e0101710d94b518d41819a2325 (diff)
Only create signatures with even S, and verification mode to check.
To fix a minor malleability found by Sergio Lerner (reported here: https://bitcointalk.org/index.php?topic=8392.msg1245898#msg1245898) The problem is that if (R,S) is a valid ECDSA signature for a given message and public key, (R,-S) is also valid. Modulo N (the order of the secp256k1 curve), this means that both (R,S) and (R,N-S) are valid. Given that N is odd, S and N-S have a different lowest bit. We solve the problem by forcing signatures to have an even S value, excluding one of the alternatives. This commit just changes the signing code to always produce even S values, and adds a verification mode to check it. This code is not enabled anywhere yet. Existing tests in key_tests.cpp verify that the produced signatures are still valid.
Diffstat (limited to 'src/key.cpp')
-rw-r--r--src/key.cpp19
1 files changed, 18 insertions, 1 deletions
diff --git a/src/key.cpp b/src/key.cpp
index 1ab4c62ebf..2247c99475 100644
--- a/src/key.cpp
+++ b/src/key.cpp
@@ -194,9 +194,26 @@ public:
}
bool Sign(const uint256 &hash, std::vector<unsigned char>& vchSig) {
+ vchSig.clear();
+ ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
+ if (sig == NULL)
+ return false;
+ if (BN_is_odd(sig->s)) {
+ // enforce even S values, by negating the value (modulo the order) if odd
+ BN_CTX *ctx = BN_CTX_new();
+ BN_CTX_start(ctx);
+ const EC_GROUP *group = EC_KEY_get0_group(pkey);
+ BIGNUM *order = BN_CTX_get(ctx);
+ EC_GROUP_get_order(group, order, ctx);
+ BN_sub(sig->s, order, sig->s);
+ BN_CTX_end(ctx);
+ BN_CTX_free(ctx);
+ }
unsigned int nSize = ECDSA_size(pkey);
vchSig.resize(nSize); // Make sure it is big enough
- assert(ECDSA_sign(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], &nSize, pkey));
+ unsigned char *pos = &vchSig[0];
+ nSize = i2d_ECDSA_SIG(sig, &pos);
+ ECDSA_SIG_free(sig);
vchSig.resize(nSize); // Shrink to fit actual size
return true;
}