【问题标题】:Why is Golang not giving me 8 bytes when I said 8?当我说 8 时,为什么 Golang 没有给我 8 个字节?
【发布时间】:2016-02-20 10:35:56
【问题描述】:

我认为x := make([]byte, N) 应该定义一个 N 字节的切片。我得到 0x015f82a975f9752b 作为它的输出,在 base 2 中是:

0001 0101 1111 1000 0010 1010 1001 0111 0101 1111 1001 0111 0101 0010 1011

不是 8。我错过了什么?

查看下面的genSalt() 函数及其输出。

package main

import (
  "crypto/rand"
  "crypto/sha256"
  "fmt"
  "golang.org/x/crypto/pbkdf2"
  "log"
)

// generate a salt with N random bytes
func genSalt() []byte {
  ret := make([]byte, 8) // N == 8 (..right?)
  _, err := rand.Read(ret)
  if err != nil {
    log.Fatal(err)
  }
  return ret
}

// pbkdf2 with sha256
// returns sha256.Size == 32 bytes
func hashPassword(cleartext, salt []byte) []byte {
  return pbkdf2.Key([]byte(cleartext), salt, 4096, sha256.Size, sha256.New)
}

func main() {
  password := "GNUsNotUnixItsWorse"
  salt := genSalt()
  hashed := hashPassword([]byte(password), salt)

  fmt.Printf("sha256: %x\n", hashed)
  fmt.Printf("salt: %x\n", salt)
  fmt.Println("len(salt)", len(salt),
    "\nlen(hashed)", len(hashed))

  // OUTPUT (sample):
  // sha256: b9c314c8fb8d183fb8773b8b2e2b2b991927915adeba44eb51c8fe6f9e13ee09
  // salt: 015f82a975f9752b
  // len(salt) 8 
  // len(hashed) 32
}

由于某种原因,这在 Go Playground 中不起作用,因此只需在本地运行即可。

(对不起,如果这是一个智障问题;我睡眠不足。)

【问题讨论】:

  • 规范说byte 是“uint8 的别名”

标签: go binary byte bytearray


【解决方案1】:

1 字节 = 8 位。

您的输出:0x015f82a975f9752b。正好是 8 个字节。

1 个字节可以显示为 2 个十六进制数字(1 个十六进制数字包含 4 个位,因此 1 个字节 = 8 个位 = 2 个十六进制数字)。

当您将其呈现为二进制时:

binary:    0001 0101 1111 1000 0010 1010 1001 0111 0101 1111 1001 0111 0101 0010 1011
hex:         1 |  5 |  f |  8 |  2 |  a |  9 |  7 |  5 |  f |  9 |  7 |  5 |  2 |  b |
byte idx:  7.  |    6.   |    5.   |    4.   |    3.   |    2.   |    1.   |    0.   |

那是 60 位,因为前 4 位是 0 并且没有打印出来。 64 位 = 8 个字节。

【讨论】:

  • 我的这个“问题”开始是因为数据库不允许我在大小有限的字段中插入十六进制值;你的回答也回答了这个问题!
猜你喜欢
  • 2016-05-29
  • 2013-12-08
  • 1970-01-01
  • 2023-02-02
  • 2010-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多