Hashing
Overview
This page contains recommendations for choosing a hashing algorithm.
General
If you need to hash passwords see the the Authentication: Password Storage page.
For other data, use a hashing algorithm from the
SHA-2orSHA-3family.Do not use vulnerable hashing algorithms from the list below. You can find examples of collision attacks at https://github.com/corkami/collisions.
Hashing implementation
Use the implementation of hash algorithms from the crypto package, such as crypto/sha256 or crypto/sha512. You can find the whole list at https://pkg.go.dev/crypto#Hash
package main
import (
"crypto/sha256"
"fmt"
)
func main() {
p := []byte("random string for hashing")
hash := sha256.New()
fmt.Printf("%x\n", hash.Sum(p))
}Use the java.security.MessageDigest class for hashing implementation. MessageDigest is not thread-safe. Use a new instance for every thread.
import java.security.MessageDigest;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
public static String sha256Hash(String data) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] encodedHash = digest.digest(data.getBytes(StandardCharsets.UTF_8));
return toHex(encodedHash)
}
public static String sha3256Hash(String data) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("SHA3-256");
byte[] encodedHash = digest.digest(data.getBytes(StandardCharsets.UTF_8));
return toHex(encodedHash)
}
private static String toHex(byte[] byteArray) {
String hex = "";
for (byte i : byteArray) {
hex += String.format("%02x", i);
}
return hex;
}Use the crypto package for hashing implementation. The list of supported algorithms is dependent on the available algorithms supported by the version of OpenSSL on the platform. Use openssl list -digest-algorithms to display the available digest algorithms.
const { createHash } = await import('node:crypto');
async function sha256_digest(data) {
const hash = createHash('sha256');
hash.update(data);
return hash.digest('hex');
}Use the hashlib package for hashing implementation. You can find the list of available algorithms here.
import hashlib
def sha256_digest(data: str) -> str:
encoded_data = data.encode('utf-8')
hash = hashlib.sha256(encoded_data)
return hash.hexdigest()
def sha3_256_digest(data: str) -> str:
encoded_data = data.encode('utf-8')
hash = hashlib.sha3_256(encoded_data)
return hash.hexdigest()Last updated