Search code examples
javasecuritysignpki

Signing and verifying data is giving wrong result in Java


I am generating public and private keys and then using that private key to sign a text data. For some reason when I verify the signature it gives False. Below are my code and I am unable to understand why it is happening.

I am using the same public and private key pairs with RSA algorthim.

 String msg = "Some data need to be signed.";

    //Creating KeyPair generator object
    KeyPairGenerator keyPairGen = null;
    try {
        keyPairGen = KeyPairGenerator.getInstance("RSA");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    //Initializing the key pair generator
    keyPairGen.initialize(2048);

    //Generate the pair of keys
    KeyPair pair = keyPairGen.generateKeyPair();
    //KeyPair pair2 = keyPairGen.generateKeyPair();

    //Getting the private key from the key pair
    PrivateKey privKey = pair.getPrivate();

    //Creating a Signature object
    Signature sign = null;
    try {
        sign = Signature.getInstance("SHA256withRSA");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    //Initialize the signature
    try {
        sign.initSign(privKey);
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
    byte[] bytes = msg.getBytes();

    //Adding data to the signature
    try {
        sign.update(bytes);
    } catch (SignatureException e) {
        e.printStackTrace();
    }

    //Calculating the signature
    try {
        byte[] signature = sign.sign();

        Signature mySig2 = Signature.getInstance("SHA256withRSA");

        mySig2.initVerify(pair.getPublic());

        boolean isSigValid = mySig2.verify(signature);

       //This part supposed to be True since I am using valid public key but it shows false. 
        log.info("Valid Signing = "+isSigValid); 

    } catch (SignatureException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }

Solution

  • You forgot to load the message into mySig2

    mySig2.update(bytes)
    

    So you're basically verifying that that's the correct signature for an empty message.