Simplest way to obfuscate and deobfuscate a string in JavaScript

前端 未结 3 1514
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 17:04

I\'m looking for a way to obfuscate and deobfuscate a string in JavaScript; by which I mean encryption and decryption when security is not an issue. Ideally something native

相关标签:
3条回答
  • 2020-12-04 17:12

    You can use btoa() and atob(). btoa() is like base64_encode() and atob() like base64_decode().

    Here is an example:

    btoa('Some text'); // U29tZSB0ZXh0
    atob('U29tZSB0ZXh0'); // Some text
    

    Keep in mind that this is not a secure way to keep secrets. Base64 is a binary-to-text encoding scheme that represents binary data in an ASCII string format by translating it into a radix-64 representation.

    0 讨论(0)
  • 2020-12-04 17:27

    It's worth noting that

    (![]+[])[+[]]+(![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]

    evaluates to the string "fail" without ever looking like a string. Seriously, enter it into node and be amazed. You can spell anything in JavaScript by being crazy.

    0 讨论(0)
  • 2020-12-04 17:29

    I'm obviously too late for an answer, but I was just working on another solution for the problem and base64 seemed to be to weak.

    It works like this:

    "abc;123!".obfs(13) // => "nopH>?@."
    "nopH>?@.".defs(13) // => "abc;123!"
    

    Code:

    /**
     * Obfuscate a plaintext string with a simple rotation algorithm similar to
     * the rot13 cipher.
     * @param  {[type]} key rotation index between 0 and n
     * @param  {Number} n   maximum char that will be affected by the algorithm
     * @return {[type]}     obfuscated string
     */
    String.prototype.obfs = function(key, n = 126) {
      // return String itself if the given parameters are invalid
      if (!(typeof(key) === 'number' && key % 1 === 0)
        || !(typeof(key) === 'number' && key % 1 === 0)) {
        return this.toString();
      }
    
      var chars = this.toString().split('');
    
      for (var i = 0; i < chars.length; i++) {
        var c = chars[i].charCodeAt(0);
    
        if (c <= n) {
          chars[i] = String.fromCharCode((chars[i].charCodeAt(0) + key) % n);
        }
      }
    
      return chars.join('');
    };
    
    /**
     * De-obfuscate an obfuscated string with the method above.
     * @param  {[type]} key rotation index between 0 and n
     * @param  {Number} n   same number that was used for obfuscation
     * @return {[type]}     plaintext string
     */
    String.prototype.defs = function(key, n = 126) {
      // return String itself if the given parameters are invalid
      if (!(typeof(key) === 'number' && key % 1 === 0)
        || !(typeof(key) === 'number' && key % 1 === 0)) {
        return this.toString();
      }
    
      return this.toString().obfs(n - key);
    };
    
    0 讨论(0)
提交回复
热议问题