1 /* rijndael.js Rijndael Reference Implementation
\r
3 This is a modified version of the software described below,
\r
4 produced in September 2003 by John Walker for use in the
\r
5 JavsScrypt browser-based encryption package. The principal
\r
6 changes are replacing the original getRandomBytes function with
\r
7 one which calls our pseudorandom generator (which must
\r
8 be instantiated and seeded before the first call on getRandomBytes),
\r
9 and changing keySizeInBits to 256. Some code not required by the
\r
10 JavsScrypt application has been commented out. Please see
\r
11 http://www.fourmilab.ch/javascrypt/ for further information on
\r
14 The following is the original copyright and application
\r
17 Copyright (c) 2001 Fritz Schneider
\r
19 This software is provided as-is, without express or implied warranty.
\r
20 Permission to use, copy, modify, distribute or sell this software, with or
\r
21 without fee, for any purpose and by any individual or organization, is hereby
\r
22 granted, provided that the above copyright notice and this paragraph appear
\r
23 in all copies. Distribution as a part of an application or binary must
\r
24 include the above copyright notice in the documentation and/or other materials
\r
25 provided with the application or distribution.
\r
27 As the above disclaimer notes, you are free to use this code however you
\r
28 want. However, I would request that you send me an email
\r
29 (fritz /at/ cs /dot/ ucsd /dot/ edu) to say hi if you find this code useful
\r
30 or instructional. Seeing that people are using the code acts as
\r
31 encouragement for me to continue development. If you *really* want to thank
\r
32 me you can buy the book I wrote with Thomas Powell, _JavaScript:
\r
33 _The_Complete_Reference_ :)
\r
35 This code is an UNOPTIMIZED REFERENCE implementation of Rijndael.
\r
36 If there is sufficient interest I can write an optimized (word-based,
\r
37 table-driven) version, although you might want to consider using a
\r
38 compiled language if speed is critical to your application. As it stands,
\r
39 one run of the monte carlo test (10,000 encryptions) can take up to
\r
40 several minutes, depending upon your processor. You shouldn't expect more
\r
41 than a few kilobytes per second in throughput.
\r
43 Also note that there is very little error checking in these functions.
\r
44 Doing proper error checking is always a good idea, but the ideal
\r
45 implementation (using the instanceof operator and exceptions) requires
\r
46 IE5+/NS6+, and I've chosen to implement this code so that it is compatible
\r
49 And finally, because JavaScript doesn't have an explicit byte/char data
\r
50 type (although JavaScript 2.0 most likely will), when I refer to "byte"
\r
51 in this code I generally mean "32 bit integer with value in the interval
\r
52 [0,255]" which I treat as a byte.
\r
54 See http://www-cse.ucsd.edu/~fritz/rijndael.html for more documentation
\r
55 of the (very simple) API provided by this code.
\r
58 fritz at cs.ucsd.edu
\r
63 // Rijndael parameters -- Valid values are 128, 192, or 256
\r
65 var keySizeInBits = 256;
\r
66 var blockSizeInBits = 128;
\r
69 // Note: in the following code the two dimensional arrays are indexed as
\r
70 // you would probably expect, as array[row][column]. The state arrays
\r
71 // are 2d arrays of the form state[4][Nb].
\r
74 // The number of rounds for the cipher, indexed by [Nk][Nb]
\r
75 var roundsArray = [ ,,,,[,,,,10,, 12,, 14],,
\r
76 [,,,,12,, 12,, 14],,
\r
77 [,,,,14,, 14,, 14] ];
\r
79 // The number of bytes to shift by in shiftRow, indexed by [Nb][row]
\r
80 var shiftOffsets = [ ,,,,[,1, 2, 3],,[,1, 2, 3],,[,1, 3, 4] ];
\r
82 // The round constants used in subkey expansion
\r
84 0x01, 0x02, 0x04, 0x08, 0x10, 0x20,
\r
85 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8,
\r
86 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc,
\r
87 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4,
\r
88 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 ];
\r
90 // Precomputed lookup table for the SBox
\r
92 99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171,
\r
93 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164,
\r
94 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113,
\r
95 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226,
\r
96 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214,
\r
97 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203,
\r
98 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69,
\r
99 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245,
\r
100 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68,
\r
101 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42,
\r
102 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73,
\r
103 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109,
\r
104 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37,
\r
105 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62,
\r
106 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225,
\r
107 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223,
\r
108 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187,
\r
111 // Precomputed lookup table for the inverse SBox
\r
112 var SBoxInverse = [
\r
113 82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215,
\r
114 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222,
\r
115 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66,
\r
116 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73,
\r
117 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92,
\r
118 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21,
\r
119 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247,
\r
120 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2,
\r
121 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220,
\r
122 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173,
\r
123 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29,
\r
124 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75,
\r
125 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168,
\r
126 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81,
\r
127 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160,
\r
128 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97,
\r
129 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12,
\r
132 // This method circularly shifts the array left by the number of elements
\r
133 // given in its parameter. It returns the resulting array and is used for
\r
134 // the ShiftRow step. Note that shift() and push() could be used for a more
\r
135 // elegant solution, but they require IE5.5+, so I chose to do it manually.
\r
137 function cyclicShiftLeft(theArray, positions) {
\r
138 var temp = theArray.slice(0, positions);
\r
139 theArray = theArray.slice(positions).concat(temp);
\r
143 // Cipher parameters ... do not change these
\r
144 var Nk = keySizeInBits / 32;
\r
145 var Nb = blockSizeInBits / 32;
\r
146 var Nr = roundsArray[Nk][Nb];
\r
148 // Multiplies the element "poly" of GF(2^8) by x. See the Rijndael spec.
\r
150 function xtime(poly) {
\r
152 return ((poly & 0x100) ? (poly ^ 0x11B) : (poly));
\r
155 // Multiplies the two elements of GF(2^8) together and returns the result.
\r
156 // See the Rijndael spec, but should be straightforward: for each power of
\r
157 // the indeterminant that has a 1 coefficient in x, add y times that power
\r
158 // to the result. x and y should be bytes representing elements of GF(2^8)
\r
160 function mult_GF256(x, y) {
\r
161 var bit, result = 0;
\r
163 for (bit = 1; bit < 256; bit *= 2, y = xtime(y)) {
\r
170 // Performs the substitution step of the cipher. State is the 2d array of
\r
171 // state information (see spec) and direction is string indicating whether
\r
172 // we are performing the forward substitution ("encrypt") or inverse
\r
173 // substitution (anything else)
\r
175 function byteSub(state, direction) {
\r
177 if (direction == "encrypt") // Point S to the SBox we're using
\r
181 for (var i = 0; i < 4; i++) // Substitute for every byte in state
\r
182 for (var j = 0; j < Nb; j++)
\r
183 state[i][j] = S[state[i][j]];
\r
186 // Performs the row shifting step of the cipher.
\r
188 function shiftRow(state, direction) {
\r
189 for (var i=1; i<4; i++) // Row 0 never shifts
\r
190 if (direction == "encrypt")
\r
191 state[i] = cyclicShiftLeft(state[i], shiftOffsets[Nb][i]);
\r
193 state[i] = cyclicShiftLeft(state[i], Nb - shiftOffsets[Nb][i]);
\r
197 // Performs the column mixing step of the cipher. Most of these steps can
\r
198 // be combined into table lookups on 32bit values (at least for encryption)
\r
199 // to greatly increase the speed.
\r
201 function mixColumn(state, direction) {
\r
202 var b = []; // Result of matrix multiplications
\r
203 for (var j = 0; j < Nb; j++) { // Go through each column...
\r
204 for (var i = 0; i < 4; i++) { // and for each row in the column...
\r
205 if (direction == "encrypt")
\r
206 b[i] = mult_GF256(state[i][j], 2) ^ // perform mixing
\r
207 mult_GF256(state[(i+1)%4][j], 3) ^
\r
208 state[(i+2)%4][j] ^
\r
211 b[i] = mult_GF256(state[i][j], 0xE) ^
\r
212 mult_GF256(state[(i+1)%4][j], 0xB) ^
\r
213 mult_GF256(state[(i+2)%4][j], 0xD) ^
\r
214 mult_GF256(state[(i+3)%4][j], 9);
\r
216 for (var i = 0; i < 4; i++) // Place result back into column
\r
217 state[i][j] = b[i];
\r
221 // Adds the current round key to the state information. Straightforward.
\r
223 function addRoundKey(state, roundKey) {
\r
224 for (var j = 0; j < Nb; j++) { // Step through columns...
\r
225 state[0][j] ^= (roundKey[j] & 0xFF); // and XOR
\r
226 state[1][j] ^= ((roundKey[j]>>8) & 0xFF);
\r
227 state[2][j] ^= ((roundKey[j]>>16) & 0xFF);
\r
228 state[3][j] ^= ((roundKey[j]>>24) & 0xFF);
\r
232 // This function creates the expanded key from the input (128/192/256-bit)
\r
233 // key. The parameter key is an array of bytes holding the value of the key.
\r
234 // The returned value is an array whose elements are the 32-bit words that
\r
235 // make up the expanded key.
\r
237 function keyExpansion(key) {
\r
238 var expandedKey = new Array();
\r
241 // in case the key size or parameters were changed...
\r
242 Nk = keySizeInBits / 32;
\r
243 Nb = blockSizeInBits / 32;
\r
244 Nr = roundsArray[Nk][Nb];
\r
246 for (var j=0; j < Nk; j++) // Fill in input key first
\r
248 (key[4*j]) | (key[4*j+1]<<8) | (key[4*j+2]<<16) | (key[4*j+3]<<24);
\r
250 // Now walk down the rest of the array filling in expanded key bytes as
\r
251 // per Rijndael's spec
\r
252 for (j = Nk; j < Nb * (Nr + 1); j++) { // For each word of expanded key
\r
253 temp = expandedKey[j - 1];
\r
255 temp = ( (SBox[(temp>>8) & 0xFF]) |
\r
256 (SBox[(temp>>16) & 0xFF]<<8) |
\r
257 (SBox[(temp>>24) & 0xFF]<<16) |
\r
258 (SBox[temp & 0xFF]<<24) ) ^ Rcon[Math.floor(j / Nk) - 1];
\r
259 else if (Nk > 6 && j % Nk == 4)
\r
260 temp = (SBox[(temp>>24) & 0xFF]<<24) |
\r
261 (SBox[(temp>>16) & 0xFF]<<16) |
\r
262 (SBox[(temp>>8) & 0xFF]<<8) |
\r
263 (SBox[temp & 0xFF]);
\r
264 expandedKey[j] = expandedKey[j-Nk] ^ temp;
\r
266 return expandedKey;
\r
269 // Rijndael's round functions...
\r
271 function Round(state, roundKey) {
\r
272 byteSub(state, "encrypt");
\r
273 shiftRow(state, "encrypt");
\r
274 mixColumn(state, "encrypt");
\r
275 addRoundKey(state, roundKey);
\r
278 function InverseRound(state, roundKey) {
\r
279 addRoundKey(state, roundKey);
\r
280 mixColumn(state, "decrypt");
\r
281 shiftRow(state, "decrypt");
\r
282 byteSub(state, "decrypt");
\r
285 function FinalRound(state, roundKey) {
\r
286 byteSub(state, "encrypt");
\r
287 shiftRow(state, "encrypt");
\r
288 addRoundKey(state, roundKey);
\r
291 function InverseFinalRound(state, roundKey){
\r
292 addRoundKey(state, roundKey);
\r
293 shiftRow(state, "decrypt");
\r
294 byteSub(state, "decrypt");
\r
297 // encrypt is the basic encryption function. It takes parameters
\r
298 // block, an array of bytes representing a plaintext block, and expandedKey,
\r
299 // an array of words representing the expanded key previously returned by
\r
300 // keyExpansion(). The ciphertext block is returned as an array of bytes.
\r
302 function encrypt(block, expandedKey) {
\r
304 if (!block || block.length*8 != blockSizeInBits)
\r
309 block = packBytes(block);
\r
310 addRoundKey(block, expandedKey);
\r
311 for (i=1; i<Nr; i++)
\r
312 Round(block, expandedKey.slice(Nb*i, Nb*(i+1)));
\r
313 FinalRound(block, expandedKey.slice(Nb*Nr));
\r
314 return unpackBytes(block);
\r
317 // decrypt is the basic decryption function. It takes parameters
\r
318 // block, an array of bytes representing a ciphertext block, and expandedKey,
\r
319 // an array of words representing the expanded key previously returned by
\r
320 // keyExpansion(). The decrypted block is returned as an array of bytes.
\r
322 function decrypt(block, expandedKey) {
\r
324 if (!block || block.length*8 != blockSizeInBits)
\r
329 block = packBytes(block);
\r
330 InverseFinalRound(block, expandedKey.slice(Nb*Nr));
\r
331 for (i = Nr - 1; i>0; i--)
\r
332 InverseRound(block, expandedKey.slice(Nb*i, Nb*(i+1)));
\r
333 addRoundKey(block, expandedKey);
\r
334 return unpackBytes(block);
\r
338 // This method takes a byte array (byteArray) and converts it to a string by
\r
339 // applying String.fromCharCode() to each value and concatenating the result.
\r
340 // The resulting string is returned. Note that this function SKIPS zero bytes
\r
341 // under the assumption that they are padding added in formatPlaintext().
\r
342 // Obviously, do not invoke this method on raw data that can contain zero
\r
343 // bytes. It is really only appropriate for printable ASCII/Latin-1
\r
344 // values. Roll your own function for more robust functionality :)
\r
346 function byteArrayToString(byteArray) {
\r
348 for(var i=0; i<byteArray.length; i++)
\r
349 if (byteArray[i] != 0)
\r
350 result += String.fromCharCode(byteArray[i]);
\r
355 // This function takes an array of bytes (byteArray) and converts them
\r
356 // to a hexadecimal string. Array element 0 is found at the beginning of
\r
357 // the resulting string, high nibble first. Consecutive elements follow
\r
358 // similarly, for example [16, 255] --> "10ff". The function returns a
\r
361 function byteArrayToHex(byteArray) {
\r
365 for (var i=0; i<byteArray.length; i++)
\r
366 result += ((byteArray[i]<16) ? "0" : "") + byteArray[i].toString(16);
\r
371 // This function converts a string containing hexadecimal digits to an
\r
372 // array of bytes. The resulting byte array is filled in the order the
\r
373 // values occur in the string, for example "10FF" --> [16, 255]. This
\r
374 // function returns an array.
\r
376 function hexToByteArray(hexString) {
\r
377 var byteArray = [];
\r
378 if (hexString.length % 2) // must have even length
\r
380 if (hexString.indexOf("0x") == 0 || hexString.indexOf("0X") == 0)
\r
381 hexString = hexString.substring(2);
\r
382 for (var i = 0; i<hexString.length; i += 2)
\r
383 byteArray[Math.floor(i/2)] = parseInt(hexString.slice(i, i+2), 16);
\r
387 // This function packs an array of bytes into the four row form defined by
\r
388 // Rijndael. It assumes the length of the array of bytes is divisible by
\r
389 // four. Bytes are filled in according to the Rijndael spec (starting with
\r
390 // column 0, row 0 to 3). This function returns a 2d array.
\r
392 function packBytes(octets) {
\r
393 var state = new Array();
\r
394 if (!octets || octets.length % 4)
\r
397 state[0] = new Array(); state[1] = new Array();
\r
398 state[2] = new Array(); state[3] = new Array();
\r
399 for (var j=0; j<octets.length; j+= 4) {
\r
400 state[0][j/4] = octets[j];
\r
401 state[1][j/4] = octets[j+1];
\r
402 state[2][j/4] = octets[j+2];
\r
403 state[3][j/4] = octets[j+3];
\r
408 // This function unpacks an array of bytes from the four row format preferred
\r
409 // by Rijndael into a single 1d array of bytes. It assumes the input "packed"
\r
410 // is a packed array. Bytes are filled in according to the Rijndael spec.
\r
411 // This function returns a 1d array of bytes.
\r
413 function unpackBytes(packed) {
\r
414 var result = new Array();
\r
415 for (var j=0; j<packed[0].length; j++) {
\r
416 result[result.length] = packed[0][j];
\r
417 result[result.length] = packed[1][j];
\r
418 result[result.length] = packed[2][j];
\r
419 result[result.length] = packed[3][j];
\r
424 // This function takes a prospective plaintext (string or array of bytes)
\r
425 // and pads it with pseudorandom bytes if its length is not a multiple of the block
\r
426 // size. If plaintext is a string, it is converted to an array of bytes
\r
427 // in the process. The type checking can be made much nicer using the
\r
428 // instanceof operator, but this operator is not available until IE5.0 so I
\r
429 // chose to use the heuristic below.
\r
431 function formatPlaintext(plaintext) {
\r
432 var bpb = blockSizeInBits / 8; // bytes per block
\r
435 // if primitive string or String instance
\r
436 if ((!((typeof plaintext == "object") &&
\r
437 ((typeof (plaintext[0])) == "number"))) &&
\r
438 ((typeof plaintext == "string") || plaintext.indexOf)) {
\r
439 plaintext = plaintext.split("");
\r
440 // Unicode issues here (ignoring high byte)
\r
441 for (i=0; i<plaintext.length; i++)
\r
442 plaintext[i] = plaintext[i].charCodeAt(0) & 0xFF;
\r
445 i = plaintext.length % bpb;
\r
447 plaintext = plaintext.concat(getRandomBytes(bpb - i));
\r
453 // Returns an array containing "howMany" random bytes.
\r
455 function getRandomBytes(howMany) {
\r
456 var i, bytes = new Array();
\r
458 for (i = 0; i < howMany; i++) {
\r
459 bytes[i] = prng.nextInt(255);
\r
464 // rijndaelEncrypt(plaintext, key, mode)
\r
465 // Encrypts the plaintext using the given key and in the given mode.
\r
466 // The parameter "plaintext" can either be a string or an array of bytes.
\r
467 // The parameter "key" must be an array of key bytes. If you have a hex
\r
468 // string representing the key, invoke hexToByteArray() on it to convert it
\r
469 // to an array of bytes. The third parameter "mode" is a string indicating
\r
470 // the encryption mode to use, either "ECB" or "CBC". If the parameter is
\r
471 // omitted, ECB is assumed.
\r
473 // An array of bytes representing the cihpertext is returned. To convert
\r
474 // this array to hex, invoke byteArrayToHex() on it.
\r
476 function rijndaelEncrypt(plaintext, key, mode) {
\r
477 var expandedKey, i, aBlock;
\r
478 var bpb = blockSizeInBits / 8; // bytes per block
\r
479 var ct; // ciphertext
\r
481 if (!plaintext || !key)
\r
483 if (key.length*8 != keySizeInBits)
\r
485 if (mode == "CBC") {
\r
486 ct = getRandomBytes(bpb); // get IV
\r
487 //dump("IV", byteArrayToHex(ct));
\r
493 // convert plaintext to byte array and pad with zeros if necessary.
\r
494 plaintext = formatPlaintext(plaintext);
\r
496 expandedKey = keyExpansion(key);
\r
498 for (var block = 0; block < plaintext.length / bpb; block++) {
\r
499 aBlock = plaintext.slice(block * bpb, (block + 1) * bpb);
\r
500 if (mode == "CBC") {
\r
501 for (var i = 0; i < bpb; i++) {
\r
502 aBlock[i] ^= ct[(block * bpb) + i];
\r
505 ct = ct.concat(encrypt(aBlock, expandedKey));
\r
511 // rijndaelDecrypt(ciphertext, key, mode)
\r
512 // Decrypts the using the given key and mode. The parameter "ciphertext"
\r
513 // must be an array of bytes. The parameter "key" must be an array of key
\r
514 // bytes. If you have a hex string representing the ciphertext or key,
\r
515 // invoke hexToByteArray() on it to convert it to an array of bytes. The
\r
516 // parameter "mode" is a string, either "CBC" or "ECB".
\r
518 // An array of bytes representing the plaintext is returned. To convert
\r
519 // this array to a hex string, invoke byteArrayToHex() on it. To convert it
\r
520 // to a string of characters, you can use byteArrayToString().
\r
522 function rijndaelDecrypt(ciphertext, key, mode) {
\r
524 var bpb = blockSizeInBits / 8; // bytes per block
\r
525 var pt = new Array(); // plaintext array
\r
526 var aBlock; // a decrypted block
\r
527 var block; // current block number
\r
529 if (!ciphertext || !key || typeof ciphertext == "string")
\r
531 if (key.length*8 != keySizeInBits)
\r
534 mode = "ECB"; // assume ECB if mode omitted
\r
537 expandedKey = keyExpansion(key);
\r
539 // work backwards to accomodate CBC mode
\r
540 for (block=(ciphertext.length / bpb)-1; block>0; block--) {
\r
542 decrypt(ciphertext.slice(block*bpb,(block+1)*bpb), expandedKey);
\r
543 if (mode == "CBC")
\r
544 for (var i=0; i<bpb; i++)
\r
545 pt[(block-1)*bpb + i] = aBlock[i] ^ ciphertext[(block-1)*bpb + i];
\r
547 pt = aBlock.concat(pt);
\r
550 // do last block if ECB (skips the IV in CBC)
\r
552 pt = decrypt(ciphertext.slice(0, bpb), expandedKey).concat(pt);
\r