Skip to content

Instantly share code, notes, and snippets.

@diazoxide
Created March 23, 2023 12:04
Show Gist options
  • Save diazoxide/efb039378e021af7b6f23348773c101f to your computer and use it in GitHub Desktop.
Save diazoxide/efb039378e021af7b6f23348773c101f to your computer and use it in GitHub Desktop.
Custom strong cryptography algorithm on JS
function xorWithKey(input, key) {
let output = "";
for (let i = 0; i < input.length; i++) {
let keyChar = String(key[i % key.length]);
output += String.fromCharCode(input.charCodeAt(i) ^ keyChar.charCodeAt(0));
}
return output;
}
function customSubstitution(input, substitutionTable) {
let output = "";
for (let i = 0; i < input.length; i++) {
let charCode = input.charCodeAt(i);
output += String.fromCharCode(substitutionTable[charCode]);
}
return output;
}
function generateSubstitutionTable(key) {
let table = Array.from({ length: 256 }, (_, i) => i);
let keySum = Array.from(key).reduce((sum, char) => sum + char.charCodeAt(0), 0);
for (let i = 0; i < 256; i++) {
let swapIndex = (keySum + i) % 256;
[table[i], table[swapIndex]] = [table[swapIndex], table[i]];
}
return table;
}
function customEncrypt(plaintext, key) {
let xorResult = xorWithKey(plaintext, key);
let substitutionTable = generateSubstitutionTable(key);
let substituted = customSubstitution(xorResult, substitutionTable);
let ciphertext = substituted.split("").reverse().join("");
return ciphertext;
}
function customDecrypt(ciphertext, key) {
let reversed = ciphertext.split("").reverse().join("");
let substitutionTable = generateSubstitutionTable(key).map((value, index) => [index, value]).sort((a, b) => a[1] - b[1]).map(([_, index]) => index);
let unsubstituted = customSubstitution(reversed, substitutionTable);
let plaintext = xorWithKey(unsubstituted, key);
return plaintext;
}
function generateRandomString(length) {
let result = "";
let characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-=_+{}[]|;:<>,.?/";
let charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
function testCustomEncryptionAndDecryption(numTests) {
for (let i = 1; i <= numTests; i++) {
let plaintext = generateRandomString(Math.floor(Math.random() * 20) + 5);
let key = Math.floor(Math.random() * 10) + 5;
// console.log(`Test ${i} - Plaintext: "${plaintext}", Key: "${key}"`);
let encrypted = customEncrypt(plaintext, key);
// console.log("Encrypted:", encrypted);
let decrypted = customDecrypt(encrypted, key);
// console.log("Decrypted:", decrypted);
if (plaintext === decrypted) {
// console.log("Test passed: original plaintext and decrypted ciphertext match.\n");
} else {
console.log("Test failed: original plaintext and decrypted ciphertext do not match.\n");
}
}
}
testCustomEncryptionAndDecryption(200000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment