title: RSA Signing with .Net and verifying with OpenSSL command
body: <p>I'm trying to sign a simple data with C# using Sha1 hash and RSA and then verify it with the OpenSSL command.</p>
  
  <p>For my tests, I've taken the localhost certificate that is preexisting on Windows.</p>
  
  <p>Here's the code used with C#:</p>
  
  <pre class="lang-csharp prettyprint-override"><code>static void Main(string[] args)
  {
      string sValTest = "sampledata";
      byte[] signature = Sign(sValTest, "localhost");
      string b64 = Convert.ToBase64String(signature);
      bool verified = Verify(sValTest, signature, @"pathToCer");
  }
  
  static byte[] Sign(string text, string certSubject)
  {
      X509Store my = new X509Store(StoreName.My, StoreLocation.LocalMachine);
      my.Open(OpenFlags.ReadOnly);
  
      RSACryptoServiceProvider csp = null;
      foreach (X509Certificate2 cert in my.Certificates)
      {
          if (cert.Subject.Contains(certSubject))
          {
              csp = (RSACryptoServiceProvider)cert.PrivateKey;
              break;
          }
      }
  
      SHA1Managed sha1 = new SHA1Managed();
      byte[] data = Enconding.ASCII.GetBytes(text);
      byte[] hash = sha1.ComputeHash(data);
  
      return csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
  }
  
  static bool Verify(string text, byte[] signature, string certPath)
  {
      X509Certificate2 cert = new X509Certificate2(certPath);
      RSACryptoServiceProvider csp = RSACryptoServiceProvider)cert.PublicKey.Key;
  
      SHA1Managed sha1 = new SHA1Managed();
      byte[] data = Encoding.ASCII.GetBytes(text);
      byte[] hash = sha1.ComputeHash(data);
  
      return csp.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signature);
  }
  </code></pre>
  
  <p>(In that example, <code>verified</code> yields <code>true</code>)</p>
  
  <p>I sent the public part of the PFX to my linux computer as well as the signature as base 64.</p>
  
  <p>I then did the following:</p>
  
  <pre class="lang-shell prettyprint-override"><code>base64 --decode sig.b64 &gt; sig
  openssl x509 -inform der -in localhost.cer  -out localhost.pem
  openssl x509 -pubkey -noout -in localhost.pem &gt; localhost.pub.pem
  echo -n "sampledata" | openssl dgst -verify localhost.pub.pem -signature sig
  </code></pre>
  
  <p>Which ends with a <code>Verification Failure</code>.</p>
  
  <p>I checked the serial number of the certificates on both sides and it matches.
  Just in case, I also checked the md5 of the signature in both stations, all clear.</p>
  
  <p>Any pointers on where is the obvious fail?</p>