Search code examples
c#hashcryptographysign

Having issue with signing a hash


I have following code copied from MSDN. I have to sign a hash with public key. When I add

RSA.FromXmlString(PublicKey);

To follownig code it is showing exception saying

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

What am I doing wrong? Is this a correct way a sign a hash with given public key?

I am using Microsoft Visual C# Express 2010 on Windows 7 Pro 64 bis OS.

    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);

    }

EDIT: What Does the

RSA.FromXmlString(PublicKey);

do? Do I need it when I sign this hash?


Solution

  • The problem is signing with public key. You can sign the hash with private key. Public key is using for verification.

    Fill the RSAParameters RSAKeyInfo

    You need to RSAParameters look at this. How can I fill in RSAParameters value in c#

    RSA.FromXmlString(RSAKeyInfo);