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

RSA Hash Binary Data and Sign (and Verify)

See more RSA Examples

Demonstrates how to sign the hash of binary data. Also demonstrates how to verify the RSA signature.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.BinData;
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 requires the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        // Load an RSA private key for signing.
        PrivateKey privKey = new PrivateKey();
        try {
            privKey.loadEncryptedPemFile("qa_data/pem/rsa_passwd.pem", "passwd");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        Rsa rsa = new Rsa();
        rsa.usePrivateKey(privKey);

        // We have some binary data (in hex) to sign
        String originalData = "0102030405060708090A";
        BinData bdData = new BinData();
        bdData.appendEncoded(originalData, "hex");

        // Hash (SHA-256) and sign the hash:
        BinData bdSignature = new BinData();
        try {
            rsa.signBd(bdData, "sha256", bdSignature);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Show the RSA signature in base64
        System.out.println(bdSignature.getEncoded("base64"));

        // ------------------------------------------
        // Get the public key from the private key
        PublicKey pubKey = new PublicKey();
        privKey.toPublicKey(pubKey);

        // Verify the signature..
        Rsa rsa2 = new Rsa();
        rsa2.usePublicKey(pubKey);

        boolean bVerified;
        try {
            rsa2.verifyBd(bdData, "sha256", bdSignature);
            bVerified = true;
        } catch (ChilkatException e) {
            bVerified = false;
        }
        System.out.println("signature verified: " + bVerified);
    }
}