Skip to main content

optee_utee/
arithmetical.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use crate::{Result, tee_check};
19#[cfg(not(feature = "std"))]
20use alloc::vec::Vec;
21use core::{cmp::max, fmt};
22use optee_utee_sys as raw;
23
24pub type BigIntUnit = u32;
25pub type BigIntFMMUnit = u32;
26pub type BigIntFMMContextUnit = u32;
27
28pub struct BigInt(Vec<BigIntUnit>);
29
30impl BigInt {
31    pub fn data_ptr(&self) -> *const u32 {
32        self.0.as_ptr()
33    }
34
35    // size represents BigInt bits
36    pub fn size_in_u32(size: u32) -> u32 {
37        size.div_ceil(32) + 2
38    }
39
40    pub fn new(bits: u32) -> Self {
41        let size: usize = Self::size_in_u32(bits) as usize;
42        let mut tmp_vec: Vec<BigIntUnit> = vec![0; size];
43        unsafe { raw::TEE_BigIntInit(tmp_vec.as_mut_ptr(), size) };
44        Self(tmp_vec)
45    }
46
47    pub fn convert_from_octet_string(&mut self, buffer: &[u8], sign: i32) -> Result<()> {
48        tee_check(unsafe {
49            raw::TEE_BigIntConvertFromOctetString(
50                self.0.as_mut_ptr(),
51                buffer.as_ptr(),
52                buffer.len(),
53                sign,
54            )
55        })
56    }
57
58    pub fn convert_to_octet_string(&self) -> Result<Vec<u8>> {
59        let mut buffer_size: usize = (self.0.len() - 2) * 4;
60        let mut tmp_vec = vec![0u8; buffer_size];
61        tee_check(unsafe {
62            raw::TEE_BigIntConvertToOctetString(
63                tmp_vec.as_mut_ptr(),
64                &mut buffer_size,
65                self.data_ptr(),
66            )
67        })?;
68        tmp_vec.truncate(buffer_size);
69        Ok(tmp_vec)
70    }
71
72    pub fn convert_from_s32(&mut self, short_val: i32) {
73        unsafe { raw::TEE_BigIntConvertFromS32(self.0.as_mut_ptr(), short_val) };
74    }
75
76    pub fn convert_to_s32(&self) -> Result<i32> {
77        let mut short_val: i32 = 0;
78        tee_check(unsafe { raw::TEE_BigIntConvertToS32(&mut short_val as _, self.data_ptr()) })?;
79        Ok(short_val)
80    }
81
82    /* return negative number if self < target,
83    0 if self == target
84    positive number if self > target*/
85    pub fn compare_big_int(&self, target: &Self) -> i32 {
86        unsafe { raw::TEE_BigIntCmp(self.data_ptr(), target.data_ptr()) }
87    }
88
89    pub fn compare_s32(&self, target: i32) -> i32 {
90        unsafe { raw::TEE_BigIntCmpS32(self.data_ptr(), target) }
91    }
92
93    pub fn shift_right(&mut self, op: &Self, bits: usize) {
94        // Should return a BigInt, while its size is based on the abs function which is missed
95        // right now
96        unsafe { raw::TEE_BigIntShiftRight(self.0.as_mut_ptr(), op.data_ptr(), bits) };
97    }
98
99    pub fn get_bit(&self, bit_index: u32) -> bool {
100        unsafe { raw::TEE_BigIntGetBit(self.data_ptr(), bit_index) }
101    }
102
103    pub fn get_bit_count(&self) -> u32 {
104        unsafe { raw::TEE_BigIntGetBitCount(self.data_ptr()) }
105    }
106
107    pub fn set_bit(&mut self, bit_index: u32, set: bool) -> Result<()> {
108        tee_check(unsafe { raw::TEE_BigIntSetBit(self.0.as_mut_ptr(), bit_index, set) })
109    }
110
111    pub fn abs(&self) -> Result<Self> {
112        let bits = Self::get_bit_count(self);
113        let mut res = Self::new(bits);
114        tee_check(unsafe { raw::TEE_BigIntAbs(res.0.as_mut_ptr(), self.data_ptr()) })?;
115        Ok(res)
116    }
117
118    pub fn add(op1: &Self, op2: &Self) -> Self {
119        let bits = max(Self::get_bit_count(op1), Self::get_bit_count(op2)) + 1;
120        let mut res = Self::new(bits);
121        unsafe { raw::TEE_BigIntAdd(res.0.as_mut_ptr(), op1.data_ptr(), op2.data_ptr()) };
122        res
123    }
124
125    pub fn sub(op1: &Self, op2: &Self) -> Self {
126        let bits = max(Self::get_bit_count(op1), Self::get_bit_count(op2)) + 1;
127        let mut res = Self::new(bits);
128        unsafe { raw::TEE_BigIntSub(res.0.as_mut_ptr(), op1.data_ptr(), op2.data_ptr()) };
129        res
130    }
131
132    pub fn neg(op: &Self) -> Self {
133        let mut res = Self::new(Self::get_bit_count(op));
134        unsafe { raw::TEE_BigIntNeg(res.0.as_mut_ptr(), op.data_ptr()) };
135        res
136    }
137
138    pub fn multiply(op1: &Self, op2: &Self) -> Self {
139        let bits = Self::get_bit_count(op1) + Self::get_bit_count(op2);
140        let mut res = Self::new(bits);
141        unsafe { raw::TEE_BigIntMul(res.0.as_mut_ptr(), op1.data_ptr(), op2.data_ptr()) };
142        res
143    }
144
145    pub fn square(op: &Self) -> Self {
146        let mut res = Self::new(2 * Self::get_bit_count(op));
147        unsafe { raw::TEE_BigIntSquare(res.0.as_mut_ptr(), op.data_ptr()) };
148        res
149    }
150
151    pub fn divide(op1: &Self, op2: &Self) -> (Self, Self) {
152        let q_bits = max(1, Self::get_bit_count(op1) - Self::get_bit_count(op2) + 1);
153        let r_bits = Self::get_bit_count(op2);
154        let mut quotient = Self::new(q_bits);
155        let mut remainder = Self::new(r_bits);
156
157        unsafe {
158            raw::TEE_BigIntDiv(
159                quotient.0.as_mut_ptr(),
160                remainder.0.as_mut_ptr(),
161                op1.data_ptr(),
162                op2.data_ptr(),
163            )
164        };
165        (quotient, remainder)
166    }
167
168    pub fn module(op: &Self, n: &Self) -> Self {
169        let mut res = Self::new(Self::get_bit_count(n));
170        unsafe { raw::TEE_BigIntMod(res.0.as_mut_ptr(), op.data_ptr(), n.data_ptr()) };
171        res
172    }
173
174    pub fn add_mod(op1: &Self, op2: &Self, n: &Self) -> Self {
175        let mut res = Self::new(Self::get_bit_count(n));
176        unsafe {
177            raw::TEE_BigIntAddMod(
178                res.0.as_mut_ptr(),
179                op1.data_ptr(),
180                op2.data_ptr(),
181                n.data_ptr(),
182            )
183        };
184        res
185    }
186
187    pub fn sub_mod(op1: &Self, op2: &Self, n: &Self) -> Self {
188        let mut res = Self::new(Self::get_bit_count(n));
189        unsafe {
190            raw::TEE_BigIntSubMod(
191                res.0.as_mut_ptr(),
192                op1.data_ptr(),
193                op2.data_ptr(),
194                n.data_ptr(),
195            )
196        };
197        res
198    }
199
200    pub fn mul_mod(op1: &Self, op2: &Self, n: &Self) -> Self {
201        let mut res = Self::new(Self::get_bit_count(n));
202        unsafe {
203            raw::TEE_BigIntMulMod(
204                res.0.as_mut_ptr(),
205                op1.data_ptr(),
206                op2.data_ptr(),
207                n.data_ptr(),
208            )
209        };
210        res
211    }
212
213    pub fn square_mod(op: &Self, n: &Self) -> Self {
214        let mut res = Self::new(Self::get_bit_count(n));
215        unsafe { raw::TEE_BigIntSquareMod(res.0.as_mut_ptr(), op.data_ptr(), n.data_ptr()) };
216        res
217    }
218
219    pub fn inv_mod(op: &Self, n: &Self) -> Self {
220        let mut res = Self::new(Self::get_bit_count(n));
221        unsafe { raw::TEE_BigIntInvMod(res.0.as_mut_ptr(), op.data_ptr(), n.data_ptr()) };
222        res
223    }
224
225    pub fn exp_mod(op1: &Self, op2: &Self, n: &Self, context: &BigIntFMMContext) -> Result<Self> {
226        let mut res = Self::new(Self::get_bit_count(n));
227        tee_check(unsafe {
228            raw::TEE_BigIntExpMod(
229                res.0.as_mut_ptr(),
230                op1.data_ptr(),
231                op2.data_ptr(),
232                n.data_ptr(),
233                context.data_ptr(),
234            )
235        })?;
236        Ok(res)
237    }
238
239    pub fn relative_prime(op1: &Self, op2: &Self) -> bool {
240        unsafe { raw::TEE_BigIntRelativePrime(op1.data_ptr(), op2.data_ptr()) }
241    }
242
243    pub fn assign(&mut self, op2: &Self) -> Result<()> {
244        tee_check(unsafe { raw::TEE_BigIntAssign(self.0.as_mut_ptr(), op2.data_ptr()) })
245    }
246
247    pub fn compute_extended_gcd(op1: &Self, op2: &Self) -> (Self, Self, Self) {
248        let gcd_bits = max(1, max(Self::get_bit_count(op1), Self::get_bit_count(op2)));
249        let mut gcd = Self::new(gcd_bits);
250        let mut u = Self::new(gcd_bits);
251        let mut v = Self::new(gcd_bits);
252        unsafe {
253            raw::TEE_BigIntComputeExtendedGcd(
254                gcd.0.as_mut_ptr(),
255                u.0.as_mut_ptr(),
256                v.0.as_mut_ptr(),
257                op1.data_ptr(),
258                op2.data_ptr(),
259            );
260        }
261        (gcd, u, v)
262    }
263
264    pub fn is_probable_prime(&self, confidence_level: u32) -> i32 {
265        unsafe { raw::TEE_BigIntIsProbablePrime(self.data_ptr(), confidence_level) }
266    }
267
268    pub fn convert_to_big_int_from_fmm(
269        &mut self,
270        src: &BigIntFMM,
271        n: &BigInt,
272        context: BigIntFMMContext,
273    ) {
274        unsafe {
275            raw::TEE_BigIntConvertFromFMM(
276                self.0.as_mut_ptr(),
277                src.data_ptr(),
278                n.data_ptr(),
279                context.data_ptr(),
280            )
281        };
282    }
283}
284
285impl fmt::Display for BigInt {
286    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
287        write!(f, "{:x?}", self.0)
288    }
289}
290
291pub struct BigIntFMMContext(Vec<BigIntFMMContextUnit>);
292
293impl BigIntFMMContext {
294    pub fn data_ptr(&self) -> *const u32 {
295        self.0.as_ptr()
296    }
297
298    fn size_in_u32(size: usize) -> usize {
299        unsafe { raw::TEE_BigIntFMMContextSizeInU32(size) }
300    }
301
302    // Globalplatform define FMMContext1 here while OP-TEE does not update yet
303    pub fn new(bits: u32, modulus: BigInt) -> Result<Self> {
304        let size: usize = Self::size_in_u32(bits as usize);
305        let mut tmp_vec: Vec<BigIntFMMContextUnit> = vec![0; size];
306        unsafe { raw::TEE_BigIntInitFMMContext(tmp_vec.as_mut_ptr(), size, modulus.data_ptr()) };
307        Ok(Self(tmp_vec))
308    }
309}
310
311pub struct BigIntFMM(Vec<BigIntFMMUnit>);
312
313impl BigIntFMM {
314    pub fn data_ptr(&self) -> *const u32 {
315        self.0.as_ptr()
316    }
317
318    fn size_in_u32(size: usize) -> usize {
319        unsafe { raw::TEE_BigIntFMMSizeInU32(size) }
320    }
321
322    pub fn new(bits: u32) -> Self {
323        let size: usize = Self::size_in_u32(bits as usize);
324        let mut tmp_vec: Vec<BigIntFMMUnit> = vec![0; size];
325        unsafe { raw::TEE_BigIntInitFMM(tmp_vec.as_mut_ptr(), size) };
326        Self(tmp_vec)
327    }
328
329    //Has to be initialized first
330    pub fn convert_from_big_int(&mut self, src: &BigInt, n: &BigInt, context: BigIntFMMContext) {
331        unsafe {
332            raw::TEE_BigIntConvertToFMM(
333                self.0.as_mut_ptr(),
334                src.data_ptr(),
335                n.data_ptr(),
336                context.data_ptr(),
337            )
338        };
339    }
340
341    //Has to be initialized first
342    pub fn compute_fmm(
343        &mut self,
344        op1: &BigIntFMM,
345        op2: &BigIntFMM,
346        n: &BigInt,
347        context: BigIntFMMContext,
348    ) {
349        unsafe {
350            raw::TEE_BigIntComputeFMM(
351                self.0.as_mut_ptr(),
352                op1.data_ptr(),
353                op2.data_ptr(),
354                n.data_ptr(),
355                context.data_ptr(),
356            )
357        };
358    }
359}