convertHash
builtins.convertHash
Nix manual
Takes 1 arguments
args
Return the specified representation of a hash string, based on the attributes presented in args:
-
hashThe hash to be converted. The hash format is detected automatically.
-
hashAlgoThe algorithm used to create the hash. Must be one of
"md5""sha1""sha256""sha512"
The attribute may be omitted when
hashis an SRI hash or when the hash is prefixed with the hash algorithm name followed by a colon. That<hashAlgo>:<hashBody>syntax is supported for backwards compatibility with existing tooling. -
toHashFormatThe format of the resulting hash. Must be one of
"base16""nix32""base32"(deprecated alias for"nix32")"base64""sri"
The result hash is the toHashFormat representation of the hash hash.
Example
Convert a SHA256 hash in Base16 to SRI:
builtins.convertHash { hash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; toHashFormat = "sri"; hashAlgo = "sha256"; }"sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="
Example
Convert a SHA256 hash in SRI to Base16:
builtins.convertHash { hash = "sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="; toHashFormat = "base16"; }"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
Example
Convert a hash in the form
<hashAlgo>:<hashBody>in Base16 to SRI:builtins.convertHash { hash = "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; toHashFormat = "sri"; }"sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="
Noogle detected
Implementation
This function is implemented in c++ and is part of the native nix runtime.
static void prim_convertHash(EvalState & state, const PosIdx pos, Value ** args, Value & v)
{
state.forceAttrs(*args[0], pos, "while evaluating the first argument passed to builtins.convertHash");
auto inputAttrs = args[0]->attrs();
auto iteratorHash = state.getAttr(state.symbols.create("hash"), inputAttrs, "while locating the attribute 'hash'");
auto hash = state.forceStringNoCtx(*iteratorHash->value, pos, "while evaluating the attribute 'hash'");
auto iteratorHashAlgo = inputAttrs->get(state.symbols.create("hashAlgo"));
std::optional<HashAlgorithm> ha = std::nullopt;
if (iteratorHashAlgo)
ha = parseHashAlgo(
state.forceStringNoCtx(*iteratorHashAlgo->value, pos, "while evaluating the attribute 'hashAlgo'"));
auto iteratorToHashFormat = state.getAttr(
state.symbols.create("toHashFormat"), args[0]->attrs(), "while locating the attribute 'toHashFormat'");
HashFormat hf = parseHashFormat(
state.forceStringNoCtx(*iteratorToHashFormat->value, pos, "while evaluating the attribute 'toHashFormat'"));
v.mkString(Hash::parseAny(hash, ha).to_string(hf, hf == HashFormat::SRI), state.mem);
}