Sample code for 30+ languages & platforms
Java

Verify an RSA Signature Against the Signed String

See more Apple Keychain Examples

Demonstrates how to validate an RSA Signature against the string that was signed.

Chilkat Java Downloads

Java
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

    //  Create the same string we previously signed in this example: 
    //  RSA Sign utf-8 Bytes of String to get Base64 RSA Signature

    CkStringBuilder sb = new CkStringBuilder();
    boolean crlfLineEnding = true;
    int i;
    for (i = 0; i <= 10; i++) {
        sb.AppendLine("This is a test.",crlfLineEnding);
        }

    String base64_rsa_sig = "gWgpEXQqvXN6wh0MuFXPiw2xCb8cnmdizBT1TD1Tpm2GlJ8gnD59DGSj35GGXk1tM+mCOvMa2uW/9gmz8p6A90JLbn918i/2wKGvcde4wXnzPO7JADSNn2UwYzf3rp4/q/JrHv1GZETRJhABSFqTxOgdmdbEJQE/zijOSctCtQAM2CTb6t2BO8uHKSSUAwPH2cbeWxqsaVRLT4ruk5nZOxhoLgLMSjupiSzbE8zSTkkFOEHD+Mbb2xwg85AI0E4DsUnp+hLwwtS0blesgSyvtBY8oJODJeFcJsR7JDOTPdzHQHgJRl/2A4ij5xT91TpXy7ok43jhT6O9j7Q3qrafIQ==";

    //  Get the public key to be used for signature verification.
    CkPublicKey pubKey = new CkPublicKey();
    success = pubKey.LoadFromFile("rsaKeys/chilkat-rsa-2048.pem");
    if (success == false) {
        System.out.println(pubKey.lastErrorText());
        return;
        }

    CkRsa rsa = new CkRsa();
    success = rsa.UsePublicKey(pubKey);
    if (success == false) {
        System.out.println(rsa.lastErrorText());
        return;
        }

    //  Verify the string against the signature.
    //  We signed the utf-8 byte representation of the string, so we must indicate
    //  to also validate against the utf-8 byte representation.
    rsa.put_Charset("utf-8");
    rsa.put_EncodingMode("base64");
    String signedString = sb.getAsString();
    success = rsa.VerifyStringENC(signedString,"sha256",base64_rsa_sig);

    if (success == false) {
        System.out.println(rsa.lastErrorText());
        System.out.println("Signature invalid.");
        }
    else {
        System.out.println("Signature valid.");
        }
  }
}