天天看點

JavaScript奇淫技巧:用try、catch實作JS代碼加密解密

JavaScript奇淫技巧:用try、catch實作JS加密解密

本文分享一種奇特的JS加密解密方法。

原理

将JS加密,然後在try、catch錯誤捕捉文法中,用eval進行執行,能執行則說明解密成功,不能執行則會抛出錯誤,并由catch捕捉進行重新解密。

源碼

加密部分:

JavaScript奇淫技巧:用try、catch實作JS代碼加密解密

解密部分:

JavaScript奇淫技巧:用try、catch實作JS代碼加密解密

完整源碼:

       /*加密部分*/

    var source_string ='alert("JShaman是好用的JavaScript混淆加密網站");';

    var encoded_string = "";

    function encode(){

        for(var i=0;i<source_string.length;i++){

            //異或加密每一個字元,異或密鑰:61

            encoded_string += String.fromCharCode(source_string.charCodeAt(i)^61);

        }

        alert(encoded_string);

        console.log("加密完成:",encoded_string);

    }

    encode();

    /*解密部分*/

    //初始解密密鑰,初始設為0,可為小于加密字元長度的任意值

    var encode_key = 0;

    //解密後的字元串,初始為加密值

    var decoded_string = encoded_string;

    function decode(){

        try{

            //eval執行,能執行則說明解密成功,因為原始代碼是alert,是能正确執行的語句

            eval(decoded_string);

            console.log("解密成功:", decoded_string);

        }catch(e){

            decoded_string ="";

            for(var i=0; i<encoded_string.length; i++){

                decoded_string += String.fromCharCode(encoded_string.charCodeAt(i) ^ encode_key );

            }

            encode_key += 1;

            decode();

        }

    }

    decode();

二重加密:

如果把以上代碼,用JShaman再次進行混淆加密,将得到更加安全的加密代碼:

運作效果

注意事項

繼續閱讀