Skip to content

Instantly share code, notes, and snippets.

@fed135
Last active January 5, 2023 06:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fed135/1cd97040181b6f70acaf1a26ac0372c8 to your computer and use it in GitHub Desktop.
Save fed135/1cd97040181b6f70acaf1a26ac0372c8 to your computer and use it in GitHub Desktop.
AES-like 8bit Uint8Array Encryption
/**
* Binary Encryption with security key
*
* This module is to be integrated with Kalm 2.0 as an optional step in payload transfer
* Kalm serializes payloads and their metadata in a Uint8 Array.
* These methods make sure that input type and size remains the same.
*/
'use strict';
function mapKey(key) {
const seed = Number(toUint8(key).join(''));
const dict = new Array(256);
for (let i = 0; i < 256; i++) {
const temp = dict[i] || i;
const rand = (seed % (i+1) + i) % 256;
dict[i] = dict[rand] || rand;
dict[rand] = temp;
}
return dict;
}
function toUint8(str) {
return str.toString()
.split('')
.map(char => char.charCodeAt(0));
}
function byteIn(keyMap, val, index) {
for (let i = 0; i < keyMap.length; i++) {
if (keyMap[i] === val) return (i + keyMap[index]) % 256;
}
}
function byteOut(keyMap, val, index) {
const diff = val - keyMap[index];
return keyMap[(diff < 0) ? 256 + diff : diff];
}
function encrypt(bytes, key) {
if (typeof bytes === 'string') bytes = toUint8(bytes);
return bytes.map(byteIn.bind(null, mapKey(String(key))));
}
function decrypt(bytes, key) {
return bytes.map(byteOut.bind(null, mapKey(String(key))));
}
module.exports = { encrypt, decrypt };
@fed135
Copy link
Author

fed135 commented Feb 27, 2017

Example:
Decrypted: "test test test test test"
Secret key: "some key"
Encrypted: [ 187, 31, 149, 189, 47, 148, 151, 150, 202, 57, 89, 222, 165, 193, 16, 198, 48, 179, 212, 162, 203, 78, 177, 179 ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment