问题
SecureString is not friendly with PCL.I Know this problem can be worked around using dependency injection But I don't want to do that instead I would like to use something in PCL that would be equivalent to SecureString.
But so far I am not able to find any other class or framework.
回答1:
System.Security.*
is mostly not present in any Portable Class Library profile. You might be able to find this in some of the higher versions of .NET Standard, which provide a much bigger subset of .NET.
You best bet, if you are fixed on using PCL is to use libraries such as PCLCrypto or roll your own code per platform and inject that at runtime.
回答2:
You can use the so called bait-and-switch trick.
In this case it means that you need to create one strong named PCL assembly containing an implementation stub of SecureString
, including those methods and properties of SecureString
that you intend to use in your application.
For example:
namespace System.Security {
public class SecureString {
public SecureString() { }
public int Length { get; }
public void AppendChar(char c) { }
}
}
It is crucial that the properties and methods you include use the exact same signature as the original class, since you are going to rely on signature equivalence when using this trick. On the other hand, you do not need to provide a functioning implementation, since this will be handled by the built-in SecureString
on each respective platform.
Next, you need to create one assembly per platform with the same strong name as the PCL assembly, simply containing a type forwarding directive to SecureString
:
[assembly: TypeForwardedTo(typeof(SecureString))]
This relies on the fact that even if no PCL profile defines SecureString
, each respective platform does. So what you are actually doing in the platform specific DLL is to point out the implementation of SecureString
that you want to use in place of the PCL declaration.
With the PCL and platform specific assemblies in place, and assuming they all share the same name (e.g. securestring.dll) and are signed with the same key, you can now use SecureString
in your implementation.
Assume for example that you have a PCL assembly foo.Core.dll that is consumed by the platform specific applications foo.Windows.dll, foo.Android.dll and foo.iOS.dll, and where foo.Core.dll uses SecureString
. Then you should organize your solution like this:
- foo.Core.dll should reference the PCL version of securestring.dll.
- foo.Windows.dll should reference foo.Core.dll and the Windows version of securestring.dll.
- foo.Android.dll should reference foo.Core.dll and the Android version of securestring.dll.
- foo.iOS.dll should reference foo.Core.dll and the iOS version of securestring.dll.
来源:https://stackoverflow.com/questions/43751029/xamarin-securestring-equivalent-in-pcl