简体   繁体   中英

How to define &mut [u8] in Rust

I want to call openssl::sign::Signer::sign , which has the signature:

pub fn sign(&self, buf: &mut [u8]) -> Result<usize, ErrorStack>

I'm trying to hand over buf . How to I make it &mut [u8] ?

cargo.toml

[dependencies]
openssl = { version = "0.10", features = ["vendored"] }

src/main.rs

use openssl::{base64, sign::Signer};

fn main() {
    let mut buffer = [];
    let str = base64::encode_block(signer.sign(&mut buffer));
}

But get an error:

openssl::base64::encode_block(signer.sign(&mut buffer));
                              ^^^^^^^^^^^^^^^^^^^ expected `&[u8]`, found enum `std::result::Result`

I'm not familiar with this crate, but base64::encode_block expects &[u8] , while the return value of Signer::sign is a Result that returns the number of bytes written as usize .

I'm not sure if the number of bytes written is what you want to encode?

If you want to encode buffer to base64 , you could do:

use openssl;

fn main() {
   let mut buf = [104, 101, 108, 108, 111];
   let encoded = openssl::base64::encode_block(&buf);

   println!("{}", encoded);
}

That should give you:

aGVsbG8=

Which is hello as base64 .

Or, as an example, if you want to sign the given buf and encode that as base64 :

use openssl::{base64, hash::MessageDigest, pkey::PKey, rsa::Rsa, sign::Signer};

fn main() {
    let keypair = Rsa::generate(2048).unwrap();
    let keypair = PKey::from_rsa(keypair).unwrap();
    let signer = Signer::new(MessageDigest::sha256(), &keypair).unwrap();

    let mut buf = [104, 101, 108, 108, 111].repeat(52);

    let written = signer.sign(&mut buf).unwrap();
    println!("bytes written: {}", written);

    let encoded = base64::encode_block(&buf);
    println!("base64: {}", encoded);
}

Which returns:

bytes written: 256
base64: wB4lBbyzpfRPInxhwm0XVKI3dQYqcUZWNdKyb4RTGDUmwq1DDDbQjMRmFBobRse3pNOxoMy+QQNSXsgI46b75hPfkar9TUowrIGk4Y+ZWWX/cwNJCJazC1dfanP4uft0fzpYJKMSfJTAxswccu1g4yT+u0V5yq+eHbeGDJ+bF2MMhCPds7wGjJguxO0e4wx+HQdVGbU9jrHQ38oIYTChG92iKLRpciiyB8vrbNEBcNNi4hlw6U0sUdz6scpXceREdPFVA6wr0otY3wSZLfcIeKELoBQkR2KPNTTCROreVJ49tXwiQdGe7Ky0NDeNba2H5tKu3uLAtAiG/hVoKEAJG2VsbG8=

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM