Last active
January 5, 2023 06:23
-
-
Save fed135/1cd97040181b6f70acaf1a26ac0372c8 to your computer and use it in GitHub Desktop.
AES-like 8bit Uint8Array Encryption
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 ]