doupu3635 2017-06-30 13:17
浏览 462
已采纳

在c#中使用Rfc2898DeriveBytes和go中的pbkdf2生成相同的密钥

Why do Rfc2898DeriveBytes in C# and pbkdf2 in go lang generate different keys?

my C# code

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()));
    }
}

output: 77U85CphtSEwPP9a2T/jaQ==


golang code

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()))
}

output: hnuuu+he4aF7vAzA8rfQtw==

Is there something different i must do?

  • 写回答

1条回答 默认 最新

  • dongmaoxi0477 2017-06-30 14:13
    关注

    You're using different variant (the constructor that takes UTF-8 string) when initializing C# instance. In addition, as already pointed by zaph, you need to use same iteration count for both C# and golang codes. The golang version takes []byte arguments both for password and salt, and the C# counterpart is 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));
    

    The output of above code is the same with golang version.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)