DEV Community

Cover image for CryptoPals Crypto Challenges Using Rust: Convert hex to base64
Naveen ⚡
Naveen ⚡

Posted on • Updated on

CryptoPals Crypto Challenges Using Rust: Convert hex to base64

This is the Challenge 1 of CryptoPals challenges implemented using Rust language.

Context

Quite simple, we're given a hex string & have to convert it into a base64 encoded format. Basically from one encoding to another.

Hex Encoding

Hex is a base 16 format using 16 symbols 0-9 and A-F. Each hexadecimal number (i.e. 0-9 & A-F) can be represented (or corresponds to) using 4 bits. Why 4 bits? Because, using 4 bits you can have 2^4 (=16) combinations. So, 0000 (binary) = 0 (hex), 1111 (binary) = F (hex). Consequently, two digits of hex need 4 bits. Hence, 0010 1101 (binary) = 2D. Note that in hex encoding there is no difference between small case letters & capital letters, they both mean same (unlike base64)

Now, let's talk about converting an ASCII text to hex. Each ASCII character is 1 byte or 8 bits of size. So, each ASCII character would require 2 digits of hex to represent! So, Z (in ASCII text) is 5A in hex, and 0 (in ASCII text, not number!) is actually 30 in hex format! You can learn more here.

Base64 Encoding

Similarly, Base64 is base 64 (duh!) encoding using 64 symbols - 0-9, A-Z, a-z, + and /. You might also see = chars appear at the end encoding output but = in base64 is just a padding applied to output to normalize output length to be a multiple of 4. Using similar logic as hex encoding above, we can see that each base64 digit represents 6 bits of data (2^6 = 64).

Theoretically, to convert hex to base64, we can first convert hex to binary to create a long string of bits (1s & 0s), divide bits into 6 bit chunks & then convert these 6 bit chunks to their corresponding base64 digits.

However, since we're using Rust, we can simplify by using two nice crates for working with hex & base64 - hex & base64.

  1. First we'd convert input hex string to raw bytes using hex::decode():
using hex;

let bytes = hex::decode(input_hex).unwrap();
Enter fullscreen mode Exit fullscreen mode
  1. Encode these bytes to base64 using base64::encode():
using base64;

let output = base64::encode(bytes);
Enter fullscreen mode Exit fullscreen mode

And we have the base64 output!

We can encapsulate it into a nice function:

use base64;
use hex;

pub fn convert_hex_to_base64(hex: &str) -> String {
    base64::encode(hex::decode(hex).unwrap())
}
Enter fullscreen mode Exit fullscreen mode

This is it!

See the code on Github.

Find me on:
Twitter - @heyNvN

naveeen.com

Top comments (0)