File tree Expand file tree Collapse file tree 2 files changed +45
-5
lines changed
Expand file tree Collapse file tree 2 files changed +45
-5
lines changed Original file line number Diff line number Diff line change 11import zeroize
22import 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
928arr_np = np .array ([0 ] * 10 , dtype = np .uint8 )
1029arr_np [:] = arr
11- assert arr_np .tobytes () == b' 1234567890'
30+ assert arr_np .tobytes () == b" 1234567890"
1231
1332print ("zeroize'ing...: " )
1433zeroize .zeroize1 (arr )
1534zeroize .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 " )
1938assert all (arr_np == 0 )
2039
40+ print ("unlocking memory" )
41+ unlock_memory ()
42+
2143print ("all good, bye!" )
Original file line number Diff line number Diff line change 11use numpy:: { PyArray1 , PyArrayMethods } ;
2+ use pyo3:: buffer:: PyBuffer ;
23use pyo3:: prelude:: * ;
3- use pyo3:: types:: PyByteArray ;
4+ use pyo3:: types:: { PyByteArray , PyMemoryView } ;
45use zeroize_rs:: Zeroize ;
56
67/// A Python module implemented in Rust.
78#[ pymodule]
89fn 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+ // }
You can’t perform that action at this time.
0 commit comments