convenience.js 9.0 KB

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