apple_cryptokit/hashing/
sha1.rs

1// SHA-1 hash algorithm implementation (insecure, for compatibility only)
2
3use super::HashFunction;
4
5/// SHA-1 output size
6pub const SHA1_OUTPUT_SIZE: usize = 20;
7
8// SHA-1 Swift FFI declarations
9extern "C" {
10    #[link_name = "sha1_hash"]
11    fn swift_sha1_hash(data: *const u8, length: i32, out_hash: *mut u8);
12}
13
14/// SHA-1 one-shot hash computation (insecure, for compatibility only)
15pub fn sha1_hash(data: &[u8]) -> [u8; 20] {
16    let mut output = [0u8; 20];
17    sha1_hash_to(data, &mut output);
18    output
19}
20
21/// SHA-1 hash computation to provided buffer (zero allocation)
22///
23/// # Arguments
24/// - `output`: must be at least 20 bytes
25///
26/// # Panics
27/// Panics if output buffer is too small
28pub fn sha1_hash_to(data: &[u8], output: &mut [u8]) {
29    assert!(
30        output.len() >= SHA1_OUTPUT_SIZE,
31        "Output buffer too small: {} < {}",
32        output.len(),
33        SHA1_OUTPUT_SIZE
34    );
35    unsafe {
36        swift_sha1_hash(data.as_ptr(), data.len() as i32, output.as_mut_ptr());
37    }
38}
39
40/// SHA-1 hash algorithm implementation
41pub struct SHA1;
42
43impl HashFunction for SHA1 {
44    const OUTPUT_SIZE: usize = SHA1_OUTPUT_SIZE;
45
46    fn hash_to(data: &[u8], output: &mut [u8]) {
47        sha1_hash_to(data, output)
48    }
49}
50
51// Re-export
52pub use SHA1 as Sha1Algorithm;