I would like to know if it is possible to encrypt and decrypt a text, using pure JavaScript. I don't want to use a key. It may be an entry lever solution. But I simply want to encode a text "my-name-1" into some text format and want to retrieve the text from it. Is this possible, without using any js libraries?
2 Answers
Without a key (or some secret for that matter), you wont get any kind of encryption.
What you mean is something like a different encoding. So maybe Base64 is something for you.
var baseString = 'my-name-1';
var encodedString = window.btoa( baseString ); // returns "bXktbmFtZS0x"
var decodedString = window.atob( encodedString ); // returns "my-name-1"
This is supported in all major browsers. IE support just in IE10+.
References:
Comments
In my case (storing a game score) I needed to add a bit of obfuscation on top of base64 encryption:
const z = ['a', 'o', 'b', 't']
const y = z[0] + z[3] + z[1] + z[2]
const x = z[2] + z[3] + z[1] + z[0]
function encrypt(str) {
return window[x]?.(str).split('').reverse().join('')
}
function decrypt(str) {
return window[y]?.(str.split('').reverse().join(''))
}
This is ok for my case because:
- I don't need real encryption
- The word
btoais not searchable in the code - The outputted string is not clearly base64 and decoding it will fail
- Makes harder (but not impossible) for the user to cheat
Disclaimer: This is not encryption and shall not be used for security purposes, this is obfuscation