Sign with the private key, verify with the public one
Sign with the private key, verify with the public one
Answer
KeyPair pair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); byte[] name = "books.example.com".getBytes(StandardCharsets.UTF_8); Signature signer = Signature.getInstance("SHA256withRSA"); signer.initSign(pair.getPrivate()); // only the key holder can do this signer.update(name); byte[] signed = signer.sign(); Signature check = Signature.getInstance("SHA256withRSA"); check.initVerify(pair.getPublic()); // anyone at all can do this check.update(name); System.out.println("authentic and unaltered? " + check.verify(signed));
This is step three of the handshake in miniature, and it buys two of the three properties at once: only the private key could have produced `signed`, which is authentication, and any alteration of `name` makes `verify` return false, which is integrity. Nothing here is confidential — the public key is public. Replace the key pair with a CA key and the name with a certificate and you have exactly what chain verification does.
JDK javadoc java.security.Signature; java.security.KeyPairGenerator