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
use crate::errors::{self, OlmUtilityError};
use std::ffi::CStr;
pub struct OlmUtility {
olm_utility_ptr: *mut olm_sys::OlmUtility,
olm_utility_buf_ptr: *mut [u8],
}
impl OlmUtility {
pub fn new() -> Self {
let olm_utility_buf: Vec<u8> = vec![0; unsafe { olm_sys::olm_utility_size() }];
let olm_utility_buf_ptr = Box::into_raw(olm_utility_buf.into_boxed_slice());
let olm_utility_ptr = unsafe { olm_sys::olm_utility(olm_utility_buf_ptr as *mut _) };
Self {
olm_utility_ptr,
olm_utility_buf_ptr,
}
}
fn last_error(olm_utility_ptr: *mut olm_sys::OlmUtility) -> OlmUtilityError {
let error_raw = unsafe { olm_sys::olm_utility_last_error(olm_utility_ptr) };
let error = unsafe { CStr::from_ptr(error_raw).to_str().unwrap() };
match error {
"BAD_MESSAGE_MAC" => OlmUtilityError::BadMessageMac,
"OUTPUT_BUFFER_TOO_SMALL" => OlmUtilityError::OutputBufferTooSmall,
"INVALID_BASE64" => OlmUtilityError::InvalidBase64,
_ => OlmUtilityError::Unknown,
}
}
pub fn sha256_bytes(&self, input_buf: &[u8]) -> String {
let output_len = unsafe { olm_sys::olm_sha256_length(self.olm_utility_ptr) };
let mut output_buf = vec![0; output_len];
let sha256_error = unsafe {
olm_sys::olm_sha256(
self.olm_utility_ptr,
input_buf.as_ptr() as *const _,
input_buf.len(),
output_buf.as_mut_ptr() as *mut _,
output_len,
)
};
let sha256_result = String::from_utf8(output_buf).unwrap();
if sha256_error == errors::olm_error() {
errors::handle_fatal_error(Self::last_error(self.olm_utility_ptr));
}
sha256_result
}
pub fn sha256_utf8_msg(&self, msg: &str) -> String {
self.sha256_bytes(msg.as_bytes())
}
pub fn ed25519_verify(
&self,
key: &str,
message: &str,
signature: &str,
) -> Result<bool, OlmUtilityError> {
let ed25519_verify_error = unsafe {
olm_sys::olm_ed25519_verify(
self.olm_utility_ptr,
key.as_ptr() as *const _,
key.len(),
message.as_ptr() as *const _,
message.len(),
signature.as_ptr() as *mut _,
signature.len(),
)
};
let ed25519_verify_result: usize = ed25519_verify_error;
if ed25519_verify_error == errors::olm_error() {
Err(Self::last_error(self.olm_utility_ptr))
} else {
Ok(ed25519_verify_result == 0)
}
}
}
impl Default for OlmUtility {
fn default() -> Self {
Self::new()
}
}
impl Drop for OlmUtility {
fn drop(&mut self) {
unsafe {
olm_sys::olm_clear_utility(self.olm_utility_ptr);
let _drop_utility_buf = Box::from_raw(self.olm_utility_buf_ptr);
}
}
}