opcua_crypto/
thumbprint.rs

1// OPCUA for Rust
2// SPDX-License-Identifier: MPL-2.0
3// Copyright (C) 2017-2022 Adam Lock
4
5//! Functionality for holding a message digest.
6use opcua_types::ByteString;
7
8/// The thumbprint holds a 20 byte representation of a certificate that can be used as a hash,
9/// handshake comparison, a filename hint or similar purpose where a shortened representation
10/// of a cert is required. Thumbprint size is dictated by the OPC UA spec
11#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
12pub struct Thumbprint {
13    /// Thumbprint is relatively small and fixed size, so use array to hold value instead of a vec
14    /// just to save heap
15    value: [u8; Thumbprint::THUMBPRINT_SIZE],
16}
17
18impl Into<ByteString> for Thumbprint {
19    fn into(self) -> ByteString {
20        ByteString::from(&self.value)
21    }
22}
23
24impl Thumbprint {
25    pub const THUMBPRINT_SIZE: usize = 20;
26
27    /// Constructs a thumbprint from a message digest which is expected to be the proper length
28    pub fn new(digest: &[u8]) -> Thumbprint {
29        if digest.len() != Thumbprint::THUMBPRINT_SIZE {
30            panic!("Thumbprint is the wrong length, {}", digest.len());
31        }
32        let mut value = [0u8; Thumbprint::THUMBPRINT_SIZE];
33        value.clone_from_slice(digest);
34        Thumbprint { value }
35    }
36
37    pub fn as_byte_string(&self) -> ByteString {
38        ByteString::from(&self.value)
39    }
40
41    /// Returns the thumbprint as a string using hexadecimal values for each byte
42    pub fn as_hex_string(&self) -> String {
43        let mut hex_string = String::with_capacity(self.value.len() * 2);
44        for b in self.value.iter() {
45            hex_string.push_str(&format!("{:02x}", b))
46        }
47        hex_string
48    }
49
50    /// Returns the thumbprint
51    pub fn value(&self) -> &[u8] {
52        &self.value[..]
53    }
54}