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

Verify the RSA Signature of a SHA256 Hash

See more RSA Examples

Demonstrates how to verify an RSA signature of a SHA256 hash.

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) {
        // This example assumes the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        // Let's say you have a file containing the 32-bytes of a SHA256 hash,
        // and a file that is an RSA signature of those 32 bytes.
        // Here's how you verify using the RSA public key found in a PEM.

        PublicKey pubKey = new PublicKey();
        try {
            pubKey.loadFromFile("rsaPubKey.pem");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        Rsa rsa = new Rsa();

        // Get the public key.
        try {
            rsa.usePublicKey(pubKey);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Get the 32-byte SHA256 hash.
        BinData bdHash = new BinData();
        try {
            bdHash.loadFile("myHash.sha256");
        } catch (ChilkatException e) {
            System.out.println("Failed to load SHA256 hash.");
            return;
        }

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

        // Verify the signature against the SHA256 hash.
        String enc = "base64";
        rsa.setEncodingMode(enc);
        try {
            rsa.verifyHashENC(bdHash.getEncoded(enc), "sha256", bdSig.getEncoded(enc));
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println("Signature validated.");
    }
}