我正试图使用C#RSACryptoProvider.VerifyData
验证OpenSSL
签名(created using openssl_sign with SHA1 in PHP)
。使用正确的公钥证书返回false。
你知道如何成功做到这一点吗?
编辑:
我尝试使用以下代码使用BouncyCastle验证OpenSSL SHA1签名,但验证失败。签名的计算方式是否不同?如何使用OpenSSL创建可由验证的签名。NET?
byte[] signatureBytes = UTF8Encoding.Default.GetBytes(signature);
byte[] dataBytes = UTF8Encoding.Default.GetBytes(data);
StreamReader sr = new StreamReader(Path.Combine(@"C:test", @"testtest.crt"));
PemReader pr = new PemReader(sr);
Org.BouncyCastle.X509.X509Certificate cert = (Org.BouncyCastle.X509.X509Certificate)pr.ReadObject();
ISigner sig = SignerUtilities.GetSigner("SHA1WithRSAEncryption");
sig.Init(false, cert.GetPublicKey());
sig.BlockUpdate(dataBytes, 0, dataBytes.Length);
if (sig.VerifySignature(signatureBytes)) {
Console.WriteLine("all good!");
}
PHP代码:
function signTokenWithPrivateKey($message, $keyLocation) {
try {
if (file_exists($keyLocation)) {
$privateKey= openssl_get_privatekey(file_get_contents($keyLocation));
$signature = '';
if (!openssl_sign($message, $signature, $privateKey)) {
die('Failed to encrypt');
}
openssl_free_key($privateKey);
}
}
catch (Exception $ex) {
}
return $signature;
}
下面的代码应该能帮你完成任务。它从给定的文件路径加载证书,然后使用公钥根据给定的签名验证数据。如果有效,则返回true。
byte[] signature = Convert.FromBase64String(Signature);
byte[] data = Encoding.UTF8.GetBytes(Data);
var x509 = new X509Certificate2(Path.Combine(@"C:test", @"testtest.crt"));
var rsa = x509.PublicKey.Key as RSACryptoServiceProvider;
if (rsa == null)
{
LogMessage("Authorize", "Invalid", Level.Alert);
return false;
}
string sha1Oid = CryptoConfig.MapNameToOID("SHA1");
//use the certificate to verify data against the signature
bool sha1Valid = rsa.VerifyData(data, sha1Oid, signature);
return sha1Valid;