JavaScript字符串加密解密函數

Javascript默認沒有編加密解密函數,需要手動編寫。

如下是完整的字符串加解密函數,用到charCodeAt()fromCharCode()encodeURIComponent()函數。

先上代碼,三個函數說明請看後面。

/**
 * 加密函數
 * @param str 待加密字符串
 * @returns {string}
 */
function str_encrypt(str) {
    var c = String.fromCharCode(str.charCodeAt(0) + str.length);

    for (var i = 1; i < str.length; i++) {
        c += String.fromCharCode(str.charCodeAt(i) + str.charCodeAt(i - 1));
    }

    return encodeURIComponent(c);
}

/**
 * 解密函數
 * @param str 待解密字符串
 * @returns {string}
 */
function str_decrypt(str) {
    str = decodeURIComponent(str);
    var c = String.fromCharCode(str.charCodeAt(0) - str.length);

    for (var i = 1; i < str.length; i++) {
        c += String.fromCharCode(str.charCodeAt(i) - c.charCodeAt(i - 1));
    }
    return c;
}

函數說明:

  • charCodeAt():返回指定位置的字符的 Unicode 編碼。這個返回值是 0 - 65535 之間的整數。
  • fromCharCode():接受一個指定的 Unicode 值,然後返回一個字符串。
  • encodeURIComponent():把字符串作爲 URI 組件進行編碼。
  • decodeURIComponent():對 encodeURIComponent() 函數編碼的 URI 進行解碼。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章