convenience.js 9.0 KB

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