X509Certificate2 构造函数抛出 磁盘上 space 不足

X509Certificate2 Constructor Throwing There is not enough space on the disk

突然之间,无需部署或进行任何其他环境更改,我们就可以

There is not enough space on the disk. at System.Security.Cryptography.CryptographicException.ThrowCryptographicException (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089) at System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromBlob (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089) at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089) at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor (System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089) at [OUR CODE]

这一行:

var certificateByes = Convert.FromBase64String(clientCertificateBody);
factory.Credentials.ClientCertificate.Certificate = new X509Certificate2(certificateByes);

我正在努力了解这会如​​何突然在 Azure Web 应用程序的上下文中中断。我们上次部署是在 11 月 20 日,昨天开始投掷。这个基本功能已经使用了几个月没有问题。

我们之前确实在这方面遇到过麻烦,我们正在读取的字符串是从密钥库中检索到的,但同样,这里没有任何改变。

我读到过不同类型的错误here and ,但我们的错误消息有所不同,这几个月来一直运行良好。

这是否与应用 运行 的时间长短有关,或者其他一些缓存问题正在填满某个临时存储位置?

经过几个小时的 research/debugging 我知道了以下内容:

  • 我们有一个逻辑错误,我们在每次加载它而不是缓存它时都创建一个新的 X509Certificate2 对象
  • 我们不得不更频繁地创建这些证书

一旦我们解决了这两个问题,并在创建证书时遵循了 here 中的提示 #5,我们就不会再看到这些错误了。作为参考,提示是不要从字节数组创建这些证书对象,因为临时文件是在幕后为您创建的,它们可能无法清理。相反,我们正在做作者建议的事情:

var bytes = new byte[]{}; //byte array representing cert body
var file = Path.Combine(Path.GetTempPath(), "Cert" + Guid.NewGuid());
try
{
    File.WriteAllBytes(file, bytes);
    return new X509Certificate2(file, /* ...options... */);
}
finally
{
    File.Delete(file);
}

我 运行 遇到了同样的问题,一个在应用服务上启用了 MSI 的服务计划。 通过代码清除包括所有目录和文件在内的临时路径无效。我猜私钥文件夹中有 65535 个文件,我检查了 Octopus deploy blog article 并尝试从代码中删除这么多位置,因为在 Kudo 或 Console 中你看不到它,但错误一直被抛出。重新部署到另一个应用服务计划不是一个选项。

所以关于 Whosebug 的另一个问题有一个更干净的解决方案的答案:

X509Certificate2 constructor throwing Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: There is not enough space on the disk

解决方案:使用 EmphemeralKeySet StorageFlag。