在Java中生成RSA签名,但在C 中验证签名失败

Generate RSA signature in Java but verify the signature failed in C++

本文关键字:验证 失败 但在 签名 Java RSA      更新时间:2023-10-16

最近我需要使用RSA在Java中签名字符串,并在C 中验证签名。

在Java中,现在我认为一切都还好,我创建了public.keystore和private.keysore。可以成功地签署数据。但是当我尝试在C 中验证它时,它显示签名失败。<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<</p>

这是我的Java代码,在Java中,我将数据签名到base64string,然后将其保存在我的本地上,为" sig.dat",我签名的数据将其保存为" signed.dat":blockquote>

public static String sign(byte[] data, String privateKey) throws Exception {
    byte[] keyBytes = Base64.decodeBase64(privateKey);
    Base64.decodeBase64(privateKey);
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initSign(privateK);
    signature.update(data);
    return Base64.encodeBase64String(signature.sign());
}

生成sig.dat and签名。dat文件:

String signStr = RSAUtils.sign("123".getBytes(), privateKey2);
boolean result = RSAUtils.verify("123".getBytes(), publicKey2, signStr);
System.out.println("result:" + result);

FileOutputStream fos = new FileOutputStream("signed.dat");
DataOutputStream dos = new DataOutputStream(fos);
dos.write("123".getBytes());
dos.close();
FileOutputStream fos2 = new FileOutputStream("sig.dat");
DataOutputStream dos2 = new DataOutputStream(fos2);
dos2.write(Base64.decodeBase64(signStr));

这是我的C 代码,我加载文件:" signed.dat"answers" sig.dat"使用API验证它:

void Verify()
{   
    //Read public key
    CryptoPP::ByteQueue bytes;
    FileSource file("pubkey.txt", true, new Base64Decoder);
    file.TransferTo(bytes);
    bytes.MessageEnd();
    RSA::PublicKey pubKey;
    pubKey.Load(bytes);
    RSASSA_PKCS1v15_SHA_Verifier verifier(pubKey);
    //Read signed message
    string signedTxt;
    FileSource("signed.dat", true, new StringSink(signedTxt));
    string sig;
    FileSource("sig.dat", true, new StringSink(sig));
    string combined(signedTxt);
    combined.append(sig);
    cout << "signedTxt------------:" << signedTxt<< endl;
    cout << "sig------------:" << sig << endl;
    //Verify signature
    try
    {
        StringSource(combined, true,
            new SignatureVerificationFilter(
                verifier, NULL,
                SignatureVerificationFilter::THROW_EXCEPTION
            )
        );
        cout << "Signature OK" << endl;
    }
    catch (SignatureVerificationFilter::SignatureVerificationFailed &err)
    {
        cout << err.what() << endl;
    }
}
string combined(signedTxt);
combined.append(sig);

将数字签名附加到要检查签名的数据上没有意义。创建它时,数字签名不包括本身:因此,为什么将其包括在要验证的数据中?