python interface for modular exponentiation

This commit is contained in:
Christoph J. Scherr 2023-05-02 15:51:58 +02:00
parent f3201c7758
commit f8e9a64577
Signed by: PlexSheep
GPG Key ID: 25B4ACF7D88186CC
4 changed files with 31 additions and 1 deletions

1
Cargo.lock generated
View File

@ -115,6 +115,7 @@ name = "plexcryptool"
version = "0.1.0"
dependencies = [
"num-bigint",
"num-traits",
"pyo3",
]

View File

@ -15,4 +15,5 @@ path = "src/main.rs"
[dependencies]
num-bigint = "0.4.3"
num-traits = "0.2.15"
pyo3 = "0.18.1"

View File

@ -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(())
}

View File

@ -1,6 +1,11 @@
#![allow(dead_code)]
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<u128> {
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<u8> to Vec<bool> ( binary representation interpreted otherwise )
fn bytes_to_bools(bytes: &Vec<u8>) -> Vec<bool> {
let mut result: Vec<bool> = Vec::new();