51

JavaScript で文字列を難読化および難読化解除する方法を探しています。これは、セキュリティが問題にならない場合の暗号化と復号化を意味します。理想的には、関数を記述しなくても「文字列を別のものに変換して元に戻す」ための JS (base64_encode()およびPHP など) にネイティブなものです。base64_decode()

どんな提案でも大歓迎です!

4

3 に答える 3

91

btoa()atob( ) を使用できます。のbtoa()ようなものです。base64_encode()atob()base64_decode()

次に例を示します。

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

これは秘密を保持するための安全な方法ではないことに注意してください。Base64 は、基数 64 表現に変換することによってバイナリ データを ASCII 文字列形式で表すバイナリからテキストへのエンコード スキームです。

于 2013-01-22T12:43:22.117 に答える
13

私は明らかに答えが遅すぎますが、問題の別の解決策に取り組んでいて、base64が弱すぎるようです。

それはこのように動作します:

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

コード:

/**
 * 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);
};
于 2016-12-30T16:00:36.267 に答える