<- Back to Tools
Encryption and Decryption
I put together some examples of encrpting and decrypting information with javascript.
I use an XOR cipher where the key is the same length as the text.
I believe that these methods are cryptographically secure, but I make no guarantees. See this link for more information. Note: The linked website talks about a repeated xor cipher. This example does not repeat the key; the key is the same length as the plaintext/cyphertext.
Upon encryption, a random key is generated.
An example of how to encypt sensitive data is located at /secured.js.
All data stays on your device.
Encryption
function encrypt(plainText){
//turn plainText into a uint8Array
plainText = new TextEncoder().encode(plainText);
//Pick a random key
key = new Uint8Array(plainText.length)
self.crypto.getRandomValues(key);
//encrypt each array element one by one
cypherText = new Uint8Array(plainText.length)
for(i=0; i<cypherText.length; i++) cypherText[i] = (plainText[i] ^ key[i]);
//convert cypherText and the random key to base64, then return them in a dictionary.
cypherText = btoa(String.fromCharCode.apply(null, cypherText))
key = btoa(String.fromCharCode.apply(null, key))
return {"cypherText":cypherText,"key":key}
}
Decryption
function decrypt(cypherText, key){
//decode cypherText and key from base64
cypherText = atob(cypherText).split('').map(function (c) { return c.charCodeAt(0); });
key = atob(key).split('').map(function (c) { return c.charCodeAt(0); });
//turn cypherText into a uint8Array, each element one by one
decodedText = new Uint8Array(cypherText.length)
for(i=0; i<cypherText.length; i++) decodedText[i] = (cypherText[i] ^ key[i]);
//return the decoded text
return new TextDecoder().decode(decodedText);
}