fix(utils): cover sha256 checksum validation (#3052)

* fix(utils): cover sha256 checksum validation

* docs: clarify sha256 checksum validation
This commit is contained in:
安正超
2026-05-22 10:45:53 +08:00
committed by GitHub
parent 0d94437788
commit 3e3fcbf44d
2 changed files with 16 additions and 4 deletions
+15 -3
View File
@@ -66,10 +66,9 @@ pub fn hex(data: impl AsRef<[u8]>) -> String {
/// * `s` - A string slice to be verified
///
/// # Returns
/// A `bool` indicating whether the input string is a valid SHA-256 checksum (64
///
/// A `bool` indicating whether the input string is exactly 64 lowercase hexadecimal characters.
/// Uppercase hexadecimal characters are not accepted.
pub fn is_sha256_checksum(s: &str) -> bool {
// TODO: optimize
let is_lowercase_hex = |c: u8| matches!(c, b'0'..=b'9' | b'a'..=b'f');
s.len() == 64 && s.as_bytes().iter().copied().all(is_lowercase_hex)
}
@@ -155,3 +154,16 @@ fn test_base64_encoding_decoding() {
assert_eq!(decoded_string, original_uuid_timestamp)
}
#[test]
fn sha256_checksum_accepts_exact_lowercase_hex() {
assert!(is_sha256_checksum("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"));
}
#[test]
fn sha256_checksum_rejects_wrong_length_or_non_lowercase_hex() {
assert!(!is_sha256_checksum("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcde"));
assert!(!is_sha256_checksum("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0"));
assert!(!is_sha256_checksum("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdeg"));
assert!(!is_sha256_checksum("0123456789ABCDEF0123456789abcdef0123456789abcdef0123456789abcdef"));
}