xamarin.android X509Certificate2 constructor/import 使用 SecureString 密码而不是纯字符串失败

xamarin.android X509Certificate2 constructor/import failed with SecureString password instead of plain string

我在 PFX 文件中有一个带有私钥的自签名证书。它作为资源添加到 Visual Studio 2015 年的 Xamarin.Android c# 应用程序中。我将其用作客户端证书以建立与 Web 服务的安全 HTTPS 连接。

为此,我将证书导入到 X509Certificate2 对象中。当我以纯文本(字符串)形式提供证书私钥的密码时,它运行良好,但我想使用使用 SecureStringX509Certificate2 constructors/import 方法。

不幸的是他们扔了

'Unable to decode certificate exception'

在那种情况下,无论使用构造函数还是导入方法,无论证书是作为字节[]还是文件名传递。

我的问题是为什么它在 SecureString 中使用密码失败,而在纯字符串中运行良好,以及如何继续使用 SecureString 作为密码。

谢谢!

格奥尔基

只是补充一下,具有相同证书文件和密码的相同代码在 Windows 10、.NET 4 下运行良好 否则 Xamarin.Android 是 6.1.1.1,Xamarin 扩展是 4.1.1.3,最小 android 目标是 API 级别 19,在 Android 6.0

上测试

原因是 SecureString 在 Mono 中不完全支持。请参阅 source 以获取评论。它调用证书 class' Import 方法并传递 (string)null:

[MonoTODO ("SecureString is incomplete")]
public override void Import (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
{
    Import (rawData, (string) null, keyStorageFlags);
}

另请注意,SecureString 不会使您的数据达到 100% secure:

Overall, SecureString is more secure than String because it limits the exposure of sensitive string data. However, those strings may still be exposed to any process or operation that has access to raw memory, such as a malicious process running on the host computer, a process dump, or a user-viewable swap file. Instead of using SecureString to protect passwords, the recommended alternative is to use an opaque handle to credentials that are stored outside of the process.