Skip to content

Instantly share code, notes, and snippets.

@mayank99
Created March 25, 2022 23:23
Show Gist options
  • Save mayank99/53c3e29641fe52ce0a6749258fe1827b to your computer and use it in GitHub Desktop.
Save mayank99/53c3e29641fe52ce0a6749258fe1827b to your computer and use it in GitHub Desktop.
A very simple mulberry cipher
const chars = [...'0123456789abcdefghijklmnopqrstuvwxyz'];
const charsMap = Object.fromEntries(chars.map((letter, i) => [letter, i]));
/**
* Function that encodes a string using mulberry32.
* @param what What do you want to encode?
* @param seed Pick a seed, any seed.
* @returns Encoded string.
*/
export const encode = (what: string, seed: number) => {
const shuffledChars = chars.slice();
shuffle(mulberry32(seed), shuffledChars);
return [...what].map((letter, i) => shuffledChars[(charsMap[letter] + i) % shuffledChars.length]).join('');
};
/**
* Function that decodes a string that was encoded using mulberry32.
* @param seed Seed that was used for encoding the original string.
* @param encoded THe original string.
* @returns Decoded string.
*/
export const decode = (encoded: string, seed: number) => {
const shuffledChars = chars.slice();
shuffle(mulberry32(seed), shuffledChars);
const shuffledMap = Object.fromEntries(shuffledChars.map((letter, i) => [letter, i]));
const max = Math.ceil(encoded.length / shuffledChars.length) * shuffledChars.length;
return [...encoded].map((letter, i) => chars[(shuffledMap[letter] - i + max) % shuffledChars.length]).join('');
};
const mulberry32 = (seed: number) => {
return () => {
seed |= 0;
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
};
const shuffle = (rand: () => number, array: unknown[]) => {
for (let currentIndex = array.length - 1; currentIndex >= 0; currentIndex--) {
const randomIndex = Math.floor(rand() * currentIndex);
[array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment