phpseclib在C#中签名并验证

时间:2014-03-19 20:29:38

标签: c# phpseclib

我需要使用RSA phpseclib使用私钥对字符串进行签名,然后在C#中进行验证。我已经看到很多关于如何在C#中加密并在php中解密的例子,但没有一个如何在php中签名字符串并在.NET中验证。

这是php代码:

include('Crypt/RSA.php');

$info = "Something";
$PrivateKey= "<RSAKeyValue><Modulus>3C5QWo4H+............"; //long string
$unsignedString = base64_encode($info);
$signedString = HashAndSignBytes($info, $PrivateKey);
file_put_contents('file.txt', $unsignedString."\n".$signedString);

function HashAndSignBytes($stringToSign, $Key) {
  $rsa = new Crypt_RSA();
  $rsa->loadKey($Key); // private key
  $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
  $signature = $rsa->sign($stringToSign);
  return base64_encode($signature);
}

这是我尝试读取文件并在C#中验证它:

const string publicKey = @"<RSAKeyValue><Modulus>3C5QWo4H.....";
TextReader reader = new StreamReader(path, Encoding.ASCII);
var unsignedString = reader.ReadLine();
var signedString = reader.ReadLine();
reader.Close();

if (VerifySignedHash(unsignedString,signedString, publicKey)) {
  //some code
}

private bool VerifySignedHash(string stringToVerify, string signedString, string publicKey)
    {
        var byteConverter = new ASCIIEncoding();
        var dataToVerify = Convert.FromBase64String(stringToVerify);
        var signedData = Convert.FromBase64String(signedString);
        try
        {
            // Create a new instance of RSACryptoServiceProvider using the 
            // key from RSAParameters.
            var rsaAlg = new RSACryptoServiceProvider();
            rsaAlg.FromXmlString(publicKey);

            // Verify the data using the signature.  Pass a new instance of SHA1CryptoServiceProvider
            // to specify the use of SHA1 for hashing.
            return rsaAlg.VerifyData(dataToVerify, new SHA1CryptoServiceProvider(), signedData);

        }
        catch (CryptographicException e)
        {
            Console.WriteLine(e.Message);
            return false;
        }
    } 

验证失败......

1 个答案:

答案 0 :(得分:4)

在你的&#34;签署&#34;代码,你base64encode原始字符串,然后将该字符串写入输出文件。但是,在C#端,您将该值读入unsignedString,但从不反转base64编码。

最终结果是您尝试验证base64Encoded字符串的字节,而不是数据本身,因此VerifyData步骤失败。

认为这是你的问题。

修改以下行可能会解决问题:

var dataToVerify = Convert.FromBase64String(stringToVerify);