使用c#中的Rfc2898DeriveBytes和go中的pbkdf2生成相同的键

时间:2017-06-30 13:17:24

标签: c# go pbkdf2

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

我的 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 ==

我必须做些什么吗?

1 个答案:

答案 0 :(得分:1)

在初始化C#实例时,您正在使用不同的变体(采用UTF-8 string的构造函数)。此外,正如zaph已经指出的那样,您需要对C#和golang代码使用相同的迭代计数。 golang版本对密码 salt 都需要[]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版本相同。