Introduction
Digital signatures are the cryptographic equivalent of handwritten signatures, but stronger. A valid digital signature cannot be forged without the private key, and it proves not only who signed but also that the document was not modified after signing. The idea was first sketched by Whitfield Diffie and Martin Hellman in 1976 and made practical by Ron Rivest, Adi Shamir, and Leonard Adleman in their 1977 RSA paper. In this digital signature rsa java tutorial we will use Java's standard java.security.Signature class to sign and verify a message with SHA-256 and RSA.
The combination SHA256withRSA is the most widely used digital signature algorithm on the internet. It signs HTTPS certificates, JWTs with the RS256 algorithm, signed Docker images, software releases, and many API requests. Every time your browser shows the green padlock icon, an RSA signature was verified somewhere in the chain of trust. The signature algorithm internally hashes the message with SHA-256, pads the hash to the modulus length using PKCS#1 v1.5 padding, and exponentiates it with the private key.
What is a Digital Signature?
A digital signature is the inverse of public-key encryption. To sign a message, you encrypt it (or more precisely, a hash of it) with your private key. Anyone who has your public key can decrypt the signature and compare it to a freshly computed hash of the message. If they match, the signature is valid.
In practice, signing is not literally "encrypt the hash with the private key" because raw RSA is malleable. Instead, signature algorithms apply a padding scheme such as PKCS#1 v1.5 or PSS to the hash before exponentiation. The padding scheme ensures that an attacker cannot forge a signature by algebraic tricks.
Compared to a Message Authentication Code (MAC), a digital signature is non-repudiable: the verifier can prove to a third party that the message was signed by the key holder, because only the key holder could have produced the signature. A MAC, by contrast, uses a shared secret, so any holder of the secret could have produced the MAC and no one can prove who did. Compared to a handwritten signature, a digital signature is mathematically bound to the exact bytes of the signed document; change one byte and the signature fails to verify.
How SHA256withRSA Works Step by Step
Suppose Alice has an RSA key pair (public key, private key) and wants to sign the message "Pay Bob $1000". Here is what happens.
Step 1: Alice computes the SHA-256 hash of the message bytes. SHA-256 produces a 32-byte digest that uniquely identifies the message.
Step 2: The signing algorithm wraps the digest in a structured padding block defined by PKCS#1 v1.5. The block starts with bytes 00 01, then a sequence of FF padding bytes, then a 00 byte, then an ASN.1 structure that identifies the hash algorithm (SHA-256), then the 32-byte digest itself.
Step 3: Alice exponentiates the padded block with her private key: signature = paddedBlock^d mod n, where d is the private exponent and n is the modulus. The result is a byte array the same length as the modulus (typically 256 bytes for a 2048-bit key).
Step 4: To verify, Bob exponentiates the signature with Alice's public key: recovered = signature^e mod n. He checks that the recovered bytes match the expected PKCS#1 v1.5 structure for SHA-256, and that the embedded digest equals a fresh SHA-256 of the message he received. If both match, the signature is valid.
Java Program for Digital Signature Using RSA and SHA-256
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.util.Base64;
public class DigitalSignatureDemo {
public static void main(String[] args) throws Exception {
// 1. Generate an RSA key pair
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
gen.initialize(2048);
KeyPair pair = gen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
PublicKey pub = pair.getPublic();
System.out.println("Algorithm: " + priv.getAlgorithm());
// 2. The message we want to sign
String message = "Pay Bob $1000 from Alice's account.";
byte[] messageBytes = message.getBytes("UTF-8");
// 3. Sign with private key
Signature signer = Signature.getInstance("SHA256withRSA");
signer.initSign(priv);
signer.update(messageBytes);
byte[] signature = signer.sign();
String sigB64 = Base64.getEncoder().encodeToString(signature);
System.out.println("Message : " + message);
System.out.println("Signature : " + sigB64);
// 4. Verify with public key
Signature verifier = Signature.getInstance("SHA256withRSA");
verifier.initVerify(pub);
verifier.update(messageBytes);
boolean valid = verifier.verify(signature);
System.out.println("Valid : " + valid);
// 5. Demonstrate tamper detection
byte[] tamperedBytes = "Pay Bob $9999 from Alice's account.".getBytes("UTF-8");
verifier.update(tamperedBytes);
boolean tamperedValid = verifier.verify(signature);
System.out.println("Tampered : " + tamperedValid);
}
}
Code Explanation Line by Line
KeyPairGenerator.getInstance("RSA") returns a factory for RSA key pairs. We initialize it for 2048 bits, which is the minimum acceptable size for new applications today. The generateKeyPair method returns a KeyPair object holding a PrivateKey and a PublicKey. In a real application the keys would be stored in a Java KeyStore or an HSM, not generated on the fly.
Signature.getInstance("SHA256withRSA") returns a Signature object configured for the SHA-256 and RSA algorithm. The initSign method initializes the signer in signing mode with the private key. The update method feeds bytes of the message into the signature. The sign method finalizes the operation and returns the signature bytes. We base64-encode the signature so it can be printed safely.
To verify, we create a new Signature instance with the same algorithm string. We call initVerify with the public key, feed the same message bytes through update, and call verify with the signature bytes. The method returns true only if the signature is mathematically valid for the supplied message and public key.
The final block demonstrates tamper detection. We feed the verifier a different message but the same signature, and verify returns false. This is the core security property of digital signatures: any change to the signed message, even a single bit, invalidates the signature.
Sample Input and Output
Algorithm: RSA Message : Pay Bob $1000 from Alice's account. Signature : xJ7kL2p... (long base64 string) Valid : true Tampered : false
The exact signature will differ every run because the key pair is freshly generated. The crucial facts are the last two lines: the original message verifies, and the tampered message does not.
Common Mistakes to Avoid
First, never use SHA1withRSA for new signatures. SHA-1 has known collisions and NIST deprecated it for digital signatures in 2011. Use SHA256withRSA or SHA384withRSA, or for the strongest security, SHA256withRSAPSS using the PSS padding scheme.
Second, never sign raw messages without hashing. RSA can only sign values smaller than the modulus, so you must hash first. The Signature class does this for you; never try to bypass it by directly exponentiating the message.
Third, never distribute a signature without also distributing the public key (or a certificate that contains it). Without the public key, the verifier cannot confirm anything.
Fourth, never use the same key pair for signing and encryption. Best practice is to maintain separate keys for separate purposes; the padding schemes and security proofs differ between RSA-OAEP (for encryption) and RSASSA-PSS (for signatures).
Real-World Applications
SHA256withRSA is the algorithm that signs TLS certificates. When you visit an HTTPS site, your browser validates the certificate by checking a signature made by a certificate authority. JWT tokens with the RS256 algorithm use SHA256withRSA. Software distribution formats such as Debian packages, RPM packages, and Docker images all use RSA signatures to prove authenticity. Bank payment networks use RSA signatures to authenticate transfers. Smartcards often sign transactions with on-card RSA keys that never leave the card.
For new applications requiring very high security, Ed25519 (an elliptic-curve signature scheme) is increasingly preferred because it has smaller signatures and is faster than RSA at the same security level.
Conclusion
It is also worth understanding the difference between signing and encryption from a key-management perspective. While both operations use the same RSA key pair, best practice is to maintain separate key pairs for signing and for encryption. The padding schemes and security proofs differ between RSA-OAEP (for encryption) and RSASSA-PSS (for signatures), so using one key pair for both purposes can violate the assumptions of the security proofs. Many compliance regimes such as FIPS 186-5 and the European eIDAS regulation explicitly require separate key pairs.
For new applications requiring very high performance or very small signatures, elliptic-curve signature schemes are preferable to RSA. ECDSA with curve P-256 produces 64-byte signatures, roughly one quarter the size of a 2048-bit RSA signature, while offering comparable security. Ed25519 is even faster and produces 64-byte signatures with 32-byte public keys. For high-volume signing workloads, switching from RSA to Ed25519 can reduce CPU usage by an order of magnitude. However, RSA remains the right choice for interoperating with legacy systems and for applications where RSA is the only signature algorithm supported.
One final point: a digital signature proves authenticity and integrity, but it does not prove the signer actually meant to sign. A malicious or compromised signer can produce a valid signature, and cryptographic verification cannot tell whether the signature was produced willingly. For legal validity of digital signatures in regulated industries, you also need non-repudiation infrastructure: a trusted timestamp from a third-party timestamp authority, an audit trail of the signing event, and possibly hardware-token-based key storage that proves the key was present in a specific device at a specific time.
In this digital signature rsa java tutorial we used the standard java.security.Signature class to sign and verify a message with SHA256withRSA. We saw how the signature algorithm internally hashes and pads before exponentiating, why tampering invalidates the signature, and why SHA-1 signatures are now obsolete. The next step is to learn about certificates and the chain of trust that allows browsers to verify HTTPS sites automatically.
Comments
Comments
Post a Comment