Yes, I know that Bouncy Castle is probably the only reasonable library for doing crypto in Java 8. However …
I can remember my first computer - Sinclair ZX Spectrum+ - with incredible 48KB RAM. The experience is still inside me and I find it hard to justify using 1.5+MB of Java code where 10 lines could do the trick. I talk about doing RSA signatures in Java 8.
Using system Java libraries for crypto is not fashionable as Bouncy Castle gives you a much wider set of functions. However, if you just need to do a bit of cryptography, Bouncy Castle may be an unnecessary dependency. Here’s how you can sign documents and verify signatures.
The first thing you need is some input data and let’s start with signature verification:
we need a signature - the code below delivers it in the base64 form so we will decode it as well;
some data that the signature is for - again, it’s base64 data as this snippet is for JWS-like signature verification; and
and we need a public key - we got it in the form of X.509 certificate, from which we extract the public key.
Note: the example below is for 4,096 bit RSA and export crypto restrictions may kick in. So if you haven’t done it yet, and experience weird problems, you may need to install an unlimited crypto policy for your Java installation. Have a look here, it’s pretty simple (once you find the right folder:) ): Java Cryptography Extension (JCE) Unlimited Strength
What is the difference for creating the signature? Well there are 2 points here:
you need a private key that will be used with signAlg.initVerify() method
instead of the verify() method, you will call the sign() method, which returns a byte array