crypto_pals/tests/basics.test.ts

45 lines
1.8 KiB
TypeScript

import test from 'node:test';
import * as path from 'node:path';
import * as assert from 'node:assert/strict';
const DATA_PATH = path.join(__dirname, '..', 'data');
import { range, fileToBuff } from '../utils';
import { hexToBuff, buffTo64, xorBuffers, encryptSingleByte, decryptSingleByte, crackSingleByteKeyMsg, detectSingleByteXor } from '../basics';
test('range', () => {
assert.deepEqual(range(0, 10), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
assert.deepEqual(range(5, 8), [5, 6, 7, 8]);
});
test('hexToBase64', () => {
const input = '49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d';
const expected = 'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t';
assert.equal(buffTo64(hexToBuff(input)), expected);
});
test('xorBuffers', () => {
const input = '1c0111001f010100061a024b53535009181c';
const key = '686974207468652062756c6c277320657965';
const expected = '746865206b696420646f6e277420706c6179';
assert.equal(xorBuffers(hexToBuff(input), hexToBuff(key)).toString('hex'), expected);
});
test('encrypt/decrypt single byte', () => {
const input = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736';
const key = 55;
assert.deepEqual(decryptSingleByte(encryptSingleByte(Buffer.from(input, 'hex'), key), key).toString('hex'), input);
});
test('crack produces english sentence', () => {
const input = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736';
const expected = 'Cooking MC\'s like a pound of bacon';
assert.equal(crackSingleByteKeyMsg(input), expected);
});
test('detect single byte xor', () => {
const input = fileToBuff(path.join(DATA_PATH, 'xorSingleByte.txt'), 'hex');
const expected = 'Now that the party is jumping';
assert.equal(detectSingleByteXor(input), expected);
});