title: How can I sign a file using RSA and SHA256 with .NET?
body: <p>My application will take a set of files and sign them. (I'm not trying to sign an assembly.)   There is a .p12 file that I get the private key from.</p>
  <p>This is the code I was trying to use, but I get a <code>System.Security.Cryptography.CryptographicException &quot;Invalid algorithm specified.&quot;</code>.</p>
  <pre><code>X509Certificate pXCert = new X509Certificate2(@&quot;keyStore.p12&quot;, &quot;password&quot;);
  RSACryptoServiceProvider csp = (RSACryptoServiceProvider)pXCert.PrivateKey;
  string id = CryptoConfig.MapNameToOID(&quot;SHA256&quot;);
  return csp.SignData(File.ReadAllBytes(filePath), id);
  </code></pre>
  <p>According to this <a href="https://stackoverflow.com/questions/7433074/why-am-i-getting-invalid-algorithm-specified-exception/7433202#7433202">answer</a> it can't be done (the <code>RSACryptoServiceProvider</code> does not support SHA-256), but I was hoping that it might be possible using a different library, like Bouncy Castle.</p>
  <p>I'm new to this stuff and I'm finding Bouncy Castle to be very confusing.  I'm porting a Java app to C# and I have to use the same type of encryption to sign the files, so I am stuck with RSA + SHA256.</p>
  <p>How can I do this using Bouncy Castle, OpenSSL.NET, Security.Cryptography, or another 3rd party library I haven't heard of?  I'm assuming, if it can be done in Java then it can be done in C#.</p>
  <p>UPDATE:</p>
  <p>this is what I got from the link in poupou's anwser</p>
  <pre><code>X509Certificate2 cert = new X509Certificate2(KeyStoreFile, password&quot;);
  RSACryptoServiceProvider rsacsp = (RSACryptoServiceProvider)cert.PrivateKey;
  CspParameters cspParam = new CspParameters();
  cspParam.KeyContainerName = rsacsp.CspKeyContainerInfo.KeyContainerName;
  cspParam.KeyNumber = rsacsp.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2;
  RSACryptoServiceProvider aescsp = new RSACryptoServiceProvider(cspParam);
  aescsp.PersistKeyInCsp = false;
  byte[] signed = aescsp.SignData(File.ReadAllBytes(file), &quot;SHA256&quot;);
  bool isValid = aescsp.VerifyData(File.ReadAllBytes(file), &quot;SHA256&quot;, signed);
  
         
  </code></pre>
  <p>The problem is that I'm not getting the same results as I got with the original tool.  As far as I can tell from reading the code the CryptoServiceProvider that does the actual signing is not using the PrivateKey from key store file.  Is that Correct?</p>