zelcon
zelcon

Reputation: 236

Why is Golang not giving me 8 bytes when I said 8?

I thought x := make([]byte, N) was supposed to define a slice of N bytes. I'm getting 0x015f82a975f9752b as the output for that, which in base 2 is:

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

Not 8. What am I missing?

See the genSalt() function below and its output.

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
}

For some reason, this won't work in Go Playground, so just run it locally.

(Sorry if this is a retarded question; I'm sleep deprived.)

Upvotes: 0

Views: 349

Answers (1)

icza
icza

Reputation: 418695

1 byte = 8 bits.

Your output: 0x015f82a975f9752b. That is exactly 8 bytes.

1 byte can be displayed as 2 hex digits (1 hex digit contains 4 bits, so 1 byte = 8 bits = 2 hex digits).

When you present it as binary:

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.   |

That is 60 bits because the first 4 bits are 0 and not printed. 64 bits = 8 bytes.

Upvotes: 7

Related Questions