最近我需要使用RSA在Java中签名字符串,并在C ++中验证签名。
在Java中,现在我认为每件事都没问题,我创建了public.keystore和private.keysore,并且可以成功签署和修复数据。但是当我尝试在C ++中验证它时,它显示签名失败。 / p>
这是我的Java代码,在java中,我将数据签名为base64String,并将其保存在我的本地作为" sig.dat",我签署的数据我保存为&#34 ; 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;
}
}
答案 0 :(得分:-2)
string combined(signedTxt);
combined.append(sig);
将数字签名附加到要检查其签名的数据是没有意义的。创建时,数字签名并不包含在内:为什么要将它包含在要验证的数据中?