localauthentication/
la_credential.rs1use std::fmt;
4
5use zeroize::Zeroizing;
6
7use crate::ffi;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11#[non_exhaustive]
12pub enum LACredentialType {
13 ApplicationPassword,
15 SmartCardPin,
17}
18
19impl LACredentialType {
20 #[must_use]
21 pub const fn raw_value(self) -> i32 {
22 match self {
23 Self::ApplicationPassword => ffi::la_credential::APPLICATION_PASSWORD,
24 Self::SmartCardPin => ffi::la_credential::SMART_CARD_PIN,
25 }
26 }
27
28 pub(crate) const fn as_ffi(self) -> i32 {
29 self.raw_value()
30 }
31}
32
33#[derive(Clone)]
35pub struct LACredential {
36 credential_type: LACredentialType,
37 bytes: Zeroizing<Vec<u8>>,
38}
39
40impl LACredential {
41 #[must_use]
43 pub fn new(credential_type: LACredentialType, bytes: impl Into<Vec<u8>>) -> Self {
44 Self {
45 credential_type,
46 bytes: Zeroizing::new(bytes.into()),
47 }
48 }
49
50 #[must_use]
52 pub fn application_password(bytes: impl Into<Vec<u8>>) -> Self {
53 Self::new(LACredentialType::ApplicationPassword, bytes)
54 }
55
56 #[must_use]
58 pub fn smart_card_pin(bytes: impl Into<Vec<u8>>) -> Self {
59 Self::new(LACredentialType::SmartCardPin, bytes)
60 }
61
62 #[must_use]
64 pub const fn credential_type(&self) -> LACredentialType {
65 self.credential_type
66 }
67
68 #[must_use]
70 pub fn bytes(&self) -> &[u8] {
71 &self.bytes
72 }
73}
74
75impl fmt::Debug for LACredential {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 f.debug_struct("LACredential")
78 .field("credential_type", &self.credential_type)
79 .field("bytes", &"<redacted>")
80 .finish()
81 }
82}
83
84impl PartialEq for LACredential {
85 fn eq(&self, other: &Self) -> bool {
86 let same_bytes = constant_time_eq(&self.bytes, &other.bytes);
87 same_bytes && self.credential_type == other.credential_type
88 }
89}
90
91impl Eq for LACredential {}
92
93fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
94 if left.len() != right.len() {
95 return false;
96 }
97 let difference = left
98 .iter()
99 .zip(right)
100 .fold(0_u8, |difference, (left, right)| {
101 difference | (left ^ right)
102 });
103 std::hint::black_box(difference) == 0
104}