签名和验证数据在 Java 中给出了错误的结果

Signing and verifying data is giving wrong result in Java

我正在生成 public 和私钥,然后使用该私钥签署文本数据。出于某种原因,当我验证签名时,它给出了 False。以下是我的代码,我无法理解为什么会这样。

我在 RSA 算法中使用相同的 public 和私钥对。

 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();
    }

您忘记将消息加载到 mySig2

mySig2.update(bytes)

所以您基本上是在验证空消息的签名是否正确。