This content originally appeared on DEV Community and was authored by Naveen Sahu
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
.
- First we'd convert input hex string to raw bytes using
hex::decode()
:
using hex;
let bytes = hex::decode(input_hex).unwrap();
- Encode these bytes to base64 using
base64::encode()
:
using base64;
let output = base64::encode(bytes);
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())
}
This is it!
See the code on Github.
Find me on:
Twitter - @heyNvN
This content originally appeared on DEV Community and was authored by Naveen Sahu
Naveen Sahu | Sciencx (2021-12-30T18:41:33+00:00) CryptoPals Crypto Challenges Using Rust: Convert hex to base64. Retrieved from https://www.scien.cx/2021/12/30/cryptopals-crypto-challenges-using-rust-convert-hex-to-base64/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.