mssql-auth 0.8.0

Authentication strategies for SQL Server connections
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
//! Windows Certificate Store Column Master Key (CMK) provider for Always Encrypted.
//!
//! This module provides integration with the Windows Certificate Store for secure key
//! management in SQL Server Always Encrypted scenarios.
//!
//! ## Overview
//!
//! The Windows Certificate Store is the operating system's built-in secure storage
//! for certificates and their associated private keys. This provider uses the Windows
//! CNG (Cryptography Next Generation) APIs to perform cryptographic operations.
//!
//! ## CMK Path Format
//!
//! The CMK path for Windows Certificate Store follows this format:
//!
//! ```text
//! CurrentUser/My/<thumbprint>
//! LocalMachine/My/<thumbprint>
//! ```
//!
//! Where:
//! - `CurrentUser` or `LocalMachine` specifies the store location
//! - `My` is the store name (typically "My" for personal certificates)
//! - `<thumbprint>` is the certificate's SHA-1 thumbprint in hex format
//!
//! ## Security Considerations
//!
//! - Private keys never leave the Windows CNG key storage
//! - Access is controlled via Windows ACLs on the private key
//! - Hardware keys (TPM, smart cards) are supported transparently
//! - All operations use the Windows CNG API, not the legacy CryptoAPI
//!
//! ## Example
//!
//! ```rust,ignore
//! use mssql_auth::windows_certstore::WindowsCertStoreProvider;
//! use mssql_auth::ColumnEncryptionConfig;
//!
//! // Create provider
//! let provider = WindowsCertStoreProvider::new();
//!
//! // Register with encryption config
//! let config = ColumnEncryptionConfig::new()
//!     .with_provider(provider);
//! ```
//!
//! ## Platform Requirements
//!
//! This module is only available on Windows and requires the `windows-certstore` feature.

use std::ffi::c_void;

use tracing::{debug, instrument};
use windows::Win32::Foundation::BOOL;
use windows::Win32::Security::Cryptography::CryptAcquireCertificatePrivateKey;
use windows::Win32::Security::Cryptography::{
    BCRYPT_OAEP_PADDING_INFO,
    // Constants
    BCRYPT_PAD_OAEP,
    BCRYPT_PAD_PKCS1,
    BCRYPT_PKCS1_PADDING_INFO,
    CERT_CLOSE_STORE_CHECK_FLAG,
    CERT_FIND_HASH,
    CERT_OPEN_STORE_FLAGS,
    CERT_QUERY_ENCODING_TYPE,
    CERT_STORE_PROV_SYSTEM_W,
    CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG,
    CRYPT_HASH_BLOB,
    // Certificate store functions
    CertCloseStore,
    CertFindCertificateInStore,
    CertFreeCertificateContext,
    CertOpenStore,
    NCRYPT_FLAGS,
    NCRYPT_KEY_HANDLE,
    NCRYPT_SILENT_FLAG,
    // CNG functions
    NCryptDecrypt,
    NCryptFreeObject,
    NCryptSignHash,
    NCryptVerifySignature,
    X509_ASN_ENCODING,
};
use windows::core::PCWSTR;

use crate::encryption::{EncryptionError, KeyStoreProvider};

/// SQL Server provider name for Windows Certificate Store.
const PROVIDER_NAME: &str = "MSSQL_CERTIFICATE_STORE";

/// Windows Certificate Store Column Master Key provider.
///
/// This provider implements the [`KeyStoreProvider`] trait to support
/// Always Encrypted operations using certificates stored in the Windows
/// Certificate Store.
///
/// ## Thread Safety
///
/// This provider is `Send + Sync` and can be safely shared across threads.
/// However, the underlying Windows CNG handles are managed per-operation.
#[derive(Debug, Clone, Default)]
pub struct WindowsCertStoreProvider {
    _private: (),
}

impl WindowsCertStoreProvider {
    /// Create a new Windows Certificate Store provider.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let provider = WindowsCertStoreProvider::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self { _private: () }
    }

    /// Parse a CMK path into store location, store name, and thumbprint.
    ///
    /// Expected format: `<StoreLocation>/<StoreName>/<Thumbprint>`
    ///
    /// Examples:
    /// - `CurrentUser/My/ABC123...`
    /// - `LocalMachine/My/DEF456...`
    fn parse_cmk_path(cmk_path: &str) -> Result<(StoreLocation, String, Vec<u8>), EncryptionError> {
        let parts: Vec<&str> = cmk_path.split('/').collect();

        if parts.len() < 3 {
            return Err(EncryptionError::CmkError(format!(
                "Invalid CMK path format: expected '<StoreLocation>/<StoreName>/<Thumbprint>', got '{}'",
                cmk_path
            )));
        }

        let store_location = match parts[0].to_uppercase().as_str() {
            "CURRENTUSER" | "CURRENT_USER" => StoreLocation::CurrentUser,
            "LOCALMACHINE" | "LOCAL_MACHINE" => StoreLocation::LocalMachine,
            _ => {
                return Err(EncryptionError::CmkError(format!(
                    "Unknown store location: '{}'. Expected 'CurrentUser' or 'LocalMachine'",
                    parts[0]
                )));
            }
        };

        let store_name = parts[1].to_string();

        // Parse thumbprint (hex string)
        let thumbprint_hex = parts[2..].join("");
        let thumbprint = hex_to_bytes(&thumbprint_hex)
            .map_err(|e| EncryptionError::CmkError(format!("Invalid thumbprint hex: {}", e)))?;

        Ok((store_location, store_name, thumbprint))
    }

    /// Get a certificate's private key handle from the Windows Certificate Store.
    fn get_private_key(
        store_location: StoreLocation,
        store_name: &str,
        thumbprint: &[u8],
    ) -> Result<CngKeyHandle, EncryptionError> {
        // Open the certificate store
        let store_name_wide: Vec<u16> = store_name
            .encode_utf16()
            .chain(std::iter::once(0))
            .collect();

        // SAFETY: CertOpenStore is called with a valid null-terminated UTF-16 store name
        // (store_name_wide, created above). The returned handle is checked for errors and
        // wrapped in CertStoreGuard for RAII cleanup via CertCloseStore.
        let store = unsafe {
            CertOpenStore(
                CERT_STORE_PROV_SYSTEM_W,
                CERT_QUERY_ENCODING_TYPE(0),
                None,
                CERT_OPEN_STORE_FLAGS(store_location.to_flags()),
                Some(store_name_wide.as_ptr() as *const c_void),
            )
        }
        .map_err(|e| {
            EncryptionError::CmkError(format!(
                "Failed to open certificate store '{}': {}",
                store_name, e
            ))
        })?;

        // Create RAII wrapper for store
        let store_guard = CertStoreGuard(store);

        // Create hash blob for certificate lookup
        let hash_blob = CRYPT_HASH_BLOB {
            cbData: thumbprint.len() as u32,
            pbData: thumbprint.as_ptr() as *mut u8,
        };

        // Find the certificate by thumbprint
        // SAFETY: store_guard.0 is a valid store handle (from CertOpenStore above).
        // hash_blob points to the stack-allocated thumbprint slice which outlives this call.
        // The returned pointer is checked for null before use and wrapped in CertContextGuard.
        let cert_context = unsafe {
            CertFindCertificateInStore(
                store_guard.0,
                X509_ASN_ENCODING,
                0,
                CERT_FIND_HASH,
                Some(&hash_blob as *const _ as *const c_void),
                None,
            )
        };

        if cert_context.is_null() {
            return Err(EncryptionError::CmkError(format!(
                "Certificate not found with thumbprint: {}",
                bytes_to_hex(thumbprint)
            )));
        }

        // Create RAII wrapper for certificate context
        let cert_guard = CertContextGuard(cert_context);

        // Acquire the private key
        let mut key_handle = NCRYPT_KEY_HANDLE::default();
        let mut key_spec = 0u32;
        let mut caller_free = BOOL::from(false);

        // SAFETY: cert_guard.0 is a valid certificate context (from CertFindCertificateInStore).
        // Output parameters (key_handle, key_spec, caller_free) are stack-allocated mutable
        // references. The result is checked before using key_handle, which is then wrapped
        // in CngKeyHandle for RAII cleanup via NCryptFreeObject.
        let result = unsafe {
            CryptAcquireCertificatePrivateKey(
                cert_guard.0,
                CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG,
                None,
                &mut key_handle,
                Some(&mut key_spec),
                Some(&mut caller_free),
            )
        };

        if result.is_err() {
            return Err(EncryptionError::CmkError(format!(
                "Failed to acquire private key for certificate: {:?}",
                result.err()
            )));
        }

        Ok(CngKeyHandle {
            handle: key_handle,
            should_free: caller_free.as_bool(),
        })
    }
}

#[async_trait::async_trait]
impl KeyStoreProvider for WindowsCertStoreProvider {
    fn provider_name(&self) -> &str {
        PROVIDER_NAME
    }

    #[instrument(skip(self, encrypted_cek), fields(cmk_path = %cmk_path, algorithm = %algorithm))]
    async fn decrypt_cek(
        &self,
        cmk_path: &str,
        algorithm: &str,
        encrypted_cek: &[u8],
    ) -> Result<Vec<u8>, EncryptionError> {
        debug!("Decrypting CEK using Windows Certificate Store");

        // Parse the CMK path
        let (store_location, store_name, thumbprint) = Self::parse_cmk_path(cmk_path)?;

        // Get the private key handle
        let key_handle = Self::get_private_key(store_location, &store_name, &thumbprint)?;

        // Parse the SQL Server encrypted CEK format
        let ciphertext = parse_sql_server_encrypted_cek(encrypted_cek)?;

        // Determine padding based on algorithm
        let (padding_info, flags) = get_padding_info(algorithm)?;

        // First call to get required output size
        let mut result_size = 0u32;
        // SAFETY: key_handle.handle is valid (from CryptAcquireCertificatePrivateKey).
        // ciphertext is a valid &[u8] slice. padding_info.as_ptr() points to the stack-
        // allocated PaddingInfo enum. Output buffer is None (size query only). The result
        // is checked before using result_size.
        let decrypt_result = unsafe {
            NCryptDecrypt(
                key_handle.handle,
                Some(ciphertext),
                Some(padding_info.as_ptr()),
                None,
                &mut result_size,
                flags,
            )
        };

        if decrypt_result.is_err() {
            return Err(EncryptionError::CekDecryptionFailed(format!(
                "NCryptDecrypt (size query) failed: {:?}",
                decrypt_result.err()
            )));
        }

        // Allocate buffer and perform actual decryption
        let mut output = vec![0u8; result_size as usize];
        // SAFETY: Same preconditions as the size query above. output is a freshly allocated
        // Vec with capacity from the size query. result_size is updated with actual bytes
        // written, and output is truncated to this size to prevent reading uninitialized memory.
        let decrypt_result = unsafe {
            NCryptDecrypt(
                key_handle.handle,
                Some(ciphertext),
                Some(padding_info.as_ptr()),
                Some(&mut output),
                &mut result_size,
                flags,
            )
        };

        if decrypt_result.is_err() {
            return Err(EncryptionError::CekDecryptionFailed(format!(
                "NCryptDecrypt failed: {:?}",
                decrypt_result.err()
            )));
        }

        output.truncate(result_size as usize);
        debug!("Successfully decrypted CEK using Windows Certificate Store");
        Ok(output)
    }

    #[instrument(skip(self, data), fields(cmk_path = %cmk_path))]
    async fn sign_data(&self, cmk_path: &str, data: &[u8]) -> Result<Vec<u8>, EncryptionError> {
        debug!("Signing data using Windows Certificate Store");

        // Parse the CMK path
        let (store_location, store_name, thumbprint) = Self::parse_cmk_path(cmk_path)?;

        // Get the private key handle
        let key_handle = Self::get_private_key(store_location, &store_name, &thumbprint)?;

        // Use PKCS#1 v1.5 padding with SHA-256 for signing
        let hash_algorithm: Vec<u16> = "SHA256\0".encode_utf16().collect();
        let padding_info = BCRYPT_PKCS1_PADDING_INFO {
            pszAlgId: PCWSTR(hash_algorithm.as_ptr()),
        };

        // First call to get required signature size
        let mut sig_size = 0u32;
        // SAFETY: key_handle.handle is valid. padding_info is a stack-allocated
        // BCRYPT_PKCS1_PADDING_INFO with pszAlgId pointing to hash_algorithm (valid for
        // the duration of this call). data is a valid &[u8]. Output buffer is None
        // (size query). Result is checked before using sig_size.
        let sign_result = unsafe {
            NCryptSignHash(
                key_handle.handle,
                Some(&padding_info as *const _ as *const c_void),
                data,
                None,
                &mut sig_size,
                BCRYPT_PAD_PKCS1,
            )
        };

        if sign_result.is_err() {
            return Err(EncryptionError::CmkError(format!(
                "NCryptSignHash (size query) failed: {:?}",
                sign_result.err()
            )));
        }

        // Allocate buffer and perform actual signing
        let mut signature = vec![0u8; sig_size as usize];
        // SAFETY: Same preconditions as the size query above. signature is a freshly
        // allocated Vec with capacity from the size query. sig_size is updated with actual
        // bytes written, and signature is truncated to this size.
        let sign_result = unsafe {
            NCryptSignHash(
                key_handle.handle,
                Some(&padding_info as *const _ as *const c_void),
                data,
                Some(&mut signature),
                &mut sig_size,
                BCRYPT_PAD_PKCS1,
            )
        };

        if sign_result.is_err() {
            return Err(EncryptionError::CmkError(format!(
                "NCryptSignHash failed: {:?}",
                sign_result.err()
            )));
        }

        signature.truncate(sig_size as usize);
        debug!("Successfully signed data using Windows Certificate Store");
        Ok(signature)
    }

    #[instrument(skip(self, data, signature), fields(cmk_path = %cmk_path))]
    async fn verify_signature(
        &self,
        cmk_path: &str,
        data: &[u8],
        signature: &[u8],
    ) -> Result<bool, EncryptionError> {
        debug!("Verifying signature using Windows Certificate Store");

        // Parse the CMK path
        let (store_location, store_name, thumbprint) = Self::parse_cmk_path(cmk_path)?;

        // Get the private key handle (we'll use it for verification too)
        let key_handle = Self::get_private_key(store_location, &store_name, &thumbprint)?;

        // Use PKCS#1 v1.5 padding with SHA-256 for verification
        let hash_algorithm: Vec<u16> = "SHA256\0".encode_utf16().collect();
        let padding_info = BCRYPT_PKCS1_PADDING_INFO {
            pszAlgId: PCWSTR(hash_algorithm.as_ptr()),
        };

        // Perform verification
        // SAFETY: key_handle.handle is valid. padding_info is a stack-allocated
        // BCRYPT_PKCS1_PADDING_INFO. data and signature are valid &[u8] slices.
        // This is a read-only verification operation with no output buffers.
        let verify_result = unsafe {
            NCryptVerifySignature(
                key_handle.handle,
                Some(&padding_info as *const _ as *const c_void),
                data,
                signature,
                BCRYPT_PAD_PKCS1,
            )
        };

        let is_valid = verify_result.is_ok();
        debug!("Signature verification result: {}", is_valid);
        Ok(is_valid)
    }
}

/// Certificate store location.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StoreLocation {
    CurrentUser,
    LocalMachine,
}

impl StoreLocation {
    /// Convert to Windows store flags.
    fn to_flags(self) -> u32 {
        match self {
            StoreLocation::CurrentUser => 0x00010000, // CERT_SYSTEM_STORE_CURRENT_USER
            StoreLocation::LocalMachine => 0x00020000, // CERT_SYSTEM_STORE_LOCAL_MACHINE
        }
    }
}

/// RAII wrapper for certificate store handle.
struct CertStoreGuard(windows::Win32::Security::Cryptography::HCERTSTORE);

impl Drop for CertStoreGuard {
    fn drop(&mut self) {
        // SAFETY: self.0 was obtained from a successful CertOpenStore call. Drop is
        // called at most once (guaranteed by the type system). The return value is
        // intentionally ignored as cleanup errors during drop should not panic.
        let _ = unsafe { CertCloseStore(self.0, CERT_CLOSE_STORE_CHECK_FLAG) };
    }
}

/// RAII wrapper for certificate context.
struct CertContextGuard(*const windows::Win32::Security::Cryptography::CERT_CONTEXT);

impl Drop for CertContextGuard {
    fn drop(&mut self) {
        if !self.0.is_null() {
            // SAFETY: self.0 is checked for null before freeing. If non-null, it was
            // obtained from CertFindCertificateInStore. Drop is called at most once.
            unsafe { CertFreeCertificateContext(Some(self.0)) };
        }
    }
}

/// RAII wrapper for CNG key handle.
struct CngKeyHandle {
    handle: NCRYPT_KEY_HANDLE,
    should_free: bool,
}

impl Drop for CngKeyHandle {
    fn drop(&mut self) {
        if self.should_free && !self.handle.is_invalid() {
            // SAFETY: Freeing is guarded by should_free (set by CryptAcquireCertificatePrivateKey's
            // caller_free output) and is_invalid() (checks handle validity). Drop is called at
            // most once. The return value is intentionally ignored during cleanup.
            let _ = unsafe { NCryptFreeObject(self.handle.0 as _) };
        }
    }
}

/// Padding info wrapper that can hold either OAEP or PKCS1 padding.
enum PaddingInfo {
    Oaep(BCRYPT_OAEP_PADDING_INFO),
    #[allow(dead_code)]
    Pkcs1(BCRYPT_PKCS1_PADDING_INFO),
}

impl PaddingInfo {
    fn as_ptr(&self) -> *const c_void {
        match self {
            PaddingInfo::Oaep(info) => info as *const _ as *const c_void,
            PaddingInfo::Pkcs1(info) => info as *const _ as *const c_void,
        }
    }
}

/// Get padding info based on algorithm name.
fn get_padding_info(algorithm: &str) -> Result<(PaddingInfo, NCRYPT_FLAGS), EncryptionError> {
    // SHA-256 hash algorithm string (null-terminated UTF-16)
    static SHA256_ALG: &str = "SHA256\0";

    match algorithm.to_uppercase().as_str() {
        "RSA_OAEP" | "RSA-OAEP" | "RSA_OAEP_256" | "RSA-OAEP-256" => {
            let hash_alg: Vec<u16> = SHA256_ALG.encode_utf16().collect();
            // SAFETY: Box::leak is used intentionally to produce a 'static PCWSTR pointer.
            // BCRYPT_OAEP_PADDING_INFO requires a valid PCWSTR for its lifetime, but the
            // PaddingInfo is returned to the caller and may outlive any local borrow.
            // The leak is bounded: at most 2 allocations (one per algorithm branch) per
            // decrypt_cek call. This is acceptable because decrypt_cek is called infrequently
            // (only during CEK decryption for Always Encrypted column access).
            let hash_alg_ptr = Box::leak(hash_alg.into_boxed_slice());

            let info = BCRYPT_OAEP_PADDING_INFO {
                pszAlgId: PCWSTR(hash_alg_ptr.as_ptr()),
                pbLabel: std::ptr::null_mut(),
                cbLabel: 0,
            };
            Ok((
                PaddingInfo::Oaep(info),
                NCRYPT_FLAGS(BCRYPT_PAD_OAEP.0 | NCRYPT_SILENT_FLAG.0),
            ))
        }
        "RSA1_5" | "RSA-1_5" | "RSA_PKCS1" | "RSA-PKCS1" => {
            let hash_alg: Vec<u16> = SHA256_ALG.encode_utf16().collect();
            // SAFETY: Box::leak is used intentionally to produce a 'static PCWSTR pointer.
            // BCRYPT_PKCS1_PADDING_INFO requires a valid PCWSTR for its lifetime. See the
            // RSA_OAEP branch above for the full rationale. The leak is bounded to at most
            // 2 allocations per decrypt_cek call.
            let hash_alg_ptr = Box::leak(hash_alg.into_boxed_slice());

            let info = BCRYPT_PKCS1_PADDING_INFO {
                pszAlgId: PCWSTR(hash_alg_ptr.as_ptr()),
            };
            Ok((
                PaddingInfo::Pkcs1(info),
                NCRYPT_FLAGS(BCRYPT_PAD_PKCS1.0 | NCRYPT_SILENT_FLAG.0),
            ))
        }
        _ => Err(EncryptionError::ConfigurationError(format!(
            "Unsupported key encryption algorithm: {}. Expected RSA_OAEP, RSA_OAEP_256, or RSA1_5",
            algorithm
        ))),
    }
}

/// Parse the SQL Server encrypted CEK format to extract the raw ciphertext.
///
/// SQL Server CEK format:
/// - Version (1 byte): 0x01
/// - Key path length (2 bytes, LE)
/// - Key path (UTF-16LE)
/// - Ciphertext length (2 bytes, LE)
/// - Ciphertext (RSA encrypted CEK)
fn parse_sql_server_encrypted_cek(data: &[u8]) -> Result<&[u8], EncryptionError> {
    if data.len() < 5 {
        return Err(EncryptionError::CekDecryptionFailed(
            "Encrypted CEK too short".into(),
        ));
    }

    // Check version byte
    if data[0] != 0x01 {
        return Err(EncryptionError::CekDecryptionFailed(format!(
            "Invalid CEK version: expected 0x01, got {:#04x}",
            data[0]
        )));
    }

    // Read key path length (2 bytes, little-endian)
    let key_path_len = u16::from_le_bytes([data[1], data[2]]) as usize;

    // Calculate offset after key path
    let ciphertext_len_offset = 3 + key_path_len;
    if data.len() < ciphertext_len_offset + 2 {
        return Err(EncryptionError::CekDecryptionFailed(
            "Encrypted CEK truncated: missing ciphertext length".into(),
        ));
    }

    // Read ciphertext length (2 bytes, little-endian)
    let ciphertext_len =
        u16::from_le_bytes([data[ciphertext_len_offset], data[ciphertext_len_offset + 1]]) as usize;

    // Calculate ciphertext offset
    let ciphertext_offset = ciphertext_len_offset + 2;
    if data.len() < ciphertext_offset + ciphertext_len {
        return Err(EncryptionError::CekDecryptionFailed(format!(
            "Encrypted CEK truncated: expected {} bytes of ciphertext, got {}",
            ciphertext_len,
            data.len() - ciphertext_offset
        )));
    }

    Ok(&data[ciphertext_offset..ciphertext_offset + ciphertext_len])
}

/// Convert a hex string to bytes.
fn hex_to_bytes(hex: &str) -> Result<Vec<u8>, &'static str> {
    let hex = hex.trim();
    if hex.len() % 2 != 0 {
        return Err("Hex string has odd length");
    }

    hex.as_bytes()
        .chunks(2)
        .map(|chunk| {
            let high = char::from(chunk[0])
                .to_digit(16)
                .ok_or("Invalid hex digit")?;
            let low = char::from(chunk[1])
                .to_digit(16)
                .ok_or("Invalid hex digit")?;
            Ok((high * 16 + low) as u8)
        })
        .collect()
}

/// Convert bytes to hex string.
fn bytes_to_hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{:02X}", b)).collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_cmk_path() {
        // Valid path with CurrentUser
        let (location, name, thumb) =
            WindowsCertStoreProvider::parse_cmk_path("CurrentUser/My/AABBCCDD").unwrap();
        assert_eq!(location, StoreLocation::CurrentUser);
        assert_eq!(name, "My");
        assert_eq!(thumb, vec![0xAA, 0xBB, 0xCC, 0xDD]);

        // Valid path with LocalMachine (case insensitive)
        let (location, name, _) =
            WindowsCertStoreProvider::parse_cmk_path("localmachine/My/1234").unwrap();
        assert_eq!(location, StoreLocation::LocalMachine);
        assert_eq!(name, "My");

        // Valid path with underscores
        let (location, _, _) =
            WindowsCertStoreProvider::parse_cmk_path("Current_User/My/1234").unwrap();
        assert_eq!(location, StoreLocation::CurrentUser);
    }

    #[test]
    fn test_parse_cmk_path_invalid() {
        // Missing thumbprint
        assert!(WindowsCertStoreProvider::parse_cmk_path("CurrentUser/My").is_err());

        // Invalid location
        assert!(WindowsCertStoreProvider::parse_cmk_path("Invalid/My/1234").is_err());

        // Invalid hex
        assert!(WindowsCertStoreProvider::parse_cmk_path("CurrentUser/My/GGGG").is_err());
    }

    #[test]
    fn test_hex_conversion() {
        assert_eq!(
            hex_to_bytes("AABBCCDD").unwrap(),
            vec![0xAA, 0xBB, 0xCC, 0xDD]
        );
        assert_eq!(
            hex_to_bytes("aabbccdd").unwrap(),
            vec![0xAA, 0xBB, 0xCC, 0xDD]
        );
        assert_eq!(hex_to_bytes("").unwrap(), vec![]);
        assert!(hex_to_bytes("ABC").is_err()); // Odd length
        assert!(hex_to_bytes("GGGG").is_err()); // Invalid chars
    }

    #[test]
    fn test_bytes_to_hex() {
        assert_eq!(bytes_to_hex(&[0xAA, 0xBB, 0xCC, 0xDD]), "AABBCCDD");
        assert_eq!(bytes_to_hex(&[0x01, 0x02, 0x0F]), "01020F");
        assert_eq!(bytes_to_hex(&[]), "");
    }

    #[test]
    fn test_parse_sql_server_encrypted_cek() {
        // Create a valid encrypted CEK structure
        let key_path = "test";
        let key_path_utf16: Vec<u8> = key_path
            .encode_utf16()
            .flat_map(|c| c.to_le_bytes())
            .collect();
        let ciphertext = vec![0xAB, 0xCD, 0xEF];

        let mut data = Vec::new();
        data.push(0x01); // Version
        data.extend_from_slice(&(key_path_utf16.len() as u16).to_le_bytes());
        data.extend_from_slice(&key_path_utf16);
        data.extend_from_slice(&(ciphertext.len() as u16).to_le_bytes());
        data.extend_from_slice(&ciphertext);

        let parsed = parse_sql_server_encrypted_cek(&data).unwrap();
        assert_eq!(parsed, &ciphertext[..]);
    }

    #[test]
    fn test_parse_sql_server_encrypted_cek_invalid() {
        // Too short
        assert!(parse_sql_server_encrypted_cek(&[0x01, 0x00]).is_err());

        // Wrong version
        assert!(parse_sql_server_encrypted_cek(&[0x02, 0x00, 0x00, 0x00, 0x00]).is_err());
    }

    #[test]
    fn test_store_location_flags() {
        assert_eq!(StoreLocation::CurrentUser.to_flags(), 0x00010000);
        assert_eq!(StoreLocation::LocalMachine.to_flags(), 0x00020000);
    }
}