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

时间:2019-05-22 14:17:44

标签: java security sign pki

我正在生成公用密钥和专用密钥,然后使用该专用密钥对文本数据进行签名。由于某种原因,当我验证签名时,它会给出False。以下是我的代码,我无法理解为什么会发生。

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

1 个答案:

答案 0 :(得分:0)

您忘记了将邮件加载到mySig2

mySig2.update(bytes)

因此,您基本上是在验证那是空消息的正确签名。