Digital Signatures in Java: Signing and Verifying with RSA, EdDSA and ML-DSA
Public key signatures in Java: why a digest alone cannot prove authorship, key pairs and the Signature class, sign/verify/tamper checks, encoding and restoring keys with KeyFactory, and choosing between RSA, RSASSA-PSS, ECDSA, Ed25519, Ed448 and the post-quantum ML-DSA.
kvi5hnuCode Sprout team member10 min readOn this page
Article 83 showed that a message digest detects changes, but only if the digest itself reaches you safely. An attacker who can replace a file can usually replace its hash too. A digital signature closes that gap. It is made with a secret that only the signer has and can be checked by anyone, so it proves two things at once: the data has not changed, and it was signed by the holder of a particular key.
Public key cryptography in one page
Signatures use key pairs. The two keys are linked mathematically, but computing one from the other is believed to be infeasible:
- The private key stays with its owner and is used to sign.
- The public key can be published to the whole world and is used to verify.

Alice hashes the document and transforms the hash with Alice's private key; the result is the signature. Bob receives the document and the signature, possibly through an untrusted channel, and runs the verification with Alice's public key. If it returns true, Bob knows that:
- the document is exactly what was signed, and
- it was signed with the private key that matches the public key Bob used.
Note the careful wording of point 2. A signature links a document to a key, not to a person. How Bob knows that the public key really belongs to Alice is the authentication problem, and certificates (article 85) are the standard answer. Note also what a signature does not do: the document itself is not hidden. Keeping data secret is encryption (articles 86 and 87).
The whole system depends on the private key staying private. Someone who steals it can sign anything in the owner's name, and every verifier will accept it. This is why private keys live in protected key stores, hardware security modules or smart cards.
The Signature class
The Java API follows the same pattern as MessageDigest: a factory method, data fed by update, and a final step.
// Alice: generate keys (once) and sign
KeyPairGenerator kpg = KeyPairGenerator.getInstance("Ed25519");
KeyPair pair = kpg.generateKeyPair();
Signature signer = Signature.getInstance("Ed25519");
signer.initSign(pair.getPrivate());
signer.update(document);
byte[] signature = signer.sign();
// Bob: verify with the public key
Signature verifier = Signature.getInstance("Ed25519");
verifier.initVerify(alicePublicKey);
verifier.update(document);
boolean ok = verifier.verify(signature);
Some details worth knowing:
updatecan be called many times, so large data can be signed in chunks or from a stream. The verifier must feed exactly the same bytes in the same order.- After
sign()orverify(), the object returns to its initialized state and can process another message with the same key. verifyreturnsfalsefor a well-formed signature that does not match. For a malformed signature (wrong length, not a valid encoding, a value outside the allowed range) many algorithms throwSignatureExceptioninstead. Code that checks untrusted input should treat that exception as "not valid", as the demo'sverifyhelper does.- Some algorithms take parameters. RSASSA-PSS needs a
PSSParameterSpecviasetParameter; ML-DSA and EdDSA choose their parameter set through the key. Signatureobjects are not thread-safe.
Choosing an algorithm
Each signature algorithm has its own key type, so the key generator and the signature must match:
| Signature algorithm | Key generator | Notes |
|---|---|---|
SHA256withRSA (also SHA384, SHA512) | RSA, 3072 bits recommended (2048 minimum) | RSA with PKCS #1 v1.5 padding. Very widely supported; large keys; deterministic. |
RSASSA-PSS | RSASSA-PSS or RSA | RSA with the probabilistic PSS padding (Java 11). Preferred over v1.5 for new RSA designs. |
SHA256withECDSA | EC with a named curve such as secp256r1 | Small keys and signatures. Needs a good random number for every signature; signatures are DER-encoded and vary in length. |
Ed25519, Ed448 (or EdDSA) | Ed25519, Ed448 | Edwards-curve signatures (Java 15). Fast, small, deterministic, and harder to misuse than ECDSA. A good default today. |
ML-DSA | ML-DSA, parameter sets ML-DSA-44, -65, -87 | Module-lattice signatures standardized in FIPS 204 (Java 24, JEP 497). Resistant to quantum computers; keys and signatures are kilobytes. |
SHA256withDSA | DSA | Classic DSA. No longer approved for creating new signatures (FIPS 186-5); only verify old ones. |
Why the push towards ML-DSA? RSA and elliptic-curve algorithms rely on factoring and discrete logarithms, both of which a large enough quantum computer could solve with Shor's algorithm. No such machine exists yet, but signatures on long-lived artifacts (firmware, archives, root certificates) may need to stay trustworthy for decades, so the industry is starting the migration now. Mixed "composite" or dual signatures with one classical and one ML-DSA signature are a common transition strategy.
Storing and exchanging keys
Key.getEncoded() returns a standard binary encoding:
- public keys use X.509 SubjectPublicKeyInfo (
getFormat()returns"X.509"), which contains an algorithm identifier and the key; - private keys use PKCS #8 (
"PKCS#8").
To turn bytes back into a key, use a KeyFactory of the right algorithm with the matching spec:
PublicKey pub = KeyFactory.getInstance("Ed25519")
.generatePublic(new X509EncodedKeySpec(encodedPublic));
PrivateKey priv = KeyFactory.getInstance("Ed25519")
.generatePrivate(new PKCS8EncodedKeySpec(encodedPrivate));
There are also algorithm-specific specs for the raw numbers (RSAPublicKeySpec, ECPublicKeySpec, EdECPublicKeySpec, ...). For text transfer, Base64-encode the bytes. The familiar -----BEGIN PUBLIC KEY----- PEM files are exactly that Base64 text with header lines; Java 25 has a preview API (java.security.PEMEncoder/PEMDecoder, JEP 470) that reads and writes them directly. In practice, private keys normally live in a password-protected KeyStore (PKCS #12), and public keys travel inside certificates, both covered in the next article.
The program
The program starts with a known-answer test: it feeds the private key from RFC 8032's first Ed25519 test vector into the key generator (through a fake SecureRandom that returns fixed bytes, a trick only for tests) and prints the public key and the signature of an empty message; both match the values published in the RFC. It then signs a short contract, shows that changing one byte of the contract or one bit of the signature, or using another key, makes verification fail, moves a public key through Base64 and KeyFactory, compares six algorithms, and signs a 1 MiB message in chunks.
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.*;
import java.util.*;
public class Solution {
static final HexFormat HEX = HexFormat.of();
/** A SecureRandom that returns fixed bytes, ONLY to make this demo repeatable. Never do this in real code. */
static final class FixedRandom extends SecureRandom {
private static final long serialVersionUID = 1L;
private final byte[] seed;
private int pos;
FixedRandom(String hex) { seed = HEX.parseHex(hex); }
@Override public void nextBytes(byte[] bytes) {
for (int i = 0; i < bytes.length; i++) bytes[i] = seed[pos++ % seed.length];
}
}
static byte[] sign(String alg, PrivateKey key, byte[] data) throws GeneralSecurityException {
Signature s = Signature.getInstance(alg);
s.initSign(key);
s.update(data);
return s.sign();
}
static boolean verify(String alg, PublicKey key, byte[] data, byte[] sig) throws GeneralSecurityException {
Signature s = Signature.getInstance(alg);
s.initVerify(key);
s.update(data);
try {
return s.verify(sig);
} catch (SignatureException e) { // malformed signature (e.g. not a valid curve point)
return false;
}
}
public static void main(String[] args) throws Exception {
System.out.println("== Ed25519 with the RFC 8032 test vector 1 ==");
var kpg = KeyPairGenerator.getInstance("Ed25519");
kpg.initialize(NamedParameterSpec.ED25519,
new FixedRandom("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60"));
KeyPair rfc = kpg.generateKeyPair();
byte[] encodedPub = rfc.getPublic().getEncoded(); // X.509 SubjectPublicKeyInfo
System.out.println("public key (last 32 of " + encodedPub.length + " encoded bytes): "
+ HEX.formatHex(encodedPub, encodedPub.length - 32, encodedPub.length));
byte[] sigEmpty = sign("Ed25519", rfc.getPrivate(), new byte[0]);
System.out.println("signature of empty message (" + sigEmpty.length + " bytes):");
System.out.println(" " + HEX.formatHex(sigEmpty, 0, 32));
System.out.println(" " + HEX.formatHex(sigEmpty, 32, 64));
System.out.println("signing again gives the same bytes: " + Arrays.equals(sigEmpty, sign("Ed25519", rfc.getPrivate(), new byte[0])));
System.out.println("\n== Sign, verify, tamper ==");
byte[] contract = "I, Alice, sell my bicycle to Bob for 50 euros.".getBytes(StandardCharsets.UTF_8);
KeyPair alice = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); // real random key
KeyPair mallory = KeyPairGenerator.getInstance("Ed25519").generateKeyPair();
byte[] sig = sign("Ed25519", alice.getPrivate(), contract);
System.out.println("verify with Alice's public key: " + verify("Ed25519", alice.getPublic(), contract, sig));
byte[] changed = contract.clone();
changed[new String(contract, StandardCharsets.UTF_8).indexOf("50")] = '9'; // one byte: 50 -> 90
System.out.println("changed contract: " + verify("Ed25519", alice.getPublic(), changed, sig) + " (" + new String(changed, StandardCharsets.UTF_8) + ")");
byte[] badSig = sig.clone();
badSig[5] ^= 1;
System.out.println("one bit of the signature flipped: " + verify("Ed25519", alice.getPublic(), contract, badSig));
System.out.println("verify with Mallory's key: " + verify("Ed25519", mallory.getPublic(), contract, sig));
System.out.println("\n== Moving a public key around: X.509 encoding and KeyFactory ==");
String transmitted = Base64.getEncoder().encodeToString(alice.getPublic().getEncoded());
System.out.println("Base64 public key length: " + transmitted.length() + " chars, format " + alice.getPublic().getFormat());
PublicKey restored = KeyFactory.getInstance("Ed25519")
.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(transmitted)));
System.out.println("restored key verifies: " + verify("Ed25519", restored, contract, sig));
System.out.println("private key format: " + alice.getPrivate().getFormat());
System.out.println("\n== Same job, different algorithms ==");
record Alg(String keyAlg, String sigAlg, AlgorithmParameterSpec params) {}
var algs = List.of(
new Alg("RSA", "SHA256withRSA", new RSAKeyGenParameterSpec(3072, RSAKeyGenParameterSpec.F4)),
new Alg("RSASSA-PSS", "RSASSA-PSS", new RSAKeyGenParameterSpec(3072, RSAKeyGenParameterSpec.F4)),
new Alg("EC", "SHA256withECDSA", new ECGenParameterSpec("secp256r1")),
new Alg("Ed25519", "Ed25519", null),
new Alg("Ed448", "Ed448", null),
new Alg("ML-DSA", "ML-DSA", NamedParameterSpec.ML_DSA_65));
System.out.printf("%-16s %10s %10s %10s %s%n", "signature", "pub bytes", "sig bytes", "repeatable", "verifies");
for (Alg a : algs) {
var g = KeyPairGenerator.getInstance(a.keyAlg());
if (a.params() != null) g.initialize(a.params());
KeyPair kp = g.generateKeyPair();
Signature s = Signature.getInstance(a.sigAlg());
if (a.sigAlg().equals("RSASSA-PSS"))
s.setParameter(new PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1));
s.initSign(kp.getPrivate());
s.update(contract);
byte[] s1 = s.sign();
s.update(contract); // after sign() the object is ready to sign again
byte[] s2 = s.sign();
s.initVerify(kp.getPublic());
s.update(contract);
boolean ok = s.verify(s1);
String sigLen = a.sigAlg().endsWith("ECDSA") ? "70-72" : String.valueOf(s1.length);
System.out.printf("%-16s %10d %10s %10s %s%n", a.sigAlg(), kp.getPublic().getEncoded().length,
sigLen, Arrays.equals(s1, s2) ? "yes" : "no", ok);
}
System.out.println("\n== Signing a large message in pieces ==");
Signature streaming = Signature.getInstance("Ed25519");
streaming.initSign(alice.getPrivate());
byte[] chunk = new byte[8192];
for (int i = 0; i < 128; i++) { Arrays.fill(chunk, (byte) i); streaming.update(chunk); }
byte[] bigSig = streaming.sign();
Signature check = Signature.getInstance("Ed25519");
check.initVerify(alice.getPublic());
for (int i = 0; i < 128; i++) { Arrays.fill(chunk, (byte) i); check.update(chunk); }
System.out.println("1 MiB signed in 8 KiB updates verifies: " + check.verify(bigSig));
}
}
== Ed25519 with the RFC 8032 test vector 1 ==
public key (last 32 of 44 encoded bytes): d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a
signature of empty message (64 bytes):
e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e06522490155
5fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b
signing again gives the same bytes: true
== Sign, verify, tamper ==
verify with Alice's public key: true
changed contract: false (I, Alice, sell my bicycle to Bob for 90 euros.)
one bit of the signature flipped: false
verify with Mallory's key: false
== Moving a public key around: X.509 encoding and KeyFactory ==
Base64 public key length: 60 chars, format X.509
restored key verifies: true
private key format: PKCS#8
== Same job, different algorithms ==
signature pub bytes sig bytes repeatable verifies
SHA256withRSA 422 384 yes true
RSASSA-PSS 420 384 no true
SHA256withECDSA 91 70-72 no true
Ed25519 44 64 yes true
Ed448 69 114 yes true
ML-DSA 1974 3309 no true
== Signing a large message in pieces ==
1 MiB signed in 8 KiB updates verifies: true
Points to notice:
- The Ed25519 X.509 encoding is 44 bytes: a 12-byte header that names the algorithm, then the 32-byte key from the RFC.
- The table shows the size trade-off: an Ed25519 signature is 64 bytes, an RSA-3072 signature 384 bytes, an ML-DSA-65 signature 3,309 bytes with a 1,952-byte public key inside its encoding.
- "repeatable" confirms which algorithms are deterministic. The ECDSA signature length is shown as a range because its DER encoding varies from run to run.
Common questions
Which signature algorithm should I choose today? Ed25519 for new designs: small keys (32 bytes) and signatures (64 bytes), fast, deterministic and hard to misuse. ECDSA P-256 or RSA-PSS (3072 bits) when interoperability requires them. ML-DSA-65 where post-quantum security matters, accepting much larger signatures (3,309 bytes on JDK 25).
What key sizes does the JDK pick if I don't initialize the generator? On JDK 25: 3072 bits for RSA, the 384-bit curve for EC, and 256 bits for AES keys. Specify sizes explicitly anyway, so the code documents its choice and doesn't change with JDK defaults.
How do I read a PEM key file from OpenSSL?
Remove the -----BEGIN ...----- lines, Base64-decode the rest, and pass the bytes to KeyFactory with X509EncodedKeySpec (public) or PKCS8EncodedKeySpec (private, BEGIN PRIVATE KEY). Older BEGIN RSA PRIVATE KEY files use PKCS #1 and must be converted (openssl pkcs8 -topk8). Java 25's preview PEMDecoder does this directly.
Is a signature the same as encryption with the private key?
No, although textbook RSA makes it look that way. Real signature schemes use padding and hashing designed for signatures, and other algorithms (ECDSA, EdDSA, ML-DSA) have no encryption equivalent at all. Always use the Signature class, never Cipher with a private key.
How do I verify a signature produced by another language or tool?
Agree on the exact algorithm (SHA256withECDSA, Ed25519, RSASSA-PSS with its parameters), the signature encoding (Java's ECDSA uses DER; some tools use raw r||s, available as SHA256withECDSAinP1363Format), and the exact bytes signed, including character encoding and line endings.
API reference
| Class / method | Purpose |
|---|---|
KeyPairGenerator.getInstance(alg), initialize(bits or spec [, random]), generateKeyPair() | Create a key pair. |
KeyPair.getPublic(), getPrivate() | The two halves. |
Signature.getInstance(alg) | "Ed25519", "SHA256withRSA", "RSASSA-PSS", "SHA256withECDSA", "ML-DSA", ... |
initSign(privateKey [, random]), update(...), sign() | Produce a signature. |
initVerify(publicKey or certificate), update(...), verify(sig) | Check a signature. |
setParameter(spec) | Algorithm parameters such as PSSParameterSpec. |
Key.getEncoded(), getFormat(), getAlgorithm() | Standard encodings: X.509 for public, PKCS #8 for private keys. |
KeyFactory.getInstance(alg).generatePublic(spec) / generatePrivate(spec) | Rebuild keys from X509EncodedKeySpec, PKCS8EncodedKeySpec or raw specs. |
NamedParameterSpec.ED25519, ED448, ML_DSA_44, ML_DSA_65, ML_DSA_87 | Named parameter sets. |
ECGenParameterSpec("secp256r1"), RSAKeyGenParameterSpec(bits, F4) | Key generation parameters. |
SignatureException | Thrown for malformed signatures or misuse. |
Summary
- A signature is created with a private key and verified with the matching public key. It proves integrity and that the key holder signed; it does not encrypt.
Signatureworks likeMessageDigest:initSign/initVerify, any number ofupdatecalls, thensignorverify. TreatSignatureExceptionon untrusted input as a failed verification.- Good defaults today are Ed25519 for new designs, RSASSA-PSS or
SHA256withRSAwith 3072-bit keys for compatibility, and ML-DSA where resistance to future quantum computers matters. Avoid DSA for new signatures. - Keys are exchanged as X.509 (public) and PKCS #8 (private) encodings and restored with
KeyFactory. - A signature ties data to a key; tying the key to a real identity needs certificates.
Practice Questions
1. Bob downloads a file, its signature and the "author's public key" from the same website, and the signature verifies. What has he proved?
Only that the file matches the signature made with the private key belonging to that public key. If an attacker controls the website, they can supply their own key pair, file and signature, and verification still succeeds. Bob must obtain the public key, or a certificate vouching for it, through an independently trusted channel.
2. Your verification code calls Signature.verify on signatures that arrive over the network and the service sometimes returns HTTP 500. What is likely happening and how do you fix it?
Malformed signatures (wrong length, invalid encoding, an Ed25519 value that is not a valid curve point) cause verify to throw SignatureException instead of returning false, and the exception escapes as a server error. Catch SignatureException around verify and treat it as an invalid signature, logging it if useful.
3. Two ECDSA signatures of the same message with the same key differ. Is something broken? Would the same be true for Ed25519?
Nothing is broken: ECDSA uses a fresh random value for each signature, so signatures differ while both verify. Ed25519 is deterministic and gives identical signatures for the same key and message. That is a security advantage, because ECDSA leaks the private key if the random value repeats or is predictable.
4. Why would a company sign its firmware with ML-DSA today, even though no quantum computer can break RSA yet?
Firmware and root keys stay in use for many years, and a signature must remain unforgeable for as long as devices trust it. If a large quantum computer appears during that time, RSA and elliptic-curve signatures could be forged. ML-DSA (FIPS 204) is designed to resist such attacks. The costs are larger keys and signatures, which is acceptable for firmware images.
5. You must send an Ed25519 public key in a JSON message and rebuild it on the other side. Write the two key lines of code.
Sender: String text = Base64.getEncoder().encodeToString(publicKey.getEncoded()); (X.509 encoding). Receiver: PublicKey key = KeyFactory.getInstance("Ed25519").generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(text)));. Because the X.509 encoding includes the algorithm identifier, a generic KeyFactory.getInstance("EdDSA") also works.
Previous: Message Digests and Password Hashing in Java: SHA-2, SHA-3 and PBKDF2
Next: Certificates in Java: keytool, Certificate Chains and Signing JAR Files
Related reading
- Message Digests and Password Hashing in Java: SHA-2, SHA-3 and PBKDF2
- User Authentication with JAAS in Java: Login Modules, Callbacks and Subjects
- Writing a Class Loader and Bytecode Verification in Java
- Class Loading in Java: The Loading Process, Loader Hierarchy and Namespaces
- The Java Scripting API: Script Engines, Bindings and Invocable

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.