Skip to content

Commit

Permalink
chore(strings): add trivial_encrypt
Browse files Browse the repository at this point in the history
  • Loading branch information
mayeul-zama committed Oct 28, 2024
1 parent 6ff5921 commit b99ceff
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
4 changes: 4 additions & 0 deletions tfhe/src/strings/ciphertext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,10 @@ impl FheAsciiChar {
}

impl FheString {
pub fn new_trivial(client_key: &ClientKey, str: &str, padding: Option<u32>) -> Self {
client_key.trivial_encrypt_ascii(str, padding)
}

/// Constructs a new `FheString` from a plaintext string, a [`ClientKey`] and an optional
/// padding length.
///
Expand Down
37 changes: 37 additions & 0 deletions tfhe/src/strings/client_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,32 @@ impl EncU16 {
}

impl ClientKey {
pub fn trivial_encrypt_ascii(&self, str: &str, padding: Option<u32>) -> FheString {
assert!(str.is_ascii() & !str.contains('\0'));

let padded = padding.map_or(false, |p| p != 0);

let num_blocks = dbg!(self.num_ascii_blocks());

let mut enc_string: Vec<_> = str
.bytes()
.map(|char| FheAsciiChar {
enc_char: self.create_trivial_radix(char, num_blocks),
})
.collect();

// Optional padding
if let Some(count) = padding {
let null = (0..count).map(|_| FheAsciiChar {
enc_char: self.create_trivial_radix(0u8, num_blocks),
});

enc_string.extend(null);
}

FheString { enc_string, padded }
}

/// Encrypts an ASCII string, optionally padding it with the specified amount of 0s, and returns
/// an [`FheString`].
///
Expand Down Expand Up @@ -103,6 +129,17 @@ impl ClientKey {
String::from_utf8(bytes).unwrap()
}

pub fn trivial_encrypt_u16(&self, val: u16, max: Option<u16>) -> EncU16 {
if let Some(max_val) = max {
assert!(val <= max_val, "val cannot be greater than max")
}

EncU16 {
cipher: self.create_trivial_radix(val, 8),
max,
}
}

/// Encrypts a u16 value. It also takes an optional `max` value to restrict the range
/// of the encrypted u16.
///
Expand Down

0 comments on commit b99ceff

Please sign in to comment.