pub struct WrappedKey { /* private fields */ }Expand description
An encryption key wrapped (encrypted) by another key.
Used in the key hierarchy to protect DEKs with KEKs, and KEKs with the master key. The wrapped key can be safely stored on disk — it cannot be unwrapped without the wrapping key.
WrappedKey layout (60 bytes):
┌────────────────────────────┬────────────────────────────┬──────────────┐
│ nonce (12 bytes) │ encrypted key (32 bytes) │ tag (16) │
└────────────────────────────┴────────────────────────────┴──────────────┘§Security
- The wrapped ciphertext is encrypted, not raw key material
- The nonce is not secret (it’s stored alongside the ciphertext)
ZeroizeOnDropis not needed since this contains no plaintext secrets- The wrapping key (KEK/MK) is what must be protected
§Example
use kimberlite_crypto::encryption::{EncryptionKey, WrappedKey, KEY_LENGTH};
// KEK wraps a DEK
let kek = EncryptionKey::generate();
let dek_bytes: [u8; KEY_LENGTH] = [0x42; KEY_LENGTH]; // In practice, use generate()
let wrapped = WrappedKey::new(&kek, &dek_bytes);
// Store wrapped.to_bytes() on disk...
// Later, unwrap with the same KEK
let unwrapped = wrapped.unwrap_key(&kek).unwrap();
assert_eq!(dek_bytes, unwrapped);Implementations§
Source§impl WrappedKey
impl WrappedKey
Sourcepub fn new(wrapping_key: &EncryptionKey, key_to_wrap: &[u8; 32]) -> Self
pub fn new(wrapping_key: &EncryptionKey, key_to_wrap: &[u8; 32]) -> Self
Wraps (encrypts) a key using the provided wrapping key.
Generates a random nonce and encrypts the key material using AES-256-GCM. The nonce is stored alongside the ciphertext for later unwrapping.
§Arguments
wrapping_key- The key used to encrypt (KEK or master key)key_to_wrap- The 32-byte key material to protect (DEK or KEK)
§Returns
A WrappedKey that can be serialized and stored safely.
Sourcepub fn unwrap_key(
&self,
wrapping_key: &EncryptionKey,
) -> Result<[u8; 32], CryptoError>
pub fn unwrap_key( &self, wrapping_key: &EncryptionKey, ) -> Result<[u8; 32], CryptoError>
Unwraps (decrypts) the key using the provided wrapping key.
Verifies the authentication tag and returns the original key material if the wrapping key is correct.
§Arguments
wrapping_key- The key used during wrapping (must match)
§Errors
Returns CryptoError::DecryptionError if:
- The wrapping key is incorrect
- The wrapped data has been tampered with
§Returns
The original 32-byte key material.
Sourcepub fn to_bytes(&self) -> [u8; 60]
pub fn to_bytes(&self) -> [u8; 60]
Serializes the wrapped key to bytes for storage.
The format is: nonce (12 bytes) || ciphertext (48 bytes).
§Returns
A 60-byte array suitable for storing on disk or in a database.
Sourcepub fn from_bytes(bytes: &[u8; 60]) -> Self
pub fn from_bytes(bytes: &[u8; 60]) -> Self
Deserializes a wrapped key from bytes.
§Arguments
bytes- A 60-byte array fromWrappedKey::to_bytes
§Returns
A WrappedKey that can be unwrapped with the original wrapping key.