存储加密/兰特生成的字符串问题

So I have the following go file(s) as part of my project to be used for hashing passwords, I also wrote some tests that to my knowledge have yet to fail.

Currently the issue is that I am trying to store the password and salt in some database as strings, and every time I retrieve them to be compared against a another string I keep getting the message in the picture from golang's bcrypt package. The tests I wrote are running fine and produce the appropriate effect. I would have supplied a go playground link but bcrypt package is part of the standard library.

I know the gibberish from crypto/rand is pretty much the same from the initial look but I am not sure if there is anything being changed on the database. I am using redis fyi.

Edit: based on the request of @3of3, I am including the DAO code from my project. Also the bcrypt only solution worked with this code but as I stated in the comments, I am aiming to stick to Mozilla's guide.

enter image description here

The salt does not roundtrip through the JSON encode / decode because the salt is not valid UTF8.

There are a few ways to fix the problem:

  • Hex or base64 encode / decode the salt in hasher.
  • Use the []byte type for salt throughout the code. The JSON encoder encodes []byte values using base64.
  • Use the gob encoder instead of the JSON encoder.

Mozilla recommends storing the extra salt separate from the bcrypted password. By storing the extra salt with the bcrypted password, the system is no more secure than using bcrypt alone.

To hex encode the salt, change

return string(p), string(salt), nil

to

return string(p), hex.EncodeToString(salt), nil

and change

    s := []byte(salt)

to

    s, err := hex.DecodeString(salt)
    if err != nil {
       return err
    }

It seems you forgot that the generated hashes are hex encoded, thus when casting the []byte variable to a string you'll get something weird. Using the hex package you can create the actual string you want:

hex.EncodeToString(hash)