本文整理匯總了TypeScript中crypto.randomBytes函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript randomBytes函數的具體用法?TypeScript randomBytes怎麽用?TypeScript randomBytes使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了randomBytes函數的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。
示例1: function
async function(ctx: Context, next: Function) {
const start = new Date();
const id = crypto.randomBytes(20).toString('hex');
logger.verbose('Started request with id', id);
try {
await next();
let currentLevel: string;
if (ctx.status >= 500) {
currentLevel = 'error';
} else if (ctx.status >= 400) {
currentLevel = 'warn';
} else if (ctx.status >= 100) {
currentLevel = 'info';
}
const done = () => {
ctx.res.removeListener('finish', done);
ctx.res.removeListener('close', done);
const ms = new Date().getMilliseconds() - start.getMilliseconds();
logger.log(currentLevel, ctx.ip, ctx.method, ctx.originalUrl, ctx.status, `${ms}ms`, id);
};
ctx.res.once('finish', done);
ctx.res.once('close', done);
} catch (e) {
logger.error(ctx.ip, ctx.method, ctx.originalUrl, e, id);
throw e;
}
};
示例2:
const setCleanTestCwd = () => {
const random = crypto.randomBytes(16).toString("hex");
const path = `${os.tmpdir()}/fs-jetpack-test-${random}`;
fse.mkdirSync(path);
createdDirectories.push(path);
process.chdir(path);
};
示例3: it
it('Should generate wallet with custom root address', function() {
const hdNode = prova.HDNode.fromSeedBuffer(crypto.randomBytes(32));
const params = {
passphrase: TestV2BitGo.V2.TEST_WALLET1_PASSCODE,
label: 'Ripple Root Address Test',
disableTransactionNotifications: true,
rootPrivateKey: hdNode.getKey().getPrivateKeyBuffer().toString('hex')
};
return basecoin.wallets().generateWallet(params)
.then(function(res) {
res.should.have.property('wallet');
res.should.have.property('userKeychain');
res.should.have.property('backupKeychain');
res.should.have.property('bitgoKeychain');
res.userKeychain.should.have.property('pub');
res.userKeychain.should.have.property('prv');
res.userKeychain.should.have.property('encryptedPrv');
res.backupKeychain.should.have.property('pub');
res.bitgoKeychain.should.have.property('pub');
res.bitgoKeychain.isBitGo.should.equal(true);
res.bitgoKeychain.should.not.have.property('prv');
res.bitgoKeychain.should.not.have.property('encryptedPrv');
});
});
示例4: createKeychain
export async function createKeychain({tmpDir, cscLink, cscKeyPassword, cscILink, cscIKeyPassword, currentDir}: CreateKeychainOptions): Promise<CodeSigningInfo> {
// travis has correct AppleWWDRCA cert
if (process.env.TRAVIS !== "true") {
await bundledCertKeychainAdded.value
}
const keychainFile = await tmpDir.getTempFile({suffix: ".keychain", disposer: removeKeychain})
const certLinks = [cscLink]
if (cscILink != null) {
certLinks.push(cscILink)
}
const certPaths = new Array(certLinks.length)
const keychainPassword = randomBytes(8).toString("base64")
const securityCommands = [
["create-keychain", "-p", keychainPassword, keychainFile],
["unlock-keychain", "-p", keychainPassword, keychainFile],
["set-keychain-settings", keychainFile]
]
// https://stackoverflow.com/questions/42484678/codesign-keychain-gets-ignored
// https://github.com/electron-userland/electron-builder/issues/1457
const list = await listUserKeychains()
if (!list.includes(keychainFile)) {
securityCommands.push(["list-keychains", "-d", "user", "-s", keychainFile].concat(list))
}
await BluebirdPromise.all([
// we do not clear downloaded files - will be removed on tmpDir cleanup automatically. not a security issue since in any case data is available as env variables and protected by password.
BluebirdPromise.map(certLinks, (link, i) => downloadCertificate(link, tmpDir, currentDir).then(it => certPaths[i] = it)),
BluebirdPromise.mapSeries(securityCommands, it => exec("security", it))
])
return await importCerts(keychainFile, certPaths, [cscKeyPassword, cscIKeyPassword].filter(it => it != null) as Array<string>)
}
示例5: function
Account.findOne({ username: req.user.username }, function(err, user) {
console.log('Resetting for user: ' + user.username);
if (!user) {
console.log('Error changing password');
return res.redirect('back');
}
user.hash = req.body.password;
var iterations = 25000;
var keylen = 512;
var saltlen = 32;
crypto.randomBytes(saltlen, function (err, salt) {
if (err) { throw err; }
salt = new Buffer(salt).toString('hex');
user.salt = salt;
// https://masteringmean.com/lessons/46-Encryption-and-password-hashing-with-Nodejs
crypto.pbkdf2(req.body.password, salt, iterations, keylen, 'sha256',
function (err, hash) {
if (err) { throw err; }
user.hash = new Buffer(hash).toString('hex');
//console.log("SALT: " + user.salt);
//console.log("HASH: "+user.hash);
user.save(function(err) {
req.logIn(user, function(err) {
});
});
return res.redirect('/homepage/');
});
});
});
示例6: createPlugin
/**
* Create an instance of an ILP plugin
*
* This functions loads an instance of an ILP plugin.
*
* The constructor options and module name can be passed to the function as parameters.
* If no parameters are provided then it willattempt to find the config in environment variables.
* If these are not found it will load a plugin connected to a local moneyd instance on port 7768.
*
* The Environment variables that can be set are:
* - ILP_PLUGIN : The name/path of the plugin module
* - ILP_PLUGIN_OPTIONS : The options passed to the constructor, serialized as a JSON object.
*
* This function replaces the module 'ilp-plugin' which has been deprecated.
*
* Example 1: Explicit config
*
* ```js
* const plugin = createPlugin({ "server" : "btp+ws://myname:0a0cfd180fb5a5d32ebdf5344ce9c076@localhost:7768" })
* ```
*
* Example 2: Config from env
*
* ```sh
* $ ILP_PLUGIN="ilp-plugin-btp" \
* ILP_PLUGIN_OPTIONS="{\"server\":\"btp+ws://myname:0a0cfd180fb5a5d32ebdf5344ce9c076@localhost:7768\"}" \
* node app.js
* ```
*
* Where `app.js` has the following:
*
* ```js
* const plugin = createPlugin()
* ```
* @param {*} pluginOptions The options passed to the plugin constructor
* @param {*} pluginModuleName The module name of the plugin, defaults to `ilp.DEFAULT_PLUGIN_MODULE`
*/
function createPlugin (pluginOptions?: any, pluginModuleName: string = DEFAULT_PLUGIN_MODULE): PluginApi.PluginV2 {
const envModuleName = process.env.ILP_PLUGIN || DEFAULT_PLUGIN_MODULE
const envOptions = process.env.ILP_PLUGIN_OPTIONS || process.env.ILP_CREDENTIALS
const moduleName = pluginModuleName || envModuleName
let options = envOptions ? JSON.parse(envOptions) : {}
// TODO: Deprecated behaviour can be removed in future
if (process.env.ILP_CREDENTIALS && !process.env.ILP_PLUGIN_OPTIONS) {
log.warn(`Loading options from environment var ILP_CREDENTIALS is deprecated, use ILP_PLUGIN_OPTIONS instead.`)
}
// Replicate behaviour of 'ilp-module' for backwards compatability
// TODO: Deprecated behaviour can be removed in future
if (moduleName === 'ilp-plugin-btp') {
const name = (pluginOptions && pluginOptions.name) || ''
if (name) {
log.warn(`'pluginOptions.name' is deprecated. ` +
`Please provide the correct options for the plugin. ` +
`Example: '{ "server" : "btp+ws://<name>:<secret>@localhost:7768" }'`)
} else {
if (pluginOptions) {
options = pluginOptions
}
}
if (Object.keys(options).length === 0) {
options.server = `btp+ws://${name}:${crypto.randomBytes(16).toString('hex')}@localhost:7768`
}
} else {
options = pluginOptions
}
const Plugin = require(moduleName)
return new Plugin(options) as PluginApi.PluginV2
}
示例7: function
crypto.pbkdf2(password, user.login.salt, user.login.iterations, 32, function(err: Error, hashedPasswordBuffer: Buffer): void {
var hashedPassword: string = hashedPasswordBuffer.toString("hex");
if (hashedPassword !== user.login.hash) {
Collections.Users.update({"_id": user["_id"]}, {$inc: {"pastLogins.failedAttempts": 1}}, {w:0}, undefined);
response.locals.loginFail = true;
response.render("login", function(err: Error, html: string): void {
if (err) {
console.error(err);
return;
}
response.send(html);
});
return;
}
// Valid login
var loginToken: string = crypto.randomBytes(64).toString("hex");
Collections.Users.update({"_id": user["_id"]}, {$set: {"pastLogins.failedAttempts": 0, "pastLogins.lastLoginTime": new Date(), "login.token": loginToken}, $push: {"pastLogins.ips": request.ip}}, {w:1}, function(err: Error) {
if (err) {
console.error(err);
return;
}
request.session["username"] = user.username;
request.session["token"] = loginToken;
response.redirect("/blog");
});
});
示例8: Error
return Promise.resolve().then(() => {
// must be bip39 mnemonic
if (!bip39.validateMnemonic(phrase)) {
throw new Error('Not a valid bip39 nmemonic')
}
// normalize plaintext to fixed length byte string
const plaintextNormalized = Buffer.from(
bip39.mnemonicToEntropy(phrase), 'hex'
)
// AES-128-CBC with SHA256 HMAC
const salt = crypto.randomBytes(16)
const keysAndIV = crypto.pbkdf2Sync(password, salt, 100000, 48, 'sha512')
const encKey = keysAndIV.slice(0, 16)
const macKey = keysAndIV.slice(16, 32)
const iv = keysAndIV.slice(32, 48)
const cipher = crypto.createCipheriv('aes-128-cbc', encKey, iv)
let cipherText = cipher.update(plaintextNormalized).toString('hex')
cipherText += cipher.final().toString('hex')
const hmacPayload = Buffer.concat([salt, Buffer.from(cipherText, 'hex')])
const hmac = crypto.createHmac('sha256', macKey)
hmac.write(hmacPayload)
const hmacDigest = hmac.digest()
const payload = Buffer.concat([salt, hmacDigest, Buffer.from(cipherText, 'hex')])
return payload
})
示例9: email_request
// EMAIL VERIFICATION
async function email_request(req, res, next) {
try {
let found_user:any = await pendingUser.findOne({ _id: req.body.user_id })
if(!found_user) return res.status(500).send({message: 'User not found'})
let duplicate_user:any = await pendingUser.findOne({ email: req.body.email })
let email_in_use = false
if(duplicate_user) email_in_use = duplicate_user.social_id !== found_user.social_id
if(await realUser.findOne({ email: req.body.email }) || email_in_use || found_user.email_verified ) return res.status(500).send({ message: 'The email adress is already getting used' })
let token:any = new emailToken({ user_id: found_user._id, token: crypto.randomBytes(16).toString('hex') })
await token.save()
found_user.email = CryptoJS.AES.encrypt(req.body.email, process.env.DECRYPT_KEY);
await found_user.save()
let confirmation_link = process.env.NODE_ENV === 'production' ? `https://signup.utopian.io` : `http://localhost:${process.env.REGISTRATION_FRONTEND_PORT}`
let transporter = nodemailer.createTransport({ host: 'smtp.gmail.com', port: 465, secure: true, auth: { user: process.env.GOOGLE_MAIL_ACCOUNT, pass: process.env.GOOGLE_MAIL_PASSWORD } })
let mailOptions = { from: process.env.GOOGLE_MAIL_ACCOUNT, to: req.body.email, subject: 'Utopian Email Confirmation', text: 'Hey there,\n\n' + `Please confirm your email for Utopian.io by clicking on this link: ${confirmation_link}/email/confirm/${token.token}` + '.\n' }
await transporter.sendMail(mailOptions)
res.status(200).send('A verification email has been sent to ' + found_user.email + '.')
} catch (error) {
console.error(error.message)
res.status(500).json({ message: filter_error_message(error.message)})
}
}
示例10: async
let proxySocket = net.createConnection(dst.port, dst.addr, async () => {
console.log(`connected: ${dst.addr}:${dst.port}`);
let reply = rawData.slice(0, rawData.length)
reply[0] = 0x05;
reply[1] = 0x00;
let encryptor = cryptoEx.createCipher(options.cipherAlgorithm, options.password);
let cipher = encryptor.cipher;
let iv = encryptor.iv;
let pl = Number((Math.random() * 0xff).toFixed());
let el = new Buffer([pl]);
let pd = crypto.randomBytes(pl);
let er = cipher.update(Buffer.concat([el, pd, reply]));
await client.writeAsync(Buffer.concat([iv, er]));
let fromClientXorStream = new XorStream(options.xorNum);
let toClientXorStream = new XorStream(pl);
let speed = options.speed;
let streamIn = speed > 0 ? client.pipe(new SpeedStream(speed)) : client;
streamIn.pipe(fromClientXorStream).pipe(proxySocket);
let streamOut = speed > 0 ? proxySocket.pipe(new SpeedStream(speed)) : proxySocket;
streamOut.pipe(toClientXorStream).pipe(client);
});