Skip to content

Instantly share code, notes, and snippets.

@GCBallesteros
Created July 14, 2020 07:48
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save GCBallesteros/9fd4d949752724255eb4addf6f97814b to your computer and use it in GitHub Desktop.
Utility functions to solve the cryptopals challenges
import fs from "fs"
export enum ByteEncoding {
Base64,
Hex,
}
export function hexToBuff(data: string): Buffer {
return Buffer.from(data, "hex");
}
export function B64ToBuff(data: string): Buffer {
return Buffer.from(data, "base64");
}
export function buffTo64(data: Buffer): string {
return data.toString("base64");
}
export function buffToHex(data: Buffer): string {
return data.toString("hex");
}
export function fileToBuff(
filename: string,
encoding: ByteEncoding,
split_lines: boolean
): Array<Buffer> {
const data = fs.readFileSync(filename, "utf8");
let data_lines: Array<string> = [];
if (split_lines) {
data_lines = data.split("\n");
} else {
data_lines = [data];
}
let output: Array<Buffer> = [];
if (encoding === ByteEncoding.Base64) {
output = data_lines.map((x) => B64ToBuff(x));
} else if (encoding === ByteEncoding.Hex) {
output = data_lines.map((x) => hexToBuff(x));
}
return output;
}
export function sliceBuffer(buf: Buffer, offset: number, step: number): any {
let arr = [];
for (let i = offset; i < buf.length; i += step) {
arr.push(buf[i]);
}
return Buffer.from(arr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment