【问题标题】:C# - compare two SecureStrings for equalityC# - 比较两个 SecureString 是否相等
【发布时间】:2023-03-11 11:45:02
【问题描述】:

我有一个带有两个 PasswordBox 的 WPF 应用程序,一个用于密码,另一个用于第二次输入密码以进行确认。我想使用PasswordBox.SecurePassword 来获取密码的SecureString,但是在我接受密码之前,我需要能够比较两个PasswordBoxes 的内容以确保相等。但是,两个相同的 SecureString 不被认为是相等的:

var secString1 = new SecureString();
var secString2 = new SecureString();
foreach (char c in "testing")
{
    secString1.AppendChar(c);
    secString2.AppendChar(c);
}
Assert.AreEqual(secString1, secString2); // This fails

我在考虑比较 PasswordBoxes 的 Password 属性会破坏仅访问 SecurePassword 的点,因为我会读取纯文本密码。在不牺牲security的情况下比较两个密码应该怎么做?

编辑:基于this question,我正在查看this blog post 关于“使用 Marshal 类将 SecureString 转换为 ANSI 或 Unicode 或 BSTR”,然后也许我可以比较那些。

【问题讨论】:

    标签: c# passwords equals securestring passwordbox


    【解决方案1】:

    看来您可以使用this 来比较两个SecureStrings。

    它使用不安全的代码来遍历字符串:

    bool SecureStringEqual(SecureString s1, SecureString s2)  
    {  
        if (s1 == null)  
        {  
            throw new ArgumentNullException("s1");  
        }  
        if (s2 == null)  
        {  
            throw new ArgumentNullException("s2");  
        }  
    
        if (s1.Length != s2.Length)  
        {  
            return false;  
        }  
    
        IntPtr bstr1 = IntPtr.Zero;  
        IntPtr bstr2 = IntPtr.Zero;  
    
        RuntimeHelpers.PrepareConstrainedRegions();  
    
        try 
        {  
            bstr1 = Marshal.SecureStringToBSTR(s1);  
            bstr2 = Marshal.SecureStringToBSTR(s2);  
    
            unsafe 
            {  
                for (Char* ptr1 = (Char*)bstr1.ToPointer(), ptr2 = (Char*)bstr2.ToPointer();  
                    *ptr1 != 0 && *ptr2 != 0;  
                     ++ptr1, ++ptr2)  
                {  
                    if (*ptr1 != *ptr2)  
                    {  
                        return false;  
                    }  
                }  
            }  
    
            return true;  
        }  
        finally 
        {  
            if (bstr1 != IntPtr.Zero)  
            {  
                Marshal.ZeroFreeBSTR(bstr1);  
            }  
    
            if (bstr2 != IntPtr.Zero)  
            {  
                Marshal.ZeroFreeBSTR(bstr2);  
            }  
        }  
    } 
    

    我在下面修改了它以在没有不安全代码的情况下工作(请注意,在调试时您可以看到纯文本字符串):

      Boolean SecureStringEqual(SecureString secureString1, SecureString secureString2)
      {
         if (secureString1 == null)
         {
            throw new ArgumentNullException("s1");
         }
         if (secureString2 == null)
         {
            throw new ArgumentNullException("s2");
         }
    
         if (secureString1.Length != secureString2.Length)
         {
            return false;
         }
    
         IntPtr ss_bstr1_ptr = IntPtr.Zero;
         IntPtr ss_bstr2_ptr = IntPtr.Zero;
    
         try
         {
            ss_bstr1_ptr = Marshal.SecureStringToBSTR(secureString1);
            ss_bstr2_ptr = Marshal.SecureStringToBSTR(secureString2);
    
            String str1 = Marshal.PtrToStringBSTR(ss_bstr1_ptr);
            String str2 = Marshal.PtrToStringBSTR(ss_bstr2_ptr);
    
            return str1.Equals(str2);
         }
         finally
         {
            if (ss_bstr1_ptr != IntPtr.Zero)
            {
               Marshal.ZeroFreeBSTR(ss_bstr1_ptr);
            }
    
            if (ss_bstr2_ptr != IntPtr.Zero)
            {
               Marshal.ZeroFreeBSTR(ss_bstr2_ptr);
            }
         }
      }
    

    【讨论】:

    • SecureString 不会覆盖 Equals,所以这也只是检查引用是否相等。
    • SwDevMan81:social.msdn 链接的建议对我有用。我使用csharpfriends.com/Articles/getArticle.aspx?articleID=351 在我的项目中允许不安全的代码。您应该提供您作为答案链接的 MSDN 文章,我会选择它。如果有人建议修复代码以不使用unsafe,那也会很有帮助!
    • @SwDevMan81:链接错误! ;) social.msdn.microsoft.com/Forums/en-US/clr/thread/… 的代码是我成功用来比较两个 SecureStrings 的代码。
    • @SwDevMan: 哎呀,这个肯定有效并且没有unsafe 块,但是使用调试器单步执行它会显示这两个str1 和str2 字符串以敏感字符串结尾纯文本数据。我更喜欢unsafe 版本,因为它只是比较指针;使用调试器单步执行它,我看不到纯文本中的可理解数据。
    • @MikeChristian - 我发布了不安全解决方案的链接。我刚刚提供了一个不使用不安全代码的替代解决方案示例。如果您担心暴露纯文本,请随意使用不安全的。
    【解决方案2】:

    这没有不安全的块并且不会以明文形式显示密码:

    public static bool IsEqualTo(this SecureString ss1, SecureString ss2)
    {
     IntPtr bstr1 = IntPtr.Zero;
     IntPtr bstr2 = IntPtr.Zero;
     try
     {
      bstr1 = Marshal.SecureStringToBSTR(ss1);
      bstr2 = Marshal.SecureStringToBSTR(ss2);
      int length1 = Marshal.ReadInt32(bstr1, -4);
      int length2 = Marshal.ReadInt32(bstr2, -4);
      if (length1 == length2)
      {
       for (int x = 0; x < length1; ++x)
       {
        byte b1 = Marshal.ReadByte(bstr1, x);
        byte b2 = Marshal.ReadByte(bstr2, x);
        if (b1 != b2) return false;
       }
      }
      else return false;
      return true;
     }
     finally
     {
      if (bstr2 != IntPtr.Zero) Marshal.ZeroFreeBSTR(bstr2);
      if (bstr1 != IntPtr.Zero) Marshal.ZeroFreeBSTR(bstr1);
     }
    }
    

    编辑:按照 Alex J 的建议修复了泄漏。

    【讨论】:

    • 如果在 Marshal.SecureStringToBSTR() 调用之后但在 try 块之前发生异常,您可能会泄漏 IntPtrs。您应该将它们放在 try 块中。
    • @AlexJ,谢谢,我已经修改了代码以修复泄漏。
    • 应该像SecureString.Equals(secstringone, secstringtwo);这样的类中内置类似这样或更多'bro-bust'的东西,干得好
    • 这段代码容易受到定时攻击。对于最初的问题,这无关紧要,但是如果您这样做是为了验证密码(您几乎可以肯定不应该这样做,因为您应该使用散列代替),这可以通过在循环之前声明 int result = 0; 来缓解,将循环体更改为result |= Marshal.ReadByte(bstr1, x) ^ Marshal.ReadByte(bstr2, x); 并返回result == 0。这将使比较恒定时间,因为它总是访问字符串中的每个字符 - 它仍然会泄漏长度,但这是不可避免的。
    • @NikolaNovak,好吧,我想我只是不知道你在回答“并且不会以明文形式显示密码”时的意思,因为Marshal.SecureStringToBSTR 确实解密了SecureString 并将解密后的副本加载到返回的内存地址,MS 称之为“非托管内存中的明文字符串”msdn.microsoft.com/en-us/library/…
    【解决方案3】:

    将@NikolaNovák 的答案翻译成普通的 PowerShell:

    param(
    [Parameter(mandatory=$true,position=0)][SecureString]$ss1,
    [Parameter(mandatory=$true,position=1)][SecureString]$ss2
    )
    
    function IsEqualTo{
       param(
        [Parameter(mandatory=$true,position=0)][SecureString]$ss1,
        [Parameter(mandatory=$true,position=1)][SecureString]$ss2
       )
    
      begin{
        [IntPtr] $bstr1 = [IntPtr]::Zero;
        [IntPtr] $bstr2 = [IntPtr]::Zero;
        [bool]$answer=$true;
      }
    
      process{
        try{
            $bstr1 = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($ss1);
            $bstr2 = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($ss2);
            [int]$length1 = [System.Runtime.InteropServices.Marshal]::ReadInt32($bstr1, -4);
            [int]$length2 = [System.Runtime.InteropServices.Marshal]::ReadInt32($bstr2, -4);
    
            if ($length1 -eq $length2){
                for ([int]$x -eq 0; $x -lt $length1; ++$x){
                    [byte]$b1 = [System.Runtime.InteropServices.Marshal]::ReadByte($bstr1, $x);
                    [byte]$b2 = [System.Runtime.InteropServices.Marshal]::ReadByte($bstr2, $x);
                    if ($b1  -ne $b2){
                        $answer=$false;
                    }
                }
            }
            else{ $answer=$false;}
        }
        catch{
        }
        finally
        {
            if ($bstr2 -ne [IntPtr]::Zero){ [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr2)};
            if ($bstr1 -ne [IntPtr]::Zero){ [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr1)};
        }
      }
      END{
        return $answer
      }
    }
    IsEqualTo -ss1 $ss1  -ss2 $ss2
    

    【讨论】:

      【解决方案4】:

      您可以采取不同的方法。我在代码中遇到了同样的问题,密码和确认的比较,两者都是 SecureString 类型。我意识到最终目标是新密码需要作为 base-64 字符串存储在数据库中。所以我所做的只是通过相同的代码传递确认字符串,就好像我要将它写入数据库一样。然后,当我有两个 base-64 字符串时,我会在那时比较它们,这是一个简单的字符串比较。

      将任何故障一直传达回 UI 层确实需要更多的管道,但最终结果似乎可以接受。希望这段代码足以给出基本的想法。

      private string CalculateHash( SecureString securePasswordString, string saltString )
      {
          IntPtr unmanagedString = IntPtr.Zero;
          try
          {
              unmanagedString = Marshal.SecureStringToGlobalAllocUnicode( securePasswordString );
              byte[] passwordBytes = Encoding.UTF8.GetBytes( Marshal.PtrToStringUni( unmanagedString ) );
              byte[] saltBytes = Encoding.UTF8.GetBytes( saltString );
              byte[] passwordPlusSaltBytes = new byte[ passwordBytes.Length + saltBytes.Length ];
              Buffer.BlockCopy( passwordBytes, 0, passwordPlusSaltBytes, 0, passwordBytes.Length );
              Buffer.BlockCopy( saltBytes, 0, passwordPlusSaltBytes, passwordBytes.Length, saltBytes.Length );
              HashAlgorithm algorithm = new SHA256Managed();
              return Convert.ToBase64String( algorithm.ComputeHash( passwordPlusSaltBytes ) );
          }
          finally
          {
              if( unmanagedString != IntPtr.Zero )
                  Marshal.ZeroFreeGlobalAllocUnicode( unmanagedString );
          }
      }
      
      string passwordSalt = "INSERT YOUR CHOSEN METHOD FOR CONSTRUCTING A PASSWORD SALT HERE";
      string passwordHashed = CalculateHash( securePasswordString, passwordSalt );
      string confirmPasswordHashed = CalculateHash( secureConfirmPasswordString, passwordSalt );
      if( passwordHashed == confirmPasswordHashed )
      {
          // Both matched so go ahead and persist the new password.
      }
      else
      {
          // Strings don't match, so communicate the failure back to the UI.
      }
      

      我是安全编程的新手,所以我欢迎任何改进建议。

      【讨论】:

        【解决方案5】:

        如果代码在 Windows Vista 或更高版本上运行,这里有一个基于 CompareStringOrdinal Windows 函数的版本,因此没有纯文本,所有缓冲区都保持不受管理。好处是它支持不区分大小写的比较。

        public static bool EqualsOrdinal(this SecureString text1, SecureString text2, bool ignoreCase = false)
        {
            if (text1 == text2)
                return true;
        
            if (text1 == null)
                return text2 == null;
        
            if (text2 == null)
                return false;
        
            if (text1.Length != text2.Length)
                return false;
        
            var b1 = IntPtr.Zero;
            var b2 = IntPtr.Zero;
            try
            {
                b1 = Marshal.SecureStringToBSTR(text1);
                b2 = Marshal.SecureStringToBSTR(text2);
                return CompareStringOrdinal(b1, text1.Length, b2, text2.Length, ignoreCase) == CSTR_EQUAL;
            }
            finally
            {
                if (b1 != IntPtr.Zero)
                {
                    Marshal.ZeroFreeBSTR(b1);
                }
        
                if (b2 != IntPtr.Zero)
                {
                    Marshal.ZeroFreeBSTR(b2);
                }
            }
        }
        
        public static bool EqualsOrdinal(this SecureString text1, string text2, bool ignoreCase = false)
        {
            if (text1 == null)
                return text2 == null;
        
            if (text2 == null)
                return false;
        
            if (text1.Length != text2.Length)
                return false;
        
            var b = IntPtr.Zero;
            try
            {
                b = Marshal.SecureStringToBSTR(text1);
                return CompareStringOrdinal(b, text1.Length, text2, text2.Length, ignoreCase) == CSTR_EQUAL;
            }
            finally
            {
                if (b != IntPtr.Zero)
                {
                    Marshal.ZeroFreeBSTR(b);
                }
            }
        }
        
        private const int CSTR_EQUAL = 2;
        
        [DllImport("kernel32")]
        private static extern int CompareStringOrdinal(IntPtr lpString1, int cchCount1, IntPtr lpString2, int cchCount2, bool bIgnoreCase);
        
        [DllImport("kernel32")]
        private static extern int CompareStringOrdinal(IntPtr lpString1, int cchCount1, [MarshalAs(UnmanagedType.LPWStr)] string lpString2, int cchCount2, bool bIgnoreCase);
        

        【讨论】:

          猜你喜欢
          • 2013-08-18
          • 2021-09-14
          • 2010-12-05
          • 2016-03-06
          • 1970-01-01
          • 2014-09-20
          • 2013-06-27
          • 1970-01-01
          相关资源
          最近更新 更多