ECDSA
Header: #include <cryptopp/eccrypto.h> and #include <cryptopp/oids.h> | Namespace: CryptoPP
Since: Crypto++ 3.2 (RFC 6979 deterministic since 6.0)
ECDSA (Elliptic Curve Digital Signature Algorithm) is a digital signature scheme over elliptic curves, specified in FIPS 186-5 and SEC 1. It reaches a given security strength with much smaller keys and signatures than RSA.
Quick Example
#include <cryptopp/eccrypto.h>
#include <cryptopp/osrng.h>
#include <cryptopp/oids.h>
#include <cryptopp/filters.h>
#include <iostream>
int main() {
using namespace CryptoPP;
AutoSeededRandomPool rng;
// Generate ECDSA key pair using P-256 (secp256r1)
ECDSA<ECP, SHA256>::PrivateKey privateKey;
privateKey.Initialize(rng, ASN1::secp256r1());
ECDSA<ECP, SHA256>::PublicKey publicKey;
privateKey.MakePublicKey(publicKey);
// Create signer and verifier
ECDSA<ECP, SHA256>::Signer signer(privateKey);
ECDSA<ECP, SHA256>::Verifier verifier(publicKey);
// Sign message
std::string message = "Hello, World!";
std::string signature;
StringSource(message, true,
new SignerFilter(rng, signer,
new StringSink(signature)
)
);
// Verify signature
bool valid = false;
StringSource(signature + message, true,
new SignatureVerificationFilter(verifier,
new ArraySink((byte*)&valid, sizeof(valid))
)
);
std::cout << "Signature valid: " << (valid ? "YES" : "NO") << std::endl;
std::cout << "Signature size: " << signature.size() << " bytes" << std::endl;
return valid ? 0 : 1;
}Usage Guidelines
Do:
- Use P-256 (secp256r1) for general purpose, P-384 or P-521 where a higher strength is required
- Pair the curve with a hash of matching strength: SHA-256 with P-256, SHA-384 with P-384, SHA-512 with P-521
- Consider deterministic ECDSA (
ECDSA_RFC6979), which does not depend on the random number generator when signing - Validate keys loaded from outside sources
Avoid:
- Curves below 224 bits, such as P-192
- SHA-1 for new signatures
- Any signer whose per-signature nonce can repeat or be predicted; either exposes the private key
Supported Curves
The NIST prime curves most often used, with the sizes this library produces for them:
| Curve | OID | Security strength | Private key | Public point | Signature |
|---|---|---|---|---|---|
| P-256 (secp256r1) | ASN1::secp256r1() | 128 bits | 32 bytes | 65 bytes uncompressed | 64 bytes |
| P-384 (secp384r1) | ASN1::secp384r1() | 192 bits | 48 bytes | 97 bytes uncompressed | 96 bytes |
| P-521 (secp521r1) | ASN1::secp521r1() | 256 bits | 66 bytes | 133 bytes uncompressed | 132 bytes |
oids.h declares many other curves, including secp256k1, the Brainpool curves and binary-field (EC2N) curves.
Signature Format
Signatures are in IEEE P1363 format: r followed by s, each padded to the byte length of the curve order, so the length is fixed for a curve. X.509, TLS and many other libraries use the ASN.1 DER format instead, which is a few bytes longer and varies in length. DSAConvertSignatureFormat() in dsa.h converts between them:
// P1363 (this library) to DER
SecByteBlock der(signer.MaxSignatureLength() + 16);
size_t derLen = DSAConvertSignatureFormat(
der, der.size(), DSA_DER,
(const byte*)signature.data(), signature.size(), DSA_P1363);
der.resize(derLen);
// And back: the DER produced above to P1363
SecByteBlock p1363(verifier.SignatureLength());
size_t p1363Len = DSAConvertSignatureFormat(
p1363, p1363.size(), DSA_P1363,
der, der.size(), DSA_DER);
// 0 means nothing was written
if (derLen == 0 || p1363Len == 0)
throw std::runtime_error("signature conversion failed");DSAConvertSignatureFormat() converts; it does not check that a signature is valid for a key. It returns the number of bytes written, or 0 with the output buffer untouched if r or s is negative or too large for the target format, if a P1363 signature or buffer has an empty or odd length, or if the output does not fit. Check the return value before using the buffer. It parses its DER input by BER rules, and malformed DER throws BERDecodeErr. Before converting a signature received from another library, require strict DER and check that r and s are each in the range 1 to n-1, where n is the curve order.
Class Templates
ECDSA<EC, H>
ECDSA with a random per-signature nonce. ECDSA<ECP, SHA256> provides the nested types PrivateKey, PublicKey, Signer and Verifier.
Template Parameters:
EC- Elliptic curve type (ECPfor prime-field curves,EC2Nfor binary-field curves)H- Hash algorithm (SHA256,SHA384,SHA512)
ECDSA_RFC6979<EC, H>
Deterministic ECDSA per RFC 6979. The nonce is derived from the private key and the message, so signing does not use the random number generator and the same key and message always give the same signature. The signatures verify with an ordinary ECDSA verifier.
Key Generation
Generate New Key Pair
AutoSeededRandomPool rng;
// Generate a private key on the curve named by the OID
ECDSA<ECP, SHA256>::PrivateKey privateKey;
privateKey.Initialize(rng, ASN1::secp256r1());
// Derive the public key
ECDSA<ECP, SHA256>::PublicKey publicKey;
privateKey.MakePublicKey(publicKey);Choose the curve by OID. GenerateRandomWithKeySize() does not work for elliptic-curve keys; it throws NotImplemented.
Validate Keys
AutoSeededRandomPool rng;
// Validate private key
bool privateValid = privateKey.Validate(rng, 3); // Level 3 runs every check
// Validate public key
bool publicValid = publicKey.Validate(rng, 3);Save and Load Keys
// Save private key (PKCS #8, unencrypted)
FileSink privateFile("private.key");
privateKey.Save(privateFile);
privateFile.MessageEnd();
// Save public key (X.509 SubjectPublicKeyInfo)
FileSink publicFile("public.key");
publicKey.Save(publicFile);
publicFile.MessageEnd();
// Load private key
FileSource privateSource("private.key", true);
ECDSA<ECP, SHA256>::PrivateKey loadedPrivate;
loadedPrivate.Load(privateSource);
// Load public key
FileSource publicSource("public.key", true);
ECDSA<ECP, SHA256>::PublicKey loadedPublic;
loadedPublic.Load(publicSource);Save() writes DER. The private key encoding is not encrypted; protect it before it reaches disk. Validate a loaded key before using it.
Signing and Verification
Sign Message
ECDSA<ECP, SHA256>::Signer signer(privateKey);
std::string message = "Message to sign";
std::string signature;
StringSource(message, true,
new SignerFilter(rng, signer,
new StringSink(signature)
)
);Verify Signature
ECDSA<ECP, SHA256>::Verifier verifier(publicKey);
bool valid = false;
StringSource(signature + message, true,
new SignatureVerificationFilter(verifier,
new ArraySink((byte*)&valid, sizeof(valid))
)
);
if (!valid) {
std::cerr << "Invalid signature!" << std::endl;
}Direct Sign/Verify (without filters)
// Sign directly
ECDSA<ECP, SHA256>::Signer signer(privateKey);
size_t sigLen = signer.MaxSignatureLength();
SecByteBlock signature(sigLen);
sigLen = signer.SignMessage(rng,
(const byte*)message.data(), message.size(),
signature);
signature.resize(sigLen);
// Verify directly
ECDSA<ECP, SHA256>::Verifier verifier(publicKey);
bool valid = verifier.VerifyMessage(
(const byte*)message.data(), message.size(),
signature, signature.size()
);Complete Example: Deterministic ECDSA (RFC 6979)
#include <cryptopp/eccrypto.h>
#include <cryptopp/osrng.h>
#include <cryptopp/oids.h>
#include <cryptopp/filters.h>
#include <cryptopp/cryptlib.h> // NullRNG
#include <iostream>
using namespace CryptoPP;
int main() {
AutoSeededRandomPool rng;
// Generate key pair
ECDSA_RFC6979<ECP, SHA256>::PrivateKey privateKey;
privateKey.Initialize(rng, ASN1::secp256r1());
ECDSA_RFC6979<ECP, SHA256>::PublicKey publicKey;
privateKey.MakePublicKey(publicKey);
// Create deterministic signer (signing does not use an RNG)
ECDSA_RFC6979<ECP, SHA256>::Signer signer(privateKey);
std::string message = "Deterministic signature test";
// Sign twice - should produce identical signatures
std::string sig1, sig2;
StringSource(message, true,
new SignerFilter(NullRNG(), signer,
new StringSink(sig1)
)
);
StringSource(message, true,
new SignerFilter(NullRNG(), signer,
new StringSink(sig2)
)
);
// The two signatures are identical
bool same = (sig1 == sig2);
std::cout << "Signatures identical: " << (same ? "YES" : "NO") << std::endl;
// Verify
ECDSA_RFC6979<ECP, SHA256>::Verifier verifier(publicKey);
bool valid = false;
StringSource(sig1 + message, true,
new SignatureVerificationFilter(verifier,
new ArraySink((byte*)&valid, sizeof(valid))
)
);
std::cout << "Signature valid: " << (valid ? "YES" : "NO") << std::endl;
return (same && valid) ? 0 : 1;
}ECDSA vs Ed25519 vs RSA
| Feature | ECDSA P-256 | Ed25519 | RSA-2048 |
|---|---|---|---|
| Private key | 32 bytes | 32 bytes | 256-byte modulus plus exponents |
| Public key | 65 bytes uncompressed | 32 bytes | 256-byte modulus plus exponent |
| Signature | 64 bytes (P1363) | 64 bytes | 256 bytes |
| Security strength | 128 bits | About 128 bits | 112 bits |
| Signing nonce | Random, or derived (RFC 6979) | Derived | PSS uses a random salt |
| Specification | FIPS 186-5, SEC 1 | RFC 8032, FIPS 186-5 | RFC 8017, FIPS 186-5 |
Use ECDSA when a protocol, a peer or a policy requires the NIST curves, for example in X.509 certificates. Where either is acceptable, Ed25519 has smaller public keys and no per-signature randomness to get wrong. cryptest b measures all three on your own hardware.
Security
Security Properties
- Security level: Depends on the curve (128 bits for P-256, 192 bits for P-384)
- Signature size: Twice the byte length of the curve order (64 bytes for P-256)
- Deterministic variant: RFC 6979 removes the dependence on the random number generator when signing
- Standards: FIPS 186-5, ANSI X9.62, SEC 1
Security Notes
- Nonce reuse exposes the private key: If the same nonce (k) signs two different messages under one key, the private key can be computed from the two signatures. A biased or partly predictable nonce is also exploitable.
ECDSA_RFC6979derives the nonce from the private key and the message, so it does not depend on the quality of the random number generator. - Hash algorithm: Use SHA-256 or stronger, matched to the curve.
- Key validation: Validate keys loaded from outside sources.
- Signature format: Convert DER signatures to P1363 before verifying; see Signature Format.
// Deterministic nonces
ECDSA_RFC6979<ECP, SHA256>::Signer signer(privateKey);When to Use ECDSA
Use ECDSA for:
- X.509 certificates and TLS - Where the certificate or peer uses an ECDSA key
- NIST curve requirements - Policies or certifications that specify P-256, P-384 or P-521
- Interoperability - Systems and platforms that require ECDSA signatures
Don’t use ECDSA for:
- Key exchange - Use ECDH or X25519
- Encryption - A signature does not hide the message
- Weak hashes - Do not pair it with SHA-1 or MD5
Thread Safety
Not thread-safe. Use separate key, signer and verifier objects in each thread.
Exceptions
UnknownOID-Initialize()was given an OID that is not a recognised curveNotImplemented-GenerateRandomWithKeySize()was called on an elliptic-curve keyBERDecodeErr-Load()was given a malformed encoding
A signature that does not verify is reported by the return value (false), not by an exception.
See Also
- Ed25519 - EdDSA signatures on Curve25519
- ECDH - Key exchange with same curves
- RSA - RSA signatures and encryption
- X25519 - Key exchange on Curve25519
References
- FIPS 186-5: Digital Signature Standard (DSS)
- RFC 6979: Deterministic Usage of the Digital Signature Algorithm (DSA) and Elliptic Curve Digital Signature Algorithm (ECDSA)
- SEC 1: Elliptic Curve Cryptography, Version 2.0
- NIST SP 800-186: Recommendations for Discrete Logarithm-based Cryptography: Elliptic Curve Domain Parameters
- NIST SP 800-57 Part 1 Revision 5: Recommendation for Key Management