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
pub mod auth;
pub mod easy;
pub mod mem {
use crate::{ECCEncryptedData, EnvelopedKeyData};
use skf_api::native::types::ECCPublicKeyBlob;
use std::cmp::min;
use std::ffi::CStr;
use std::slice;
/// Returns the position of the first null byte
///
/// [ptr] - The pointer to the buffer
///
/// [len] - The length of the buffer
///
/// # Examples
/// ```
/// use skf_rs::helper::mem::first_null_byte;
/// let ptr = b"Hello\0World\0".as_ptr();
/// unsafe {
/// assert_eq!(Some(5), first_null_byte(ptr, 12));
/// assert_eq!(None, first_null_byte(ptr, 5));
/// assert_eq!(Some(4), first_null_byte(ptr.add(1), 11));
/// assert_eq!(Some(0), first_null_byte(ptr.add(5), 7));
/// }
/// ```
#[inline]
#[must_use]
pub unsafe fn first_null_byte(ptr: *const u8, len: usize) -> Option<usize> {
let slice = unsafe { slice::from_raw_parts(ptr, len) };
slice.iter().position(|&x| x == 0)
}
/// Returns the position of the first two null byte
///
/// [ptr] - The pointer to the buffer
///
/// [len] - The length of the buffer
///
/// # Examples
/// ```
/// use skf_rs::helper::mem::first_two_null_byte;
/// let ptr = b"Hello\0World\0\0".as_ptr();
/// unsafe {
/// assert_eq!(Some(12), first_two_null_byte(ptr, 13));
/// assert_eq!(Some(11), first_two_null_byte(ptr.add(1), 12));
/// assert_eq!(None, first_two_null_byte(ptr, 12));
/// }
/// ```
#[inline]
#[must_use]
pub const unsafe fn first_two_null_byte(ptr: *const u8, len: usize) -> Option<usize> {
let mut pos = 0;
while pos < len {
if *ptr.add(pos) == 0 && pos + 1 < len && *ptr.add(pos + 1) == 0 {
return Some(pos + 1);
}
pos += 1;
}
None
}
/// Parse a C string from buffer
///
/// [ptr] - The pointer to the buffer
///
/// [len] - The length of the buffer
/// # Examples
/// ```
/// use std::ffi::CStr;
/// use skf_rs::helper::mem::parse_cstr;
/// let ptr = b"Hello\0World\0".as_ptr();
/// unsafe {
/// assert_eq!(Some(CStr::from_bytes_with_nul(b"Hello\0").unwrap()), parse_cstr(ptr, 12));
/// assert_eq!(Some(CStr::from_bytes_with_nul(b"lo\0").unwrap()), parse_cstr(ptr.add(3), 12));
/// assert_eq!(Some(CStr::from_bytes_with_nul(b"World\0").unwrap()), parse_cstr(ptr.add(6), 12));
/// assert_eq!(Some(CStr::from_bytes_with_nul(b"\0").unwrap()), parse_cstr(ptr.add(5), 1));
/// assert_eq!(None, parse_cstr(ptr, 1));
/// }
/// ```
#[inline]
#[must_use]
pub unsafe fn parse_cstr<'a>(ptr: *const u8, len: usize) -> Option<&'a CStr> {
let slice = unsafe { slice::from_raw_parts(ptr, len) };
CStr::from_bytes_until_nul(slice).ok()
}
/// Parse a C string from buffer, use `CStr::to_string_lossy` to convert data
///
/// [ptr] - The pointer to the buffer
///
/// [len] - The length of the buffer
#[must_use]
pub unsafe fn parse_cstr_lossy(ptr: *const u8, len: usize) -> Option<String> {
let val = unsafe { parse_cstr(ptr, len) };
val.map(|s| s.to_string_lossy().to_string())
}
/// Parse C string list from buffer, the list may end with two null byte
///
/// [ptr] - The pointer to the buffer
///
/// [len] - The length of the buffer
/// # Examples
/// ```
/// use std::ffi::CStr;
/// use skf_rs::helper::mem::parse_cstr_list;
/// unsafe {
/// let list = parse_cstr_list(b"Hello\0World\0\0".as_ptr(), 13);
/// assert_eq!(CStr::from_bytes_with_nul(b"Hello\0").unwrap(), *list.get(0).unwrap());
/// assert_eq!(CStr::from_bytes_with_nul(b"World\0").unwrap(), *list.get(1).unwrap());
///
/// let list = parse_cstr_list(b"Hello\0World\0".as_ptr(), 12);
/// assert_eq!(CStr::from_bytes_with_nul(b"Hello\0").unwrap(), *list.get(0).unwrap());
/// assert_eq!(CStr::from_bytes_with_nul(b"World\0").unwrap(), *list.get(1).unwrap());
///
/// let list = parse_cstr_list(b"Hello\0World".as_ptr(), 11);
/// assert_eq!(CStr::from_bytes_with_nul(b"Hello\0").unwrap(), *list.get(0).unwrap());
///
/// let list = parse_cstr_list(b"Hello".as_ptr(), 5);
/// assert!(list.is_empty());
/// }
/// ```
#[inline]
#[must_use]
pub unsafe fn parse_cstr_list<'a>(ptr: *const u8, len: usize) -> Vec<&'a CStr> {
let mut list: Vec<&CStr> = Vec::new();
let mut next_str = 0;
let mut pos = 0;
while pos < len {
if *ptr.add(pos) == 0 {
let bytes = slice::from_raw_parts(ptr.add(next_str), pos - next_str + 1);
list.push(CStr::from_bytes_with_nul_unchecked(bytes));
next_str = pos + 1;
if next_str < len && *ptr.add(next_str) == 0 {
break;
}
}
pos += 1;
}
list
}
/// Parse C string list from buffer, the list may end with two null byte
///
/// [ptr] - The pointer to the buffer
///
/// [len] - The length of the buffer
#[must_use]
pub unsafe fn parse_cstr_list_lossy(ptr: *const u8, len: usize) -> Vec<String> {
let list = unsafe { parse_cstr_list(ptr, len) };
list.iter()
.map(|s| s.to_string_lossy().to_string())
.collect()
}
/// Write string to buffer
///
/// [src] - The string to write,if too long, it will be truncated
///
/// [buffer] - The buffer to write to,at least one byte to fill with null byte
///
/// ## Memory copy
///
/// - if the string is too long,it will be truncated,and the last byte will be set to null byte
/// - if the string is smaller than the buffer size,it will be filled with null byte
///
/// ## example
/// ```
/// use skf_rs::helper::mem::write_cstr;
///
/// let mut buffer = [0u8; 11];
/// unsafe {
/// write_cstr("Hello World", &mut buffer);
///}
///assert_eq!(b"Hello Worl\0", &buffer);
///```
pub unsafe fn write_cstr(src: impl AsRef<str>, buffer: &mut [u8]) {
let src = src.as_ref().as_bytes();
let len = min(src.len(), buffer.len());
debug_assert!(len > 0);
unsafe {
std::ptr::copy(src.as_ptr(), buffer.as_mut_ptr(), len);
}
if len < buffer.len() {
buffer[len] = 0;
} else {
buffer[len - 1] = 0;
}
}
/// Write string to buffer
///
/// [src] - The string to write
///
/// [buffer_ptr] - The buffer to write to
///
/// [buffer_len] - The length of the buffer
pub unsafe fn write_cstr_ptr(src: impl AsRef<str>, buffer_ptr: *mut u8, buffer_len: usize) {
let bytes = slice::from_raw_parts_mut(buffer_ptr, buffer_len);
write_cstr(src, bytes);
}
impl ECCEncryptedData {
/// Convert to bytes of `ECCCipherBlob`
pub fn blob_bytes(&self) -> Vec<u8> {
use skf_api::native::types::ULONG;
let len = 64 + 64 + 32 + 4 + self.cipher.len();
let mut vec: Vec<u8> = Vec::with_capacity(len);
let cipher_len: [u8; 4] = (self.cipher.len() as ULONG).to_ne_bytes();
vec.extend_from_slice(&self.ec_x);
vec.extend_from_slice(&self.ec_y);
vec.extend_from_slice(&self.hash);
vec.extend_from_slice(&cipher_len);
vec.extend_from_slice(&self.cipher);
vec
}
}
impl EnvelopedKeyData {
/// Convert to bytes of `EnvelopedKeyBlob`
pub fn blob_bytes(&self) -> Vec<u8> {
use skf_api::native::types::ULONG;
let cipher_blob = self.ecc_cipher.blob_bytes();
let len = 4 + 4 + 4 + 64 + std::mem::size_of::<ECCPublicKeyBlob>() + cipher_blob.len();
let mut vec: Vec<u8> = Vec::with_capacity(len);
// version
let bytes: [u8; 4] = (self.version as ULONG).to_ne_bytes();
vec.extend_from_slice(&bytes);
// sym_alg_id
let bytes: [u8; 4] = (self.sym_alg_id as ULONG).to_ne_bytes();
vec.extend_from_slice(&bytes);
// bits
let bytes: [u8; 4] = (self.bits as ULONG).to_ne_bytes();
vec.extend_from_slice(&bytes);
// encrypted_pri_key
vec.extend_from_slice(&self.encrypted_pri_key);
// pub_key.bit_len
let bytes: [u8; 4] = (self.pub_key.bit_len as ULONG).to_ne_bytes();
vec.extend_from_slice(&bytes);
// pub_key.x_coordinate
vec.extend_from_slice(&self.pub_key.x_coordinate);
// pub_key.y_coordinate
vec.extend_from_slice(&self.pub_key.y_coordinate);
// cipher
vec.extend_from_slice(&cipher_blob);
vec
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ECCEncryptedData;
#[test]
fn parse_terminated_cstr_list_test() {
unsafe {
let list = parse_cstr_list(b"Hello\0\0".as_ptr(), 7);
assert_eq!(1, list.len());
let list = parse_cstr_list(b"Hello\0World\0\0".as_ptr(), 13);
assert_eq!(
CStr::from_bytes_with_nul(b"Hello\0").unwrap(),
*list.first().unwrap()
);
assert_eq!(
CStr::from_bytes_with_nul(b"World\0").unwrap(),
*list.get(1).unwrap()
);
}
}
#[test]
fn write_cstr_test() {
let input = "Hello World";
let mut buffer = [0u8; 12];
unsafe {
write_cstr(input, &mut buffer);
}
assert_eq!(b"Hello World\0", &buffer);
let mut buffer = [0u8; 11];
unsafe {
write_cstr(input, &mut buffer);
}
assert_eq!(b"Hello Worl\0", &buffer);
let mut buffer = [0u8; 1];
unsafe {
write_cstr(input, &mut buffer);
}
assert_eq!(b"\0", &buffer);
}
#[test]
fn cipher_blob_data_test() {
use skf_api::native::types::ECCCipherBlob;
let data = ECCEncryptedData {
ec_x: [1u8; 64],
ec_y: [2u8; 64],
hash: [3u8; 32],
cipher: vec![1u8, 2u8, 3u8, 4u8, 5u8],
};
let mem = data.blob_bytes();
assert_eq!(mem.len(), 64 + 64 + 32 + 4 + 5);
unsafe {
let blob_ptr = mem.as_ptr() as *const ECCCipherBlob;
let blob = &*blob_ptr;
assert_eq!(blob.x_coordinate, [1u8; 64]);
assert_eq!(blob.y_coordinate, [2u8; 64]);
assert_eq!(blob.hash, [3u8; 32]);
assert_eq!(std::ptr::addr_of!(blob.cipher_len).read_unaligned(), 5);
assert_eq!(blob.cipher, [1u8]);
}
}
}
}
pub mod param {
use crate::error::InvalidArgumentError;
use crate::Result;
use std::ffi::CString;
/// Convert `&str` to `CString`
///
/// ## Errors
/// This function will return an error if conversion from `&str` to `CString` fails,The error message use `param_name` to describe the parameter.
pub fn as_cstring(
param_name: impl AsRef<str>,
param_value: impl AsRef<str>,
) -> Result<CString> {
let value = CString::new(param_value.as_ref()).map_err(|e| {
InvalidArgumentError::new(
format!("parameter '{}' is invalid", param_name.as_ref()),
Some(anyhow::Error::new(e)),
)
})?;
Ok(value)
}
}