Question

I have performed some research on a variety of conversion methods, and have arrived on the usage of explicit or implicit operators.

Noting that System.Security.SecureString is a sealed class (it can not be inherited from), is it possible to write an explicit or implicit operator that is able to perform conversion between a System.Security.SecureString and a System.String (utilizing the methodology described here).

For instance, I do know you must write the operator in a (partial) class of the object being converted. Therefore, I figured the best way to do this was to inherit the class, and write the necessary operators.

Is it possible to a) perform a conversion using an explicit or implicit operator for a System.Security.SecureString to a System.String, b) perform a conversion of a class object who's class is sealed?

If not, is there another method outside of utilizing a class method, that will perform the conversion?

Please provide a pragmatic answer assuming I am a consumer of Microsoft's products.

Was it helpful?

Solution 2

As has been discussed elsewhere, the simple answer to your original question is no, it's not possible to add an operator to SecureString to do anything as it's sealed.

The answer to "(b) perform a conversion of a class object who's class is sealed" is more complex.

What you can do is create your own struct, eg called EncryptedString that has a SecureString as a private field. You are then free to add any SecureString <-> string conversion and comparison operators and methods to that struct to meet your needs. That isn't strictly speaking perform[ing] a conversion of a class object, instead it is composing a new type to meet your needs. As the saying goes "Composition over inheritance" (see http://en.wikipedia.org/wiki/Composition_over_inheritance), so actually this approach both meets your needs and is seen as OO "best practice".

Now for the disclaimer:

The whole point of SecureString is that, unlike string, it is secure. If you start converting a SecureString to a string (or allowing a SecureString to be created from a string), you'll undermine the whole point of the class.

So if you need to do comparisons, please use Marshal.SecureStringToBSTR() and Marshal.StringToBSTR() to convert the two to BSTR structures, compare them, wipe the memory and free it, or some similar mechanism to minimize the chances of compromising the security of SecureStrings.

OTHER TIPS

Noting that System.Security.SecureString is a sealed class, is it possible to write an explicit or implicit operator that is able to perform conversion between a System.Security.SecureString and a System.String?

Yes, if you are a member of the Base Class Library team you can do so. Of course, doing so is a bad idea.

If you are not a member of the BCL team then no. You need to be able to change the source code of one of the two classes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top