convenience.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. /** @fileOverview Convenince functions centered around JSON encapsulation.
  2. *
  3. * @author Emily Stark
  4. * @author Mike Hamburg
  5. * @author Dan Boneh
  6. */
  7. /** @namespace JSON encapsulation */
  8. sjcl.json = {
  9. /** Default values for encryption */
  10. defaults: { v:1, iter:1000, ks:128, ts:64, mode:"ccm", adata:"", cipher:"aes" },
  11. /** Simple encryption function.
  12. * @param {String|bitArray} password The password or key.
  13. * @param {String} plaintext The data to encrypt.
  14. * @param {Object} [params] The parameters including tag, iv and salt.
  15. * @param {Object} [rp] A returned version with filled-in parameters.
  16. * @return {String} The ciphertext.
  17. * @throws {sjcl.exception.invalid} if a parameter is invalid.
  18. */
  19. encrypt: function (password, plaintext, params, rp) {
  20. params = params || {};
  21. rp = rp || {};
  22. var j = sjcl.json, p = j._add({ iv: sjcl.random.randomWords(4,0) },
  23. j.defaults), tmp, prp;
  24. j._add(p, params);
  25. if (typeof p.salt === "string") {
  26. p.salt = sjcl.codec.base64.toBits(p.salt);
  27. }
  28. if (typeof p.iv === "string") {
  29. p.iv = sjcl.codec.base64.toBits(p.iv);
  30. }
  31. if (!sjcl.mode[p.mode] ||
  32. !sjcl.cipher[p.cipher] ||
  33. (typeof password === "string" && p.iter <= 100) ||
  34. (p.ts !== 64 && p.ts !== 96 && p.ts !== 128) ||
  35. (p.ks !== 128 && p.ks !== 192 && p.ks !== 256) ||
  36. (p.iv.length < 2 || p.iv.length > 4)) {
  37. throw new sjcl.exception.invalid("json encrypt: invalid parameters");
  38. }
  39. if (typeof password === "string") {
  40. tmp = sjcl.misc.cachedPbkdf2(password, p);
  41. password = tmp.key.slice(0,p.ks/32);
  42. p.salt = tmp.salt;
  43. }
  44. if (typeof plaintext === "string") {
  45. plaintext = sjcl.codec.utf8String.toBits(plaintext);
  46. }
  47. prp = new sjcl.cipher[p.cipher](password);
  48. /* return the json data */
  49. j._add(rp, p);
  50. rp.key = password;
  51. /* do the encryption */
  52. p.ct = sjcl.mode[p.mode].encrypt(prp, plaintext, p.iv, p.adata, p.ts);
  53. return j.encode(j._subtract(p, j.defaults));
  54. },
  55. /** Simple decryption function.
  56. * @param {String|bitArray} password The password or key.
  57. * @param {String} ciphertext The ciphertext to decrypt.
  58. * @param {Object} [params] Additional non-default parameters.
  59. * @param {Object} [rp] A returned object with filled parameters.
  60. * @return {String} The plaintext.
  61. * @throws {sjcl.exception.invalid} if a parameter is invalid.
  62. * @throws {sjcl.exception.corrupt} if the ciphertext is corrupt.
  63. */
  64. decrypt: function (password, ciphertext, params, rp) {
  65. params = params || {};
  66. rp = rp || {};
  67. var j = sjcl.json, p = j._add(j._add(j._add({},j.defaults),j.decode(ciphertext)), params, true), ct, tmp, prp;
  68. if (typeof p.salt === "string") {
  69. p.salt = sjcl.codec.base64.toBits(p.salt);
  70. }
  71. if (typeof p.iv === "string") {
  72. p.iv = sjcl.codec.base64.toBits(p.iv);
  73. }
  74. if (!sjcl.mode[p.mode] ||
  75. !sjcl.cipher[p.cipher] ||
  76. (typeof password === "string" && p.iter <= 100) ||
  77. (p.ts !== 64 && p.ts !== 96 && p.ts !== 128) ||
  78. (p.ks !== 128 && p.ks !== 192 && p.ks !== 256) ||
  79. (!p.iv) ||
  80. (p.iv.length < 2 || p.iv.length > 4)) {
  81. throw new sjcl.exception.invalid("json decrypt: invalid parameters");
  82. }
  83. if (typeof password === "string") {
  84. tmp = sjcl.misc.cachedPbkdf2(password, p);
  85. password = tmp.key.slice(0,p.ks/32);
  86. p.salt = tmp.salt;
  87. }
  88. prp = new sjcl.cipher[p.cipher](password);
  89. /* do the decryption */
  90. ct = sjcl.mode[p.mode].decrypt(prp, p.ct, p.iv, p.adata, p.ts);
  91. /* return the json data */
  92. j._add(rp, p);
  93. rp.key = password;
  94. return sjcl.codec.utf8String.fromBits(ct);
  95. },
  96. /** Encode a flat structure into a JSON string.
  97. * @param {Object} obj The structure to encode.
  98. * @return {String} A JSON string.
  99. * @throws {sjcl.exception.invalid} if obj has a non-alphanumeric property.
  100. * @throws {sjcl.exception.bug} if a parameter has an unsupported type.
  101. */
  102. encode: function (obj) {
  103. var i, out='{', comma='';
  104. for (i in obj) {
  105. if (obj.hasOwnProperty(i)) {
  106. if (!i.match(/^[a-z0-9]+$/i)) {
  107. throw new sjcl.exception.invalid("json encode: invalid property name");
  108. }
  109. out += comma + '"' + i + '"' + ':';
  110. comma = ',';
  111. switch (typeof obj[i]) {
  112. case 'number':
  113. case 'boolean':
  114. out += obj[i];
  115. break;
  116. case 'string':
  117. out += '"' + escape(obj[i]) + '"';
  118. break;
  119. case 'object':
  120. out += '"' + sjcl.codec.base64.fromBits(obj[i],1) + '"';
  121. break;
  122. default:
  123. throw new sjcl.exception.bug("json encode: unsupported type");
  124. }
  125. }
  126. }
  127. return out+'}';
  128. },
  129. /** Decode a simple (flat) JSON string into a structure. The ciphertext,
  130. * adata, salt and iv will be base64-decoded.
  131. * @param {String} str The string.
  132. * @return {Object} The decoded structure.
  133. * @throws {sjcl.exception.invalid} if str isn't (simple) JSON.
  134. */
  135. decode: function (str) {
  136. str = str.replace(/\s/g,'');
  137. if (!str.match(/^\{.*\}$/)) {
  138. throw new sjcl.exception.invalid("json decode: this isn't json!");
  139. }
  140. var a = str.replace(/^\{|\}$/g, '').split(/,/), out={}, i, m;
  141. for (i=0; i<a.length; i++) {
  142. if (!(m=a[i].match(/^(?:(["']?)([a-z][a-z0-9]*)\1):(?:(\d+)|"([a-z0-9+\/%*_.@=\-]*)")$/i))) {
  143. throw new sjcl.exception.invalid("json decode: this isn't json!");
  144. }
  145. if (m[3]) {
  146. out[m[2]] = parseInt(m[3],10);
  147. } else {
  148. out[m[2]] = m[2].match(/^(ct|salt|iv)$/) ? sjcl.codec.base64.toBits(m[4]) : unescape(m[4]);
  149. }
  150. }
  151. return out;
  152. },
  153. /** Insert all elements of src into target, modifying and returning target.
  154. * @param {Object} target The object to be modified.
  155. * @param {Object} src The object to pull data from.
  156. * @param {boolean} [requireSame=false] If true, throw an exception if any field of target differs from corresponding field of src.
  157. * @return {Object} target.
  158. * @private
  159. */
  160. _add: function (target, src, requireSame) {
  161. if (target === undefined) { target = {}; }
  162. if (src === undefined) { return target; }
  163. var i;
  164. for (i in src) {
  165. if (src.hasOwnProperty(i)) {
  166. if (requireSame && target[i] !== undefined && target[i] !== src[i]) {
  167. throw new sjcl.exception.invalid("required parameter overridden");
  168. }
  169. target[i] = src[i];
  170. }
  171. }
  172. return target;
  173. },
  174. /** Remove all elements of minus from plus. Does not modify plus.
  175. * @private
  176. */
  177. _subtract: function (plus, minus) {
  178. var out = {}, i;
  179. for (i in plus) {
  180. if (plus.hasOwnProperty(i) && plus[i] !== minus[i]) {
  181. out[i] = plus[i];
  182. }
  183. }
  184. return out;
  185. },
  186. /** Return only the specified elements of src.
  187. * @private
  188. */
  189. _filter: function (src, filter) {
  190. var out = {}, i;
  191. for (i=0; i<filter.length; i++) {
  192. if (src[filter[i]] !== undefined) {
  193. out[filter[i]] = src[filter[i]];
  194. }
  195. }
  196. return out;
  197. }
  198. };
  199. /** Simple encryption function; convenient shorthand for sjcl.json.encrypt.
  200. * @param {String|bitArray} password The password or key.
  201. * @param {String} plaintext The data to encrypt.
  202. * @param {Object} [params] The parameters including tag, iv and salt.
  203. * @param {Object} [rp] A returned version with filled-in parameters.
  204. * @return {String} The ciphertext.
  205. */
  206. sjcl.encrypt = sjcl.json.encrypt;
  207. /** Simple decryption function; convenient shorthand for sjcl.json.decrypt.
  208. * @param {String|bitArray} password The password or key.
  209. * @param {String} ciphertext The ciphertext to decrypt.
  210. * @param {Object} [params] Additional non-default parameters.
  211. * @param {Object} [rp] A returned object with filled parameters.
  212. * @return {String} The plaintext.
  213. */
  214. sjcl.decrypt = sjcl.json.decrypt;
  215. /** The cache for cachedPbkdf2.
  216. * @private
  217. */
  218. sjcl.misc._pbkdf2Cache = {};
  219. /** Cached PBKDF2 key derivation.
  220. * @param {String} The password.
  221. * @param {Object} The derivation params (iteration count and optional salt).
  222. * @return {Object} The derived data in key, the salt in salt.
  223. */
  224. sjcl.misc.cachedPbkdf2 = function (password, obj) {
  225. var cache = sjcl.misc._pbkdf2Cache, c, cp, str, salt, iter;
  226. obj = obj || {};
  227. iter = obj.iter || 1000;
  228. /* open the cache for this password and iteration count */
  229. cp = cache[password] = cache[password] || {};
  230. c = cp[iter] = cp[iter] || { firstSalt: (obj.salt && obj.salt.length) ?
  231. obj.salt.slice(0) : sjcl.random.randomWords(2,0) };
  232. salt = (obj.salt === undefined) ? c.firstSalt : obj.salt;
  233. c[salt] = c[salt] || sjcl.misc.pbkdf2(password, salt, obj.iter);
  234. return { key: c[salt].slice(0), salt:salt.slice(0) };
  235. };