Sample code for 30+ languages & platforms
Java Requires Chilkat v11.0.0+

Generate RSA Key and Sign a String

See more RSA Examples

Demonstrates how to generate a new RSA public/private key pair and use it to generate a signature for a string. The (binary) digital signature is returned as a hexidecimalized string.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.PrivateKey;
import com.chilkatsoft.chilkat2.PublicKey;
import com.chilkatsoft.chilkat2.Rsa;

public class ChilkatExample {

    public static void main(String[] args) {
        // This example assumes the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        Rsa rsa = new Rsa();

        // Generate a 2048-bit RSA key.
        PrivateKey privKey = new PrivateKey();
        rsa.genKey(2048, privKey);

        rsa.usePrivateKey(privKey);

        // Return the signature in hex.
        rsa.setEncodingMode("hex");

        String strData = "This is the string to be signed.";

        // Sign the SHA256 hash of the string.
        String hexSig = rsa.signStringENC(strData, "sha256");

        System.out.println(hexSig);

        // Now verify the signature:
        PublicKey pubKey = new PublicKey();
        privKey.toPublicKey(pubKey);
        rsa.usePublicKey(pubKey);

        try {
            rsa.verifyStringENC(strData, "sha256", hexSig);
            System.out.println("Signature verified!");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
        }

        // Try it with an invalid signature:
        try {
            rsa.verifyStringENC(strData, "sha256", "not a valid sig");
            System.out.println("Signature verified!");
        } catch (ChilkatException e) {
            System.out.println("Signature validation failed!");
        }

        // Try it with invalid data:
        try {
            rsa.verifyStringENC("Not the original data", "sha256", hexSig);
            System.out.println("Signature verified!");
        } catch (ChilkatException e) {
            System.out.println("Signature validation failed!");
        }
    }
}