xain xain - 1 year ago 75
Java Question

Sign string using given Public Key

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


Answer Source

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");
        byte[] signatureBytes = sig.sign();
        System.out.println("Singature:" + new BASE64Encoder().encode(signatureBytes));



    private static KeyPair getKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        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.