c# - 在 c# 中使用 Rfc2898DeriveBytes 在 go 中使用 pbkdf2 生成相同的 key

标签 c# go pbkdf2

为什么C#中的Rfc2898DeriveBytes和go lang中的pbkdf2生成不同的key?

我的C#代码

using System;
using System.Security.Cryptography;
using System.Text;

public class Test
{
        private static byte[] passBytes = new byte[]
        {164,176,124,62,244,154,226,211,177,90,202,180,12,142,25,225};

        private static byte[] saltBytes = new byte[]
        {173,205,190,172,239,190,242,63,219,205,173,196,218,171,142,214};

        public static byte[] GetKey()
        {
            var key = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(passBytes, 0, 16), saltBytes).GetBytes(16);
            return key;
        }

    public static void Main()
    {
        System.Console.WriteLine(Convert.ToBase64String(GetKey()));
    }
}

输出: 77U85CphtSEwPP9a2T/jaQ==


golang代码

package main

import (

    b64 "encoding/base64"
    "golang.org/x/crypto/pbkdf2"
    "crypto/sha1"

)

var (
    pass[]byte = []byte{164,176,124,62,244,154,226,211,177,90,202,180,12,142,25,225}
    salt[]byte = []byte{173,205,190,172,239,190,242,63,219,205,173,196,218,171,142,214}
)


func getKey() (key[]byte){
    key =  pbkdf2.Key(pass,salt,1000,16,sha1.New)
    return
}


func main() {
    print(b64.StdEncoding.EncodeToString(getKey()))
}

输出: hnuuu+he4aF7vAzA8rfQtw==

我必须做些不同的事情吗?

最佳答案

初始化 C# 实例时,您正在使用不同的变体(采用 UTF-8 string 的构造函数)。此外,正如 zaph 已经指出的那样,您需要对 C# 和 golang 代码使用相同的迭代计数。 golang 版本为 passwordsalt 使用 []byte 参数,而 C# 版本是 Rfc2898DeriveBytes Constructor (Byte[] password, Byte[] salt, Int32 iterations) .

byte[] passBytes = new byte[]
    {164,176,124,62,244,154,226,211,177,90,202,180,12,142,25,225};

byte[] saltBytes = new byte[]
    {173,205,190,172,239,190,242,63,219,205,173,196,218,171,142,214};

var pbkdf2 = new Rfc2898DeriveBytes(passBytes, saltBytes, 1000);
var key = Convert.ToBase64String(pbkdf2.GetBytes(16));

以上代码的输出与golang版本相同。

关于c# - 在 c# 中使用 Rfc2898DeriveBytes 在 go 中使用 pbkdf2 生成相同的 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44847460/

相关文章:

c# - LinqToDb : Rank is server-side method

c# - 使用 ajax 调用将模型作为列表从 View 传递到 Controller

c# - 为什么计时器在 Windows 服务中不起作用?

c - PKCS5_PBKDF2_HMAC : binary password

android - android中的PBKDF2安全 key

C# RFC2898DeriveBytes 正在工作,但 Python PBKDF2 生成的 key 和 IV 不适用于 Python AES 解密

c# - 是否可以反射(reflect)托管程序集?

go - 如何使用反射将值分配给未知结构

go - Go 中具有大起始索引的 slice (的底层数组)可以有效地分配内存吗?

postgresql - gorm没有将db值映射到实体