This article shares a unique encryption and decryption method for JavaScript code.
Technical Principles
Encrypt JavaScript code, and then "try" to decrypt it in the try-catch error handling syntax. If the decryption is successful and the code can be executed, it means the decryption is successful. If the code cannot be executed, it means the decryption has failed, and an error will be thrown which can be caught by the catch to attempt decryption again.
The following code implements JavaScript encryption.
var source_string ='alert("JShaman Javscript Obfuscator");';
var encoded_string = "";
function encode(){
for(var i=0;i<source_string.length;i++){
encoded_string += String.fromCharCode(source_string.charCodeAt(i) ^ 9);
}
console.log("Encrypted string:"+encoded_string);
}
encode();
Execute output
The following code implements decryption.
var encode_key = 0;
var encoded_string = "hel{}!+CZahdhg)Chzj{`y})Fko|zjh}f{+ 2";
var decoded_string = encoded_string;
function decode(){
try{
console.log("Execute:",decoded_string);
eval(decoded_string);
}catch(e){
encode_key += 1;
decoded_string ="";
for(var i=0; i<encoded_string.length; i++){
decoded_string += String.fromCharCode(encoded_string.charCodeAt(i) ^ encode_key );
}
console.log("Decrypted string", decoded_string, encode_key);
decode();
}
}
decode();
Explanation: Assuming that the key is unknown, the code in the try section will attempt to decrypt an incorrect ciphertext, which naturally cannot be executed. The program flow will then be caught by the catch and the key will be modified to attempt decryption again. This process will continue indefinitely until the correct key is found. In this demonstration, a simple XOR encryption is used. If a more complex encryption algorithm with a less guessable key is used, the encryption effectiveness of this method will be very good.
Execute output
Precautions
This is a novel encryption method, where the encrypted code can be used independently. Without the key, if analyzed using a general reverse method, it will result in countless decryption results, which can seriously interfere with the analyst. However, there are certain limitations to using this method: because decryption relies on eval execution, the encrypted statement needs to be executable, such as wrapped in statements like alert, console.log, eval, etc.
Top comments (0)