How can I create an empty [u8]
that I can then pass to an openssl function so it can write it's result to it?
fn test_encrypt(key_pair: openssl::rsa::Rsa) {
let text = b"Hello";
println!("{:?}", text);
let mut result = b" ";
let pad = openssl::rsa::Padding::from_raw(1);
key_pair.private_encrypt(text, result, pad);
}
My code currently results in the following error:
error[E0308]: mismatched types
--> src/main.rs:20:36
|
20 | key_pair.private_encrypt(text, result, pad);
| ^^^^^^ types differ in mutability
|
= note: expected type `&mut [u8]`
found type `&[u8; 0]`
Reading the error messages will help you far more; mismatched types, types differ in mutability, expected type &mut [u8]
, found type &[u8; 0]
. You problem isn't how to create an array, it's that you aren't creating the right type of array.
Printing the type of the variable will show that b" "
creates a &[u8; 1]
— an immutable reference to an array. It doesn't matter what you try, you won't be able to write into this data. In fact, it's stored in the static data in the compiled executable.
Instead, you need something that can be used as a mutable slice. The two primary ways are to create an actual array or a Vec
:
// Array
let mut result = [0; 24];
key_pair.private_encrypt(text, &mut result, pad);
// Vec
let mut result = vec![0; 24];
key_pair.private_encrypt(text, &mut result, pad);
An array is stack-allocated and has a fixed size and capacity which must be equal. A vector is heap-allocated, has a dynamic size and capacity that may differ from each other.
Both of these can be dereferenced to a &mut [u8]
.
Picking the appropriate size for your array or vector is something that is application specific. Checking the OpenSSL documentation is the right course of action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With