Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Cryptomoji - Encrypt messages as emoji
var emoji = require('node-emoji')
var emojiList = emoji.search('');
function emojiNum(emoji) {
for (var i = 0; i < emojiList.length; i++) {
if (emojiList[i].key === emoji) {
return i;
}
}
return -1;
}
function numEmoji(index) {
for (var i = 0; i < emojiList.length; i++) {
if (i === index) {
return emojiList[i].emoji;
}
}
return -1;
}
function decryptChar(z, p) {
return (z + p) % 26;
}
function encryptChar(c, p) {
var lo = -1;
var hi = -1;
var n = 0;
while (true) {
var z = 26 * n + c - p;
if (lo < 0 && z > 0) {
lo = n;
}
if (z > emojiList.length) {
hi = n - 1;
break;
}
n++;
}
// One letter can map to multiple emoji, pick one at random
return 26 * Math.floor(Math.random() * (hi-lo+1) + lo) + c - p;
}
// Split the emoji string into an emoji list
function emojiSplit(key) {
var unemoji = emoji.unemojify(key);
var emojis = [];
var regex = /:([^:]+):/g;
var match = regex.exec(unemoji);
while (match != null) {
emojis.push(match[1]);
match = regex.exec(unemoji);
}
return emojis;
}
function decrypt(cypher, key) {
var cypherList = emojiSplit(cypher);
var keyList = emojiSplit(key);
var output = '';
for (var i = 0; i < cypherList.length; i++) {
var cypherVal = emojiNum(cypherList[i]);
var keyVal = emojiNum(keyList[i % keyList.length]);
var d = decryptChar(cypherVal, keyVal);
output += String.fromCharCode(d + 97);
}
return output;
}
function encrypt(msg, key) {
var keyList = emojiSplit(key);
var cypher = '';
for (var i = 0; i < msg.length; i++) {
var plaintextChar = msg[i].charCodeAt(0) - 97;
var keyEmoji = keyList[i % keyList.length];
var cyphermojiNum = encryptChar(plaintextChar, emojiNum(keyEmoji));
var cyphermoji = numEmoji(cyphermojiNum);
cypher += cyphermoji;
}
return cypher;
}
var msg = "test";
var key = "🤔😰";
var e = encrypt(msg, key);
console.log(e);
var d = decrypt(e, key);
console.log(d);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment