@@ -99,22 +99,37 @@ struct DecodeNamePair
9999
100100} // namespace
101101
102+ static DecodeNamePair baseExplicit (HashFormat format)
103+ {
104+ switch (format) {
105+ case HashFormat::Base16:
106+ return {base16::decode, " base16" };
107+ case HashFormat::Nix32:
108+ return {BaseNix32::decode, " nix32" };
109+ case HashFormat::Base64:
110+ return {base64::decode, " Base64" };
111+ case HashFormat::SRI:
112+ assert (false );
113+ }
114+ }
115+
102116/* *
103117 * Given the expected size of the message once decoded it, figure out
104118 * which encoding we are using by looking at the size of the encoded
105119 * message.
106120 */
107- static DecodeNamePair baseFromSize (std::string_view rest, HashAlgorithm algo)
121+ static HashFormat baseFromSize (std::string_view rest, HashAlgorithm algo)
108122{
109123 auto hashSize = regularHashSize (algo);
124+
110125 if (rest.size () == base16::encodedLength (hashSize))
111- return {base16::decode, " base16 " } ;
126+ return HashFormat::Base16 ;
112127
113128 if (rest.size () == BaseNix32::encodedLength (hashSize))
114- return {BaseNix32::decode, " nix32 " } ;
129+ return HashFormat::Nix32 ;
115130
116131 if (rest.size () == base64::encodedLength (hashSize))
117- return {base64::decode, " Base64" } ;
132+ return HashFormat:: Base64;
118133
119134 throw BadHash (" hash '%s' has wrong length for hash algorithm '%s'" , rest, printHashAlgo (algo));
120135}
@@ -135,7 +150,8 @@ static Hash parseLowLevel(std::string_view rest, HashAlgorithm algo, DecodeNameP
135150 e.addTrace ({}, " While decoding hash '%s'" , rest);
136151 }
137152 if (d.size () != res.hashSize )
138- throw BadHash (" invalid %s hash '%s' %d %d" , pair.encodingName , rest);
153+ throw BadHash (
154+ " invalid %s hash '%s', length %d != expected length %d" , pair.encodingName , rest, d.size (), res.hashSize );
139155 assert (res.hashSize );
140156 memcpy (res.hash , d.data (), res.hashSize );
141157
@@ -189,7 +205,7 @@ static Hash parseAnyHelper(std::string_view rest, auto resolveAlgo)
189205 } else {
190206 /* Otherwise, decide via the length of the hash (for the
191207 given algorithm) what base encoding it is. */
192- return baseFromSize (rest, algo);
208+ return baseExplicit ( baseFromSize (rest, algo) );
193209 }
194210 }();
195211
@@ -224,7 +240,12 @@ Hash Hash::parseAny(std::string_view original, std::optional<HashAlgorithm> optA
224240
225241Hash Hash::parseNonSRIUnprefixed (std::string_view s, HashAlgorithm algo)
226242{
227- return parseLowLevel (s, algo, baseFromSize (s, algo));
243+ return parseExplicitFormatUnprefixed (s, algo, baseFromSize (s, algo));
244+ }
245+
246+ Hash Hash::parseExplicitFormatUnprefixed (std::string_view s, HashAlgorithm algo, HashFormat format)
247+ {
248+ return parseLowLevel (s, algo, baseExplicit (format));
228249}
229250
230251Hash Hash::random (HashAlgorithm algo)
0 commit comments