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
use crate::integer::ServerKey as IntegerServerKey;
use crate::strings::ciphertext::{FheString, UIntArg};
use crate::strings::server_key::{FheStringIsEmpty, FheStringLen, ServerKey};
use rayon::prelude::*;
use std::borrow::Borrow;
impl<T: Borrow<IntegerServerKey> + Sync> ServerKey<T> {
/// Returns the length of an encrypted string as an `FheStringLen` enum.
///
/// If the encrypted string has no padding, the length is the clear length of the char vector.
/// If there is padding, the length is calculated homomorphically and returned as an
/// encrypted `RadixCiphertext`.
///
/// # Examples
///
/// ```rust
/// use tfhe::integer::{ClientKey, ServerKey};
/// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;
/// use tfhe::strings::ciphertext::FheString;
/// use tfhe::strings::server_key::FheStringLen;
/// let ck = ClientKey::new(PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128);
/// let sk = ServerKey::new_radix_server_key(&ck);
/// let ck = tfhe::strings::ClientKey::new(ck);
/// let sk = tfhe::strings::ServerKey::new(sk);
/// let s = "hello";
/// let number_of_nulls = 3;
///
/// let enc_s_no_padding = FheString::new(&ck, s, None);
/// let enc_s_with_padding = FheString::new(&ck, s, Some(number_of_nulls));
///
/// let result_no_padding = sk.len(&enc_s_no_padding);
/// let result_with_padding = sk.len(&enc_s_with_padding);
///
/// match result_no_padding {
/// FheStringLen::NoPadding(length) => assert_eq!(length, 5),
/// FheStringLen::Padding(_) => panic!("Unexpected padding"),
/// }
///
/// match result_with_padding {
/// FheStringLen::NoPadding(_) => panic!("Unexpected no padding"),
/// FheStringLen::Padding(ciphertext) => {
/// // Homomorphically computed length, requires decryption for actual length
/// let length = ck.inner().decrypt_radix::<u32>(&ciphertext);
/// assert_eq!(length, 5)
/// }
/// }
/// ```
pub fn len(&self, str: &FheString) -> FheStringLen {
let sk = self.inner();
if str.is_padded() {
let non_zero_chars: Vec<_> = str
.chars()
.par_iter()
.map(|char| {
let bool = sk.scalar_ne_parallelized(char.ciphertext(), 0u8);
bool.into_radix(16, sk)
})
.collect();
// If we add the number of non-zero elements we get the actual length, without padding
let len = sk
.sum_ciphertexts_parallelized(non_zero_chars.iter())
.expect("There's at least one padding character");
FheStringLen::Padding(len)
} else {
FheStringLen::NoPadding(str.len())
}
}
/// Returns whether an encrypted string is empty or not as an `FheStringIsEmpty` enum.
///
/// If the encrypted string has no padding, the result is a clear boolean.
/// If there is padding, the result is calculated homomorphically and returned as an
/// encrypted `RadixCiphertext`.
///
/// # Examples
///
/// ```rust
/// use tfhe::integer::{ClientKey, ServerKey};
/// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;
/// use tfhe::strings::ciphertext::FheString;
/// use tfhe::strings::server_key::FheStringIsEmpty;
///
/// let ck = ClientKey::new(PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128);
/// let sk = ServerKey::new_radix_server_key(&ck);
/// let ck = tfhe::strings::ClientKey::new(ck);
/// let sk = tfhe::strings::ServerKey::new(sk);
/// let s = "";
/// let number_of_nulls = 2;
///
/// let enc_s_no_padding = FheString::new(&ck, s, None);
/// let enc_s_with_padding = FheString::new(&ck, s, Some(number_of_nulls));
///
/// let result_no_padding = sk.is_empty(&enc_s_no_padding);
/// let result_with_padding = sk.is_empty(&enc_s_with_padding);
///
/// match result_no_padding {
/// FheStringIsEmpty::NoPadding(is_empty) => assert!(is_empty),
/// FheStringIsEmpty::Padding(_) => panic!("Unexpected padding"),
/// }
///
/// match result_with_padding {
/// FheStringIsEmpty::NoPadding(_) => panic!("Unexpected no padding"),
/// FheStringIsEmpty::Padding(ciphertext) => {
/// // Homomorphically computed emptiness, requires decryption for actual value
/// let is_empty = ck.inner().decrypt_bool(&ciphertext);
/// assert!(is_empty)
/// }
/// }
/// ```
pub fn is_empty(&self, str: &FheString) -> FheStringIsEmpty {
let sk = self.inner();
if str.is_padded() {
if str.len() == 1 {
return FheStringIsEmpty::Padding(sk.create_trivial_boolean_block(true));
}
let str_uint = str.to_uint();
let result = sk.scalar_eq_parallelized(&str_uint, 0u8);
FheStringIsEmpty::Padding(result)
} else {
FheStringIsEmpty::NoPadding(str.len() == 0)
}
}
/// Returns a new encrypted string with all characters converted to uppercase.
///
/// # Examples
///
/// ```rust
/// use tfhe::integer::{ClientKey, ServerKey};
/// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;
/// use tfhe::strings::ciphertext::FheString;
///
/// let ck = ClientKey::new(PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128);
/// let sk = ServerKey::new_radix_server_key(&ck);
/// let ck = tfhe::strings::ClientKey::new(ck);
/// let sk = tfhe::strings::ServerKey::new(sk);
/// let s = "Hello World";
///
/// let enc_s = FheString::new(&ck, s, None);
///
/// let result = sk.to_uppercase(&enc_s);
/// let uppercased = ck.decrypt_ascii(&result);
///
/// assert_eq!(uppercased, "HELLO WORLD");
/// ```
pub fn to_uppercase(&self, str: &FheString) -> FheString {
let sk = self.inner();
let mut uppercase = str.clone();
// Returns 1 if the corresponding character is lowercase, 0 otherwise
let lowercase_chars: Vec<_> = str
.chars()
.par_iter()
.map(|char| {
let (ge_97, le_122) = rayon::join(
|| sk.scalar_ge_parallelized(char.ciphertext(), 97u8),
|| sk.scalar_le_parallelized(char.ciphertext(), 122u8),
);
sk.boolean_bitand(&ge_97, &le_122)
})
.collect();
// Subtraction by 32 makes the character uppercase
uppercase
.chars_mut()
.par_iter_mut()
.zip(lowercase_chars.into_par_iter())
.for_each(|(char, is_lowercase)| {
let mut subtract = sk.create_trivial_radix(32, self.num_ascii_blocks());
sk.mul_assign_parallelized(&mut subtract, &is_lowercase.into_radix(1, sk));
sk.sub_assign_parallelized(char.ciphertext_mut(), &subtract);
});
uppercase
}
/// Returns a new encrypted string with all characters converted to lowercase.
///
/// # Examples
///
/// ```rust
/// use tfhe::integer::{ClientKey, ServerKey};
/// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;
/// use tfhe::strings::ciphertext::FheString;
///
/// let ck = ClientKey::new(PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128);
/// let sk = ServerKey::new_radix_server_key(&ck);
/// let ck = tfhe::strings::ClientKey::new(ck);
/// let sk = tfhe::strings::ServerKey::new(sk);
/// let s = "Hello World";
///
/// let enc_s = FheString::new(&ck, s, None);
///
/// let result = sk.to_lowercase(&enc_s);
/// let lowercased = ck.decrypt_ascii(&result);
///
/// assert_eq!(lowercased, "hello world");
/// ```
pub fn to_lowercase(&self, str: &FheString) -> FheString {
let sk = self.inner();
let mut lowercase = str.clone();
// Returns 1 if the corresponding character is uppercase, 0 otherwise
let uppercase_chars: Vec<_> = str
.chars()
.par_iter()
.map(|char| {
let (ge_65, le_90) = rayon::join(
|| sk.scalar_ge_parallelized(char.ciphertext(), 65u8),
|| sk.scalar_le_parallelized(char.ciphertext(), 90u8),
);
sk.boolean_bitand(&ge_65, &le_90)
})
.collect();
// Addition by 32 makes the character lowercase
lowercase
.chars_mut()
.par_iter_mut()
.zip(uppercase_chars)
.for_each(|(char, is_uppercase)| {
let mut add = sk.create_trivial_radix(32, self.num_ascii_blocks());
sk.mul_assign_parallelized(&mut add, &is_uppercase.into_radix(1, sk));
sk.add_assign_parallelized(char.ciphertext_mut(), &add);
});
lowercase
}
/// Concatenates two encrypted strings and returns the result as a new encrypted string.
///
/// This function is equivalent to using the `+` operator on standard strings.
///
/// # Examples
///
/// ```rust
/// use tfhe::integer::{ClientKey, ServerKey};
/// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;
/// use tfhe::strings::ciphertext::FheString;
///
/// let ck = ClientKey::new(PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128);
/// let sk = ServerKey::new_radix_server_key(&ck);
/// let ck = tfhe::strings::ClientKey::new(ck);
/// let sk = tfhe::strings::ServerKey::new(sk);
/// let (lhs, rhs) = ("Hello, ", "world!");
///
/// let enc_lhs = FheString::new(&ck, lhs, None);
/// let enc_rhs = FheString::new(&ck, rhs, None);
///
/// let result = sk.concat(&enc_lhs, &enc_rhs);
/// let concatenated = ck.decrypt_ascii(&result);
///
/// assert_eq!(concatenated, "Hello, world!");
/// ```
pub fn concat(&self, lhs: &FheString, rhs: &FheString) -> FheString {
let sk = self.inner();
let mut result = lhs.clone();
match self.len(lhs) {
// No homomorphic operation required if the lhs is not padded
FheStringLen::NoPadding(_) => {
result.chars_vec().extend_from_slice(rhs.chars());
result.set_is_padded(rhs.is_padded());
}
// If lhs is padded we can shift it right such that all nulls move to the start, then
// we append the rhs and shift it left again to move the nulls to the new end
FheStringLen::Padding(len) => {
let padded_len = sk.create_trivial_radix(lhs.len() as u32, 16);
let number_of_nulls = sk.sub_parallelized(&padded_len, &len);
result = self.right_shift_chars(&result, &number_of_nulls);
result.chars_vec().extend_from_slice(rhs.chars());
result = self.left_shift_chars(&result, &number_of_nulls);
result.set_is_padded(true);
}
}
result
}
/// Returns a new encrypted string which is the original encrypted string repeated `n` times.
///
/// The number of repetitions `n` is specified by a `UIntArg`, which can be either `Clear` or
/// `Enc`.
///
/// # Examples
///
/// ```rust
/// use tfhe::integer::{ClientKey, ServerKey};
/// use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;
/// use tfhe::strings::ciphertext::{FheString, UIntArg};
///
/// let ck = ClientKey::new(PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128);
/// let sk = ServerKey::new_radix_server_key(&ck);
/// let ck = tfhe::strings::ClientKey::new(ck);
/// let sk = tfhe::strings::ServerKey::new(sk);
/// let s = "hi";
///
/// let enc_s = FheString::new(&ck, s, None);
///
/// // Using Clear count
/// let clear_count = UIntArg::Clear(3);
/// let result_clear = sk.repeat(&enc_s, &clear_count);
/// let repeated_clear = ck.decrypt_ascii(&result_clear);
///
/// assert_eq!(repeated_clear, "hihihi");
///
/// // Using Encrypted count
/// let max = 3; // Restricts the range of enc_n to 0..=max
/// let enc_n = ck.encrypt_u16(3, Some(max));
/// let enc_count = UIntArg::Enc(enc_n);
/// let result_enc = sk.repeat(&enc_s, &enc_count);
/// let repeated_enc = ck.decrypt_ascii(&result_enc);
///
/// assert_eq!(repeated_enc, "hihihi");
/// ```
pub fn repeat(&self, str: &FheString, n: &UIntArg) -> FheString {
let sk = self.inner();
if matches!(n, UIntArg::Clear(0)) {
return FheString::empty();
}
if str.is_empty() {
return FheString::empty();
}
let mut result = str.clone();
// Note that if n = 3, at most we have to append the str 2 times
match n {
UIntArg::Clear(clear_n) => {
for _ in 0..*clear_n - 1 {
result = self.concat(&result, str);
}
}
UIntArg::Enc(enc_n) => {
let n_is_zero = sk.scalar_eq_parallelized(enc_n.cipher(), 0);
result = self.conditional_string(&n_is_zero, &FheString::empty(), &result);
for i in 0..enc_n.max().unwrap_or(u16::MAX).saturating_sub(1) {
let n_is_exceeded = sk.scalar_le_parallelized(enc_n.cipher(), i + 1);
let append = self.conditional_string(&n_is_exceeded, &FheString::empty(), str);
result = self.concat(&result, &append);
}
// If str was not padded and n == max we don't get nulls at the end. However if
// n < max we do, and as these conditions are unknown we have to ensure result is
// actually padded
if !str.is_padded() {
result.append_null(self);
}
}
}
result
}
}