Rust中字串的base64編碼與解碼

banq發表於2022-09-21

將字串編碼為 base64 的程式:

use base64::encode;
use std::error::Error;

fn main() -> Result<(), Box<dyn Error>>{

   let string = b"Welcome to Linuxhint";
   let encoded = encode(string);
   println!("Base64: {}", encoded);
   Ok(())

}

解碼 Base64的程式碼:

use base64::decode;
use std::str;
use std::error::Error;

fn main() -> Result<(), Box<dyn Error>>{

 let b64 = "V2VsY29tZSB0byBMaW51eGhpbnQ=";
 let decoded = &decode(b64).unwrap()[..];
 println!("String: {:?}", str::from_utf8(decoded));
 Ok(())

}

 

相關文章