Rust crypto_bigint库Wrapping Uint取余操作编译错误求助
解决crypto_bigint中Wrapping类型的取余与模幂运算问题
问题核心
crypto_bigint的Wrapping<Uint>类型未为同类型实现Rem(取余) trait,仅针对**NonZero
修正后的代码
use crypto_bigint::{NonZero, Wrapping, U2048}; pub fn mod_exp( base: Wrapping<U2048>, exp: Wrapping<U2048>, modulus: &NonZero<U2048>, ) -> Wrapping<U2048> { let one = Wrapping(U2048::ONE); let zero = Wrapping(U2048::ZERO); let mut result = one; let mut base = base % modulus; // 直接用%对NonZero模数取余 let mut exp = exp; while exp > zero { if exp & one == one { // Wrapping已实现BitAnd,直接用& result = (result * base).rem(modulus); } exp >>= 1; // Wrapping已实现Shr,直接用>>= base = (base * base).rem(modulus); } result }
关键说明
模数改用NonZero类型:
密码学场景下模数必然非零,使用NonZero<U2048>符合crypto_bigint的安全设计,也能满足Remtrait的要求。如果你的输入是Wrapping<U2048>类型的模数,可先转换:// 需确保模数不为0,否则unwrap会触发panic let non_zero_modulus = NonZero::new(modulus.0).unwrap();利用Wrapping的运算符重载:
Wrapping<Uint>已实现BitAnd、Shr、Mul等常用trait,无需手动拆包访问.0,直接使用运算符即可简化代码。取余操作的正确姿势:
无论是%运算符还是.rem()方法,都需要传入NonZero类型的参数——这是编译器报错的根本原因。
内容的提问来源于stack exchange,提问作者Benoit Avril
相关产品推荐
相关产品推荐

