I have the following code in bash:
signed_request = $(printf "PLAIN TEXT REQUEST" |
openssl rsautl -sign -inkey "keyfile.pem" | openssl enc -base64 | _chomp )
Basically, this code takes a plain text, signs it with a private key and encodes using Base64
How could I do a code with exactly the same functionality in Java?
You can use JDK security API. Take a look at this working sample, hope it can get you started:
EDIT: The example above uses internal Sun's encoder (
sun.misc.BASE64Encoder
). It is best to use something like Base64 fromCommons Codec
.I copy the link @Aqua posted as a new answer, because I think it's FAR more useful than any of the answers given yet. Use THIS to read/write private/public keys from files: http://codeartisan.blogspot.ru/2009/05/public-key-cryptography-in-java.html
The link doesn't say anythig about signing and verifying, but signing is a lot easier. I used this code to sign:
And to verify:
Also, you can use not-yet-commons-ssl to obtain the private key from a file and encode using
org.apache.commons.ssl.Base64
. Using Max's example: