繁体   English   中英

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

[英]Generate RSA signature in Java but verify the signature failed in C++

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

在Java中,现在我觉得一切都好,我创建了public.keystore和private.keysore,并且可以成功对数据进行签名和验证。但是当我尝试在C++中验证它时,它显示签名失败。

这是我的 Java 代码,在 Java 中,我将数据签名为 base64String,并将其保存在本地作为“sig.dat”,我签名的数据将其保存为“signed.dat”:

 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 和 signed.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”和“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);

将数字签名附加到要检查签名的数据是没有意义的。 数字签名在您创建时并未包含自身:为什么要将其包含在要验证的数据中?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM