JavaScript string encryption and decryption?
I'm interested in building a small app for personal use that will encrypt and decrypt information on the client side using JavaScript. The encrypted information will be stored in a database on a server, but never the decrypted version.
It doesn't have to be super duper secure, but I would like to use a currently unbroken algorithm.
Ideally I'd be able to do something like
var gibberish = encrypt(string, salt, key);
to generate the encoded string, and something like
var sensical = decrypt(gibberish, key);
to decode it later.
So far I've seen this: http://bitwiseshiftleft.github.io/sjcl/
Any other libraries I should look at?
var encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase");
//U2FsdGVkX18ZUVvShFSES21qHsQEqZXMxQ9zgHy+bu0=
var decrypted = CryptoJS.AES.decrypt(encrypted, "Secret Passphrase");
//4d657373616765
document.getElementById("demo1").innerHTML = encrypted;
document.getElementById("demo2").innerHTML = decrypted;
document.getElementById("demo3").innerHTML = decrypted.toString(CryptoJS.enc.Utf8);
Full working sample actually is:
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js" integrity="sha256-/H4YS+7aYb9kJ5OKhFYPUjSJdrtV6AeyJOtTkw6X72o=" crossorigin="anonymous"></script>
<br><br>
<label>encrypted</label>
<div id="demo1"></div>
<br>
<label>decrypted</label>
<div id="demo2"></div>
<br>
<label>Actual Message</label>
<div id="demo3"></div>
How about CryptoJS?
It's a solid crypto library, with a lot of functionality. It implements hashers, HMAC, PBKDF2 and ciphers. In this case ciphers is what you need. Check out the quick-start quide on the project's homepage.
You could do something like with the AES:
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
<script>
var encryptedAES = CryptoJS.AES.encrypt("Message", "My Secret Passphrase");
var decryptedBytes = CryptoJS.AES.decrypt(encryptedAES, "My Secret Passphrase");
var plaintext = decryptedBytes.toString(CryptoJS.enc.Utf8);
</script>
As for security, at the moment of my writing AES algorithm is thought to be unbroken
Edit :
Seems online URL is down & you can use the downloaded files for encryption from below given link & place the respective files in your root folder of the application.
https://code.google.com/archive/p/crypto-js/downloads
or used other CDN like https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/aes-min.js
I created an insecure but simple text cipher/decipher utility. No dependencies with any external library.
These are the functions:
const cipher = salt => {
const textToChars = text => text.split('').map(c => c.charCodeAt(0));
const byteHex = n => ("0" + Number(n).toString(16)).substr(-2);
const applySaltToChar = code => textToChars(salt).reduce((a,b) => a ^ b, code);
return text => text.split('')
.map(textToChars)
.map(applySaltToChar)
.map(byteHex)
.join('');
}
const decipher = salt => {
const textToChars = text => text.split('').map(c => c.charCodeAt(0));
const applySaltToChar = code => textToChars(salt).reduce((a,b) => a ^ b, code);
return encoded => encoded.match(/.{1,2}/g)
.map(hex => parseInt(hex, 16))
.map(applySaltToChar)
.map(charCode => String.fromCharCode(charCode))
.join('');
}
// To create a cipher
const myCipher = cipher('mySecretSalt')
//Then cipher any text:
console.log(myCipher('the secret string'))
//To decipher, you need to create a decipher and use it:
const myDecipher = decipher('mySecretSalt')
console.log(myDecipher("7c606d287b6d6b7a6d7c287b7c7a61666f"))
The existing answers which leverage SJCL, CryptoJS, and/or WebCrypto aren't necessarily wrong but they're not as safe as you might initially suspect. Generally you want to use libsodium. First I'll explain why, then how.
Why Not SJCL, CryptoJS, WebCrypto, etc.?
Short answer: In order for your encryption to actually be secure, these libraries expect you to make too many choices e.g. the block cipher mode (CBC, CTR, GCM; if you can't tell which of the three I just listed is secure to use and under what constraints, you shouldn't be burdened with this sort of choice at all).
Unless your job title is cryptography engineer, the odds are stacked against you implementing it securely.
Why to Avoid CryptoJS?
CryptoJS offers a handful of building blocks and expects you to know how to use them securely. It even defaults to CBC mode (archived).
Why is CBC mode bad?
Read this write-up on AES-CBC vulnerabilities.
Why to Avoid WebCrypto?
WebCrypto is a potluck standard, designed by committee, for purposes that are orthogonal to cryptography engineering. Specifically, WebCrypto was meant to replace Flash, not provide security.
Why to Avoid SJCL?
SJCL's public API and documentation begs users to encrypt data with a human-remembered password. This is rarely, if ever, what you want to do in the real world.
Additionally: Its default PBKDF2 round count is roughly 86 times as small as you want it to be. AES-128-CCM is probably fine.
Out of the three options above, SJCL is the least likely to end in tears. But there are better options available.
Why is Libsodium Better?
You don't need to choose between a menu of cipher modes, hash functions, and other needless options. You'll never risk screwing up your parameters and removing all security from your protocol.
Instead, libsodium just gives you simple options tuned for maximum security and minimalistic APIs.
-
crypto_box()
/crypto_box_open()
offer authenticated public-key encryption.- The algorithm in question combines X25519 (ECDH over Curve25519) and XSalsa20-Poly1305, but you don't need to know (or even care) about that to use it securely
-
crypto_secretbox()
/crypto_secretbox_open()
offer shared-key authenticated encryption.- The algorithm in question is XSalsa20-Poly1305, but you don't need to know/care
Additionally, libsodium has bindings in dozens of popular programming languages, so it's very likely that libsodium will just work when trying to interoperate with another programming stack. Also, libsodium tends to be very fast without sacrificing security.
How to Use Libsodium in JavaScript?
First, you need to decide one thing:
- Do you just want to encrypt/decrypt data (and maybe still somehow use the plaintext in database queries securely) and not worry about the details? Or...
- Do you need to implement a specific protocol?
If you selected the first option, get CipherSweet.js.
The documentation is available online. EncryptedField
is sufficient for most use cases, but the EncryptedRow
and EncryptedMultiRows
APIs may be easier if you have a lot of distinct fields you want to encrypt.
With CipherSweet, you don't need to even know what a nonce/IV is to use it securely.
Additionally, this handles int
/float
encryption without leaking facts about the contents through ciphertext size.
Otherwise, you'll want sodium-plus, which is a user-friendly frontend to various libsodium wrappers. Sodium-Plus allows you to write performant, asynchronous, cross-platform code that's easy to audit and reason about.
To install sodium-plus, simply run...
npm install sodium-plus
There is currently no public CDN for browser support. This will change soon. However, you can grab sodium-plus.min.js
from the latest Github release if you need it.
const { SodiumPlus } = require('sodium-plus');
let sodium;
(async function () {
if (!sodium) sodium = await SodiumPlus.auto();
let plaintext = 'Your message goes here';
let key = await sodium.crypto_secretbox_keygen();
let nonce = await sodium.randombytes_buf(24);
let ciphertext = await sodium.crypto_secretbox(
plaintext,
nonce,
key
);
console.log(ciphertext.toString('hex'));
let decrypted = await sodium.crypto_secretbox_open(
ciphertext,
nonce,
key
);
console.log(decrypted.toString());
})();
The documentation for sodium-plus is available on Github.
If you'd like a step-by-step tutorial, this dev.to article has what you're looking for.
This code is based on @Jorgeblom's answer above.
@Jorgeblom my man, that's fantastic small crypto lib :D I touch it a bit because I didn't like that I have to assign the salt and to call it again but in general, for my needs is absolutely perfect.
const crypt = (salt, text) => {
const textToChars = (text) => text.split("").map((c) => c.charCodeAt(0));
const byteHex = (n) => ("0" + Number(n).toString(16)).substr(-2);
const applySaltToChar = (code) => textToChars(salt).reduce((a, b) => a ^ b, code);
return text
.split("")
.map(textToChars)
.map(applySaltToChar)
.map(byteHex)
.join("");
};
const decrypt = (salt, encoded) => {
const textToChars = (text) => text.split("").map((c) => c.charCodeAt(0));
const applySaltToChar = (code) => textToChars(salt).reduce((a, b) => a ^ b, code);
return encoded
.match(/.{1,2}/g)
.map((hex) => parseInt(hex, 16))
.map(applySaltToChar)
.map((charCode) => String.fromCharCode(charCode))
.join("");
};
And you use it
// encrypting
const encrypted_text = crypt("salt", "Hello"); // -> 426f666665
// decrypting
const decrypted_string = decrypt("salt", "426f666665"); // -> Hello