Created
November 6, 2023 19:06
-
-
Save marvhus/f48065d1a88b4e7f21310d5812232aa9 to your computer and use it in GitHub Desktop.
Encoder and Decoder for John Hammond's Snyk Rust challenge. https://www.youtube.com/watch?v=4ZFypGpGfAo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fs; | |
const CHARSET: &[u8] = b"QWlKoxp3mT9EeRb4YzgG6rNj1OLvZ5SDfMBaXtP8JyIFVH07uh2wicdnUAC#@q"; | |
fn encode(input: String) -> String { | |
let input_bytes = input.as_bytes(); | |
let mut output = Vec::new(); | |
let mut temp = 0u32; | |
let mut temp_len = 0u8; | |
for &byte in input_bytes { | |
temp = (temp << 8) | byte as u32; | |
temp_len += 8; | |
while temp_len >= 6 { | |
temp_len -= 6; | |
output.push(CHARSET[((temp >> temp_len) & 0x3F) as usize]); | |
} | |
} | |
if temp_len > 0 { | |
output.push(CHARSET[((temp << (6 - temp_len)) & 0x3F) as usize]); | |
} | |
while output.len() % 4 != 0 { | |
output.push(b'='); | |
} | |
String::from_utf8(output).unwrap() | |
} | |
fn decode(input: String) -> String { | |
let mut output = Vec::new(); | |
let mut temp = 0u32; | |
let mut temp_len = 0u8; | |
for char in input.chars() { | |
if char == '=' { break; } | |
let index = CHARSET.iter().position(|&r| r == char as u8).unwrap(); | |
temp = (temp << 6) | index as u32; | |
temp_len += 6; | |
while temp_len >= 8 { | |
output.push(((temp >> temp_len) & 0xFF) as u8); | |
temp_len -= 8; | |
} | |
} | |
if temp_len > 0 { | |
output.push(((temp << (8 - temp_len)) & 0xFF) as u8); | |
} | |
String::from_utf8(output).unwrap() | |
} | |
fn main() { | |
let content = fs::read_to_string("flag.txt").expect("Unable to read flag.txt"); | |
let out = encode(content); | |
println!("{}", out); | |
let reversed = decode(out); | |
println!("{}", reversed); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment