如何将十六进制值转换为Rust中的Base64

Dav*_*ias 5 base64 hex rust

我在理解Rust中的特征概念时遇到了一些问题.我正在尝试将一个简单的十六进制值编码为Base64,但没有运气,这是我的代码(还有一个字符串到Base64的例子)

extern crate serialize;

use serialize::base64::{ToBase64, STANDARD};
use serialize::hex::{FromHex, ToHex};

fn main () {
  let stringOfText = "This is a String";
  let mut config = STANDARD;

  println!("String to base64 = {}", stringOfText.as_bytes().to_base64(config));

  // Can't figure out this 
Run Code Online (Sandbox Code Playgroud)

Vladimir提供的解决方案适用于0x标记的十六进制值.现在我想要转换以字符串表示的十六进制值:

extern crate serialize;

use serialize::base64::{ToBase64, STANDARD};
use serialize::hex::{FromHex, ToHex};
fn main () {
  let stringOfText = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
  let mut config = STANDARD;

  println!("String to base64 = {}", stringOfText.from_hex().from_utf8_owned().as_bytes().to_base64(config));

  // result should be: SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t

}
Run Code Online (Sandbox Code Playgroud)

from_hex()给我一个Vec<u8>,.to_base64()并期待一个缓冲区u8,首先我想转换Vec<u8>为字符串,然后使用as_bytes()获取缓冲区,到目前为止仍然没有运气.

Jon*_*tan 7

Rust目前正在发展,已接受的答案不再适用.具体来说,该extern crate语句不允许引用参数,现在是rustc-serialize包的名称rustc_serialize.

以下代码正确base64编码字符串,产生与接受的答案相同的结果(rustc 1.3.0):

extern crate rustc_serialize as serialize;

use serialize::base64::{self, ToBase64};
use serialize::hex::FromHex;

fn main() {
    let input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
    let result = input.from_hex().unwrap().to_base64(base64::STANDARD);
    println!("{}", result);
}
Run Code Online (Sandbox Code Playgroud)

结果:

SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t


fir*_*ant 6

It is now 2017, and rustc-serialize is now deprecated as well (see here). The new big serialization library is called serde but I think that's a little heavy for this problem.

Here's a quick solution that manually converts from the String of hex to a Vec<u8> and then uses this to convert to a base64-encoded String.

I am not convinced that this for loop is anywhere near the best solution for converting a String of hex into a Vec<u8>, but I'm fairly new to Rust and this is all I've got. Comments/improvements are appreciated.

(Hey, wait a minute, I recognize these encoded strings, are you doing cryptopals?)

extern crate base64;
use std::u8;
use self::base64::{encode};

pub fn hex_to_base64(hex: String) -> String {

    // Make vector of bytes from octets
    let mut bytes = Vec::new();
    for i in 0..(hex.len()/2) {
        let res = u8::from_str_radix(&hex[2*i .. 2*i+2], 16);
        match res {
            Ok(v) => bytes.push(v),
            Err(e) => println!("Problem with hex: {}", e),
        };
    };

    encode(&bytes) // now convert from Vec<u8> to b64-encoded String
}    
Run Code Online (Sandbox Code Playgroud)

  • 我不知道OP,但我知道。感谢您的提示。 (2认同)
  • 四年后...当然可以! (2认同)