1'use strict'; 2 3const { 4 Symbol, 5} = primordials; 6 7const { 8 getCiphers: _getCiphers, 9 getCurves: _getCurves, 10 getHashes: _getHashes, 11 setEngine: _setEngine, 12} = internalBinding('crypto'); 13 14const { 15 ENGINE_METHOD_ALL 16} = internalBinding('constants').crypto; 17 18const { 19 hideStackFrames, 20 codes: { 21 ERR_CRYPTO_ENGINE_UNKNOWN, 22 ERR_INVALID_ARG_TYPE, 23 } 24} = require('internal/errors'); 25const { validateString } = require('internal/validators'); 26const { Buffer } = require('buffer'); 27const { 28 cachedResult, 29 filterDuplicateStrings 30} = require('internal/util'); 31const { 32 isArrayBufferView 33} = require('internal/util/types'); 34 35const kHandle = Symbol('kHandle'); 36 37var defaultEncoding = 'buffer'; 38 39function setDefaultEncoding(val) { 40 defaultEncoding = val; 41} 42 43function getDefaultEncoding() { 44 return defaultEncoding; 45} 46 47// This is here because many functions accepted binary strings without 48// any explicit encoding in older versions of node, and we don't want 49// to break them unnecessarily. 50function toBuf(val, encoding) { 51 if (typeof val === 'string') { 52 if (encoding === 'buffer') 53 encoding = 'utf8'; 54 return Buffer.from(val, encoding); 55 } 56 return val; 57} 58 59const getCiphers = cachedResult(() => filterDuplicateStrings(_getCiphers())); 60const getHashes = cachedResult(() => filterDuplicateStrings(_getHashes())); 61const getCurves = cachedResult(() => filterDuplicateStrings(_getCurves())); 62 63function setEngine(id, flags) { 64 validateString(id, 'id'); 65 if (flags && typeof flags !== 'number') 66 throw new ERR_INVALID_ARG_TYPE('flags', 'number', flags); 67 flags = flags >>> 0; 68 69 // Use provided engine for everything by default 70 if (flags === 0) 71 flags = ENGINE_METHOD_ALL; 72 73 if (!_setEngine(id, flags)) 74 throw new ERR_CRYPTO_ENGINE_UNKNOWN(id); 75} 76 77const getArrayBufferView = hideStackFrames((buffer, name, encoding) => { 78 if (typeof buffer === 'string') { 79 if (encoding === 'buffer') 80 encoding = 'utf8'; 81 return Buffer.from(buffer, encoding); 82 } 83 if (!isArrayBufferView(buffer)) { 84 throw new ERR_INVALID_ARG_TYPE( 85 name, 86 ['string', 'Buffer', 'TypedArray', 'DataView'], 87 buffer 88 ); 89 } 90 return buffer; 91}); 92 93module.exports = { 94 getArrayBufferView, 95 getCiphers, 96 getCurves, 97 getDefaultEncoding, 98 getHashes, 99 kHandle, 100 setDefaultEncoding, 101 setEngine, 102 toBuf 103}; 104