convenience.js 8.8 KB

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