34

I need to use SecureString for a Microsoft's class and i found the following code on the internet:

public static class SecureStringExt
{
    public static SecureString ConvertToSecureString(this string password)
    {
        if (password == null)
            throw new ArgumentNullException("password");

        unsafe //Red highlighted line
        {
            fixed (char* passwordChars = password)
            {
                var securePassword = new SecureString(passwordChars, password.Length);
                securePassword.MakeReadOnly();
                return securePassword;
            }
        }
    }
}

The only problem is that the unsafe keyword keeps throwing me error saying Cannot use unsafe construct in safe context. Unfortunately i couldn't find why is this happening...

Note: The above code runs in LINQPad but not in VS2013 (with resharper).

CodeArtist
  • 5,534
  • 8
  • 40
  • 65
  • 6
    I don't understand why you need to use unsafe here, you create secure string without unsafe code. Check my answer. – mybirthname Sep 20 '14 at 22:33
  • 3
    The documentation says you shouldn't use that constructor. See http://msdn.microsoft.com/en-us/library/176bafkd(v=vs.110).aspx Use the code @mybirthname gave in his answer – MicroVirus Sep 20 '14 at 22:39

2 Answers2

70

I am not sure if you need unsafe code in that case (see answer of @mybirthname).

But when unsafe code is needed, it can be enabled in Project properties.

  • In the main menu, click Project and then <ProjectName> properties...
  • Click on the Build page.
  • Select Allow unsafe code.

Allow unsafe code

Or one can specify /unsafe compiler option explicitly.

AlexD
  • 32,156
  • 3
  • 71
  • 65
  • Can that be declared? – jww Sep 20 '14 at 22:32
  • @jww What do you mean? – AlexD Sep 20 '14 at 22:37
  • By using attributes. Something like [Declarative Security](http://msdn.microsoft.com/en-us/library/kaacwy28%28v=vs.110%29.aspx). It seems better to turn it off on an as-needed basis, rather than turning it off everywhere. – jww Sep 20 '14 at 23:31
  • 1
    @jww I completely agree that enabling unsafe compilation should be minimized. However I doubt that attributes will help with `unsafe {...}`. Compiler gives `error CS0227: Unsafe code may only appear if compiling with /unsafe`. If you have an idea how to do it, let me know please. – AlexD Sep 21 '14 at 00:50
  • that's what I was asking :) – jww Sep 21 '14 at 00:52
11
    public static SecureString GetSecureString(string password)
    {
        SecureString secureString = new SecureString();

        foreach (char c in password)
        {
            secureString.AppendChar(c);
        }

        secureString.MakeReadOnly();
        return secureString;
    }

You can make same thing without unsafe code.

mybirthname
  • 17,949
  • 3
  • 31
  • 55