bitwiseshiftleft / sjcl Goto Github PK
View Code? Open in Web Editor NEWStanford Javascript Crypto Library
Home Page: http://bitwiseshiftleft.github.com/sjcl/
License: Other
Stanford Javascript Crypto Library
Home Page: http://bitwiseshiftleft.github.com/sjcl/
License: Other
On http://bitwiseshiftleft.github.com/sjcl/doc/symbols/sjcl.json.html#.encrypt it states that a bitArray key can be used instead of a password. How does one go about constructing this key and using it with sjcl? Does it have to be in a special format?
One question. Can SJCL be safely used in Web Workers?
Since Javascript Typed Arrays enjoy an increasing adoption by browser vendors perhaps this excellent library can be made even faster by using typed arrays for low level IO.
Hello
I found some small to medium issues in the (re)seeding code.
--- core/random.js.orig 2012-06-25 13:53:53.777523059 +0200
+++ core/random.js 2012-06-25 16:42:28.637261673 +0200
@@ -95,8 +95,7 @@
case "number":
data=[data];
ty=1;
- break;
-
+ // fall through
case "object":
if (estimatedEntropy === undefined) {
/* horrible entropy estimator */
@@ -235,7 +234,7 @@
/* private */
_pools : [new sjcl.hash.sha256()],
_poolEntropy : [0],
- _reseedCount : 0,
+ _reseedCount : 1,
_robins : {},
_eventId : 0,
@@ -321,7 +320,8 @@
}
/* if we used the last pool, push a new one onto the stack */
- if (this._reseedCount >= 1 << this._pools.length) {
+ if (this._reseedCount >= (1 << (this._pools.length - 1))
+ && this._pools.length < 32) {
this._pools.push(new sjcl.hash.sha256());
this._poolEntropy.push(0);
}
Best Regards,
Das
Using Palm webOS 1.4.1.1 on a palm pixi failed to complete all browser tests. It appeared to stop running all tests on test Running SHA-256 from catameringue...
I am not sure if there is a way to determine if the deficiencies are in the palm browser.
In random.js on line 224 there is a bug that prevents event handlers from being removed.
cbs.hasOwnProperty[j]
should be:
cbs.hasOwnProperty(j)
Square brackets should be changed to parentheses.
I have a need to use Java to decrypt data that was encrypted using sjcl. So I am attempting to load sjcl in Rhino and decrypt it.
I am having an issue using sjcl in Rhino. Here is an example snippet:
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
URL url = new URL("https://github.com/bitwiseshiftleft/sjcl/raw/version-0.8/sjcl.js");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
engine.eval(in);
in.close();
engine.eval("try { sjcl.encrypt('password', 'data') } catch(e) { print(e) }");
and I am getting the following printing:
INVALID: ccm: invalid tag length
Is there something I am not setting up in Rhino?
When running the tests on the test page http://bitwiseshiftleft.github.com/sjcl/browserTest/ in Internet Explorer 7.0.5730.11 on Windows XP SP3, the browser popped up an error message saying "Error: 'length' is null or not an object" during one of the OCB 2.0 mode tests.
I've noticed that sjcl.random.getProgress() returns 'undefined' at times. After some digging I found that Closure compression changes:
1.0
to
1["0"]
Fortunately, the only place where numerical decimal notation is used is in sjcl.random.getProgress(), so I've just changed the numbers from 1.0 to 1 (I hope this is acceptable Javascript practice). I'd include a patch, but my familiarity with GIT is so-so. There are only two lines in one function to change.
I don't intend to forward this along to the Closure project, so if someone else would like to, feel free.
I would love to see a list of apps that use this library. I can share mine, if you're interested.
Hello,
I run into an issue with my custom SRP implementation using sjcl.bn objects. Here's an example:
At the step when I need to calculate SRP session key S:
S0 = B.sub(k.mulmod(v, N));
S1 = a.add(u.mulmod(x, N));
S = S0.powermod(S1, N);
The problematic line is 1. I independently verified the same formula with the same numbers in Python:
S0 = B - ((k*v) % N)
S1 = a + ((u*x) % N)
S = pow(S0, S1, N)
Everything but S0 is identical. The ((k*v) % N) part is also the same in Python and using SJCL. But the problem is the subtraction: B.sub(...). It calculates differently and causes incorrect S calculation, which essentially means the SRP login process fails.
Here is a complete snippet of both JavaScript and Python code illustrating the bug:
var B, k, v, N, a, u, x, S0, kv, S1, S;
B = new sjcl.bn('2B6259D230E3D04F2DDD130C6F459AE0974D40ECA6EC15F7D16F669A7D9D6D9BA23BBD403CDCFD8C40777C037609D271AEB1BF3F6BBFFFCFDB7CBFB5468188B723B777FAAA16ED8F02B53B9CF98403324A511F485585F2A8A64C352995A622B663C17B6AAB20A54D84835F6FD037ED6492DFFE0CFC46EE7E609A2DEDB03BB186');
k = new sjcl.bn('5A7E44E5FFFE806E05960CBDDC15FE6E1E57A6FFE5777B567E9B1B64663C0DC8');
v = new sjcl.bn('99978C1D06B08C91FE4D8866D62FB0EC268B7A94796FFD3E530280D5BA63CC2455103737EB3DE0966B880972A75A388B37CB06E2C590E89AE41B8D2892389EF69EF59E9A0BC1F097366F01C6FF8D14038D8268B2A0B26C94F50EF728A008DFBE5A5462E1D213A41B0CF494930958F83B89A0278785A3FCE8EB861E7A7F28A846');
N = new sjcl.bn('EEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE48E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B297BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9AFD5138FE8376435B9FC61D2FC0EB06E3');
a = new sjcl.bn('F2E03F07677571D1679D16A522AAB55A49F5BD17C75C431F87FEA2B105AC7A37');
u = new sjcl.bn('7E088362ECB87C142A191FF550266E0D3877AA56B4AE16DA62FF3A019049C437');
x = new sjcl.bn('EAC38BB1874E6BCFA4188C7D8D361A419914DFCA');
kv = k.mulmod(v, N);
console.log('kv='+sjcl.codec.hex.fromBits(kv.toBits()).toUpperCase());
S0 = B.sub(kv);
console.log('S0='+sjcl.codec.hex.fromBits(S0.toBits()).toUpperCase());
S1 = a.add(u.mulmod(x, N));
console.log('S1='+sjcl.codec.hex.fromBits(S1.toBits()).toUpperCase());
S = S0.powermod(S1, N);
console.log('S='+sjcl.codec.hex.fromBits(S.toBits()).toUpperCase());
B = long('2B6259D230E3D04F2DDD130C6F459AE0974D40ECA6EC15F7D16F669A7D9D6D9BA23BBD403CDCFD8C40777C037609D271AEB1BF3F6BBFFFCFDB7CBFB5468188B723B777FAAA16ED8F02B53B9CF98403324A511F485585F2A8A64C352995A622B663C17B6AAB20A54D84835F6FD037ED6492DFFE0CFC46EE7E609A2DEDB03BB186', 16)
k = long('5A7E44E5FFFE806E05960CBDDC15FE6E1E57A6FFE5777B567E9B1B64663C0DC8', 16)
v = long('99978C1D06B08C91FE4D8866D62FB0EC268B7A94796FFD3E530280D5BA63CC2455103737EB3DE0966B880972A75A388B37CB06E2C590E89AE41B8D2892389EF69EF59E9A0BC1F097366F01C6FF8D14038D8268B2A0B26C94F50EF728A008DFBE5A5462E1D213A41B0CF494930958F83B89A0278785A3FCE8EB861E7A7F28A846', 16)
N = long('EEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE48E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B297BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9AFD5138FE8376435B9FC61D2FC0EB06E3', 16)
a = long('F2E03F07677571D1679D16A522AAB55A49F5BD17C75C431F87FEA2B105AC7A37', 16)
u = long('7E088362ECB87C142A191FF550266E0D3877AA56B4AE16DA62FF3A019049C437', 16)
x = long('EAC38BB1874E6BCFA4188C7D8D361A419914DFCA', 16)
kv = (k*v) % N
print 'kv=%X' % kv
S0 = B - kv
print 'S0=%X' % S0
S1 = a + ((u*x) % N)
print 'S1=%X' % S1
S = pow(S0, S1, N)
print 'S=%X' % S
As you can see from the output S0 does not match, which causes calculated S to be different (and huge! - takes a few seconds to calculate). Al the other values are the same (apart from the leading zeros in kv and S1 - due to the way bitArrays get encoded to hex).
I'd appreciate to tell me whether I'm doing something wrong or it's a definite bug in SJCL.
Thanks!
Hi All,
I am trying to incorporate Encryption and Decryption using SJCL and Rhino. I was able to sucessfully call encrypt function and encrypt the text. But When i call decrypt function i get following error, any help or hints with this issue would be of great help.
Decrypt Funtion:
exec(var rp = { }; var result = sjcl.decrypt('Siva', {iv : '9VJFbwZs/HhyN81aKrKLZA',salt : 'FVj3L6Omt14' ,ct : 'zi1SfGfSZMY5Rcdx+DOzfiM'}, {}, rp))
result = scope.get("result", scope);
org.mozilla.javascript.EcmaError: TypeError: Cannot find function replace in object [object Object]. (classpath:https://github.com/bitwiseshiftleft/sjcl/raw/version-0.8/sjcl.js#38)
at org.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3785)
at org.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3763)
at org.mozilla.javascript.ScriptRuntime.typeError(ScriptRuntime.java:3791)
at org.mozilla.javascript.ScriptRuntime.typeError2(ScriptRuntime.java:3810)
at org.mozilla.javascript.ScriptRuntime.notFunctionError(ScriptRuntime.java:3881)
at org.mozilla.javascript.ScriptRuntime.getPropFunctionAndThisHelper(ScriptRuntime.java:2360)
at org.mozilla.javascript.ScriptRuntime.getPropFunctionAndThis(ScriptRuntime.java:2327)
at org.mozilla.javascript.Interpreter.interpretLoop(Interpreter.java:1514)
at script(classpath:https://github.com/bitwiseshiftleft/sjcl/raw/version-0.8/sjcl.js:38)
at script(classpath:https://github.com/bitwiseshiftleft/sjcl/raw/version-0.8/sjcl.js:35)
at script(start:1)
at org.mozilla.javascript.Interpreter.interpret(Interpreter.java:854)
at org.mozilla.javascript.InterpretedFunction.call(InterpretedFunction.java:164)
at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:426)
at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3178)
at org.mozilla.javascript.InterpretedFunction.exec(InterpretedFunction.java:175)
at AppTest.exec(AppTest.java:44)
at AppTest.test2(AppTest.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.internal.runners.TestMethodRunner.executeMethodBody(TestMethodRunner.java:99)
at org.junit.internal.runners.TestMethodRunner.runUnprotected(TestMethodRunner.java:81)
at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)
at org.junit.internal.runners.TestMethodRunner.runMethod(TestMethodRunner.java:75)
at org.junit.internal.runners.TestMethodRunner.run(TestMethodRunner.java:45)
at org.junit.internal.runners.TestClassMethodsRunner.invokeTestMethod(TestClassMethodsRunner.java:71)
at org.junit.internal.runners.TestClassMethodsRunner.run(TestClassMethodsRunner.java:35)
at org.junit.internal.runners.TestClassRunner$1.runUnprotected(TestClassRunner.java:42)
at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)
at org.junit.internal.runners.TestClassRunner.run(TestClassRunner.java:52)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Below is the sample code which i used to encrypt and decrypt:
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.Reader;
import java.net.URL;
import org.junit.Test;
import org.mozilla.javascript.*;
import org.mozilla.javascript.tools.shell.Global;
public class AppTest {
public AppTest() {
}
@Test
public void test2() throws Exception {
Global global = new Global();
Context context = createAndInitializeContext( global );
Scriptable scope = context.initStandardObjects( global );
URL url = new URL("https://github.com/bitwiseshiftleft/sjcl/raw/version-0.8/sjcl.js");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
compileAndExec(in, "classpath:" + url.toString(), context, scope);
in.close();
exec("var p = {mode : 'ccm',iv : '9VJFbwZs/HhyN81aKrKLZA',salt : 'FVj3L6Omt14'}; var result = sjcl.encrypt('password', 'data', p, {})", "start", context,scope);
Object result = scope.get("result", scope);
if (result != Scriptable.NOT_FOUND) {
String json = Context.toString(result);
System.out.println(json);
}
exec("var rp = {}; var result = sjcl.decrypt('Siva', {iv : '9VJFbwZs/HhyN81aKrKLZA',salt : 'FVj3L6Omt14' ,ct : 'zi1SfGfSZMY5Rcdx+DOzfiM'}, {}, rp)", "start", context,scope);
//exec("var rp = {}; var result = sjcl.decrypt('password', "+result+" , {}, rp);", "start", context,scope);
result = scope.get("result", scope);
if (result != Scriptable.NOT_FOUND) {
String json = Context.toString(result);
System.out.println(json);
}
}
public static void exec(String script, String name, Context context, Scriptable scope) {
context.compileString(script, name, 1, null).exec(context,scope);
}
public static void compileAndExec(Reader in, String name, Context rhinoContext, Scriptable scope) throws IOException {
rhinoContext.compileReader(in, name, 1, null).exec(rhinoContext,scope);
}
private Context createAndInitializeContext(Global global) {
Context context = ContextFactory.getGlobal().enterContext();
global.init(context);
context.setOptimizationLevel(-1);
context.setLanguageVersion(Context.VERSION_1_5);
return context;
}
}
Thanks and Regards,
Bhargav
If you change parameters, even the password, and click encrypt, nothing happens, no error is given or anything. This is a bit misleading. The only way to change the params is to reload the page, or decrypt (with the same pw etc) and then you can change parameters.
PS it would be very nice if you would create a document with the exact algorithms and encodings you use, I see a lot of questions about recreating them on stackoverflow...
In the sha256.js the IVs become always initialized und do not use constants, in the sha1.js the IVs are constants.
I think in a 'libary' there should be only one way to init the IVs.
Hi i hope this is a good place to ask this question, im looking for a way to decrypt the result of sjcl in ruby.
The makefile references a directory called browser that I think has been moved to browserTest. The "rhino" command is not defined when you install rhino and instead just just call Java. Lint complains about a tab in core/random.js. Below is a patch to fix these issues.
@@ -68,7 +69,7 @@
test: sjcl.js $(TEST_SCRIPTS) test/run_tests_rhino.js
tidy:
find . -name '*~' -delete
diff -Naur orig.sjcl/core/random.js sjcl/core/random.js
--- orig.sjcl/core/random.js 2010-12-26 09:21:25.000000000 -0700
+++ sjcl/core/random.js 2010-12-26 09:18:04.000000000 -0700
@@ -221,7 +221,7 @@
*/
for (j in cbs) {
if (cbs.hasOwnProperty(j) && cbs[j] === cb) {
jsTemp.push(j);
Suppose that an attacker can inject code into your web app. In the current version of SJCL, that attacker can steal the keys to any object he has access to, for example by dumping the aes._key array.
I've talked to a JavaScript security guy, and he thinks that it may be possible to partially defend against this attack. It's tricky work, though, so it would definitely belong in a future revision of SJCL. It's not clear yet just how much code would have to be rewritten to enforce security boundaries on this kind of thing, and defending the whole library is probably nigh on impossible. But it's probably possible to protect the aes._keys array, for example.
Would you be interested in such a feature? Reply to this issue, and we can discuss.
To know the full capability of this library, updated documentation is needed. The documentation on http://crypto.stanford.edu/sjcl/ is 2 years old.
Hi,
I think I've managed to figure out how to produce ECC-Elgamal key pairs by going through the ecc.js and ecc_test.js, but I can't figure out how the shared key is produced for encryption, and I can't find any documentation anywhere to verify that I'm actually working the functions correctly.
Hello,
I am trying to encrypt a PDF file locally in a javascript based mobile app, and I am using sjcl.js directly.
What I do is that I pull out the content in the form of a text string, and encrypt it using the standard AES configuration, example:
function encrypt(plaintext) {
var ciphertextObject = sjcl.encrypt(staticAESKey, plaintext);
return ciphertextObject;
}
function decrypt(ciphertext) {
return sjcl.decrypt(staticAESKey, ciphertext);
}
This works fine in general, for example when comparing the plaintext "hello world", and its corresponding decrypted ciphertext.
PROBLEM EXAMPLE:
Below I try encrypting parts of the PDF content and checking that the decrypt matches the plaintext. This succeeds for some parts of the content, and fails for some other part of the content. For example it succeds on the last 1500 letters substring, but fails on the last 2000 substring, and it also fails on the (length - 2000, length - 1500) substring, so it's not about the length itself.
var pdfContent = some string with length about 11000
var len = pdfContent.length;
var t = pdfContent.substring(len - 2000, len);
var encr = encrypt(t);
if (t == decrypt(encr))
{ //SUCCESS - the decrypted text matches the plaintext }
When PRINTING the results, it seems all OK, it must be a very small difference.
So - should I make some configurations to ensure that encrypting larger strings work? Or is there something else I do wrong?
Any help would be greatly appreciated.
Thanks
PS. I iterated through the content and tested if it worked for substrings of 500, as you can see it only fails in certain spots. it is really weird:
Succeeded with i = 97000
Succeeded with i = 97500
Succeeded with i = 98000
Succeeded with i = 98500
Succeeded with i = 99000
Succeeded with i = 99500
Succeeded with i = 100000
Succeeded with i = 100500
Succeeded with i = 101000
Failed with i = 101500
Succeeded with i = 102000
Succeeded with i = 102500
Succeeded with i = 103000
Succeeded with i = 103500
Succeeded with i = 104000
Succeeded with i = 104500
Succeeded with i = 105000
Failed with i = 105500
Succeeded with i = 106000
Succeeded with i = 106500
Succeeded with i = 107000
Succeeded with i = 107500
Succeeded with i = 108000
Succeeded with i = 108500
Succeeded with i = 109000
Tested with IE Tester 0.4.4 on Win7 Pro. SJCL only runs on IE7.0. All test fails on other IE versions with an invalid character error.
In the tests the file sha256_test_brute_force.js has in line 31 "thiz". Should it be "this" instead of "thiz"?
hash = sjcl.codec.hex.fromBits(cumulative.finalize());
thiz.require(hash === "f305c76d5d457ddf04f1927166f5e13429407049a5c5f29021916321fcdcd8b4");
cb && cb();
It might be good to have a mailing list for discussion. Maybe it would be easy to set up a Google Group?
the sjcl.misc.hmac.encrypt function accepts two parameters: data and encoding.
The encoding parameter is passed to the first pass of the sha254 update function, which only takes a single parameter and so ignores the encoding.
sjcl.misc.hmac.prototype.encrypt = sjcl.misc.hmac.prototype.mac = function (data, encoding) {
var w = new (this._hash)(this._baseHash[0]).update(data, encoding).finalize();
//...
};
update: function (data) {
if (typeof data === "string") {
data = sjcl.codec.utf8String.toBits(data);
}
//...
}
Happy to submit a patch for this if you think you will have time to merge it.
Thanks
Andy
Hi,
First, thanks for making this great library.
I noticed that the built-in JSON encoder serializes object property names without quotes, like this: '{iv: "...", ...}'. I ran into trouble with this when using a JSON decoder on the server-side that expects quotes around property names.
After double-checking the grammar, it looks like property names are strings, which must be quoted (e.g. '{"iv": "...", ...}'). I also checked the JSON grammar in the ECMAScript specification; it requires quoted strings too.
I'm planning to use
sjcl.encrypt("password", "data")
and
sjcl.decypt("password", "data")
As described on the main page and documentation I assume that - "data" means just a cyphertext, and that convenience.js wraps the function so that it would only require a password and cyphertext (without the other fields present in the returned json). Are my assumptions wrong? I'm unable to call this simplified function - it always requires and returns a json string with other fields.
sjcl.hash.sha1
does not seem to be part of the sjcl.js
file in master, even though its in the source and tested.
@@ -193,8 +193,8 @@ sjcl.random = {
if (!this._collectorsStarted) { return; }
if (window.removeEventListener) {
- window.removeEventListener("load", this._loadTimeCollector);
- window.removeEventListener("mousemove", this._mouseCollector);
+ window.removeEventListener("load", this._loadTimeCollector, false);
+ window.removeEventListener("mousemove", this._mouseCollector, false);
} else if (window.detachEvent) {
window.detachEvent("onload", this._loadTimeCollector);
window.detachEvent("onmousemove", this._mouseCollector);
Hi all,
I'm a sjcl lib newbie and i tried to implement your great lib in my own app.
This is my console log when trying to decrypt a cipher text:
info: {"iv":"dF WOrTZuP1jyrG3nQShog","v":1,"iter":1000,"ks":128,"ts":64,"mode":"ccm","adata":"",
"cipher":"aes","salt":"O0kTE3nPq2E","ct":"ZoI8uDoN4oucEXXp2Q"}
error: An exception occurred.
Traceback (most recent call last):
CORRUPT: ccm: tag doesn't match
I don't know how to fix this error. Could you help me please ?
Hi there,
I was just curious about something I was seeing. I have used some other implementations of PBKDF2 in the past and have verified their results match each other. However, when I use your implementation, the result is different than what I was expecting.
If I use sjcl.codec.hex.fromBits(sjcl.misc.pbkdf2('apples', ' ', 1000, 256)), I get the following:
fa58c1f24a8d80874f50ed625116da7f566f445153d1b57d0b82713ce73696ee
However, if I use others I get this:
3e52e1b8d706bffcf7ed58a73dc74924ddbec3994719cd4ec8334d0e2848b588
Can you help me find out what is going wrong, if I'm missing something? I checked through the other issues but didn't see anything similar.
Thanks,
A
Really the one that you download from the link in that sentence is 17k.
I am working on adding support for SRP (see http://srp.stanford.edu, RFC 2945, and RFC 5054). Is this something that you'd accept into SJCL? Is it OK if I just submit an implementation of the client side and not the server side?
We're trying to generate some keys in our app but we keep getting the "slow JS" prompt from IE8.
sjcl.ecc.ecdsa.generateKeys(256,10);
I want to use Base64 to pack public keys, but can't find the way to do it. Both base64 over number.toBits and number.limbs returns gibberish
Is there a convenient way to share sjcl.ecc.elGamal.generateKeys(384, 10).pub across a network? The closest thing I could come to is use JSON.decycle and then stringifying the object, but retrocycling it and reparsing it on the other end does not result in an object that supports .kem. Furthermore, the resulting object is huge, over 10,000 characters.
How am I supposed to share an ECC public key with other people across a network?
I am using the latest version of sjcl and I am signing data using ECDSA and 256-bit curve. I have written my own serialization and deserialization functions and it all checks out in Javascript and verification of deserialized data works. I am trying to separately implement the checking routine in C basing on OpenSSL. Suffice to say, everything initializes and sets up correctly to the point when the verification simply fails, without apparent reason.
I matched the curve using:
EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
I set the point using x,y coordinated from pub._point
EC_POINT_set_affine_coordinates_GFp(group, point, x, y, NULL);
I properly initialize ECDSA_SIG sig;
with x, y and printed numbers in hex using BN_bn2hex
all match up to the numbers printed in Javascript using bn.toString()
. Hashes match as well. The last step is:ECDSA_do_verify(calculatedMessageHash, 32, &sig, key))
, which fails whereas the JS decodedPublic.verify(readHash, signature);
happily passes.
I am out of ideas, should it work at all? It is the same algorithm is it not? I would appreciate any help and I could paste more code or publish whole tests if it helps.
I thank you for any advice you might give.
Hi All,
I am getting following error when i try to invoke encrypt function from java script engine library in java 6.
javax.script.ScriptException: sun.org.mozilla.javascript.internal.JavaScriptException: [object Object](Unknown source>#19) in at line number 19
at com.sun.script.javascript.RhinoScriptEngine.invoke(Unknown Source)
at com.sun.script.javascript.RhinoScriptEngine.invokeFunction(Unknown Source)
at Test.main(Test.java:152)
Source:
public static void main(String[] args){
try {
ScriptEngineManager mgr = new ScriptEngineManager();
List<ScriptEngineFactory> factories = mgr.getEngineFactories();
System.out.println("Available script engines:");
for (int i = 0; i < factories.size(); i++) {
ScriptEngineFactory factory = factories.get(i);
String engine = factory.getEngineName();
String language = factory.getLanguageName();
System.out.println("-------------------------------------------");
System.out.println("Language: " + language);
System.out.println("Engine: " + engine);
System.out.println("-------------------------------------------");
}
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("ECMAScript");
File script_file = new File("C:\\Users\\Bhargav\\Downloads\\sjcl\\sjcl\\sjcl.js");
Reader reader = new FileReader(script_file);
engine.eval(reader);
String script = "function decode(encoded_value){"
+ "var decoded_value = sjcl.decrypt('asdf',encoded_value);"
+ "return decoded_value;}"
+ "function encode(plain_text){"
+ "print(sjcl.encrypt('asdf', 'plain_text'));"
+ "var encoded_value = sjcl.encrypt('asdf', plain_text);"
+ "return encoded_value;}";
engine.eval(script);
Invocable invocableEngine = (Invocable) engine;
String plain_text = "Encrypting Text";
String cypher_text = (String) invocableEngine.invokeFunction("encode", plain_text);
String plain_text_return = (String)invocableEngine.invokeFunction("decode", cypher_text);
System.out.print("plain_text="+plain_text+"\ncypher_text=" +cypher_text + "\nplain_text_return=" + plain_text_return+"\n");
} catch (Exception e) {
e.printStackTrace();
}
}
Any help on this would be much appreciated.
Thanks,
Bhargav
This sample page below get the message on an iOS 3.x ipod touch
Javascript Execution Exceeded Timeout.
It is seems in this environment, that its taking too long to decrypt.
I had assumed the iter parameter is only for the encryption. Is it the case that lower this would make the decryption less time intensive?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<script src="https://github.com/bitwiseshiftleft/sjcl/raw/master/sjcl.js"></script>
<script type="text/javascript">
var password = '71a640009d374130886f4dc754d9659c';
var chapterKeyEncoded = '{iv:"UD4Gs9ueDk/23+cfK3wffA",salt:"49rIgfxNe2k",ct:"+Z/6RgumF9AEhZFJ4Wu3ATwJKtrpf7xtsNG5VrxFYGeHDQEq8zxcUw"}';
var result = sjcl.decrypt(password, chapterKeyEncoded);
alert(result);
</script>
</head>
<body>
</body>
</html>
One question. Is the PKBDF2 implementation of SJCL compatble with .Net's Rfc2898DeriveBytes class?
I'm trying to port implement the equivalent of this C# Code to the SJCL but can't get the javascript implementation to produce matching values:
C# Code:
var Salt2 = "pQ.+!M=+";
var salt = Salt2 + username;
var rfc2898 = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(salt), Rfc2898Iterations);
return Convert.ToBase64String(rfc2898.GetBytes(32));
Javascript Code:
var Salt2 = "pQ.+!M=+";
var username = "foo";
var password = "bar";
var salt = sjcl.codec.utf8String.toBits(Salt2 + username);
var rfc2898 = sjcl.misc.cachedPbkdf2(password, { salt: salt , iter: Rfc2898Iterations });
var passwordHash = sjcl.codec.base64.fromBits(rfc2898.key);
alert(passwordHash );
Unrelated to attackers who can run arbitrary code in the page, there is the issue of attackers who can arrange that you pass malformed data to the encrypt/decrypt commands, for example, data containing fractions, NaNs, undefined's, bitArrays with strange shapes, and so on.
Off the top of my head, I don't know of any attack against SJCL, but it will take a careful audit to make sure there isn't one. I've opened this issue to remind me to perform such an audit. In the mean time, make sure that the data you pass to SJCL has the right type.
Ok, I understand this is not strictly an issue, but still.
Quick skimming of the code does not make it clear.
This http://stackoverflow.com/questions/11135420/elliptic-curve-cryptography-with-sjcl-in-js-and-openssl-in-ruby suggests using justindthomas' branch - is this right?
It is really confusing to have the random pools filled before even starting the collectors. This goes against the basic use of the random object.
js> sjcl.encrypt('key','msg1')
"{"iv":"kmrGkwPuCgWL3O2kSxM2mw","salt":"LAYdXKPN2ME","ct":"jb1ZdwKyVJtpdsjt"}"
js> sjcl.encrypt('key','msg2')
"{"iv":"Lsz7XdhDBTCypE8j025oxw","salt":"LAYdXKPN2ME","ct":"LIW0j871za8OWgSu"}"
A lot of error in the CCM and OCB tests about not matching tags. When disabling the javascript JIT compiler via opera:config#Extensions|EcmaScriptJIT everything works okay. I'll just report it here as a hint, as I think it's their compiler that breaks it (but I'm not sure entirely).
I'm posting this hint to their dev blog as well: http://my.opera.com/desktopteam/blog/
I wrote a proof-of-concept GCM mode support for sjcl, since it only seems to support CCM so far. The code needs a bit cleaning up and some bugs need to be fixed, but would you be interested in merging it to the sjcl release if I finish it up and make a pull request? A sneak peek can be found from https://github.com/juhovh/sjcl repository.
If I'm running prog below at
http://bitwiseshiftleft.github.com/sjcl/demo/
in firebug this gives much larger times for 'ocb2' mode than for 'ccm' mode!
At demo page is stated, that 'ocb2' mode should be faster...
Results of prog below:
["ocb2", 53247, 71147, 1141, 1241]
["ccm", 53247, 71146, 40, 44]
Prog in firebug:
+++
var pt = "Hello World!";
var i;
for (i = 0; i < 12; ++i) {
pt = pt + " " + pt;
}
var mode = 'ocb2'; //or 'ccm'
pt;
var pw = "should be more difficult";
var t1 = +new Date();
var ct = sjcl.encrypt(pw, pt, { "iv":"cVJMG+LQrLnii+ObhawZ4g", ks:256, ts:128, adata:'4712', mode:mode });
var t2 = +new Date();
sjcl.decrypt(pw, ct);
var t3 = +new Date();
var time1 = t2 - t1;
var time2 = t3 - t2;
[ mode, pt.length, ct.length, time1, time2 ]
+++
Would be great :D
"Generator isn't seeded" message is thrown for Firefox 15 (nightly and aurora included) for the ECC_CONV test.
I also tried to add entropy manually and also use the startCollectors(). random.getProgress() shows 1 and random.isReady() gives a result of 2...
I can gather addition information if necessary I'm just unable to track down the core issue.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.