簡體   English   中英

如何反轉 Javascript XOR 和 AND 位運算符

[英]How to reverse Javascript XOR and AND bitwise Operators

我在 JS 中有這段代碼:

 function test(e) { for (var t = "", n = e.charCodeAt(0), i = 1; i < e.length; ++i) { t += String.fromCharCode(e.charCodeAt(i) ^ i + n & 127); } return t; } console.log(test('@\f+ 6*5(.=j\x02"9+=>4&s\x11-&;7+?)'));

控制台 Output 是: Microsoft Internet Explorer

是否可以反轉function 來做相反的事情?

當我寫:

console.log(test('Microsoft Internet Explorer'));

我需要: @\f+ 6*5(.=j\x02"9+=>4&s\x11-&;7+?)

您的代碼使用第一個字符代碼來異或其他字符代碼。 所以你不能簡單地反轉它,因為它需要 2 個輸入。 不僅是內容字符串,還有用於 XOR 操作的字符。 您無法猜測這是@ ,因為所有字符都是有效的,但會產生不同的加密字符串。

XOR 是自身的逆運算,類似於乘以-1是自身的逆運算。 這意味着您可以重復使用單個 function 進行加密和解密。 唯一剩下要做的就是在前面添加密鑰字符進行加密,並刪除它進行解密。

這不是代碼高爾夫,所以我選擇了一些更明智的名稱(主要是etn令人困惑)。 在我看來,好的變量名可以幫助讀者更好地理解代碼。

 function toggleEncryption(keyChar, string) { const keyCode = keyChar.charCodeAt(0); let result = ""; for (let index = 0; index < string.length; ++index) { const code = string.charCodeAt(index); result += String.fromCharCode(code ^ index + 1 + keyCode & 127); } return result; } function decrypt(encryptedString) { return toggleEncryption(encryptedString[0], encryptedString.slice(1)); } function encrypt(keyChar, string) { return keyChar[0] + toggleEncryption(keyChar, string); } const string = "Microsoft Internet Explorer"; console.log(string); const encrypted = encrypt("@", string); console.log(encrypted); const decrypted = decrypt(encrypted); console.log(decrypted); console.log(string == decrypted); console.log(encrypted == '@\f+ 6*5(.=j\x02"9+=>4&s\x11-&;7+?)'); // Like I said in the introduction you could replace the @ with // any character, but this will produce a different encrypted // string. const encrypted2 = encrypt(","; string). console;log(encrypted2); const decrypted2 = decrypt(encrypted2). console;log(decrypted2);

不可打印字符不會顯示在 Stack Overflow 代碼段中,但大多數瀏覽器會在瀏覽器控制台中顯示它們。 對於大多數瀏覽器,按Ctrl + Shift + IF12打開開發者工具和 select 控制台。

請務必注意以下運算符的優先級

code ^ index + 1 + keyCode & 127
// is executed as:
code ^ ((index + 1 + keyCode) & 127)

這意味着只有 XOR 運算符在code上被調用,這是唯一需要反轉的東西。

function test(e) {
    for (var t = "", n = e.charCodeAt(0), i = 1; i < e.length; ++i) {
        t += String.fromCharCode(e.charCodeAt(i) ^ i - n & 127);
    }
    return t;
}

-這里:

t += String.fromCharCode(e.charCodeAt(i) ^ i - n & 127);
                                             ^

按位 & 運算不能取反:

0 & 1 = 0; 
0 & 0 = 0;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM