签署哈希时遇到问题

时间:2014-08-27 03:53:15

标签: c# hash cryptography sign

我有以下从MSDN复制的代码。我必须用公钥签名哈希。当我添加

RSA.FromXmlString(PublicKey);

要跟随代码,它会显示异常

Object contains only the public half of a key pair. A private key must also be provided.

我做错了什么?这是一个正确的方式标志给定公钥的哈希?

我在Windows 7 Pro 64 bis OS上使用Microsoft Visual C#Express 2010。

    try
    {
        //Create a new instance of RSACryptoServiceProvider.

        RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
        RSA.FromXmlString(PublicKey);
        //The hash to sign.
        byte[] Hash = { 59, 4, 248, 102, 77, 97, 142, 201, 210, 12, 224, 93, 25, 41, 100, 197, 213, 134, 130, 135 };

        //Create an RSAOPKCS1SignatureFormatter object and pass it the 
        //RSACryptoServiceProvider to transfer the key information.
        RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter((AsymmetricAlgorithm)RSA);

        //Set the hash algorithm to SHA1.
        RSAFormatter.SetHashAlgorithm("SHA1");

        //Create a signature for HashValue and return it.
        byte[] SignedHash = RSAFormatter.CreateSignature(Hash);

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

    }

编辑:

是什么
RSA.FromXmlString(PublicKey);

做什么?我签署此哈希时是否需要它?

1 个答案:

答案 0 :(得分:1)

问题是用公钥签名。您可以使用私钥对哈希进行签名。公钥用于验证。

填写RSAParameters RSAKeyInfo

你需要RSAParameters看看这个。 How can I fill in RSAParameters value in c#

RSA.FromXmlString(RSAKeyInfo);