Search code examples
c#rsasha256rsa-sha256

How to do signature using SHA256withRSA algorithm in C#


I tried search solution to my query, I couldn't able find match I am looking for, this is very basic, but to my better understanding I am posting below query.

I want to encode and do signature for my string using "SHA256withRSA" algorithm. I could able to see lot of sample code in java using "SHA256withRSA" but in C# I could see first we are hashed data using SHA256 then we are sign hash using RSACryptoServiceProvider.

My questions are:

  1. In C# we have separate algorithm of "SHA256withRSA", If yes, help with sample code.

  2. If no then what would be better approach to achieve it in C#?


Solution

  • Do not use RSACryptoServiceProvider unless you are doing interop with CAPI, like opening a named key.

    To do RSA signing with SHA-(2-)256:

    byte[] signature = rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
    

    You can get the RSA object from a cert:

    using (RSA rsa = cert.GetRSAPrivateKey())
    {
        ...
    }
    

    Or you can make one up from existing RSA parameters:

    using (RSA rsa = RSA.Create(rsaParameters))
    {
       ...
    }
    

    Or you can make up a new key from nothing:

    using (RSA rsa = RSA.Create(2048))
    {
        // you’ll need to save the parameters somewhere to have a stable key
        rsaParameters = rsa.ExportParameters(true));
        ...
    }