How to use the createCipheriv function from crypto
Find comprehensive JavaScript crypto.createCipheriv code examples handpicked from public code repositorys.
crypto.createCipheriv is a Node.js method that creates a Cipher object, which can be used for encrypting data with a specified algorithm, key, and initialization vector.
GitHub: HR/Crypter
75 76 77 78 79 80 81 82 83 84
const dataDest = fs.createWriteStream(dataDestPath) const credsDest = fs.createWriteStream(credsDestPath) // generate a cryptographically secure random iv const iv = scrypto.randomBytes(CRYPTO.DEFAULTS.IVLENGTH) // create the AES-256-GCM cipher with iv and derive encryption key const cipher = scrypto.createCipheriv( CRYPTO.DEFAULTS.ALGORITHM, dcreds.key, iv )
156 157 158 159 160 161 162 163 164
if(isBase64){ buffer = base64ToArrayBuffer(data) } const iv = randomString(12) const cipher = crypto.createCipheriv("aes-256-gcm", utf8StringToArrayBuffer(key), utf8StringToArrayBuffer(iv)) const encrypted = arrayBufferConcat(cipher.update(buffer), cipher.final()) const authTag = cipher.getAuthTag() const ciphertext = arrayBufferConcat(encrypted, authTag)
How does crypto.createCipheriv work?
crypto.createCipheriv is a method in Node.js's built-in crypto module that creates a Cipher object, which can be used to encrypt data using a specific algorithm and encryption key, along with an optional initialization vector (IV) that adds additional randomness to the encryption. It takes four arguments: the encryption algorithm, the encryption key, the initialization vector (IV), and an optional set of additional options.
159 160 161 162 163 164 165 166 167 168
data += decipher.final('utf-8'); return data.replace(/\x00.*$/,""); }; AES.prototype._cipher = function(data, out_enc) { var cipher = crypto.createCipheriv('aes-256-cbc', this._key, this._iv); var enc_data = cipher.update(data + "\0",'utf-8', out_enc); enc_data += cipher.final(out_enc); return enc_data; };
+ 3 other calls in file
144 145 146 147 148 149 150 151 152 153
* from https://gist.github.com/bnoordhuis/2de2766d3d3a47ebe41aaaec7e8b14df */ function sizes(cipher) { for (let nkey = 1, niv = 0; ;) { try { crypto.createCipheriv(cipher, '.'.repeat(nkey), '.'.repeat(niv)); return [nkey, niv]; } catch (e) { if (/(invalid iv length|Invalid initialization vector)/i.test(e.message)) { niv += 1;
+ 5 other calls in file
Ai Example
1 2 3 4 5 6 7 8 9 10 11
const crypto = require("crypto"); const algorithm = "aes-256-cbc"; // the encryption algorithm to use const key = Buffer.from("0123456789abcdef0123456789abcdef", "hex"); // the symmetric key to use (must be 32 bytes for aes-256-cbc) const iv = crypto.randomBytes(16); // generate a random 16-byte initialization vector const cipher = crypto.createCipheriv(algorithm, key, iv); // create the cipher object with the algorithm, key, and iv let encrypted = cipher.update("Hello, world!", "utf8", "base64"); // encrypt the plaintext data encrypted += cipher.final("base64"); // finalize the encryption and append any remaining ciphertext console.log(`Encrypted data: ${encrypted}`);
In this example, we use the crypto module to create a symmetric cipher with the aes-256-cbc algorithm, a 32-byte key (in hexadecimal format), and a random 16-byte initialization vector. We then use the cipher object to encrypt the plaintext string 'Hello, world!' and store the resulting ciphertext in the encrypted variable. Finally, we print out the encrypted data to the console.
102 103 104 105 106 107 108 109 110 111
/*** Example symmetric encryption/decryption functions from ch4/symmetric-encryption/aes-256-gcm.js ***/ async function symmetricEncrypt(key, plaintext) { const iv = await randomBytes(12) const cipher = crypto.createCipheriv('aes-256-gcm', key, iv) const encrypted = Buffer.concat([ cipher.update(plaintext, 'utf8'), cipher.final() ])
13 14 15 16 17 18 19 20 21 22
* @returns { Promise<string> } */ async function encrypt(key, data){ const iv = await randomBytesAsync(16); const cipher = crypto.createCipheriv('aes-256-cbc', key, iv); return new Promise((resolve, reject) => { let encrypted = ''; cipher.on('readable', () => {
GitHub: vseryakov/backendjs
19 20 21 22 23 24 25 26 27 28
const encode = options.encode === "binary" ? undefined : options.encode || "base64"; key = Buffer.isBuffer(key) ? key : typeof key == "string" ? key : String(key); data = Buffer.isBuffer(data) ? data : Buffer.from(typeof data == "string" ? data : String(data)); const iv = crypto.randomBytes(options.iv_length || 16); const password = crypto.pbkdf2Sync(key, iv.toString(), options.key_iterations || 10000, options.key_length || 32, options.key_hash || 'sha256'); const cipher = crypto.createCipheriv(options.algorithm || 'aes-256-cbc', password, iv); var msg = Buffer.concat([iv, cipher.update(data), cipher.final()]); if (encode) msg = msg.toString(encode); } catch (e) { msg = '';
GitHub: aleph-im/aleph-js
78 79 80 81 82 83 84 85 86 87
}).then(function(result) { resolve(Buffer.from(new Uint8Array(result))); }); } else { if (op === 'encrypt') { var cipher = nodeCrypto.createCipheriv('aes-256-cbc', key, iv); cipher.update(data); resolve(cipher.final()); } else if (op === 'decrypt') {
108 109 110 111 112 113 114 115 116
plaintextLength: Buffer.from(test.plain, inputEncoding).length }; } { const encrypt = crypto.createCipheriv(test.algo, Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex'), options);
+ 41 other calls in file
GitHub: nwjs/node
126 127 128 129 130 131 132 133 134 135
let options; if (mode === 'ccm') options = { authTagLength: 8 }; else if (mode === 'ocb' || algo === 'chacha20-poly1305') options = { authTagLength: 16 }; crypto.createCipheriv(algo, crypto.randomBytes(keyLength), crypto.randomBytes(ivLength || 0), options); }
GitHub: akeneo/sample-apps
4 5 6 7 8 9 10 11 12 13
static algorithm = "aes-256-ctr"; static encoder(payload, key) { const iv_length = crypto.getCipherInfo(Codec.algorithm).ivLength; const iv = crypto.randomBytes(iv_length); const cipher = crypto.createCipheriv(Codec.algorithm, key, iv) const encodedSub = cipher.update(payload, 'utf8', 'hex') + cipher.final('hex') const encodedIv = iv.toString('hex'); return { sub: encodedSub, vector: encodedIv }; }
GitHub: vulkanojs/vulkano
9 10 11 12 13 14 15 16 17 18
} encrypt(clearText) { const iv = crypto.randomBytes(16); const cipher = crypto.createCipheriv(this.algorithm, this.key, iv); const encrypted = cipher.update(clearText, 'utf8', 'hex'); return [ encrypted + cipher.final('hex'),
270 271 272 273 274 275 276 277 278 279
} sendMsgRaw(deviceId, protocol, timestamp, payload) { const localKey = localKeys.get(deviceId); const aesKey = this.md5bin(this._encodeTimestamp(timestamp) + localKey + salt); const cipher = crypto.createCipheriv("aes-128-ecb", aesKey, null); const encrypted = Buffer.concat([cipher.update(payload), cipher.final()]); const msg = Buffer.alloc(23 + encrypted.length); msg.write("1.0"); msg.writeUint32BE(seq++ & 0xffffffff, 3);
GitHub: nmiannay/soli-crypt
6 7 8 9 10 11 12 13 14 15
const pipelineAsync = promisify(pipeline); async function encrypt(readStream, writeStream, publicKey) { const iv = crypto.randomBytes(IV_LENGTH); const sessionKey = crypto.randomBytes(SESSION_KEY_LENGTH); const cipher = crypto.createCipheriv('aes-256-gcm', sessionKey, iv); await pipelineAsync( readStream, cipher,
59 60 61 62 63 64 65 66 67 68
try{ const iv = crypto.randomBytes(16); const ivString = iv.toString('base64') //console.log("iv: " + ivString) const cipher = crypto.createCipheriv('aes256', key.subarray(0,32), iv); let encryptedData = cipher.update(data,'utf-8') encryptedData = Buffer.concat([encryptedData, cipher.final()]);
+ 3 other calls in file
1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
let resizedIV = Buffer.allocUnsafe(16); let iv = crypto.createHash("sha256").update("myHashedIV").digest(); iv.copy(resizedIV); let key = crypto.createHash("sha256").update(password).digest(); let cipher = crypto.createCipheriv("aes256", key, resizedIV); let encryptedPass = cipher.update(schoolPassword, "utf8", "hex"); encryptedPass += cipher.final("hex"); await _users(db).updateOne({username: username}, {$set: {schoolPassword: encryptedPass}});
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
let iv = crypto.randomBytes(16); let algorithm = 'aes-256-ctr'; const cipher = crypto.createCipheriv(algorithm, pwhash, iv); const encrypted = Buffer.concat([cipher.update(text), cipher.final()]); return {
160 161 162 163 164 165 166 167 168 169
: basename.split('.').slice(0, -1).join('.'); // use halves of a sha256 as the aes128 key and iv const hashVal = hash(name + SECRET_KEY_POSTFIX); const k = hashVal.slice(0, 16); const iv = hashVal.slice(16, 32); const cipher = crypto.createCipheriv('aes128', k, iv); // NB: hex is more bytes than base64 when raw but fewer when compressed after let ciphertext = cipher.update( asset.source.buffer(), 'utf8',
GitHub: decaptcha/backend
38 39 40 41 42 43 44 45 46 47 48
value, key = PRIVATE_KEY, algo = ENC_ALGO, iv = INITIALIZATION_VECTOR ) => { const cipher = crypto.createCipheriv(algo, key, iv); return cipher.update(value, "utf8", "hex") + cipher.final("hex"); }; /**
GitHub: HoundDev/greyhoundapi
764 765 766 767 768 769 770 771 772 773
throw new Error('OpenSSL Version too old, vulnerability to Heartbleed'); } // let iv = crypto.randomBytes(IV_LENGTH); let iv = process.env.ENC_IV; iv = Buffer.from(iv, 'utf8'); let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(password), iv); let encrypted = cipher.update(text); encrypted = Buffer.concat([encrypted, cipher.final()]); return iv.toString('hex') + ':' + encrypted.toString('hex');
crypto.createHash is the most popular function in crypto (882 examples)