I have a base64 string that I have to decode, which is AwELBwc=
. Using the XOR cipher key given to me, which is 26364
, I have to decode the string to get a number, which I already know ( 7813
).
How would this be done in Javascript, where you take a base64-encoded string, run it through a XOR cipher with a known key, then output the result?
This code should do what you want:
function base64ToArray(base64String) { var bstr = atob(base64String); var bytes = []; for (var i = 0; i < bstr.length; i++) { bytes.push(bstr.charCodeAt(i)); } return bytes; } let key = [2,6,3,6,4]; let cipherTextBase64 = 'AwELBwc='; let cipherTextBytes = base64ToArray(cipherTextBase64); let result = key.map((value,index) => { return value ^ cipherTextBytes[index]; }); document.getElementById('output').innerHTML = 'Result: ' + result.join(); console.log('Result: ', result);
<div id="output"> </div>
The function below is inspired by the xor character by character method that Terry Lennox used in his answer.
function xorDecryptBase64(base64string, cipher) { let keys = cipher.toString().split(''); let charCodes = atob(base64string).split('') .map(function(c){return c.charCodeAt(0)}); return Number(charCodes .map(function(v,i){return v ^ keys[i%keys.length]}) .slice(1).join('') ); } console.log(xorDecryptBase64('AwELBwc=', 26364)); console.log(xorDecryptBase64('AwAFAAIEAA==', 26364));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.