Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sign string with private key

How can I get the signature of a string using SHA1withRSA if I already have the Private Key as byte[] or String?

like image 947
xain Avatar asked Aug 28 '11 23:08

xain


People also ask

Is it possible to sign a message with a private key?

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.

How do I sign my RSA private key?

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.


1 Answers

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.

like image 135
Prabath Siriwardena Avatar answered Sep 22 '22 21:09

Prabath Siriwardena