diff --git a/Cargo.lock b/Cargo.lock index 3665f5a..c2a516e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -115,6 +115,7 @@ name = "plexcryptool" version = "0.1.0" dependencies = [ "num-bigint", + "num-traits", "pyo3", ] diff --git a/Cargo.toml b/Cargo.toml index ed9457c..d8320f1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,4 +15,5 @@ path = "src/main.rs" [dependencies] num-bigint = "0.4.3" +num-traits = "0.2.15" pyo3 = "0.18.1" diff --git a/src/lib.rs b/src/lib.rs index dbabba6..ec9ff39 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -15,6 +15,7 @@ fn register_binary_module(py: Python, parent_module: &PyModule) -> PyResult<()> #[pymodule] fn register_math_module(py: Python, parent_module: &PyModule) -> PyResult<()> { let math_module = PyModule::new(py, "math")?; + math_module.add_function(wrap_pyfunction!(modular_exponentiation::py_modular_exponentiation, math_module)?)?; parent_module.add_submodule(math_module)?; Ok(()) } diff --git a/src/modular_exponentiation.rs b/src/modular_exponentiation.rs index 915c819..320db5b 100644 --- a/src/modular_exponentiation.rs +++ b/src/modular_exponentiation.rs @@ -1,6 +1,11 @@ #![allow(dead_code)] -use num_bigint::BigInt; +use num_bigint::BigInt; +use num_traits::ToPrimitive; +use num_traits::FromPrimitive; +use pyo3::exceptions::PyException; +use pyo3::exceptions::PyValueError; +use pyo3::prelude::*; /// works, but is forbidden for class pub fn calc_exp_in_field_lib( @@ -43,6 +48,28 @@ pub fn modular_exponentiation( return exp; } +#[pyfunction] +pub fn py_modular_exponentiation( + base: i128, + orig_exp: i128, + field: i128) -> PyResult { + let big_res = modular_exponentiation( + BigInt::from(base), + BigInt::from(orig_exp), + BigInt::from(field) + ); + let res = big_res.to_u128(); + match res { + Some(v) => { + return Ok(v); + } + None => { + return Err(PyValueError::new_err("result is too big!")); + } + } + +} + // Vec to Vec ( binary representation interpreted otherwise ) fn bytes_to_bools(bytes: &Vec) -> Vec { let mut result: Vec = Vec::new();