Giter Club home page Giter Club logo

sjcl's People

Contributors

alex-slesarev avatar bitwiseshiftleft avatar bren2010 avatar catatonicprime avatar evilaliv3 avatar federicobond avatar fluidblue avatar fromkeith avatar fruiz500 avatar ggozad avatar gyf304 avatar iwanvdschoor avatar jmkf avatar justmoon avatar miha-stopar avatar moderndegree avatar nilos avatar nstarke avatar ph4r05 avatar robyoder avatar sc00bz avatar simbo1905 avatar sqs avatar stbuehler avatar tanx avatar vayu avatar vibornoff avatar vincentbernat avatar wizzard0 avatar ycuv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sjcl's Issues

Few little issues with makefile

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 @@

bytecode limit.

test: sjcl.js $(TEST_SCRIPTS) test/run_tests_rhino.js

  • @rhino -O -1 -w test/run_tests_rhino.js $< $(TEST_SCRIPTS)
  • @$(RHINO) -O -1 -w test/run_tests_rhino.js $< $(TEST_SCRIPTS)

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) {
  •    if (cbs.hasOwnProperty(j) && cbs[j] === cb) {
     jsTemp.push(j);
    
    }
    }

ECC_Conv test fails in FireFox

"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.

Execution Exceeded Timeout - iOS

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>

Documentation for ECC?

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.

Error on `sjcl.random.stopCollectors()`

@@ -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);

ECDSA signature verification using OpenSSL

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.

Protecting against an attacker who can inject code

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.

Sharing ECC public keys across network

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?

sha256 - iv's are not constants

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.

default salt value is a function of the encryption key

js> sjcl.encrypt('key','msg1')
"{"iv":"kmrGkwPuCgWL3O2kSxM2mw","salt":"LAYdXKPN2ME","ct":"jb1ZdwKyVJtpdsjt"}"
js> sjcl.encrypt('key','msg2')
"{"iv":"Lsz7XdhDBTCypE8j025oxw","salt":"LAYdXKPN2ME","ct":"LIW0j871za8OWgSu"}"

Demo page does not allow to change params

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...

Inconsistant results in PBKDF2

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

Bug in random.js

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.

Issue while invoking SJSL encrypt using JAVA Script Engine library in JAVA6

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

sjcl in Rhino

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?

sjcl.misc.hmac encrypt function ignoring parameter encoding

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

JSON object encoding

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.

Protecting against attackers who pass malformed data

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.

thiz.require in sha256_test_brute_force.js

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();

Add SRP support

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?

sjcl.decrypt doesn't seem behave like documented

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.

Derived Works

I would love to see a list of apps that use this library. I can share mine, if you're interested.

master does not contain sha1

sjcl.hash.sha1 does not seem to be part of the sjcl.js file in master, even though its in the source and tested.

ocb2 mode slower than ccm mode

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 ]
+++

Support for Galois/Counter mode (GCM)

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.

Base64 for BigNumbers

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

ccm: tag doesn't match

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 ?

palm webOS and sjcl browser tests

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.

sjcl.bn.sub() does not calculate correctly for certain arguments

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!

random.js (re)seeding patches

Hello

I found some small to medium issues in the (re)seeding code.

  1. when "addEntropy"ing a number it never gets added to the hash, but counted if "estimatedEntropy" is set
  2. when "_reseedCount" starts at zero, the first two reseeds from the pools only use the first pool
  3. and I didn't really get, how the pool-adding logic was designed. If "_reseedCount" starts at zero, a second pool is added after the first pool has been used for the third time! It was my understanding, that one would want to add a second pool after the first one was used for the first time and the thrid one after the second is used for the first time (at the second reseed) and so on.
    Plus I added a check, that not more than 32 pools will be created (even if this case is unlikely to occur in Javascript).
--- 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

Error in closure compress causes errors in sjcl.js

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.

Porting Help

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 );

AES encryption problem for large string

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

Issue with SJCL decrypt function while invoking it through Rhino

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.