title: C#: Keyset does not exist in Azure Functions on consumption plan
body: <p>Many of us faced "Keyset does not esist" exception when trying to work with X509Certificate2.
  The symptoms are:</p>
  
  <ol>
  <li><p>You load .pfx into X509Certificate2</p></li>
  <li><p>You use it in any operation requiring private key</p></li>
  <li><p>You get "Keyset does not exist" exception.</p></li>
  </ol>
  
  <p>In code it looks like the following:</p>
  
  <pre><code>string CreateJWTToken(byte[] certificate, string psw, string serviceUserIss, string serviceUserSub, string serviceUserAud)
      {
          using (X509Certificate2 combinedCertificate = new X509Certificate2(certificate, psw,
                X509KeyStorageFlags.MachineKeySet
              | X509KeyStorageFlags.PersistKeySet 
              | X509KeyStorageFlags.Exportable))
          {
              var signingKey = new X509SecurityKey(combinedCertificate);
              var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(signingKey, SecurityAlgorithms.RsaSha256);
              var header = new JwtHeader(credentials);
              var payload = new JwtPayload
              {
                 { "iss", serviceUserIss},
                 { "sub", serviceUserSub},
                 { "aud", serviceUserAud},
                 { "exp", $"{unixTimestamp}"}
              };
              var secToken = new JwtSecurityToken(header, payload);
              var handler = new JwtSecurityTokenHandler();
              return handler.WriteToken(secToken); // here exception is thrown
          }
      }
  </code></pre>
  
  <p>It works fine locally, and even in local Azure Functions host, but for some reason it sometimes (like in 5% cases) throws "Keyset does not exist" when run in Azure Function (timer-triggered) on consumption plan.</p>