【问题标题】:Compare 2 secrets in constant time using Windows crypto API使用 Windows 加密 API 在恒定时间内比较 2 个秘密
【发布时间】:2016-03-25 19:03:55
【问题描述】:

使用 Windows 加密 API,如何在恒定时间内比较两个字节数组是否相等?

编辑:秘密的长度是固定的,是公开的知识。

【问题讨论】:

    标签: windows cryptography cng timing-attack


    【解决方案1】:

    时间安全比较需要知道哪个数组来自用户(这决定了它将花费的时间),以及哪个数组是你的秘密(你不想泄露它有多长的秘密)

    //Code released into public domain. No attribution required.
    Boolean TimingSafeArrayCompare(Byte[] safe, Byte[] user)
    {
       /*
          A timing safe array comparison.
    
          To prevent leaking length information,  
          it is important that user input is always used as the second parameter.
    
             safe: The internal (safe) value to be checked
             user: The user submitted (unsafe) value
    
          Returns True if the two arrays are identical.
       */
       int safeLen = safe.Length;
       int userLen = user.Length;
    
       // Set the result to the difference between the lengths.
       // This means that arrays of different length will already cause nDiff to be non-zero
       int nDiff = safeLen - userLen;
    
       // Note that we ALWAYS iterate over the user-supplied length
       // This is to prevent leaking length information
       for (i = 0 to userLen-1)
       {
          //Using mod here is a trick to prevent leaking.
          //It's safe, since if the lengths are different, nDiff will already be non-zero
          nDiff = nDiff | ( User[i] xor Safe[i mod safeLen] );
       }
    
       // They are only identical strings if nDiff is exactly zero
       return (nDiff == 0);
    }
    

    这是一种巧妙的技术,我第一次看到here

    【讨论】:

    • 我认为代码有一些错误。从语法上讲,因为大括号不匹配,其次,为什么要在索引中加 1?你不是那样比较第一个字节
    • @PaulBastian 它是从我脑海中的 Delphi 转录而来的,其中字符串的索引从 1 开始。所提供的代码没有特定语言,需要读者根据他们的特定语言调整算法。
    猜你喜欢
    • 2014-03-20
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    • 2012-03-09
    • 2016-09-23
    • 2017-10-31
    • 2021-04-10
    • 2019-11-14
    相关资源
    最近更新 更多