“Invalid provider type specified” CryptographicException when trying to load private key of certificate

前端 未结 18 2906
盖世英雄少女心
盖世英雄少女心 2020-11-29 22:04

I\'m trying to read the private key of a certificate which has been shared with me by a third-party service provider, so I can use it to encrypt some XML before sending it t

18条回答
  •  眼角桃花
    2020-11-29 22:33

    In my case, the following code worked fine in localhost (both NET 3.5 and NET 4.7):

     var certificate = new X509Certificate2(certificateBytes, password);
    
     string xml = "....";
     XmlDocument xmlDocument = new XmlDocument();
     xmlDocument.PreserveWhitespace = true;
     xmlDocument.LoadXml(xml);
    
     SignedXml signedXml = new SignedXml(xmlDocument);
     signedXml.SigningKey = certificate.PrivateKey;
    
     //etc...
    

    But it failed when deployed to an Azure Web App, at certificate.PrivateKey

    It worked by changing the code as follows:

     var certificate = new X509Certificate2(certificateBytes, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
                                                                       //^ Here
     string xml = "....";
     XmlDocument xmlDocument = new XmlDocument();
     xmlDocument.PreserveWhitespace = true;
     xmlDocument.LoadXml(xml);
    
     SignedXml signedXml = new SignedXml(xmlDocument);
     signedXml.SigningKey = certificate.GetRSAPrivateKey();
                                          // ^ Here too
    
     //etc...
    

    A whole day of work lost thanks to Microsoft Azure, once again in my life.

提交回复
热议问题