crypto-base-buffer.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. /**
  2. * Created by bmf on 11/2/13.
  3. */
  4. /* jslint node: true */
  5. 'use strict';
  6. var assert = require('assert');
  7. var binding = require('../build/Release/sodium');
  8. var toBuffer = require('./toBuffer');
  9. module.exports = function CryptoBaseBuffer() {
  10. var self = this;
  11. /**
  12. * Expected size of the buffer.
  13. * All buffers need to have expectedSize bytes to be valid
  14. * */
  15. self.expectedSize = 0; // This should be set to the appropriate Lib Sodium constant
  16. /** internal state buffer */
  17. self.baseBuffer = undefined;
  18. /** default encoding to use in all string operations */
  19. self.defaultEncoding = undefined;
  20. /** Default valid string encoding schemes */
  21. self.validEncodings = /^(?:hex|base64)$/;
  22. /** Type of data stored in the buffer. (key, pulicKey, secretKey, nonce) **/
  23. self.type = undefined;
  24. /**
  25. * Initialize object
  26. * If a key is not given generate a new random key.
  27. *
  28. * Valid keys, once converted to a node buffer, must have expectedSize in length.
  29. * If a key is represented by a string the string length depends on the encoding
  30. * so do not rely on string lengths to calculate key sizes.
  31. *
  32. * @param {number} expectedSize expected size of the buffer in bytes
  33. * @param {String|Buffer|Array} [value] value to initialize the buffer with
  34. * @param {Srting} [encoding] encoding to use in conversion if value is a string. Defaults to 'hex'
  35. */
  36. self.init = function(options) {
  37. options = options || {};
  38. assert(typeof options.expectedSize == 'number' && options.expectedSize > 0, 'options.expectedSize > 0');
  39. if ( !options.type ) {
  40. throw self.error('type must be passed to init');
  41. }
  42. assert(typeof options.type == 'string');
  43. self.type = options.type;
  44. if ( !options.expectedSize ) {
  45. throw self.error('expectedSize must be passed to init');
  46. }
  47. self.expectedSize = options.expectedSize;
  48. if( !options.buffer ) {
  49. self.generate();
  50. return;
  51. }
  52. self.set(options.buffer, options.encoding);
  53. };
  54. /**
  55. * Set the default encoding to use in all string conversions
  56. * @param {String} encoding encoding to use
  57. */
  58. self.setEncoding = function(encoding) {
  59. assert(typeof encoding == 'string');
  60. assert(encoding.match(self.validEncodings));
  61. self.defaultEncoding = encoding;
  62. };
  63. /**
  64. * Get the current default encoding
  65. * @returns {undefined|String}
  66. */
  67. self.getEncoding = function() {
  68. return self.defaultEncoding;
  69. };
  70. /**
  71. * Return the type of data stored in the buffer.
  72. * Example: "BoxKeyPublicKey" for a Box object's public key
  73. * @returns {undefined|String}
  74. */
  75. self.getType = function() {
  76. return self.type;
  77. };
  78. /**
  79. * Set the valid string encodings
  80. *
  81. * A lot of cryptographic functions rely on random buffer data that cannot
  82. * be accurately converted to and from some encoding schemes. This method
  83. * allows you to restrict the string encoding to settings you know will work
  84. *
  85. * @param {Array} encList array of strings with supported encodings
  86. */
  87. self.setValidEncodings = function(encList) {
  88. if( !encList ) {
  89. return;
  90. }
  91. assert(encList instanceof Array);
  92. var rxStr = '^(?:';
  93. var l = encList.length;
  94. for(var i=0; i < l; i++) {
  95. if( encList[i] === 'utf8' ) {
  96. throw self.error('utf8 cannot be used to decode random byte buffers. Crypto is "random"');
  97. }
  98. rxStr += encList[i];
  99. if( i != l-1 ) rxStr += '|';
  100. }
  101. rxStr += ')$';
  102. self.validEncodings = new RegExp(rxStr);
  103. };
  104. /**
  105. * Generate a new Error appropriate to use with throw
  106. * @param errorMessage
  107. * @returns {Error}
  108. */
  109. self.error = function(errorMessage) {
  110. return new Error('[CryptoBaseBuffer] ' + self.type + ' ' + errorMessage);
  111. };
  112. /**
  113. * Convert value into a buffer
  114. *
  115. * @param {String|Buffer|Array} value a buffer, and array of bytes or a string that you want to convert to a buffer
  116. * @param {String} [encoding] encoding to use in conversion if value is a string. Defaults to 'hex'
  117. * @returns {*}
  118. */
  119. self.toBuffer = function(value, encoding) {
  120. encoding = encoding || self.defaultEncoding;
  121. if( encoding && !encoding.match(self.validEncodings)) {
  122. throw self.error('invalid encoding');
  123. }
  124. return toBuffer(value, encoding);
  125. };
  126. /**
  127. * Get the length of the buffer
  128. * @returns {number} length in bytes of the buffer
  129. */
  130. self.size = function() {
  131. return self.expectedSize;
  132. };
  133. /**
  134. * Get the length of the buffer
  135. * @returns {number} length in bytes of the buffer
  136. */
  137. self.bytes = self.size;
  138. /**
  139. * Check if value could be used by CryptoBaseBuffer as a buffer
  140. *
  141. * @param {String|Buffer|Array} value to test
  142. * @param {String} [encoding] encoding to use in conversion if value is a string. Defaults to 'hex'
  143. * @returns {boolean} true if value could be used as a CryptoBaseBuffer
  144. */
  145. self.isValid = function(value, encoding) {
  146. if( !self.expectedSize ) {
  147. throw self.error('expectedSize must be set in the sub-class by calling init()');
  148. }
  149. if( typeof value === 'string' ) {
  150. encoding = encoding || self.defaultEncoding || 'hex';
  151. if( encoding === 'utf8' ) {
  152. throw self.error('utf8 cannot be used to encode/decode random byte buffers. Crypto is "random"');
  153. }
  154. if( encoding && !encoding.match(self.validEncodings)) {
  155. throw self.error('invalid encoding');
  156. }
  157. return Buffer.byteLength(value, encoding) == self.expectedSize;
  158. }
  159. if( typeof value == 'object' ) {
  160. if( value instanceof Array || value instanceof Buffer ) {
  161. return value.length == self.expectedSize;
  162. }
  163. if( value instanceof CryptoBaseBuffer ) {
  164. return value.size() == self.expectedSize;
  165. }
  166. }
  167. return false;
  168. };
  169. /**
  170. * Wipe buffer securely
  171. */
  172. self.wipe = function() {
  173. if( self.baseBuffer ) {
  174. binding.memzero(self.baseBuffer);
  175. }
  176. };
  177. /**
  178. * Fill buffer with random bytes
  179. * This method can be redefined in each sub-class to implement
  180. * the specific needs of that class
  181. */
  182. self.generate = function() {
  183. if( !self.expectedSize ) {
  184. throw self.error('expectedSize must be set in the sub-class by calling init()');
  185. }
  186. self.baseBuffer = Buffer.allocUnsafe(self.expectedSize);
  187. binding.randombytes_buf(self.baseBuffer);
  188. };
  189. /**
  190. * Getter for the baseBuffer
  191. * @returns {undefined| Buffer} secret key
  192. */
  193. self.get = function() {
  194. return self.baseBuffer;
  195. };
  196. /**
  197. * Set the secret key to a known value
  198. * @param {String|Buffer|Array} value the secret value to set the buffer to
  199. * @param {String} [encoding] If v is a string you can specify the encoding.
  200. */
  201. self.set = function(value, encoding) {
  202. encoding = encoding || self.defaultEncoding;
  203. if( !value ) {
  204. self.wipe();
  205. return;
  206. }
  207. if( encoding && !encoding.match(self.validEncodings)) {
  208. throw self.error('invalid encoding');
  209. }
  210. if( !self.isValid(value, encoding) ) {
  211. throw self.error('baseBuffer length must be ' + self.expectedSize + ' bytes');
  212. }
  213. if( value instanceof CryptoBaseBuffer ) {
  214. self.baseBuffer = value;
  215. }
  216. else {
  217. self.baseBuffer = self.toBuffer(value, encoding);
  218. }
  219. };
  220. /**
  221. * Convert the secret key to a string object
  222. * @param encoding {String} optional sting encoding. defaults to 'hex'
  223. */
  224. self.toString = function(encoding) {
  225. encoding = encoding || self.defaultEncoding || 'hex';
  226. if( encoding.toLowerCase() === 'utf8' ) {
  227. throw self.error('utf8 cannot be used to decode random byte buffers. Crypto is "random"');
  228. }
  229. if( encoding && !encoding.match(self.validEncodings)) {
  230. throw self.error('invalid encoding');
  231. }
  232. if( !self.baseBuffer ) {
  233. throw self.error('buffer has not been generated or set yet.');
  234. }
  235. return self.baseBuffer.toString(encoding);
  236. };
  237. /**
  238. * Serialize a CryptoBaseBuffer
  239. *
  240. * @param {String} [encoding] encoding used to convert the buffer to a string
  241. * @returns {string} parsable JSON string
  242. */
  243. self.serialize = function(encoding) {
  244. encoding = encoding || self.defaultEncoding || 'hex';
  245. if( encoding.toLowerCase() === 'utf8' ) {
  246. throw self.error('utf8 cannot be used to decode random byte buffers. Crypto is "random"');
  247. }
  248. var out = '{ "buffer:"' + self.toString(encoding) + ',';
  249. out += ' "encoding:"' + encoding + '}';
  250. return out;
  251. };
  252. /**
  253. * Deserialize object. Take a parsable JSON string and create a valid buffer object
  254. *
  255. * @param {Object} obj parsable JSON String
  256. */
  257. self.deserialize = function(obj) {
  258. var o;
  259. try {
  260. o = JSON.parse(obj);
  261. }
  262. catch (e) {
  263. throw self.error('invalid object to deserialize: ' + e.message);
  264. }
  265. self.set(o.buffer, o.encoding);
  266. };
  267. // some aliases
  268. self.toJSON = self.serialize;
  269. self.parse = self.deserialize;
  270. };