为什么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
版本为 password 和 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
版本相同。
关于c# - 在 c# 中使用 Rfc2898DeriveBytes 在 go 中使用 pbkdf2 生成相同的 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44847460/