【问题标题】:From C# encryption key derivation to Ruby (PBKDF2)从 C# 加密密钥派生到 Ruby (PBKDF2)
【发布时间】:2015-10-06 11:13:53
【问题描述】:

我正在尝试将以下用 C# 编写的密钥生成方法重写为其 Ruby 等效项:

        private static byte[] CreateKey(string password, int length)
        {
            var salt = new byte[] { 0x01, 0x02, 0x23, 0x34, 0x37, 0x48, 0x24, 0x63, 0x99, 0x04 };

            const int Iterations = 1000;
            using (var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, salt, Iterations))
                return rfc2898DeriveBytes.GetBytes(length);
        }

我正在使用PBKDF2 实现。这是我的 Ruby 代码:

def create_key password, length
    salt_a = [0x01, 0x02, 0x23, 0x34, 0x37, 0x48, 0x24, 0x63, 0x99, 0x04]
    salt = salt_a.pack('C*') # Think here there is something to change
    iterations = 1000
    derived_b = PBKDF2.new do |p| 
      p.password = password
      p.salt = salt
      p.iterations = iterations
      p.key_length = length
      p.hash_function = OpenSSL::Digest::SHA1
    end
    derived_b.bin_string # and here too
end

为了工作,这两种方法应该返回相同的输出。问题是我无法弄清楚如何做到这一点。 PBKDF2 实现将 salt 作为 String,但 C# 采用字节数组...我认为问题就在那里。

【问题讨论】:

  • 盐只是添加到密码末尾的随机字节集,以阻止字典攻击。 C# 实现直接执行此操作。要在 Ruby 中获得相同的字节,您可能需要指定编码。

标签: c# ruby encryption salt rfc2898


【解决方案1】:

如果您可以使用最新版本的 OpenSSL,那么这对我有用:

SALT = [ 0x94, 0x67, 0x16, 0xe6, 0x20, 0xd4, 0x56, 0x46, 0x67, 0x56, 0x46, 0x56, 0x23 ].pack("c*")
PBKDF2_ITERATIONS = 1000

def create_key(password, length)
  OpenSSL::PKCS5::pbkdf2_hmac_sha1(password, SALT, PBKDF2_ITERATIONS, length)
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 2019-08-13
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    相关资源
    最近更新 更多