DJC
DJC

Reputation: 113

using this code how do you know if sha256 or sha512 would be used?

  1. Stupid question, in the code below, considering the name is sha512.New512_256, is 512 or 256 used? How do you control which you want? I know I'm missing something elementary here..

  2. Also, as I'm looking more at this I'm wondering if hmac is not what I want at all... I'm looking to create some small hashing utilities that will hash any string input or files given as parameters. I would specify the type of hash to use as an input parameter as well... so I would expect the same hash result for the same hash algo used on the same file or string every time... should I be using something else?

thanks

import (
    "crypto/hmac"
    "crypto/sha512"
)

func Hash(tag string, data []byte) []byte {
    h := hmac.New(sha512.New512_256, []byte(tag))
    h.Write(data)
    return h.Sum(nil)
}

Upvotes: 1

Views: 1176

Answers (1)

kelalaka
kelalaka

Reputation: 5636

SHA512 is in the SHA-2 families. Variants are listed in NIST FIPS 180-4

- SHA-512/256 truncated from SHA-512 with different initial values 
- SHA-512/224 truncated from SHA-512 with different initial values
- SHA-384     truncated from SHA-512 with different initial values
- SHA-512

- SHA-224     truncated from SHA-256 with different initial values
- SHA-256

To separate the domains (called domain separation) of these hash functions from their truncated version, different initial values are used. Otherwise, an attack on the truncated version can be carried into other versions, v.v.

  • first question

With sha512.New512_256 you actually choose a hash function from SHA-512 and in this case, it is SHA-512/256, You can select the others from the list of godoc.org by looking their string.

  • second question

You may need hash not hmac. HMAC is a keyed hash-based message authentication code and it useful to authenticate with a key. For every time to control the hash (or checksum), you will need the key.

The library, however, uses Sum512 or Sum512_256 etc. to calculate the checksum (hash) of a given data. Sample code to calculate the hash is:

sha_512 := sha512.New()
sha_512.Write([]byte(input))
hash := base64.URLEncoding.EncodeToString(sha_512.Sum(nil))

On Truncation

At first, the idea of truncation may seem unsound. Actually it is not. SHA-512 and SHA-256 have length extension attacks. However, the truncated versions have resistances, see table on wikipedia.

It should also be noted that the SHA3 family is designed to have resistance against the length extension attacks. The capacity prevents the attacks.

Upvotes: 2

Related Questions