2016-11-17 65 views
0

我正在从S3中为ASP.NET云应用程序运行证书存储。 S3CertificateStore类从S3中读取.pfx文件和密码文件,并在内存中创建证书。.NET从AWS S3读取加密文件 - 某些文件在产品上失败,在开发中成功

private void LoadPrivateCerts(X509Certificate2Collection certificates) 
     { 
      var s3Files = S3Facade.ListObjects(Config.Bucket, Config.PrivatePath).ToList(); 

      foreach (var filePath in s3Files) 
      { 
       if (filePath.EndsWith(".pass") || filePath.EndsWith("/")) 
       { 
        continue; 
       } 
       try 
       { 
        var certBytes = S3Facade.GetObject(Config.Bucket, filePath); 
        var pwdBytes = S3Facade.GetObject(Config.Bucket, filePath + ".pass"); 
        var pwd = Encoding.UTF8.GetString(pwdBytes); 

        var cert = new X509Certificate2(certBytes, pwd, X509KeyStorageFlags.Exportable); // needs to be exportable! 
        certificates.Add(cert); 
       } 
       catch (Exception e) 
       { 
        exceptions.Add(e); 
       } 
      } 
     } 

当我在本地运行时,所有证书都从S3中拉出并正确重建。但是,当我在EC2实例上运行代码时,某些证书没有问题,而其他证书都失败了。 (相同的总是失败)。

EXCEPTION: The system cannot find the file specified. 

    at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) 
    at System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromBlob(Byte[] rawData, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx) 
    at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob(Byte[] rawData, Object password, X509KeyStorageFlags keyStorageFlags) 

我很困惑。在工作中可能会出现某种字符编码差异吗?我不认为任何密码都有高位字符,但我可能在某些东西已经消失后看到它们。

有什么建议吗?

+0

所有文件都在同一个存储桶中,并且都具有相同的所有者。如果我添加到日志记录中,当代码在本地运行时,可以看到.pfx和.pfx.pass文件具有相同的字节数。 –

+0

您是否尝试过使用File.ReadAllBytes()将其加载到字节数组中并将该数组传递给X509Certificate2构造函数?例如,底层加密库不像符号链接,所以也许这些文件有一个不满意的属性。 – bartonjs

+0

谢谢bartonjs。在此设置中,文件实际上是字节数组,正如您所建议的那样,在我们尝试构建证书时。 –

回答

0

我发现了一个可行的解决方案。如果将IIS AppPool设置“加载用户配置文件”设置为True,则证书构建工作。在.ebextension文件下面的脚本似乎做的伎俩:

c:\windows\system32\inetsrv\appcmd.exe set config /section:applicationPools "/[name='DefaultAppPool'].processModel.loadUserProfile:true" 

我还是不明白,为什么证书建筑是一贯成功的一些证书,始终没有给别人,这种变化之前。

+0

下面是解释为什么加载用户配置文件影响证书加载的不同答案。 http://stackoverflow.com/a/17149834/492405 – vcsjones