Debian Codegraph @

dojox/sql/_crypto.js

raw symbols SCIP
1 dojo.provide("dojox.sql._crypto");
2 dojo.mixin(dojox.sql._crypto, {
3 // summary:
4 // dojox.sql cryptography code
5 // description:
6 // Taken from http://www.movable-type.co.uk/scripts/aes.html by
7 // Chris Veness (CLA signed); adapted for Dojo and Google Gears Worker Pool
8 // by Brad Neuberg, [email protected]
9
10 // _POOL_SIZE:
11 // Size of worker pool to create to help with crypto
12 _POOL_SIZE: 100,
13
14 encrypt: function(plaintext, password, callback){
15 // summary:
16 // Use Corrected Block TEA to encrypt plaintext using password
17 // (note plaintext & password must be strings not string objects).
18 // Results will be returned to the 'callback' asychronously.
19 this._initWorkerPool();
20
21 var msg ={plaintext: plaintext, password: password};
22 msg = dojo.toJson(msg);
23 msg = "encr:" + String(msg);
24
25 this._assignWork(msg, callback);
26 },
27
28 decrypt: function(ciphertext, password, callback){
29 // summary:
30 // Use Corrected Block TEA to decrypt ciphertext using password
31 // (note ciphertext & password must be strings not string objects).
32 // Results will be returned to the 'callback' asychronously.
33 this._initWorkerPool();
34
35 var msg = {ciphertext: ciphertext, password: password};
36 msg = dojo.toJson(msg);
37 msg = "decr:" + String(msg);
38
39 this._assignWork(msg, callback);
40 },
41
42 _initWorkerPool: function(){
43 // bugs in Google Gears prevents us from dynamically creating
44 // and destroying workers as we need them -- the worker
45 // pool functionality stops working after a number of crypto
46 // cycles (probably related to a memory leak in Google Gears).
47 // this is too bad, since it results in much simpler code.
48
49 // instead, we have to create a pool of workers and reuse them. we
50 // keep a stack of 'unemployed' Worker IDs that are currently not working.
51 // if a work request comes in, we pop off the 'unemployed' stack
52 // and put them to work, storing them in an 'employed' hashtable,
53 // keyed by their Worker ID with the value being the callback function
54 // that wants the result. when an employed worker is done, we get
55 // a message in our 'manager' which adds this worker back to the
56 // unemployed stack and routes the result to the callback that
57 // wanted it. if all the workers were employed in the past but
58 // more work needed to be done (i.e. it's a tight labor pool ;)
59 // then the work messages are pushed onto
60 // a 'handleMessage' queue as an object tuple{msg: msg, callback: callback}
61
62 if(!this._manager){
63 try{
64 this._manager = google.gears.factory.create("beta.workerpool", "1.0");
65 this._unemployed = [];
66 this._employed ={};
67 this._handleMessage = [];
68
69 var self = this;
70 this._manager.onmessage = function(msg, sender){
71 // get the callback necessary to serve this result
72 var callback = self._employed["_" + sender];
73
74 // make this worker unemployed
75 self._employed["_" + sender] = undefined;
76 self._unemployed.push("_" + sender);
77
78 // see if we need to assign new work
79 // that was queued up needing to be done
80 if(self._handleMessage.length){
81 var handleMe = self._handleMessage.shift();
82 self._assignWork(handleMe.msg, handleMe.callback);
83 }
84
85 // return results
86 callback(msg);
87 };
88
89 var workerInit = "function _workerInit(){"
90 + "gearsWorkerPool.onmessage = "
91 + String(this._workerHandler)
92 + ";"
93 + "}";
94
95 var code = workerInit + " _workerInit();";
96
97 // create our worker pool
98 for(var i = 0; i < this._POOL_SIZE; i++){
99 this._unemployed.push("_" + this._manager.createWorker(code));
100 }
101 }catch(exp){
102 throw exp.message||exp;
103 }
104 }
105 },
106
107 _assignWork: function(msg, callback){
108 // can we immediately assign this work?
109 if(!this._handleMessage.length && this._unemployed.length){
110 // get an unemployed worker
111 var workerID = this._unemployed.shift().substring(1); // remove _
112
113 // list this worker as employed
114 this._employed["_" + workerID] = callback;
115
116 // do the worke
117 this._manager.sendMessage(msg, parseInt(workerID,10));
118 }else{
119 // we have to queue it up
120 this._handleMessage ={msg: msg, callback: callback};
121 }
122 },
123
124 _workerHandler: function(msg, sender){
125
126 /* Begin AES Implementation */
127
128 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
129
130 // Sbox is pre-computed multiplicative inverse in GF(2^8) used in SubBytes and KeyExpansion [§5.1.1]
131 var Sbox = [0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
132 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
133 0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
134 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
135 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
136 0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
137 0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
138 0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
139 0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
140 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
141 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
142 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
143 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
144 0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
145 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
146 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16];
147
148 // Rcon is Round Constant used for the Key Expansion [1st col is 2^(r-1) in GF(2^8)] [§5.2]
149 var Rcon = [ [0x00, 0x00, 0x00, 0x00],
150 [0x01, 0x00, 0x00, 0x00],
151 [0x02, 0x00, 0x00, 0x00],
152 [0x04, 0x00, 0x00, 0x00],
153 [0x08, 0x00, 0x00, 0x00],
154 [0x10, 0x00, 0x00, 0x00],
155 [0x20, 0x00, 0x00, 0x00],
156 [0x40, 0x00, 0x00, 0x00],
157 [0x80, 0x00, 0x00, 0x00],
158 [0x1b, 0x00, 0x00, 0x00],
159 [0x36, 0x00, 0x00, 0x00] ];
160
161 /*
162 * AES Cipher function: encrypt 'input' with Rijndael algorithm
163 *
164 * takes byte-array 'input' (16 bytes)
165 * 2D byte-array key schedule 'w' (Nr+1 x Nb bytes)
166 *
167 * applies Nr rounds (10/12/14) using key schedule w for 'add round key' stage
168 *
169 * returns byte-array encrypted value (16 bytes)
170 */
171 function Cipher(input, w) { // main Cipher function [§5.1]
172 var Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES)
173 var Nr = w.length/Nb - 1; // no of rounds: 10/12/14 for 128/192/256-bit keys
174
175 var state = [[],[],[],[]]; // initialise 4xNb byte-array 'state' with input [§3.4]
176 for (var i=0; i<4*Nb; i++) state[i%4][Math.floor(i/4)] = input[i];
177
178 state = AddRoundKey(state, w, 0, Nb);
179
180 for (var round=1; round<Nr; round++) {
181 state = SubBytes(state, Nb);
182 state = ShiftRows(state, Nb);
183 state = MixColumns(state, Nb);
184 state = AddRoundKey(state, w, round, Nb);
185 }
186
187 state = SubBytes(state, Nb);
188 state = ShiftRows(state, Nb);
189 state = AddRoundKey(state, w, Nr, Nb);
190
191 var output = new Array(4*Nb); // convert state to 1-d array before returning [§3.4]
192 for (var i=0; i<4*Nb; i++) output[i] = state[i%4][Math.floor(i/4)];
193 return output;
194 }
195
196
197 function SubBytes(s, Nb) { // apply SBox to state S [§5.1.1]
198 for (var r=0; r<4; r++) {
199 for (var c=0; c<Nb; c++) s[r][c] = Sbox[s[r][c]];
200 }
201 return s;
202 }
203
204
205 function ShiftRows(s, Nb) { // shift row r of state S left by r bytes [§5.1.2]
206 var t = new Array(4);
207 for (var r=1; r<4; r++) {
208 for (var c=0; c<4; c++) t[c] = s[r][(c+r)%Nb]; // shift into temp copy
209 for (var c=0; c<4; c++) s[r][c] = t[c]; // and copy back
210 } // note that this will work for Nb=4,5,6, but not 7,8 (always 4 for AES):
211 return s; // see fp.gladman.plus.com/cryptography_technology/rijndael/aes.spec.311.pdf
212 }
213
214
215 function MixColumns(s, Nb) { // combine bytes of each col of state S [§5.1.3]
216 for (var c=0; c<4; c++) {
217 var a = new Array(4); // 'a' is a copy of the current column from 's'
218 var b = new Array(4); // 'b' is a•{02} in GF(2^8)
219 for (var i=0; i<4; i++) {
220 a[i] = s[i][c];
221 b[i] = s[i][c]&0x80 ? s[i][c]<<1 ^ 0x011b : s[i][c]<<1;
222 }
223 // a[n] ^ b[n] is a•{03} in GF(2^8)
224 s[0][c] = b[0] ^ a[1] ^ b[1] ^ a[2] ^ a[3]; // 2*a0 + 3*a1 + a2 + a3
225 s[1][c] = a[0] ^ b[1] ^ a[2] ^ b[2] ^ a[3]; // a0 * 2*a1 + 3*a2 + a3
226 s[2][c] = a[0] ^ a[1] ^ b[2] ^ a[3] ^ b[3]; // a0 + a1 + 2*a2 + 3*a3
227 s[3][c] = a[0] ^ b[0] ^ a[1] ^ a[2] ^ b[3]; // 3*a0 + a1 + a2 + 2*a3
228 }
229 return s;
230 }
231
232
233 function AddRoundKey(state, w, rnd, Nb) { // xor Round Key into state S [§5.1.4]
234 for (var r=0; r<4; r++) {
235 for (var c=0; c<Nb; c++) state[r][c] ^= w[rnd*4+c][r];
236 }
237 return state;
238 }
239
240
241 function KeyExpansion(key) { // generate Key Schedule (byte-array Nr+1 x Nb) from Key [§5.2]
242 var Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES)
243 var Nk = key.length/4 // key length (in words): 4/6/8 for 128/192/256-bit keys
244 var Nr = Nk + 6; // no of rounds: 10/12/14 for 128/192/256-bit keys
245
246 var w = new Array(Nb*(Nr+1));
247 var temp = new Array(4);
248
249 for (var i=0; i<Nk; i++) {
250 var r = [key[4*i], key[4*i+1], key[4*i+2], key[4*i+3]];
251 w[i] = r;
252 }
253
254 for (var i=Nk; i<(Nb*(Nr+1)); i++) {
255 w[i] = new Array(4);
256 for (var t=0; t<4; t++) temp[t] = w[i-1][t];
257 if (i % Nk == 0) {
258 temp = SubWord(RotWord(temp));
259 for (var t=0; t<4; t++) temp[t] ^= Rcon[i/Nk][t];
260 } else if (Nk > 6 && i%Nk == 4) {
261 temp = SubWord(temp);
262 }
263 for (var t=0; t<4; t++) w[i][t] = w[i-Nk][t] ^ temp[t];
264 }
265
266 return w;
267 }
268
269 function SubWord(w) { // apply SBox to 4-byte word w
270 for (var i=0; i<4; i++) w[i] = Sbox[w[i]];
271 return w;
272 }
273
274 function RotWord(w) { // rotate 4-byte word w left by one byte
275 w[4] = w[0];
276 for (var i=0; i<4; i++) w[i] = w[i+1];
277 return w;
278 }
279
280 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
281
282 /*
283 * Use AES to encrypt 'plaintext' with 'password' using 'nBits' key, in 'Counter' mode of operation
284 * - see http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
285 * for each block
286 * - outputblock = cipher(counter, key)
287 * - cipherblock = plaintext xor outputblock
288 */
289 function AESEncryptCtr(plaintext, password, nBits) {
290 if (!(nBits==128 || nBits==192 || nBits==256)) return ''; // standard allows 128/192/256 bit keys
291
292 // for this example script, generate the key by applying Cipher to 1st 16/24/32 chars of password;
293 // for real-world applications, a more secure approach would be to hash the password e.g. with SHA-1
294 var nBytes = nBits/8; // no bytes in key
295 var pwBytes = new Array(nBytes);
296 for (var i=0; i<nBytes; i++) pwBytes[i] = password.charCodeAt(i) & 0xff;
297
298 var key = Cipher(pwBytes, KeyExpansion(pwBytes));
299
300 key = key.concat(key.slice(0, nBytes-16)); // key is now 16/24/32 bytes long
301
302 // initialise counter block (NIST SP800-38A §B.2): millisecond time-stamp for nonce in 1st 8 bytes,
303 // block counter in 2nd 8 bytes
304 var blockSize = 16; // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
305 var counterBlock = new Array(blockSize); // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
306 var nonce = (new Date()).getTime(); // milliseconds since 1-Jan-1970
307
308 // encode nonce in two stages to cater for JavaScript 32-bit limit on bitwise ops
309 for (var i=0; i<4; i++) counterBlock[i] = (nonce >>> i*8) & 0xff;
310 for (var i=0; i<4; i++) counterBlock[i+4] = (nonce/0x100000000 >>> i*8) & 0xff;
311
312 // generate key schedule - an expansion of the key into distinct Key Rounds for each round
313 var keySchedule = KeyExpansion(key);
314
315 var blockCount = Math.ceil(plaintext.length/blockSize);
316 var ciphertext = new Array(blockCount); // ciphertext as array of strings
317
318 for (var b=0; b<blockCount; b++) {
319 // set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
320 // again done in two stages for 32-bit ops
321 for (var c=0; c<4; c++) counterBlock[15-c] = (b >>> c*8) & 0xff;
322 for (var c=0; c<4; c++) counterBlock[15-c-4] = (b/0x100000000 >>> c*8)
323
324 var cipherCntr = Cipher(counterBlock, keySchedule); // -- encrypt counter block --
325
326 // calculate length of final block:
327 var blockLength = b<blockCount-1 ? blockSize : (plaintext.length-1)%blockSize+1;
328
329 var ct = '';
330 for (var i=0; i<blockLength; i++) { // -- xor plaintext with ciphered counter byte-by-byte --
331 var plaintextByte = plaintext.charCodeAt(b*blockSize+i);
332 var cipherByte = plaintextByte ^ cipherCntr[i];
333 ct += String.fromCharCode(cipherByte);
334 }
335 // ct is now ciphertext for this block
336
337 ciphertext[b] = escCtrlChars(ct); // escape troublesome characters in ciphertext
338 }
339
340 // convert the nonce to a string to go on the front of the ciphertext
341 var ctrTxt = '';
342 for (var i=0; i<8; i++) ctrTxt += String.fromCharCode(counterBlock[i]);
343 ctrTxt = escCtrlChars(ctrTxt);
344
345 // use '-' to separate blocks, use Array.join to concatenate arrays of strings for efficiency
346 return ctrTxt + '-' + ciphertext.join('-');
347 }
348
349
350 /*
351 * Use AES to decrypt 'ciphertext' with 'password' using 'nBits' key, in Counter mode of operation
352 *
353 * for each block
354 * - outputblock = cipher(counter, key)
355 * - cipherblock = plaintext xor outputblock
356 */
357 function AESDecryptCtr(ciphertext, password, nBits) {
358 if (!(nBits==128 || nBits==192 || nBits==256)) return ''; // standard allows 128/192/256 bit keys
359
360 var nBytes = nBits/8; // no bytes in key
361 var pwBytes = new Array(nBytes);
362 for (var i=0; i<nBytes; i++) pwBytes[i] = password.charCodeAt(i) & 0xff;
363 var pwKeySchedule = KeyExpansion(pwBytes);
364 var key = Cipher(pwBytes, pwKeySchedule);
365 key = key.concat(key.slice(0, nBytes-16)); // key is now 16/24/32 bytes long
366
367 var keySchedule = KeyExpansion(key);
368
369 ciphertext = ciphertext.split('-'); // split ciphertext into array of block-length strings
370
371 // recover nonce from 1st element of ciphertext
372 var blockSize = 16; // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
373 var counterBlock = new Array(blockSize);
374 var ctrTxt = unescCtrlChars(ciphertext[0]);
375 for (var i=0; i<8; i++) counterBlock[i] = ctrTxt.charCodeAt(i);
376
377 var plaintext = new Array(ciphertext.length-1);
378
379 for (var b=1; b<ciphertext.length; b++) {
380 // set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
381 for (var c=0; c<4; c++) counterBlock[15-c] = ((b-1) >>> c*8) & 0xff;
382 for (var c=0; c<4; c++) counterBlock[15-c-4] = ((b/0x100000000-1) >>> c*8) & 0xff;
383
384 var cipherCntr = Cipher(counterBlock, keySchedule); // encrypt counter block
385
386 ciphertext[b] = unescCtrlChars(ciphertext[b]);
387
388 var pt = '';
389 for (var i=0; i<ciphertext[b].length; i++) {
390 // -- xor plaintext with ciphered counter byte-by-byte --
391 var ciphertextByte = ciphertext[b].charCodeAt(i);
392 var plaintextByte = ciphertextByte ^ cipherCntr[i];
393 pt += String.fromCharCode(plaintextByte);
394 }
395 // pt is now plaintext for this block
396
397 plaintext[b-1] = pt; // b-1 'cos no initial nonce block in plaintext
398 }
399
400 return plaintext.join('');
401 }
402
403 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
404
405 function escCtrlChars(str) { // escape control chars which might cause problems handling ciphertext
406 return str.replace(/[\0\t\n\v\f\r\xa0!-]/g, function(c) { return '!' + c.charCodeAt(0) + '!'; });
407 } // \xa0 to cater for bug in Firefox; include '-' to leave it free for use as a block marker
408
409 function unescCtrlChars(str) { // unescape potentially problematic control characters
410 return str.replace(/!\d\d?\d?!/g, function(c) { return String.fromCharCode(c.slice(1,-1)); });
411 }
412
413 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
414
415 function encrypt(plaintext, password){
416 return AESEncryptCtr(plaintext, password, 256);
417 }
418
419 function decrypt(ciphertext, password){
420 return AESDecryptCtr(ciphertext, password, 256);
421 }
422
423 /* End AES Implementation */
424
425 var cmd = msg.substr(0,4);
426 var arg = msg.substr(5);
427 if(cmd == "encr"){
428 arg = eval("(" + arg + ")");
429 var plaintext = arg.plaintext;
430 var password = arg.password;
431 var results = encrypt(plaintext, password);
432 gearsWorkerPool.sendMessage(String(results), sender);
433 }else if(cmd == "decr"){
434 arg = eval("(" + arg + ")");
435 var ciphertext = arg.ciphertext;
436 var password = arg.password;
437 var results = decrypt(ciphertext, password);
438 gearsWorkerPool.sendMessage(String(results), sender);
439 }
440 }
441 });