Skip to main content

esp_hal/rsa/
mod.rs

1//! # RSA (Rivest–Shamir–Adleman) accelerator.
2//!
3//! ## Overview
4//!
5//! The RSA accelerator provides hardware support for high precision computation
6//! used in various RSA asymmetric cipher algorithms by significantly reducing
7//! their software complexity. Compared with RSA algorithms implemented solely
8//! in software, this hardware accelerator can speed up RSA algorithms
9//! significantly.
10//!
11//! ## Configuration
12//!
13//! The RSA accelerator also supports operands of different lengths, which
14//! provides more flexibility during the computation.
15
16#[cfg_attr(rsa_version = "1", path = "low_level/v1.rs")]
17#[cfg_attr(rsa_version = "2", path = "low_level/v2.rs")]
18#[cfg_attr(rsa_version = "3", path = "low_level/v3.rs")]
19mod low_level;
20
21use core::{marker::PhantomData, ptr::NonNull, task::Poll};
22
23#[cfg(rsa_version = "1")]
24use esp_sync::NonReentrantMutex;
25use procmacros::{handler, ram};
26
27use crate::{
28    Async,
29    Blocking,
30    DriverMode,
31    asynch::AtomicWaker,
32    interrupt::InterruptHandler,
33    pac,
34    peripherals::RSA,
35    rtc_cntl::WakeLock,
36    system::{CryptoClockGuard, GenericPeripheralGuard, Peripheral as PeripheralEnable},
37    trm_markdown_link,
38    work_queue::{self, Status, VTable, WorkQueue, WorkQueueDriver, WorkQueueFrontend},
39};
40
41/// RSA peripheral driver.
42pub struct Rsa<'d, Dm: DriverMode> {
43    rsa: RSA<'d>,
44    phantom: PhantomData<Dm>,
45    _guard: RsaGuard,
46}
47
48/// RSA accelerator configuration.
49///
50/// The default is the most secure: constant time on and search acceleration off. The ESP32 has
51/// neither option, so its `Config` is empty.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, procmacros::BuilderLite)]
53#[cfg_attr(feature = "defmt", derive(defmt::Format))]
54#[non_exhaustive]
55pub struct Config {
56    /// Constant time operation for modular exponentiation.
57    ///
58    /// Turning it off makes modular exponentiation faster for an exponent with many 0 bits,
59    /// and exposes the exponent to timing-based side-channel attacks. Turn it off only for a
60    /// public exponent, such as when verifying a signature.
61    ///
62    /// Default value: `true`.
63    #[cfg(not(rsa_version = "1"))]
64    constant_time: bool,
65
66    /// Search acceleration for modular exponentiation.
67    ///
68    /// Turning it on makes modular exponentiation faster by skipping the exponent's bits above
69    /// its most significant set bit, and exposes the exponent's length. Turn it on only for a
70    /// public exponent, such as when verifying a signature.
71    ///
72    /// Default value: `false`.
73    #[cfg(not(rsa_version = "1"))]
74    search_acceleration: bool,
75}
76
77#[cfg_attr(rsa_version = "1", expect(clippy::derivable_impls))]
78impl Default for Config {
79    fn default() -> Self {
80        Self {
81            #[cfg(not(rsa_version = "1"))]
82            constant_time: true,
83            #[cfg(not(rsa_version = "1"))]
84            search_acceleration: false,
85        }
86    }
87}
88
89/// RSA configuration error.
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
91#[cfg_attr(feature = "defmt", derive(defmt::Format))]
92#[non_exhaustive]
93pub enum ConfigError {}
94
95// There are two distinct peripheral versions: ESP32, and all else. There is a naming split in the
96// later devices, and they use different (memory size, operand size increment) parameters, but they
97// are largely the same.
98
99/// How many words are there in an operand size increment.
100///
101/// I.e. if the RSA hardware works with operands of 512, 1024, 1536, ... bits, the increment is 512
102/// bits, or 16 words.
103const WORDS_PER_INCREMENT: u32 = property!("rsa.size_increment") / 32;
104
105struct RsaGuard {
106    _guard: GenericPeripheralGuard<{ PeripheralEnable::Rsa as u8 }>,
107    _clock_guard: CryptoClockGuard,
108}
109
110impl RsaGuard {
111    fn new() -> Self {
112        let _clock_guard = CryptoClockGuard::new();
113        let _guard = GenericPeripheralGuard::new();
114        cfg_select! {
115            rsa_version = "1" => {}
116            esp32s31 => {}
117            _ => {
118                crate::peripherals::SYSTEM::regs()
119                    .rsa_pd_ctrl()
120                    .modify(|_, w| {
121                        w.rsa_mem_force_pd().clear_bit();
122                        w.rsa_mem_force_pu().set_bit();
123                        w.rsa_mem_pd().clear_bit()
124                    });
125            }
126        }
127
128        Self {
129            _guard,
130            _clock_guard,
131        }
132    }
133}
134
135impl Drop for RsaGuard {
136    fn drop(&mut self) {
137        unsafe {
138            // Stopping the peripheral's clock source pends an interrupt. Since the clocks
139            // are stopped when the handler runs, we're not able to clear the interrupt flag,
140            // which means the interrupt handler keeps getting triggered indefinitely.
141            // To prevent this, we disable interrupts manually before stopping the peripheral.
142            crate::peripherals::RSA::steal().disable_peri_interrupt_on_all_cores();
143        }
144
145        cfg_select! {
146            rsa_version = "1" => {}
147            esp32s31 => {}
148            _ => {
149                crate::peripherals::SYSTEM::regs()
150                    .rsa_pd_ctrl()
151                    .modify(|_, w| {
152                        w.rsa_mem_force_pd().clear_bit();
153                        w.rsa_mem_force_pu().clear_bit();
154                        w.rsa_mem_pd().set_bit()
155                    });
156            }
157        }
158    }
159}
160
161impl<'d> Rsa<'d, Blocking> {
162    /// Creates a new instance in [Blocking] mode, with the given configuration.
163    ///
164    /// Optionally an interrupt handler can be bound.
165    pub fn new(rsa: RSA<'d>, config: Config) -> Result<Self, ConfigError> {
166        let mut this = Self {
167            rsa,
168            phantom: PhantomData,
169            _guard: RsaGuard::new(),
170        };
171
172        while !this.ready() {}
173
174        this.apply_config(&config)?;
175        Ok(this)
176    }
177
178    /// Reconfigures the RSA driver to operate in asynchronous mode.
179    pub fn into_async(mut self) -> Rsa<'d, Async> {
180        self.set_interrupt_handler(rsa_interrupt_handler);
181        self.enable_disable_interrupt(true);
182
183        Rsa {
184            rsa: self.rsa,
185            phantom: PhantomData,
186            _guard: self._guard,
187        }
188    }
189
190    /// Enables or disables the RSA interrupt.
191    ///
192    /// When enabled rsa peripheral would generate an interrupt when a operation
193    /// is finished.
194    pub fn enable_disable_interrupt(&mut self, enable: bool) {
195        self.internal_enable_disable_interrupt(enable);
196    }
197
198    /// Registers an interrupt handler for the RSA peripheral.
199    ///
200    /// Replaces any previously registered interrupt handlers.
201    #[instability::unstable]
202    pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
203        self.rsa.disable_peri_interrupt_on_all_cores();
204        self.rsa.bind_peri_interrupt(handler);
205    }
206}
207
208impl crate::private::Sealed for Rsa<'_, Blocking> {}
209
210#[instability::unstable]
211impl crate::interrupt::InterruptConfigurable for Rsa<'_, Blocking> {
212    fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
213        self.set_interrupt_handler(handler);
214    }
215}
216
217impl<'d> Rsa<'d, Async> {
218    /// Reconfigures the RSA driver to operate in [`Blocking`] mode.
219    pub fn into_blocking(self) -> Rsa<'d, Blocking> {
220        self.internal_enable_disable_interrupt(false);
221        self.rsa.disable_peri_interrupt_on_all_cores();
222
223        Rsa {
224            rsa: self.rsa,
225            phantom: PhantomData,
226            _guard: self._guard,
227        }
228    }
229}
230
231impl<'d, Dm: DriverMode> Rsa<'d, Dm> {
232    fn internal_enable_disable_interrupt(&self, enable: bool) {
233        low_level::enable_disable_interrupt(self.regs(), enable);
234    }
235
236    fn regs(&self) -> &pac::rsa::RegisterBlock {
237        self.rsa.register_block()
238    }
239
240    /// Returns whether RSA memory blocks are initialized after reset.
241    fn ready(&self) -> bool {
242        low_level::ready(self.regs())
243    }
244
245    /// Starts the modular exponentiation operation.
246    fn start_modexp(&self) {
247        self.start_operation(low_level::start_modexp);
248    }
249
250    /// Starts the multiplication operation.
251    fn start_multi(&self) {
252        self.start_operation(low_level::start_multi);
253    }
254
255    /// Starts the modular multiplication operation.
256    fn start_modmulti(&self) {
257        self.start_operation(low_level::start_modmulti);
258    }
259
260    fn start_operation(&self, start: impl FnOnce(&pac::rsa::RegisterBlock)) {
261        cfg_select! {
262            rsa_version = "1" => SIGNALED.with(|signaled| {
263                *signaled = false;
264                start(self.regs());
265            }),
266            _ => start(self.regs()),
267        }
268    }
269
270    /// Clears the RSA interrupt flag.
271    fn clear_interrupt(&mut self) {
272        low_level::clear_interrupt(self.regs());
273    }
274
275    /// Returns whether the RSA peripheral is idle.
276    fn is_idle(&self) -> bool {
277        cfg_select! {
278            rsa_version = "1" => {
279                SIGNALED.with(|signaled| *signaled || low_level::is_idle(self.regs()))
280            }
281            _ => low_level::is_idle(self.regs()),
282        }
283    }
284
285    fn wait_for_idle(&mut self) {
286        while !self.is_idle() {}
287        self.clear_interrupt();
288    }
289
290    /// Writes the result size of the multiplication.
291    fn write_multi_mode(&mut self, mode: u32, modular: bool) {
292        low_level::write_multi_mode(self.regs(), mode, modular);
293    }
294
295    /// Writes the result size of the modular exponentiation.
296    fn write_modexp_mode(&mut self, mode: u32) {
297        low_level::write_modexp_mode(self.regs(), mode);
298    }
299
300    fn write_operand_b(&mut self, operand: &[u32]) {
301        for (reg, op) in self.regs().y_mem_iter().zip(operand.iter().copied()) {
302            reg.write(|w| unsafe { w.bits(op) });
303        }
304    }
305
306    fn write_modulus(&mut self, modulus: &[u32]) {
307        for (reg, op) in self.regs().m_mem_iter().zip(modulus.iter().copied()) {
308            reg.write(|w| unsafe { w.bits(op) });
309        }
310    }
311
312    fn write_mprime(&mut self, m_prime: u32) {
313        self.regs().m_prime().write(|w| unsafe { w.bits(m_prime) });
314    }
315
316    fn write_operand_a(&mut self, operand: &[u32]) {
317        for (reg, op) in self.regs().x_mem_iter().zip(operand.iter().copied()) {
318            reg.write(|w| unsafe { w.bits(op) });
319        }
320    }
321
322    fn write_multi_operand_b(&mut self, operand: &[u32]) {
323        for (reg, op) in self
324            .regs()
325            .z_mem_iter()
326            .skip(operand.len())
327            .zip(operand.iter().copied())
328        {
329            reg.write(|w| unsafe { w.bits(op) });
330        }
331    }
332
333    fn write_r(&mut self, r: &[u32]) {
334        for (reg, op) in self.regs().z_mem_iter().zip(r.iter().copied()) {
335            reg.write(|w| unsafe { w.bits(op) });
336        }
337    }
338
339    fn read_out(&self, outbuf: &mut [u32]) {
340        for (reg, op) in self.regs().z_mem_iter().zip(outbuf.iter_mut()) {
341            *op = reg.read().bits();
342        }
343
344        #[cfg(clear_crypto_secrets)]
345        self.clear_secrets();
346    }
347
348    /// Removes the operands and intermediate results from the peripheral.
349    #[cfg(clear_crypto_secrets)]
350    fn clear_secrets(&self) {
351        for reg in self.regs().x_mem_iter() {
352            reg.write(|w| unsafe { w.bits(0) });
353        }
354        for reg in self.regs().y_mem_iter() {
355            reg.write(|w| unsafe { w.bits(0) });
356        }
357        for reg in self.regs().z_mem_iter() {
358            reg.write(|w| unsafe { w.bits(0) });
359        }
360        for reg in self.regs().m_mem_iter() {
361            reg.write(|w| unsafe { w.bits(0) });
362        }
363    }
364
365    fn read_results(&mut self, outbuf: &mut [u32]) {
366        self.wait_for_idle();
367        self.read_out(outbuf);
368    }
369
370    /// Applies a new configuration.
371    ///
372    /// For more information on the options, refer to the
373    #[doc = trm_markdown_link!("rsa")]
374    pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> {
375        self.write_config(config);
376        Ok(())
377    }
378
379    fn write_config(&mut self, _config: &Config) {
380        #[cfg(not(rsa_version = "1"))]
381        {
382            self.regs()
383                .constant_time()
384                .write(|w| w.constant_time().bit(_config.constant_time));
385            self.regs()
386                .search_enable()
387                .write(|w| w.search_enable().bit(_config.search_acceleration));
388        }
389    }
390
391    /// Returns whether the search functionality is enabled in the RSA hardware.
392    #[cfg(not(rsa_version = "1"))]
393    fn is_search_enabled(&mut self) -> bool {
394        self.regs()
395            .search_enable()
396            .read()
397            .search_enable()
398            .bit_is_set()
399    }
400
401    /// Sets the search position in the RSA hardware.
402    #[cfg(not(rsa_version = "1"))]
403    fn write_search_position(&mut self, search_position: u32) {
404        self.regs()
405            .search_pos()
406            .write(|w| unsafe { w.bits(search_position) });
407    }
408}
409
410/// Defines the input size of an RSA operation.
411pub trait RsaMode: crate::private::Sealed {
412    /// The input data type used for the operation.
413    type InputType: AsRef<[u32]> + AsMut<[u32]>;
414}
415
416/// Defines the output type of RSA multiplications.
417pub trait Multi: RsaMode {
418    /// The type of the output produced by the operation.
419    type OutputType: AsRef<[u32]> + AsMut<[u32]>;
420}
421
422/// Defines the exponentiation and multiplication lengths for RSA operations.
423pub mod operand_sizes {
424    for_each_rsa_exponentiation!(
425        ($x:literal) => {
426            paste::paste! {
427                #[doc = concat!(stringify!($x), "-bit RSA operation.")]
428                pub struct [<Op $x>];
429
430                impl crate::private::Sealed for [<Op $x>] {}
431                impl crate::rsa::RsaMode for [<Op $x>] {
432                    type InputType = [u32; $x / 32];
433                }
434            }
435        };
436    );
437
438    for_each_rsa_multiplication!(
439        ($x:literal) => {
440            impl crate::rsa::Multi for paste::paste!( [<Op $x>] ) {
441                type OutputType = [u32; $x * 2 / 32];
442            }
443        };
444    );
445}
446
447/// Support for the RSA peripheral's modular exponentiation feature that could be
448/// used to find the `(base ^ exponent) mod modulus`.
449///
450/// Each operand is a little endian byte array of the same size.
451pub struct RsaModularExponentiation<'a, 'd, T: RsaMode, Dm: DriverMode> {
452    rsa: &'a mut Rsa<'d, Dm>,
453    phantom: PhantomData<T>,
454}
455
456impl<'a, 'd, T: RsaMode, Dm: DriverMode, const N: usize> RsaModularExponentiation<'a, 'd, T, Dm>
457where
458    T: RsaMode<InputType = [u32; N]>,
459{
460    /// Creates an instance of `RsaModularExponentiation`.
461    ///
462    /// `m_prime` could be calculated using `-(modular multiplicative inverse of
463    /// modulus) mod 2^32`.
464    ///
465    /// For more information refer to the
466    #[doc = trm_markdown_link!("rsa")]
467    pub fn new(
468        rsa: &'a mut Rsa<'d, Dm>,
469        exponent: &T::InputType,
470        modulus: &T::InputType,
471        m_prime: u32,
472    ) -> Self {
473        Self::write_mode(rsa);
474        rsa.write_operand_b(exponent);
475        rsa.write_modulus(modulus);
476        rsa.write_mprime(m_prime);
477
478        #[cfg(not(rsa_version = "1"))]
479        if rsa.is_search_enabled() {
480            rsa.write_search_position(Self::find_search_pos(exponent));
481        }
482
483        Self {
484            rsa,
485            phantom: PhantomData,
486        }
487    }
488
489    fn set_up_exponentiation(&mut self, base: &T::InputType, r: &T::InputType) {
490        self.rsa.write_operand_a(base);
491        self.rsa.write_r(r);
492    }
493
494    /// Starts the modular exponentiation operation.
495    ///
496    /// `r` can be calculated using `2 ^ ( bitlength * 2 ) mod modulus`.
497    ///
498    /// For more information refer to the
499    #[doc = trm_markdown_link!("rsa")]
500    pub fn start_exponentiation(&mut self, base: &T::InputType, r: &T::InputType) {
501        self.set_up_exponentiation(base, r);
502        self.rsa.start_modexp();
503    }
504
505    /// Reads the result to the given buffer.
506    ///
507    /// This is a blocking function: it waits for the RSA operation to complete,
508    /// then reads the results into the provided buffer. `start_exponentiation` must be
509    /// called before calling this function.
510    pub fn read_results(&mut self, outbuf: &mut T::InputType) {
511        self.rsa.read_results(outbuf);
512    }
513
514    #[cfg(not(rsa_version = "1"))]
515    fn find_search_pos(exponent: &T::InputType) -> u32 {
516        for (i, byte) in exponent.iter().rev().enumerate() {
517            if *byte == 0 {
518                continue;
519            }
520            return (exponent.len() * 32) as u32 - (byte.leading_zeros() + i as u32 * 32) - 1;
521        }
522        0
523    }
524
525    /// Sets the modular exponentiation mode for the RSA hardware.
526    fn write_mode(rsa: &mut Rsa<'d, Dm>) {
527        rsa.write_modexp_mode(N as u32 / WORDS_PER_INCREMENT - 1);
528    }
529}
530
531/// Support for the RSA peripheral's modular multiplication feature that could be
532/// used to find the `(operand a * operand b) mod modulus`.
533///
534/// Each operand is a little endian byte array of the same size.
535pub struct RsaModularMultiplication<'a, 'd, T, Dm>
536where
537    T: RsaMode,
538    Dm: DriverMode,
539{
540    rsa: &'a mut Rsa<'d, Dm>,
541    phantom: PhantomData<T>,
542}
543
544impl<'a, 'd, T, Dm, const N: usize> RsaModularMultiplication<'a, 'd, T, Dm>
545where
546    T: RsaMode<InputType = [u32; N]>,
547    Dm: DriverMode,
548{
549    /// Creates an instance of `RsaModularMultiplication`.
550    ///
551    /// - `r` can be calculated using `2 ^ ( bitlength * 2 ) mod modulus`.
552    /// - `m_prime` can be calculated using `-(modular multiplicative inverse of modulus) mod 2^32`.
553    ///
554    /// For more information refer to the
555    #[doc = trm_markdown_link!("rsa")]
556    pub fn new(
557        rsa: &'a mut Rsa<'d, Dm>,
558        operand_a: &T::InputType,
559        modulus: &T::InputType,
560        r: &T::InputType,
561        m_prime: u32,
562    ) -> Self {
563        rsa.write_multi_mode(N as u32 / WORDS_PER_INCREMENT - 1, true);
564
565        rsa.write_mprime(m_prime);
566        rsa.write_modulus(modulus);
567        rsa.write_operand_a(operand_a);
568        rsa.write_r(r);
569
570        Self {
571            rsa,
572            phantom: PhantomData,
573        }
574    }
575
576    /// Starts the modular multiplication operation.
577    ///
578    /// For more information refer to the
579    #[doc = trm_markdown_link!("rsa")]
580    pub fn start_modular_multiplication(&mut self, operand_b: &T::InputType) {
581        self.set_up_modular_multiplication(operand_b);
582        self.rsa.start_modmulti();
583    }
584
585    /// Reads the result to the given buffer.
586    ///
587    /// This is a blocking function: it waits for the RSA operation to complete,
588    /// then reads the results into the provided buffer. `start_modular_multiplication` must be
589    /// called before calling this function.
590    pub fn read_results(&mut self, outbuf: &mut T::InputType) {
591        self.rsa.read_results(outbuf);
592    }
593
594    fn set_up_modular_multiplication(&mut self, operand_b: &T::InputType) {
595        if cfg!(rsa_version = "1") {
596            self.rsa.start_multi();
597            self.rsa.wait_for_idle();
598
599            self.rsa.write_operand_a(operand_b);
600        } else {
601            self.rsa.write_operand_b(operand_b);
602        }
603    }
604}
605
606/// Support for the RSA peripheral's large number multiplication feature that could
607/// be used to find the `operand a * operand b`.
608///
609/// Each operand is a little endian byte array of the same size.
610pub struct RsaMultiplication<'a, 'd, T, Dm>
611where
612    T: RsaMode + Multi,
613    Dm: DriverMode,
614{
615    rsa: &'a mut Rsa<'d, Dm>,
616    phantom: PhantomData<T>,
617}
618
619impl<'a, 'd, T, Dm, const N: usize> RsaMultiplication<'a, 'd, T, Dm>
620where
621    T: RsaMode<InputType = [u32; N]>,
622    T: Multi,
623    Dm: DriverMode,
624{
625    /// Creates an instance of `RsaMultiplication`.
626    pub fn new(rsa: &'a mut Rsa<'d, Dm>, operand_a: &T::InputType) -> Self {
627        // Non-modular multiplication result is twice as wide as its operands.
628        rsa.write_multi_mode(2 * N as u32 / WORDS_PER_INCREMENT - 1, false);
629        rsa.write_operand_a(operand_a);
630
631        Self {
632            rsa,
633            phantom: PhantomData,
634        }
635    }
636
637    /// Starts the multiplication operation.
638    pub fn start_multiplication(&mut self, operand_b: &T::InputType) {
639        self.set_up_multiplication(operand_b);
640        self.rsa.start_multi();
641    }
642
643    /// Reads the result to the given buffer.
644    ///
645    /// This is a blocking function: it waits for the RSA operation to complete,
646    /// then reads the results into the provided buffer. `start_multiplication` must be
647    /// called before calling this function.
648    pub fn read_results<const O: usize>(&mut self, outbuf: &mut T::OutputType)
649    where
650        T: Multi<OutputType = [u32; O]>,
651    {
652        self.rsa.read_results(outbuf);
653    }
654
655    fn set_up_multiplication(&mut self, operand_b: &T::InputType) {
656        self.rsa.write_multi_operand_b(operand_b);
657    }
658}
659
660static WAKER: AtomicWaker = AtomicWaker::new();
661#[cfg(rsa_version = "1")]
662static SIGNALED: NonReentrantMutex<bool> = NonReentrantMutex::new(false);
663
664/// `Future` that waits for the RSA operation to complete.
665#[must_use = "futures do nothing unless you `.await` or poll them"]
666struct RsaFuture<'a, 'd> {
667    driver: &'a Rsa<'d, Async>,
668    _wake_lock: WakeLock,
669}
670
671impl<'a, 'd> RsaFuture<'a, 'd> {
672    fn new(driver: &'a Rsa<'d, Async>) -> Self {
673        driver.internal_enable_disable_interrupt(true);
674
675        Self {
676            driver,
677            _wake_lock: WakeLock::new(),
678        }
679    }
680
681    fn is_done(&self) -> bool {
682        cfg_select! {
683            rsa_version = "1" => SIGNALED.with(|signaled| *signaled),
684            _ => self.driver.is_idle(),
685        }
686    }
687}
688
689impl Drop for RsaFuture<'_, '_> {
690    fn drop(&mut self) {
691        self.driver.internal_enable_disable_interrupt(false);
692    }
693}
694
695impl core::future::Future for RsaFuture<'_, '_> {
696    type Output = ();
697
698    fn poll(
699        self: core::pin::Pin<&mut Self>,
700        cx: &mut core::task::Context<'_>,
701    ) -> core::task::Poll<Self::Output> {
702        WAKER.register(cx.waker());
703        if self.is_done() {
704            Poll::Ready(())
705        } else {
706            Poll::Pending
707        }
708    }
709}
710
711impl<T: RsaMode, const N: usize> RsaModularExponentiation<'_, '_, T, Async>
712where
713    T: RsaMode<InputType = [u32; N]>,
714{
715    /// Asynchronously performs an RSA modular exponentiation operation.
716    pub async fn exponentiation(
717        &mut self,
718        base: &T::InputType,
719        r: &T::InputType,
720        outbuf: &mut T::InputType,
721    ) {
722        self.set_up_exponentiation(base, r);
723        let fut = RsaFuture::new(self.rsa);
724        self.rsa.start_modexp();
725        fut.await;
726        self.rsa.read_out(outbuf);
727    }
728}
729
730impl<T: RsaMode, const N: usize> RsaModularMultiplication<'_, '_, T, Async>
731where
732    T: RsaMode<InputType = [u32; N]>,
733{
734    /// Asynchronously performs an RSA modular multiplication operation.
735    pub async fn modular_multiplication(
736        &mut self,
737        operand_b: &T::InputType,
738        outbuf: &mut T::InputType,
739    ) {
740        if cfg!(rsa_version = "1") {
741            let fut = RsaFuture::new(self.rsa);
742            self.rsa.start_multi();
743            fut.await;
744
745            self.rsa.write_operand_a(operand_b);
746        } else {
747            self.set_up_modular_multiplication(operand_b);
748        }
749
750        let fut = RsaFuture::new(self.rsa);
751        self.rsa.start_modmulti();
752        fut.await;
753        self.rsa.read_out(outbuf);
754    }
755}
756
757impl<T: RsaMode + Multi, const N: usize> RsaMultiplication<'_, '_, T, Async>
758where
759    T: RsaMode<InputType = [u32; N]>,
760{
761    /// Asynchronously performs an RSA multiplication operation.
762    pub async fn multiplication<const O: usize>(
763        &mut self,
764        operand_b: &T::InputType,
765        outbuf: &mut T::OutputType,
766    ) where
767        T: Multi<OutputType = [u32; O]>,
768    {
769        self.set_up_multiplication(operand_b);
770        let fut = RsaFuture::new(self.rsa);
771        self.rsa.start_multi();
772        fut.await;
773        self.rsa.read_out(outbuf);
774    }
775}
776
777#[handler]
778/// Interrupt handler for RSA.
779pub(super) fn rsa_interrupt_handler() {
780    let rsa = RSA::regs();
781
782    cfg_select! {
783        rsa_version = "1" => SIGNALED.with(|signaled| {
784            // A blocking read may have already acknowledged this interrupt.
785            if low_level::is_idle(rsa) {
786                *signaled = true;
787                low_level::clear_interrupt(rsa);
788            }
789        }),
790        _ => low_level::clear_interrupt(rsa),
791    }
792
793    WAKER.wake();
794}
795
796static RSA_WORK_QUEUE: WorkQueue<RsaWorkItem> = WorkQueue::new();
797const RSA_VTABLE: VTable<RsaWorkItem> = VTable {
798    post: |driver, item| {
799        // Start processing immediately.
800        let driver = unsafe { RsaBackend::from_raw(driver) };
801        Some(driver.process_item(item))
802    },
803    poll: |driver, item| {
804        let driver = unsafe { RsaBackend::from_raw(driver) };
805        driver.process_item(item)
806    },
807    cancel: |driver, item| {
808        let driver = unsafe { RsaBackend::from_raw(driver) };
809        driver.cancel(item)
810    },
811    stop: |driver| {
812        let driver = unsafe { RsaBackend::from_raw(driver) };
813        driver.deinitialize()
814    },
815};
816
817#[derive(Default)]
818enum RsaBackendState<'d> {
819    #[default]
820    Idle,
821    Initializing(Rsa<'d, Blocking>),
822    Ready(Rsa<'d, Blocking>),
823    #[cfg(rsa_version = "1")]
824    ModularMultiplicationRoundOne(Rsa<'d, Blocking>),
825    Processing(Rsa<'d, Blocking>),
826}
827
828#[procmacros::doc_replace]
829/// RSA processing backend.
830///
831/// The backend processes work items placed in the RSA work queue. The backend needs to be created
832/// and started for operations to be processed. Operations can be performed on the RSA accelerator
833/// without carrying around the peripheral singleton, or the driver.
834///
835/// The [`RsaContext`] struct can enqueue work items that this backend will process.
836///
837/// # Examples
838///
839/// ```rust, no_run
840/// # {before_snippet}
841/// use esp_hal::rsa::{RsaBackend, RsaContext, operand_sizes::Op512};
842/// #
843/// let mut rsa_backend = RsaBackend::new(peripherals.RSA);
844/// let _driver = rsa_backend.start();
845///
846/// async fn perform_512bit_big_number_multiplication(
847///     operand_a: &[u32; 16],
848///     operand_b: &[u32; 16],
849///     result: &mut [u32; 32],
850/// ) {
851///     let mut rsa = RsaContext::new();
852///
853///     let mut handle = rsa.multiply::<Op512>(operand_a, operand_b, result);
854///     handle.wait().await;
855/// }
856/// # {after_snippet}
857/// ```
858pub struct RsaBackend<'d> {
859    peri: RSA<'d>,
860    state: RsaBackendState<'d>,
861}
862
863impl<'d> RsaBackend<'d> {
864    #[procmacros::doc_replace]
865    /// Creates a new RSA backend.
866    ///
867    /// # Examples
868    ///
869    /// ```rust, no_run
870    /// # {before_snippet}
871    /// use esp_hal::rsa::RsaBackend;
872    /// #
873    /// let mut rsa = RsaBackend::new(peripherals.RSA);
874    /// # {after_snippet}
875    /// ```
876    pub fn new(rsa: RSA<'d>) -> Self {
877        Self {
878            peri: rsa,
879            state: RsaBackendState::Idle,
880        }
881    }
882
883    #[procmacros::doc_replace]
884    /// Registers the RSA driver to process RSA operations.
885    ///
886    /// The driver stops operating when the returned object is dropped.
887    ///
888    /// # Examples
889    ///
890    /// ```rust, no_run
891    /// # {before_snippet}
892    /// use esp_hal::rsa::RsaBackend;
893    /// #
894    /// let mut rsa = RsaBackend::new(peripherals.RSA);
895    /// // Start the backend, which allows processing RSA operations.
896    /// let _backend = rsa.start();
897    /// # {after_snippet}
898    /// ```
899    pub fn start(&mut self) -> RsaWorkQueueDriver<'_, 'd> {
900        RsaWorkQueueDriver {
901            inner: WorkQueueDriver::new(self, RSA_VTABLE, &RSA_WORK_QUEUE),
902        }
903    }
904
905    // WorkQueue callbacks. They may run in any context.
906
907    unsafe fn from_raw<'any>(ptr: NonNull<()>) -> &'any mut Self {
908        unsafe { ptr.cast::<RsaBackend<'_>>().as_mut() }
909    }
910
911    fn process_item(&mut self, item: &mut RsaWorkItem) -> work_queue::Poll {
912        // Use `low_level` here. `Rsa::is_idle` and `Rsa::start_*` use `SIGNALED`, which only
913        // `rsa_interrupt_handler` updates.
914        match core::mem::take(&mut self.state) {
915            RsaBackendState::Idle => {
916                let driver = Rsa {
917                    rsa: unsafe { self.peri.clone_unchecked() },
918                    phantom: PhantomData,
919                    _guard: RsaGuard::new(),
920                };
921                self.state = RsaBackendState::Initializing(driver);
922                work_queue::Poll::Pending(true)
923            }
924            RsaBackendState::Initializing(mut rsa) => {
925                // Wait for the peripheral to finish initializing. Ideally we need a way to
926                // instruct the work queue to wake the polling task immediately.
927                self.state = if rsa.ready() {
928                    rsa.set_interrupt_handler(rsa_work_queue_handler);
929                    low_level::clear_interrupt(rsa.regs());
930                    rsa.enable_disable_interrupt(true);
931                    RsaBackendState::Ready(rsa)
932                } else {
933                    RsaBackendState::Initializing(rsa)
934                };
935                work_queue::Poll::Pending(true)
936            }
937            RsaBackendState::Ready(mut rsa) => {
938                rsa.write_config(&item.config);
939
940                match item.operation {
941                    RsaOperation::Multiplication { x, y } => {
942                        let n = x.len() as u32;
943                        rsa.write_operand_a(unsafe { x.as_ref() });
944
945                        // Non-modular multiplication result is twice as wide as its operands.
946                        rsa.write_multi_mode(2 * n / WORDS_PER_INCREMENT - 1, false);
947                        rsa.write_multi_operand_b(unsafe { y.as_ref() });
948                        low_level::start_multi(rsa.regs());
949                    }
950
951                    RsaOperation::ModularMultiplication {
952                        x,
953                        #[cfg(not(rsa_version = "1"))]
954                        y,
955                        m,
956                        m_prime,
957                        r: r_inv,
958                        ..
959                    } => {
960                        let n = x.len() as u32;
961                        rsa.write_operand_a(unsafe { x.as_ref() });
962
963                        rsa.write_multi_mode(n / WORDS_PER_INCREMENT - 1, true);
964
965                        #[cfg(not(rsa_version = "1"))]
966                        rsa.write_operand_b(unsafe { y.as_ref() });
967
968                        rsa.write_modulus(unsafe { m.as_ref() });
969                        rsa.write_mprime(m_prime);
970                        rsa.write_r(unsafe { r_inv.as_ref() });
971
972                        low_level::start_modmulti(rsa.regs());
973
974                        #[cfg(rsa_version = "1")]
975                        {
976                            // ESP32 requires a two-step process where Y needs to be written to the
977                            // X memory.
978                            self.state = RsaBackendState::ModularMultiplicationRoundOne(rsa);
979
980                            return work_queue::Poll::Pending(false);
981                        }
982                    }
983                    RsaOperation::ModularExponentiation {
984                        x,
985                        y,
986                        m,
987                        m_prime,
988                        r_inv,
989                    } => {
990                        let n = x.len() as u32;
991                        rsa.write_operand_a(unsafe { x.as_ref() });
992
993                        rsa.write_modexp_mode(n / WORDS_PER_INCREMENT - 1);
994                        rsa.write_operand_b(unsafe { y.as_ref() });
995                        rsa.write_modulus(unsafe { m.as_ref() });
996                        rsa.write_mprime(m_prime);
997                        rsa.write_r(unsafe { r_inv.as_ref() });
998
999                        #[cfg(not(rsa_version = "1"))]
1000                        if item.config.search_acceleration {
1001                            fn find_search_pos(exponent: &[u32]) -> u32 {
1002                                for (i, byte) in exponent.iter().rev().enumerate() {
1003                                    if *byte == 0 {
1004                                        continue;
1005                                    }
1006                                    return (exponent.len() * 32) as u32
1007                                        - (byte.leading_zeros() + i as u32 * 32)
1008                                        - 1;
1009                                }
1010                                0
1011                            }
1012                            rsa.write_search_position(find_search_pos(unsafe { y.as_ref() }));
1013                        }
1014
1015                        low_level::start_modexp(rsa.regs());
1016                    }
1017                }
1018
1019                self.state = RsaBackendState::Processing(rsa);
1020
1021                work_queue::Poll::Pending(false)
1022            }
1023
1024            #[cfg(rsa_version = "1")]
1025            RsaBackendState::ModularMultiplicationRoundOne(mut rsa) => {
1026                if low_level::is_idle(rsa.regs()) {
1027                    let RsaOperation::ModularMultiplication { y, .. } = item.operation else {
1028                        unreachable!();
1029                    };
1030
1031                    low_level::clear_interrupt(rsa.regs());
1032
1033                    // Y needs to be written to the X memory.
1034                    rsa.write_operand_a(unsafe { y.as_ref() });
1035                    low_level::start_modmulti(rsa.regs());
1036
1037                    self.state = RsaBackendState::Processing(rsa);
1038                } else {
1039                    // Wait for the operation to complete
1040                    self.state = RsaBackendState::ModularMultiplicationRoundOne(rsa);
1041                }
1042                work_queue::Poll::Pending(false)
1043            }
1044
1045            RsaBackendState::Processing(rsa) => {
1046                if low_level::is_idle(rsa.regs()) {
1047                    low_level::clear_interrupt(rsa.regs());
1048                    rsa.read_out(unsafe { item.result.as_mut() });
1049
1050                    self.state = RsaBackendState::Ready(rsa);
1051                    work_queue::Poll::Ready(Status::Completed)
1052                } else {
1053                    self.state = RsaBackendState::Processing(rsa);
1054                    work_queue::Poll::Pending(false)
1055                }
1056            }
1057        }
1058    }
1059
1060    fn cancel(&mut self, _item: &mut RsaWorkItem) {
1061        // Drop the driver to reset it. We don't read the result, so the work item remains
1062        // unchanged, effectively cancelling it.
1063        self.state = RsaBackendState::Idle;
1064    }
1065
1066    fn deinitialize(&mut self) {
1067        self.state = RsaBackendState::Idle;
1068    }
1069}
1070
1071/// An active work queue driver.
1072///
1073/// This object must be kept around, otherwise RSA operations will never complete.
1074///
1075/// For a usage example, see [`RsaBackend`].
1076pub struct RsaWorkQueueDriver<'t, 'd> {
1077    inner: WorkQueueDriver<'t, RsaBackend<'d>, RsaWorkItem>,
1078}
1079
1080impl<'t, 'd> RsaWorkQueueDriver<'t, 'd> {
1081    /// Finishes processing the current work queue item, then stops the driver.
1082    pub fn stop(self) -> impl Future<Output = ()> {
1083        self.inner.stop()
1084    }
1085}
1086
1087#[derive(Clone)]
1088struct RsaWorkItem {
1089    config: Config,
1090
1091    // The operation to execute.
1092    operation: RsaOperation,
1093    result: NonNull<[u32]>,
1094}
1095
1096unsafe impl Sync for RsaWorkItem {}
1097unsafe impl Send for RsaWorkItem {}
1098
1099#[derive(Clone)]
1100enum RsaOperation {
1101    // Z = X * Y
1102    // len(Z) = len(X) + len(Y)
1103    Multiplication {
1104        x: NonNull<[u32]>,
1105        y: NonNull<[u32]>,
1106    },
1107    // Z = X * Y mod M
1108    ModularMultiplication {
1109        x: NonNull<[u32]>,
1110        y: NonNull<[u32]>,
1111        m: NonNull<[u32]>,
1112        r: NonNull<[u32]>,
1113        m_prime: u32,
1114    },
1115    // Z = X ^ Y mod M
1116    ModularExponentiation {
1117        x: NonNull<[u32]>,
1118        y: NonNull<[u32]>,
1119        m: NonNull<[u32]>,
1120        r_inv: NonNull<[u32]>,
1121        m_prime: u32,
1122    },
1123}
1124
1125#[handler]
1126#[ram]
1127fn rsa_work_queue_handler() {
1128    // Only `process_item` clears the interrupt. A clear here can drop the completion of the
1129    // operation that `process` started.
1130    RSA_WORK_QUEUE.process();
1131}
1132
1133/// An RSA work queue user.
1134///
1135/// This object allows performing [big number multiplication][Self::multiply], [big number modular
1136/// multiplication][Self::modular_multiply] and [big number modular
1137/// exponentiation][Self::modular_exponentiate] with hardware acceleration. To perform these
1138/// operations, the [`RsaBackend`] must be started, otherwise these operations will never complete.
1139#[cfg_attr(
1140    not(rsa_version = "1"),
1141    doc = " \nThe context is created with a secure configuration by default. You can enable hardware acceleration
1142    options using [enable_search_acceleration][Self::enable_search_acceleration] and
1143    [enable_acceleration][Self::enable_acceleration] when appropriate."
1144)]
1145#[derive(Clone)]
1146pub struct RsaContext {
1147    frontend: WorkQueueFrontend<RsaWorkItem>,
1148}
1149
1150impl Default for RsaContext {
1151    fn default() -> Self {
1152        Self::new()
1153    }
1154}
1155
1156impl RsaContext {
1157    /// Creates a new context.
1158    pub fn new() -> Self {
1159        Self {
1160            frontend: WorkQueueFrontend::new(RsaWorkItem {
1161                config: Config::default(),
1162                operation: RsaOperation::Multiplication {
1163                    x: NonNull::from(&[]),
1164                    y: NonNull::from(&[]),
1165                },
1166                result: NonNull::from(&mut []),
1167            }),
1168        }
1169    }
1170
1171    #[cfg(not(rsa_version = "1"))]
1172    /// Enables search acceleration.
1173    ///
1174    /// When enabled it would increase the performance of modular
1175    /// exponentiation by discarding the exponent's bits before the most
1176    /// significant set bit.
1177    ///
1178    /// Compromises security by effectively decreasing the key length.
1179    ///
1180    /// For more information refer to the
1181    #[doc = trm_markdown_link!("rsa")]
1182    pub fn enable_search_acceleration(&mut self) {
1183        self.frontend.data_mut().config.search_acceleration = true;
1184    }
1185
1186    #[cfg(not(rsa_version = "1"))]
1187    /// Enables acceleration by disabling constant time operation.
1188    ///
1189    /// Disabling constant time operation increases the performance of modular
1190    /// exponentiation by simplifying the calculation concerning the 0 bits
1191    /// of the exponent. I.e. the less the Hamming weight, the greater the
1192    /// performance.
1193    ///
1194    /// Compromises security by enabling timing-based side-channel attacks.
1195    ///
1196    /// For more information refer to the
1197    #[doc = trm_markdown_link!("rsa")]
1198    pub fn enable_acceleration(&mut self) {
1199        self.frontend.data_mut().config.constant_time = false;
1200    }
1201
1202    fn post(&mut self) -> RsaHandle<'_> {
1203        RsaHandle(self.frontend.post(&RSA_WORK_QUEUE))
1204    }
1205
1206    #[procmacros::doc_replace]
1207    /// Starts a modular exponentiation operation, performing `Z = X ^ Y mod M`.
1208    ///
1209    /// Software needs to pre-calculate the following values:
1210    ///
1211    /// - `r`: `2 ^ ( bitlength * 2 ) mod M`.
1212    /// - `m_prime` can be calculated using `-(modular multiplicative inverse of M) mod 2^32`.
1213    ///
1214    /// It is relatively easy to calculate these values using the `crypto-bigint` crate:
1215    ///
1216    /// ```rust,no_run
1217    /// # {before_snippet}
1218    /// use crypto_bigint::{U512, Uint};
1219    /// const fn compute_r(modulus: &U512) -> U512 {
1220    ///     let mut d = [0_u32; U512::LIMBS * 2 + 1];
1221    ///     d[d.len() - 1] = 1;
1222    ///     let d = Uint::from_words(d);
1223    ///     d.wrapping_rem_vartime(&modulus.resize()).resize()
1224    /// }
1225    ///
1226    /// const fn compute_mprime(modulus: &U512) -> u32 {
1227    ///     let m_inv = modulus
1228    ///         .invert_mod2k(32)
1229    ///         .expect_copied("modulus must be odd")
1230    ///         .to_words()[0];
1231    ///     (-1 * m_inv as i64 & (u32::MAX as i64)) as u32
1232    /// }
1233    ///
1234    /// // Inputs
1235    /// const X: U512 = Uint::from_be_hex(
1236    ///     "c7f61058f96db3bd87dbab08ab03b4f7f2f864eac249144adea6a65f97803b719d8ca980b7b3c0389c1c7c6\
1237    ///    7dc353c5e0ec11f5fc8ce7f6073796cc8f73fa878",
1238    /// );
1239    /// const Y: U512 = Uint::from_be_hex(
1240    ///     "1763db3344e97be15d04de4868badb12a38046bb793f7630d87cf100aa1c759afac15a01f3c4c83ec2d2f66\
1241    ///    6bd22f71c3c1f075ec0e2cb0cb29994d091b73f51",
1242    /// );
1243    /// const M: U512 = Uint::from_be_hex(
1244    ///     "6b6bb3d2b6cbeb45a769eaa0384e611e1b89b0c9b45a045aca1c5fd6e8785b38df7118cf5dd45b9b63d293b\
1245    ///    67aeafa9ba25feb8712f188cb139b7d9b9af1c361",
1246    /// );
1247    ///
1248    /// // Values derived using the functions we defined above:
1249    /// let r = compute_r(&M);
1250    /// let mprime = compute_mprime(&M);
1251    ///
1252    /// use esp_hal::rsa::{RsaContext, operand_sizes::Op512};
1253    ///
1254    /// // Now perform the actual computation:
1255    /// let mut rsa = RsaContext::new();
1256    /// let mut outbuf = [0; 16];
1257    /// let mut handle = rsa.modular_multiply::<Op512>(
1258    ///     X.as_words(),
1259    ///     Y.as_words(),
1260    ///     M.as_words(),
1261    ///     r.as_words(),
1262    ///     mprime,
1263    ///     &mut outbuf,
1264    /// );
1265    /// handle.wait_blocking();
1266    /// # {after_snippet}
1267    /// ```
1268    ///
1269    /// Returns an [`RsaHandle`] for the asynchronous calculation that can be used to poll the
1270    /// status of the calculation, to wait for it to finish, or to cancel the operation (by
1271    /// dropping the handle).
1272    ///
1273    /// When the operation is completed, the result is stored in `result`
1274    pub fn modular_exponentiate<'t, OP>(
1275        &'t mut self,
1276        x: &'t OP::InputType,
1277        y: &'t OP::InputType,
1278        m: &'t OP::InputType,
1279        r: &'t OP::InputType,
1280        m_prime: u32,
1281        result: &'t mut OP::InputType,
1282    ) -> RsaHandle<'t>
1283    where
1284        OP: RsaMode,
1285    {
1286        self.frontend.data_mut().operation = RsaOperation::ModularExponentiation {
1287            x: NonNull::from(x.as_ref()),
1288            y: NonNull::from(y.as_ref()),
1289            m: NonNull::from(m.as_ref()),
1290            r_inv: NonNull::from(r.as_ref()),
1291            m_prime,
1292        };
1293        self.frontend.data_mut().result = NonNull::from(result.as_mut());
1294        self.post()
1295    }
1296
1297    /// Starts a modular multiplication operation, performing `Z = X * Y mod M`.
1298    ///
1299    /// Software needs to pre-calculate the following values:
1300    ///
1301    /// - `r`: `2 ^ ( bitlength * 2 ) mod M`.
1302    /// - `m_prime` can be calculated using `-(modular multiplicative inverse of M) mod 2^32`.
1303    ///
1304    /// For an example how these values can be calculated and used, see
1305    /// [Self::modular_exponentiate].
1306    ///
1307    /// Returns an [`RsaHandle`] for the asynchronous calculation that can be used to poll the
1308    /// status of the calculation, to wait for it to finish, or to cancel the operation (by
1309    /// dropping the handle).
1310    ///
1311    /// When the operation is completed, the result is stored in `result`
1312    pub fn modular_multiply<'t, OP>(
1313        &'t mut self,
1314        x: &'t OP::InputType,
1315        y: &'t OP::InputType,
1316        m: &'t OP::InputType,
1317        r: &'t OP::InputType,
1318        m_prime: u32,
1319        result: &'t mut OP::InputType,
1320    ) -> RsaHandle<'t>
1321    where
1322        OP: RsaMode,
1323    {
1324        self.frontend.data_mut().operation = RsaOperation::ModularMultiplication {
1325            x: NonNull::from(x.as_ref()),
1326            y: NonNull::from(y.as_ref()),
1327            m: NonNull::from(m.as_ref()),
1328            r: NonNull::from(r.as_ref()),
1329            m_prime,
1330        };
1331        self.frontend.data_mut().result = NonNull::from(result.as_mut());
1332        self.post()
1333    }
1334
1335    #[procmacros::doc_replace]
1336    /// Starts a multiplication operation, performing `Z = X * Y`.
1337    ///
1338    /// Returns an [`RsaHandle`] for the asynchronous calculation that can be used to poll the
1339    /// status of the calculation, to wait for it to finish, or to cancel the operation (by
1340    /// dropping the handle).
1341    ///
1342    /// When the operation is completed, the result is stored in `result`. The `result` is twice as
1343    /// wide as the inputs.
1344    ///
1345    /// # Examples
1346    ///
1347    /// ```rust,no_run
1348    /// # {before_snippet}
1349    ///
1350    /// // Inputs
1351    /// # let x: [u32; 16] = [0; 16];
1352    /// # let y: [u32; 16] = [0; 16];
1353    /// // let x: [u32; 16] = [...];
1354    /// // let y: [u32; 16] = [...];
1355    /// let mut outbuf = [0; 32];
1356    ///
1357    /// use esp_hal::rsa::{RsaContext, operand_sizes::Op512};
1358    ///
1359    /// // Now perform the actual computation:
1360    /// let mut rsa = RsaContext::new();
1361    /// let mut handle = rsa.multiply::<Op512>(&x, &y, &mut outbuf);
1362    /// handle.wait_blocking();
1363    /// # {after_snippet}
1364    /// ```
1365    pub fn multiply<'t, OP>(
1366        &'t mut self,
1367        x: &'t OP::InputType,
1368        y: &'t OP::InputType,
1369        result: &'t mut OP::OutputType,
1370    ) -> RsaHandle<'t>
1371    where
1372        OP: Multi,
1373    {
1374        self.frontend.data_mut().operation = RsaOperation::Multiplication {
1375            x: NonNull::from(x.as_ref()),
1376            y: NonNull::from(y.as_ref()),
1377        };
1378        self.frontend.data_mut().result = NonNull::from(result.as_mut());
1379        self.post()
1380    }
1381}
1382
1383/// The handle to the pending RSA operation.
1384pub struct RsaHandle<'t>(work_queue::Handle<'t, RsaWorkItem>);
1385
1386impl RsaHandle<'_> {
1387    /// Polls the status of the work item.
1388    #[inline]
1389    pub fn poll(&mut self) -> bool {
1390        self.0.poll()
1391    }
1392
1393    /// Blocks until the work item is processed.
1394    #[inline]
1395    pub fn wait_blocking(self) {
1396        self.0.wait_blocking();
1397    }
1398
1399    /// Waits for the work item to be processed.
1400    #[inline]
1401    pub fn wait(&mut self) -> impl Future<Output = Status> {
1402        self.0.wait()
1403    }
1404}