How can I get the signature of a string using SHA1withRSA
if I already have the Private Key as byte[]
or String
?
Private keys enable: You can decrypt a message secured by your public key. You can sign your message with your private key so that the recipients know the message could only have come from you.
To sign a message m, just apply the RSA function with the private key to produce a signature s; to verify, apply the RSA function with the public key to the signature, and check that the result equals the expected message. That's the textbook description of RSA signatures.
I guess what you say is you know the key pair before hand and want to sign/verify with that.
Please see the following code.
import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.Signature; import sun.misc.BASE64Encoder; public class MainClass { public static void main(String[] args) throws Exception { KeyPair keyPair = getKeyPair(); byte[] data = "test".getBytes("UTF8"); Signature sig = Signature.getInstance("SHA1WithRSA"); sig.initSign(keyPair.getPrivate()); sig.update(data); byte[] signatureBytes = sig.sign(); System.out.println("Signature:" + new BASE64Encoder().encode(signatureBytes)); sig.initVerify(keyPair.getPublic()); sig.update(data); System.out.println(sig.verify(signatureBytes)); } private static KeyPair getKeyPair() throws NoSuchAlgorithmException { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(1024); return kpg.genKeyPair(); } }
Here you need to change the method getKeyPair() to supply your known key pair. You may load it from a java key store [JKS].
You can't just have an arbitrary byte array either as your public key or private key. They should be generated in relation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With