MCPcopy Create free account
hub / github.com/cryptii/cryptii / createCipher

Method createCipher

src/Encoder/BlockCipher.js:202–266  ·  view source on GitHub ↗

* Creates message cipher using given algorithm. * @protected * @param {string} name Algorithm name * @param {Uint8Array} message Message bytes * @return {Promise}

(name, mode, key, iv, padding, isEncode, message)

Source from the content-addressed store, hash-verified

200 * @return {Promise}
201 */
202 async createCipher (name, mode, key, iv, padding, isEncode, message) {
203 const algorithm = BlockCipherEncoder.getAlgorithm(name)
204
205 const { hasIV } = BlockCipherEncoder.getMode(mode)
206 if (!hasIV) {
207 iv = new Uint8Array([])
208 }
209
210 if (EnvUtil.isNode()) {
211 const cipherName = algorithm.nodeAlgorithm + '-' + mode
212
213 // Node v8.x - convert Uint8Array to Buffer - not needed for v10
214 iv = global.Buffer.from(iv)
215 message = global.Buffer.from(message)
216
217 // Create message cipher using Node Crypto async
218 return new Promise((resolve, reject) => {
219 const cipher = isEncode
220 ? nodeCrypto.createCipheriv(cipherName, key, iv)
221 : nodeCrypto.createDecipheriv(cipherName, key, iv)
222
223 cipher.setAutoPadding(padding)
224
225 const resultBuffer = Buffer.concat([
226 cipher.update(message),
227 cipher.final()
228 ])
229
230 resolve(new Uint8Array(resultBuffer))
231 })
232 } else {
233 const cipherName = algorithm.browserAlgorithm + '-' + mode
234
235 // Get crypto subtle instance
236 const crypto = window.crypto || window.msCrypto
237 const cryptoSubtle = crypto.subtle || crypto.webkitSubtle
238
239 // Create key instance
240 const cryptoKey = await cryptoSubtle.importKey(
241 'raw', key, { name: cipherName }, false, ['encrypt', 'decrypt'])
242
243 // Create message cipher using Web Crypto API
244 const algo = {
245 name: cipherName,
246 iv,
247 counter: iv,
248 length: algorithm.blockSize
249 }
250
251 let result = isEncode
252 ? cryptoSubtle.encrypt(algo, cryptoKey, message)
253 : cryptoSubtle.decrypt(algo, cryptoKey, message)
254
255 // IE11 exception
256 if (result.oncomplete !== undefined) {
257 // Wrap IE11 CryptoOperation object in a promise
258 result = new Promise((resolve, reject) => {
259 result.oncomplete = resolve.bind(this, result.result)

Callers 1

performTranslateMethod · 0.95

Calls 4

getAlgorithmMethod · 0.80
getModeMethod · 0.80
isNodeMethod · 0.80
updateMethod · 0.45

Tested by

no test coverage detected