Javascript crypto SJCL GCM not decrypting what I encrypted - javascript

I'm currently experimenting with SJCL but I'm having trouble with encryption/decryption. With the lack of good examples I came up with what you see below but it's not working. Can anybody point out what I'm doing wrong? Thanks in advance.
<html>
<!-- sjcl made with: ./configure --with-all -compress=none && make -->
<script type="text/javascript" src="sjcl.js"></script>
<body>
<script>
var p = {
"iv": "PnWtrKCP2DKcLyNC18RKAw==",
"ts": 128,
"mode": "gcm",
"adata": "You can read me",
"cipher": "aes",
"key": "QiJysyALRxUESl18XKl0FcpXQJvFB2Z3Q3A61tdNNM0=" // pbkdf2 key
};
var prp = new sjcl.cipher[p.cipher](sjcl.codec.base64.toBits(p.key));
var plain = "My plaintext";
var ct = sjcl.codec.base64.fromBits(sjcl.mode[p.mode].encrypt(prp, sjcl.codec.bytes.toBits(plain), p.iv, p.adata, p.ts));
var pt = sjcl.codec.base64.fromBits(sjcl.mode[p.mode].decrypt(prp, sjcl.codec.base64.toBits(ct), p.iv, p.adata, p.ts));
document.writeln("ct: " + ct + "<br>");
document.writeln("pt: " + pt + "<br>");
</script>
<hr><pre>
Results in:
encrypted: 5Z2QQ9s6gfORlr6qLvlwjO/J+/TbfSbOs79c4w==
decrypted: AAAAAAAAAAAAAAAA
</pre></body></html>

I think your problem is sjcl.codec.bytes.toBits(plaintext). If you run that by itself, you get [0,0,0]. I think you want sjcl.codec.utf8String.toBits(plaintext) instead.
You would use bytes.toBits if you have an actual byte (octet) array (like [255, 34, 12, 16]), but in this case you're using a string so it needs to be converted differently.
Also, I've had problems with using strings for IVs, you may want to run it through the same conversion as the key before passing it in (base64.toBits(iv)).

Related

Parsing JSON string from python to Javascript

I am working on a terrarium controller project, at this moment I want to get the timeperiod of the lighting. In python I have a function called: getStatus() it returns a JSON string to Javascript, which will handle the data further. But it doesn't work.
Here's my python code:
def getStatus ():
data=[["HOUR_ON", HOUR_ON],["MINUTE_ON", MINUTE_ON], ["HOUR_OFF", HOUR_OFF], ["MINUTE_OFF", MINUTE_OFF]]
return json.dumps(data)
And overhere the Javascript:
var alertFunction = function macroCallback(macro, args, light) {
alert(macro + " returned with " + light);
var obj = JSON.parse(light);
document.getElementById("testSection").innerHTML="Light turns on at: "+ obj[0].HOUR_ON+":"+obj[0].MINUTE_ON + "\n"+"Light goes out at: "+obj[1].HOUR_OFF+":"+obj[1].MINUTE_OFF;
alert("after parsing: "+obj[0]);
document.getElementById("testSection").innerHTML=light;
}
The string seems to be send back from the server and will be parsed correctly, only accessing the string doesn't work I get four times undefined in the innerHTML section.
I hope someone can help me out!
Greetings and thanks!
Marco
Without changing your Python code, alter your javascript code to access the elements of the array using indices, not with attributes:
var alertFunction = function macroCallback(macro, args, light) {
alert(macro + " returned with " + light);
var obj = JSON.parse(light);
document.getElementById("testSection").innerHTML="Light turns on at: "+ obj[0][1]+":"+obj[1][1] + "\n"+"Light goes out at: "+obj[2][1]+":"+obj[3][1];
alert("after parsing: "+obj[0]);
document.getElementById("testSection").innerHTML=light;
}
However, it would be better to follow jcubic's advice and change your Python code to use a dictionary:
def getStatus ():
data={"HOUR_ON": HOUR_ON,
"MINUTE_ON": MINUTE_ON,
"HOUR_OFF": HOUR_OFF,
"MINUTE_OFF": MINUTE_OFF}
return json.dumps(data)
For example this produces a JSON string like this:
'{"HOUR_OFF": 13, "MINUTE_ON": 30, "MINUTE_OFF": 20, "HOUR_ON": 12}'
Also change your javascript to access the attributes of the object, which is much more readable:
var alertFunction = function macroCallback(macro, args, light) {
alert(macro + " returned with " + light);
var obj = JSON.parse(light);
document.getElementById("testSection").innerHTML="Light turns on at: "+ obj.HOUR_ON + ":" + obj.MINUTE_ON + "\n" + "Light goes out at: "+obj.HOUR_OFF+":"+obj.MINUTE_OFF;
alert("after parsing: "+obj[0]);
document.getElementById("testSection").innerHTML=light;
}
You've saved array instead of object try:
data=[{"HOUR_ON": HOUR_ON},{"MINUTE_ON": MINUTE_ON}, {"HOUR_OFF": HOUR_OFF}, {"MINUTE_OFF": MINUTE_OFF}]
or better just one object:
data={"HOUR_ON": HOUR_ON, "MINUTE_ON": MINUTE_ON, "HOUR_OFF": HOUR_OFF, "MINUTE_OFF": MINUTE_OFF}

Exception thrown by cryptojs while decrypting an encrypted message

I get an exception while trying to decrypt a cryptojs encrypted message. My decryption javascript code is given below. I am kind of stuck with no clue of what is happening. I did some debugging and could see that Base64 within the cipher-core library was undefined...
function decrypt(){
var salt = CryptoJS.enc.Hex.parse("3A79D3242F9D0DCE0C811DCCE7F830C5");
var iv = CryptoJS.enc.Hex.parse("9BCBD77036744C7F26DF591AE6A772C6");
var encryptedBase64 = "eKCnyuKiH3lvknsNZq9hARCr6xtDLU/De7sPc3RPSRFAh7WCurBKmDZx/Ol0mbROBtAJBCT0+U927iygd4GspQ==";
var key = CryptoJS.PBKDF2("passwordA", salt, { keySize: 128/32, iterations: 100 });
console.log('key '+key);
var encryptedStr = encryptedBase64; //CryptoJS.enc.Base64.parse(encryptedBase64);
console.log('encryptedStr : '+ encryptedStr );
var decrypted = CryptoJS.AES.decrypt(encryptedStr, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
console.log('decrypted : '+ decrypted);
var decryptedText = decrypted.toString(CryptoJS.enc.Utf8);
console.log('decrypted text : '+ decryptedText);
}
I get the following exception
TypeError: Cannot read property 'parse'
of undefined at Object.m.OpenSSL.parse(http: //domain.com/PEMSWeb/offlinePageDemo/offlineInspectionApp/CryptoJSv3.1.2/components/cipher-core-min.js:12:101)
at Object.f.SerializableCipher.k.extend._parse(http: //domain.com/PEMSWeb/offlinePageDemo/offlineInspectionApp/CryptoJSv3.1.2/components/cipher-core-min.js:13:220)
at Object.f.SerializableCipher.k.extend.decrypt(http: //domain.com/PEMSWeb/offlinePageDemo/offlineInspectionApp/CryptoJSv3.1.2/components/cipher-core-min.js:13:99)
at Object.decrypt(http: //domain.com/PEMSWeb/offlinePageDemo/offlineInspectionApp/CryptoJSv3.1.2/components/cipher-core-min.js:8:308)
I have no idea what is going wrong ...something is going incorrect within cryptojs
Updated
I have the following libraries in my page in the same sequence
1) CryptoJSv3.1.2/components/core-min.js
2) CryptoJSv3.1.2/components/cipher-core-min.js
3) CryptoJSv3.1.2/components/enc-base64-min.js
4) CryptoJSv3.1.2/components/enc-utf16-min.js
5) CryptoJSv3.1.2/rollups/aes.js
6) CryptoJSv3.1.2/rollups/pbkdf2.js
I'm not sure why you need the components scripts, but you should change the order around. This is a working ordering found by trial and error:
<script src="components/core-min.js "></script>
<script src="rollups/aes.js"></script>
<script src="components/cipher-core-min.js"></script>
<script src="components/enc-base64-min.js"></script>
<script src="rollups/pbkdf2.js"></script>
<script src="components/enc-utf16-min.js"></script>
and minimal cover set that is needed for the shown code is
<script src="rollups/aes.js"></script>
<script src="rollups/pbkdf2.js"></script>
core is contained in the rollups, base64 is contained in aes. utf16 is not needed in the code. I'm not sure what cipher-core does, but I guess it is also contained in aes.
The files are available for self-hosting from the Google Code Archive.

Replace array-mapped variables with the actual variable name/string?

I am trying to edit a Greasemonkey/jQuery script. I can't post the link here.
The code is obfuscated and compressed with minify.
It starts like this:
var _0x21e9 = ["\x67\x65\x74\x4D\x6F\x6E\x74\x68", "\x67\x65\x74\x55\x54\x43\x44\x61\x74\x65", ...
After "decoding" it, I got this:
var _0x21e9=["getMonth","getUTCDate","getFullYear", ...
It is a huge list (500+ ). Then, it has some variables like this:
month = date[_0x21e9[0]](), day = date[_0x21e9[1]](), ...
_0x21e9[0] is getMonth, _0x21e9[1] is getUTCDate, etc.
Is it possible to replace the square brackets with the actual variable name? How?
I have little knowledge in javascript/jQuery and can not "read" the code the way it is right now.
I just want to use some functions from this huge script and remove the others I do not need.
Update: I tried using jsbeautifier.org as suggested here and in the duplicated question but nothing changed, except the "indent".
It did not replace the array variables with the decoded names.
For example:
jsbeautifier still gives: month = date[_0x21e9[0]]().
But I need: month = date["getMonth"]().
None of the online deobfuscators seem to do this, How can I?
Is there a way for me to share the code with someone, at least part of it? I read I can not post pastebin, or similar here. I can not post it the full code here.
Here is another part of the code:
$(_0x21e9[8] + vid)[_0x21e9[18]]();
[8] is "." and [18] is "remove". Manually replacing it gives a strange result.
I haven't seen any online deobfuscator that does this yet, but the principle is simple.
Construct a text filter that parses the "key" array and then replaces each instance that that array is referenced, with the appropriate array value.
For example, suppose you have a file, evil.js that looks like this (AFTER you have run it though jsbeautifier.org with the Detect packers and obfuscators? and the Unescape printable chars... options set):
var _0xf17f = ["(", ")", 'div', "createElement", "id", "log", "console"];
var _0x41dcx3 = eval(_0xf17f[0] + '{id: 3}' + _0xf17f[1]);
var _0x41dcx4 = document[_0xf17f[3]](_0xf17f[2]);
var _0x41dcx5 = _0x41dcx3[_0xf17f[4]];
window[_0xf17f[6]][_0xf17f[5]](_0x41dcx5);
In that case, the "key" variable would be _0xf17f and the "key" array would be ["(", ")", ...].
The filter process would look like this:
Extract the key name using text processing on the js file. Result: _0xf17f
Extract the string src of the key array. Result:
keyArrayStr = '["(", ")", \'div\', "createElement", "id", "log", "console"]';
In javascript, we can then use .replace() to parse the rest of the JS src. Like so:
var keyArrayStr = '["(", ")", \'div\', "createElement", "id", "log", "console"]';
var restOfSrc = "var _0x41dcx3 = eval(_0xf17f[0] + '{id: 3}' + _0xf17f[1]);\n"
+ "var _0x41dcx4 = document[_0xf17f[3]](_0xf17f[2]);\n"
+ "var _0x41dcx5 = _0x41dcx3[_0xf17f[4]];\n"
+ "window[_0xf17f[6]][_0xf17f[5]](_0x41dcx5);\n"
;
var keyArray = eval (keyArrayStr);
//-- Note that `_0xf17f` is the key name we already determined.
var keyRegExp = /_0xf17f\s*\[\s*(\d+)\s*\]/g;
var deObsTxt = restOfSrc.replace (keyRegExp, function (matchStr, p1Str) {
return '"' + keyArray[ parseInt(p1Str, 10) ] + '"';
} );
console.log (deObsTxt);
if you run that code, you get:
var _0x41dcx3 = eval("(" + '{id: 3}' + ")");
var _0x41dcx4 = document["createElement"]("div");
var _0x41dcx5 = _0x41dcx3["id"];
window["console"]["log"](_0x41dcx5);
-- which is a bit easier to read/understand.
I've also created an online page that takes JS source and does all 3 remapping steps in a slightly more automated and robust manner. You can see it at:
jsbin.com/hazevo
(Note that that tool expects the source to start with the "key" variable declaration, like your code samples do)
#Brock Adams solution is brilliant, but there is a small bug: it doesn't take into account simple quoted vars.
Example:
var _0xbd34 = ["hello ", '"my" world'];
(function($) {
alert(_0xbd34[0] + _0xbd34[1])
});
If you try to decipher this example, it will result on this:
alert("hello " + ""my" world")
To resolve this, just edit the replacedSrc.replace into #Brock code:
replacedSrc = replacedSrc.replace (nameRegex, function (matchStr, p1Str) {
var quote = keyArry[parseInt (p1Str, 10)].indexOf('"')==-1? '"' : "'";
return quote + keyArry[ parseInt (p1Str, 10) ] + quote;
} );
Here you have a patched version.
for (var i = 0; i < _0x21e9.length; i++) {
var funcName = _0x21e9[i];
_0x21e9[funcName] = funcName;
}
this will add all the function names as keys to the array. allowing you to do
date[_0x21e9["getMonth"]]()

Download .csv with javascript

i want generate .csv in javascript. i have the object, the name is "archivo". the
This problem is when generate the file csv, in each line add ',', i don't know what happen
archivo=[], each line is string + '\n'.
if (navigator.appName == 'Microsoft Internet Explorer') {
var popup = window.open('','csv','');
popup.document.body.innerHTML = '<pre>' + archivo[i] + '</pre>';
}else{
location.href='data:application/download; charset=utf8,' + encodeURIComponent(archivo);
}
any can help me?
You should consider using a CSV generator library, that handles all this for you.
I've written a light-weight client-side CSV generator library that might come in handy. Check it out on http://atornblad.se/github/ (scroll down to the headline saying Client-side CSV file generator)
It requires a functioning FileSaver implementation handling calls to window.saveAs(). Check out Eli Grey's solution on http://eligrey.com/blog/post/saving-generated-files-on-the-client-side
When in place, you simply generate and save CSV files on the fly like this:
var propertyOrder = ["name", "age", "height"];
var csv = new Csv(propertyOrder);
csv.add({ name : "Anders",
age : 38,
height : "178cm" });
csv.add({ name : "John Doe",
age : 50,
height : "184cm" });
csv.saveAs("people.csv");

jsSHA, CryptoJS and OpenSSL libraries giving different results

New to JS, I'm also learning to use crypto libraries. I don't understand why signing/encoding the same message with the same secret yields differing results.
I'm using jsSHA 1.3.1 found here, and CryptoJS 3.0.2 described here trying to create a base64 sha-1 encoded hmac signature. Here's the code:
In html...
<script src="lib/jsSHA/src/sha1.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/hmac-sha1.js"></script>
And in js...
var message = "shah me";
var secret = "hide me";
var crypto = CryptoJS.HmacSHA1(message, secret).toString(CryptoJS.enc.Base64) + '=';
var shaObj = new jsSHA(message, "ASCII");
var jssha = shaObj.getHMAC(secret, "ASCII", "B64") + '=';
return "crypto answer is " + crypto + " jssha answer is " + jssha;
Can you help me explain why these results differ?
crypto answer is 3e929e69920fb7d423f816bfcd6654484f1f6d56= jssha
answer is PpKeaZIPt9Qj+Ba/zWZUSE8fbVY=
What's more, both of these differ with the signature I'm generating in rails, like this...
digest = OpenSSL::Digest::Digest.new('sha1')
raw_signature = OpenSSL::HMAC.digest(digest, "hide me","shah me")
b64_signature = Base64.encode64(raw_signature).strip
(would have liked to supply a fiddle, which seems to be a very good common practice, but that, too, is new to me and I was unable to get one working for this question).
Thanks in advance.
There are 3 errors in your code :)
You're missing the enc-base64-min.js for crypto-js. Without it, CryptoJS.enc.Base64 will be undefined
You're missing a parameter when calling .getHMAC(). It's .getHMAC(secret, secret_type, hash_type, output_encoding)
With 1+2 adding a = isn't necessary (nor right)
<script src="lib/jsSHA/src/sha1.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/hmac-sha1.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/components/enc-base64-min.js"></script>
var message = "shah me";
var secret = "hide me";
var crypto = CryptoJS.HmacSHA1(message, secret).toString(CryptoJS.enc.Base64);
var shaObj = new jsSHA(message, "ASCII");
var jssha = shaObj.getHMAC(secret, "ASCII", "SHA-1", "B64");
return "crypto answer is " + crypto + " jssha answer is " + jssha;
Example

Categories

Resources