← 返回首页
Use of a broken or weak cryptographic hashing algorithm on sensitive data — CodeQL query help documentation CodeQL docs
CodeQL documentation
CodeQL resources

Use of a broken or weak cryptographic hashing algorithm on sensitive data

ID: go/weak-sensitive-data-hashing Kind: path-problem Security severity: 7.5 Severity: warning Precision: high Tags: - security - external/cwe/cwe-327 - external/cwe/cwe-328 - external/cwe/cwe-916 Query suites: - go-code-scanning.qls - go-security-extended.qls - go-security-and-quality.qls

Click to see the query in the CodeQL repository

Using a broken or weak cryptographic hash function can leave data vulnerable, and should not be used in security related code.

A strong cryptographic hash function should be resistant to:

As an example, both MD5 and SHA-1 are known to be vulnerable to collision attacks.

Since it’s OK to use a weak cryptographic hash function in a non-security context, this query only alerts when these are used to hash sensitive data (such as passwords, certificates, usernames).

Use of broken or weak cryptographic algorithms that are not hashing algorithms, is handled by the rb/weak-cryptographic-algorithm query.

Recommendation

Ensure that you use a strong, modern cryptographic hash function:

Example

The following example shows two functions for checking whether the hash of a secret matches a known value. The first function uses SHA-1 that is known to be vulnerable to collision attacks. The second function uses SHA-256 that is a strong cryptographic hashing function.

package main import ( "crypto/sha1" "crypto/sha256" "slices" ) func SecretMatchesKnownHashBad(secret []byte, known_hash []byte) bool { // BAD, SHA1 is a weak crypto algorithm and secret is sensitive data h := sha1.New() return slices.Equal(h.Sum(secret), known_hash) } func SecretMatchesKnownHashGood(secret []byte, known_hash []byte) bool { // GOOD, SHA256 is a strong hashing algorithm h := sha256.New() return slices.Equal(h.Sum(secret), known_hash) }

Example

The following example shows two functions for hashing passwords. The first example uses SHA-256 to hash passwords. Although SHA-256 is a strong cryptographic hash function, it is not suitable for password hashing since it is not computationally expensive. The second function uses PBKDF2, which is a strong password hashing algorithm.

package main import ( "crypto/pbkdf2" "crypto/rand" "crypto/sha256" "crypto/sha512" ) func GetPasswordHashBad(password string) [32]byte { // BAD, SHA256 is a strong hashing algorithm but it is not computationally expensive return sha256.Sum256([]byte(password)) } func GetPasswordHashGood(password string) []byte { // GOOD, PBKDF2 is a strong hashing algorithm and it is computationally expensive salt := make([]byte, 16) rand.Read(salt) key, _ := pbkdf2.Key(sha512.New, password, salt, 4096, 32) return key }

References