Skip to content

Commit 2a1cd88

Browse files
committed
docs
1 parent 91768e7 commit 2a1cd88

File tree

2 files changed

+45
-5
lines changed

2 files changed

+45
-5
lines changed

main.py

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,43 @@
11
import zeroize
22
import numpy as np
3+
import ctypes
34

45

6+
# Lock memory using ctypes
7+
def lock_memory():
8+
libc = ctypes.CDLL("libc.so.6")
9+
# Lock all current and future pages from being swapped out
10+
libc.mlockall(ctypes.c_int(0x02 | 0x04)) # MCL_CURRENT | MCL_FUTURE
11+
12+
13+
def unlock_memory():
14+
libc = ctypes.CDLL("libc.so.6")
15+
# Unlock all locked pages
16+
libc.munlockall()
17+
18+
19+
print("locking memory")
20+
lock_memory()
21+
22+
print("allocate memory")
23+
524
# regular array
6-
arr = bytearray(b'1234567890')
25+
arr = bytearray(b"1234567890")
726

827
# numpy array
928
arr_np = np.array([0] * 10, dtype=np.uint8)
1029
arr_np[:] = arr
11-
assert arr_np.tobytes() == b'1234567890'
30+
assert arr_np.tobytes() == b"1234567890"
1231

1332
print("zeroize'ing...: ")
1433
zeroize.zeroize1(arr)
1534
zeroize.zeroize_np(arr_np)
1635

17-
print("checking if is zeroized...")
18-
assert arr == bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
36+
print("checking if is zeroized")
37+
assert arr == bytearray(b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
1938
assert all(arr_np == 0)
2039

40+
print("unlocking memory")
41+
unlock_memory()
42+
2143
print("all good, bye!")

src/lib.rs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
use numpy::{PyArray1, PyArrayMethods};
2+
use pyo3::buffer::PyBuffer;
23
use pyo3::prelude::*;
3-
use pyo3::types::PyByteArray;
4+
use pyo3::types::{PyByteArray, PyMemoryView};
45
use zeroize_rs::Zeroize;
56

67
/// A Python module implemented in Rust.
78
#[pymodule]
89
fn zeroize(_py: Python, m: &PyModule) -> PyResult<()> {
910
m.add_function(wrap_pyfunction!(zeroize1, m)?)?;
1011
m.add_function(wrap_pyfunction!(zeroize_np, m)?)?;
12+
// m.add_function(wrap_pyfunction!(zeroize_mv, m)?)?;
1113
Ok(())
1214
}
1315

@@ -23,3 +25,19 @@ fn zeroize_np<'py>(arr: &Bound<'py, PyArray1<u8>>) -> PyResult<()> {
2325
unsafe { arr.as_slice_mut().unwrap().zeroize(); }
2426
Ok(())
2527
}
28+
29+
// #[pyfunction]
30+
// fn zeroize_mv<'py>(arr: &PyMemoryView, len: usize) -> PyResult<()> {
31+
// // Get the buffer information
32+
// let buffer = PyBuffer::<u8>::get(arr)?;
33+
//
34+
// // Get the raw mutable pointer and length of the memory view
35+
// let ptr = arr.as_ptr() as *mut u8;
36+
//
37+
// // Create a mutable slice from the raw pointer and length
38+
// let arr: &mut [u8] = unsafe { std::slice::from_raw_parts_mut(ptr, len) };
39+
//
40+
// arr.zeroize();
41+
//
42+
// Ok(())
43+
// }

0 commit comments

Comments
 (0)