How to sign string with private key

60,236

Solution 1

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.

Solution 2

public static String sign(String plainText, PrivateKey privateKey) throws Exception {
    Signature privateSignature = Signature.getInstance("SHA256withRSA");
    privateSignature.initSign(privateKey);
    privateSignature.update(plainText.getBytes(UTF_8));

    byte[] signature = privateSignature.sign();

    return Base64.getEncoder().encodeToString(signature);
}

public static boolean verify(String plainText, String signature, PublicKey publicKey) throws Exception {
    Signature publicSignature = Signature.getInstance("SHA256withRSA");
    publicSignature.initVerify(publicKey);
    publicSignature.update(plainText.getBytes(UTF_8));

    byte[] signatureBytes = Base64.getDecoder().decode(signature);

    return publicSignature.verify(signatureBytes);
}

Solution 3

I use bouncy-castle to sign data and verify it.

you should add maven dependency:

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.56</version>
</dependency>
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcpkix-jdk15on</artifactId>
    <version>1.56</version>
</dependency>

Load RSA private or public key from a disk file into a Java object

First, we need to be able to load RSA private or public key from a disk file into a Java object of a proper class from Bouncy Castle

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.lang3.Validate;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.util.PrivateKeyFactory;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;

public class KeyUtil {

    public static AsymmetricKeyParameter loadPublicKey(InputStream is) {
        SubjectPublicKeyInfo spki = (SubjectPublicKeyInfo) readPemObject(is);
        try {
            return PublicKeyFactory.createKey(spki);
        } catch (IOException ex) {
            throw new RuntimeException("Cannot create public key object based on input data", ex);
        }
    }

    public static AsymmetricKeyParameter loadPrivateKey(InputStream is) {
        PEMKeyPair keyPair = (PEMKeyPair) readPemObject(is);
        PrivateKeyInfo pki = keyPair.getPrivateKeyInfo();
        try {
            return PrivateKeyFactory.createKey(pki);
        } catch (IOException ex) {
            throw new RuntimeException("Cannot create private key object based on input data", ex);
        }
    }

    private static Object readPemObject(InputStream is) {
        try {
            Validate.notNull(is, "Input data stream cannot be null");
            InputStreamReader isr = new InputStreamReader(is, "UTF-8");
            PEMParser pemParser = new PEMParser(isr);

            Object obj = pemParser.readObject();
            if (obj == null) {
                throw new Exception("No PEM object found");
            }
            return obj;
        } catch (Throwable ex) {
            throw new RuntimeException("Cannot read PEM object from input data", ex);
        }
    }
}

Creation of an RSA digital signature

        // GIVEN: InputStream prvKeyInpStream
    AsymmetricKeyParameter privKey = KeyUtil.loadPrivateKey(prvKeyInpStream);

    // GIVEN: byte[] messageBytes = ...
    RSADigestSigner signer = new RSADigestSigner(new SHA512Digest());
    signer.init(true, privKey);
    signer.update(messageBytes, 0, messageBytes.length);

    try {
        byte[] signature = signer.generateSignature();
    } catch (Exception ex) {
        throw new RuntimeException("Cannot generate RSA signature. " + ex.getMessage(), ex);
    }

Verification of an RSA digital signature

// GIVEN: InputStream pubKeyInpStream
AsymmetricKeyParameter publKey = KeyUtil.loadPublicKey(pubKeyInpStream);

// GIVEN: byte[] messageBytes
RSADigestSigner signer = new RSADigestSigner(new SHA512Digest());
signer.init(false, publKey);
signer.update(messageBytes, 0, messageBytes.length);

// GIVEN: byte[] signature - see code sample above
boolean isValidSignature = signer.verifySignature(signature);
Share:
60,236

Related videos on Youtube

xain
Author by

xain

SW PM,architect and programmer

Updated on January 02, 2020

Comments

  • xain
    xain over 4 years

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

    • rczajka
      rczajka over 12 years
      You can't sign anything with a public key.
    • monksy
      monksy over 12 years
      A public key can only be used to read the message, but you can't sign a new message with a public key. A private key can be used to sign the message.
    • StFS
      StFS almost 7 years
      The above two comments are actually not true (usually). Most often you can encrypt (and therefore sign) stuff with either key (private or public). This is how asymmetric encryption works. If Bob wants to send an encrypted message to Alice, he actually uses Alice's public key to encrypt his message and she will use her private key to decrypt. If he also wants to sign the message, he uses his private key to encrypt a hash of the message and Alice uses Bob's public key to decrypt that hash and verify it against the message received.
  • Diego Palomar
    Diego Palomar almost 7 years
    He is not asking how to encrypt data, he is asking how to sign data. encrypt != sign
  • fragmentedreality
    fragmentedreality over 4 years
    Hi Durga and welcome to SO. It is really nice to post code-snippets in an answer. Even better if you add a little bit of explanation to it. Thank you for your first contribution, though!
  • Carlos Silva
    Carlos Silva over 2 years
    what is defined in getPrivateKey?
  • Michael Starkie
    Michael Starkie over 2 years
    What if you had to verify in another program? Say that the client wants to sign and encode a string to be passed in a URL and the server wants to decode the string using the public key? The above example won't work because the Signature object wont be the same instance on the server side.
  • Michael Starkie
    Michael Starkie over 2 years
    Oh. I see. You have to pass both the data and the digital signature to the server side.