20

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?

1
  • 3
    Base64, Rot13, etc come to mind... hardly "encryption" though. Commented May 17, 2013 at 9:33

2 Answers 2

59

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:

Sign up to request clarification or add additional context in comments.

Comments

2

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 btoa is 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.