簡體   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