Major improvement, security handling, file handling +fixes
This commit is contained in:
@@ -99,6 +99,37 @@ impl DecryptStream {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn decrypt_bytes(ciphertext: &[u8], wrapped_key: &[u8], master_key: &MasterKey) -> cgcx_core::Result<Vec<u8>> {
|
||||
let key = unwrap_content_key(wrapped_key, master_key)?;
|
||||
if ciphertext.len() < 17 {
|
||||
return Err(cgcx_core::CgcxError::Crypto("ciphertext too short".into()));
|
||||
}
|
||||
let header = xchacha20poly1305::Header::from_slice(&ciphertext[..17])
|
||||
.ok_or_else(|| cgcx_core::CgcxError::Crypto("invalid header".into()))?;
|
||||
let mut stream = DecryptStream::new(&key, &header)?;
|
||||
let mut plaintext = Vec::new();
|
||||
let mut offset = 17;
|
||||
while offset < ciphertext.len() {
|
||||
if offset + 4 > ciphertext.len() {
|
||||
return Err(cgcx_core::CgcxError::Crypto("truncated length prefix".into()));
|
||||
}
|
||||
let len = u32::from_le_bytes([
|
||||
ciphertext[offset],
|
||||
ciphertext[offset + 1],
|
||||
ciphertext[offset + 2],
|
||||
ciphertext[offset + 3],
|
||||
]) as usize;
|
||||
offset += 4;
|
||||
if offset + len > ciphertext.len() {
|
||||
return Err(cgcx_core::CgcxError::Crypto("truncated ciphertext".into()));
|
||||
}
|
||||
let (pt, _tag) = stream.pull(&ciphertext[offset..offset + len])?;
|
||||
plaintext.extend_from_slice(&pt);
|
||||
offset += len;
|
||||
}
|
||||
Ok(plaintext)
|
||||
}
|
||||
|
||||
pub fn hash_file_at_path(path: &Path) -> cgcx_core::Result<[u8; 32]> {
|
||||
let mut hasher = Hasher::new();
|
||||
let mut file = std::fs::File::open(path)?;
|
||||
|
||||
Reference in New Issue
Block a user