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

Verfies an RSA Signature

See more Apple Keychain Examples

Verifies an RSA signature against the original data.

Chilkat Java Downloads

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

public class ChilkatExample {

    public static void main(String[] args) {
        // The following data was signed by the following example:
        // RSA Sign using a Private Key on a USB Token or Smartcard
        BinData bd = new BinData();
        for (int i = 0; i <= 100; i++) {
            bd.appendEncoded("000102030405060708090A0B0C0D0E0F", "hex");
        }

        // Load the signature
        BinData bdSig = new BinData();
        try {
            bdSig.loadFile("rsaSignatures/test1.sig");
        } catch (ChilkatException e) {
            System.out.println("Failed to load the RSA signature");
            return;
        }

        // Get the public key to be used for signature verification.
        PublicKey pubKey = new PublicKey();
        try {
            pubKey.loadFromFile("rsaKeys/chilkat-rsa-2048.pem");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        Rsa rsa = new Rsa();
        try {
            rsa.usePublicKey(pubKey);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Verify the hash of the data against the signature.
        // We pass in the original data.  Internally, the hash is generated
        // and used to validate the signature.
        // Validating the RSA signature means two things:
        // (1) the original data is exactly what was signed, and
        // (2) it was signed by the owner of the RSA private key.

        try {
            rsa.verifyBd(bd, "sha256", bdSig);
            System.out.println("Signature valid.");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            System.out.println("Signature invalid.");
        }
    }
}