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

RSA Sign Binary Data and Verify (Recover the Original Data)

See more RSA Examples

Demonstrates how to RSA sign binary data and then verify/recover the original data.

Note: This example uses methods introduced in Chilkat v9.5.0.77.

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 bd = new BinData();
        bd.appendEncoded(originalData, "hex");

        // If successful, the contents of bd are replaced with the RSA signature.
        try {
            rsa.signRawBd(bd);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

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

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

        // Verify the signature and extract the original data.
        Rsa rsa2 = new Rsa();
        rsa2.usePublicKey(pubKey);

        boolean bVerified;
        try {
            rsa2.verifyRawBd(bd);
            bVerified = true;
        } catch (ChilkatException e) {
            bVerified = false;
        }
        System.out.println("signature verified: " + bVerified);

        // Show the original data:
        System.out.println("original data: " + bd.getEncoded("hex"));
    }
}