How to use crypto

Comprehensive crypto code examples:

How to use crypto.update:

47
48
49
50
51
52
53
54
55
56
// comparing given password with hashed password
await bcrypt
  .compare(password, user.password)
  .then(async function (result) {
    if (result) {
      /*const token = crypto.update(jwtSecret).digest("hex");
    const hash = crypto.createHash("sha256").update(token).digest("hex");*/
      const token = jwt.sign({ user: user.username }, JWT_SECRET, {
        expiresIn: "3hrs",
      });

How to use crypto.js:

19
20
21
22
23
24
25
26
27
28
};
//saving the user
const user = await UsersModel.create(data);

//if user details is captured
//create a token with crypto.js

if (user) {
  let setToken = await TokenModel.create({
    userID: user.userID,

How to use crypto.Sign:

13
14
15
16
17
18
19
20
21
22
23
const certPem = fixtures.readKey('rsa_cert.crt');
const keyPem = fixtures.readKey('rsa_private.pem');
const keySize = 2048;


{
  const Sign = crypto.Sign;
  const instance = Sign('SHA256');
  assert(instance instanceof Sign, 'Sign is expected to return a new ' +
                                   'instance when called without `new`');
}

How to use crypto.Verify:

20
21
22
23
24
25
26
27
28
29
30
  assert(instance instanceof Sign, 'Sign is expected to return a new ' +
                                   'instance when called without `new`');
}


{
  const Verify = crypto.Verify;
  const instance = Verify('SHA256');
  assert(instance instanceof Verify, 'Verify is expected to return a new ' +
                                     'instance when called without `new`');
}

How to use crypto.r:

How to use crypto.Hmac:

4
5
6
7
8
9
10
11
12
13
14
15


const assert = require('assert');
const crypto = require('crypto');


{
  const Hmac = crypto.Hmac;
  const instance = crypto.Hmac('sha256', 'Node');
  assert(instance instanceof Hmac, 'Hmac is expected to return a new instance' +
                                   ' when called without `new`');
}

How to use crypto.pbkdf2Async:

33
34
35
36
37
38
39
40
41
42
let locals = {};
return User.findOne({ 'email': email}).exec()
    .then(function (user) {
        locals.user = user;
        console.log("User Found");
        return Crypto.pbkdf2Async(password, user.login.salt, 100000, 512, 'sha512');
    }).then(function (hash) {
        if (!locals.user.login.hashed_password.equals(hash)) {
            console.log("Password didn't match");
            return Promise.reject("Password didn't match");

How to use crypto.aes:

102
103
104
105
106
107
108
109
110
111
    var key = fold(1,NodeCrypto.createHash("sha256").update(secret).digest());
    var ivz = new Buffer(12);
    ivz.fill(0);

    // aes-128 decipher the inner
    var inner = NodeCrypto.aes(false, key, Buffer.concat([iv,ivz]), innerc);

    return inner;
  };
}

How to use crypto.RSA_PKCS1_PADDING:

167
168
169
170
171
172
173
174
175
176
var padding;
if (algorithmType == EncryptAlgorithmType.RsaPkcs) {
  if (this.keyType != KeyType.RSA)
    return SyncPromise.reject(new Error("The key type must be RSA"));

  padding = cryptoConstants.RSA_PKCS1_PADDING;
}
else if (algorithmType == EncryptAlgorithmType.RsaOaep) {
  if (this.keyType != KeyType.RSA)
    return SyncPromise.reject(new Error("The key type must be RSA"));

How to use crypto.KeyObject:

190
191
192
193
194
195
196
197
198
createSecretKey = (buffer) => {
  if (!Buffer.isBuffer(buffer) || !buffer.length) {
    throw new TypeError('input must be a non-empty Buffer instance')
  }

  const keyObject = new KeyObject()
  i(keyObject).buffer = Buffer.from(buffer)
  i(keyObject).symmetricKeySize = buffer.length
  i(keyObject).type = 'secret'

How to use crypto.getCurves:

193
194
195
196
197
198
199
200
201
202
203
204
// Test ECDH.


test(crypto.generateKeyPairSync('ec', { namedCurve: 'secp256k1' }),
     crypto.generateKeyPairSync('ec', { namedCurve: 'secp256k1' }));


const not256k1 = crypto.getCurves().find((c) => /^sec.*(224|384|512)/.test(c));
assert.throws(() => {
  test(crypto.generateKeyPairSync('ec', { namedCurve: 'secp256k1' }),
       crypto.generateKeyPairSync('ec', { namedCurve: not256k1 }));
}, {

How to use crypto.DEFAULT_ENCODING:

186
187
188
189
190
191
192
193
194
195
196
197
    assert.deepStrictEqual(actual.toString('hex'), expected.toString('hex'));
  }));
}


{
  const defaultEncoding = crypto.DEFAULT_ENCODING;
  const defaults = { N: 16384, p: 1, r: 8 };
  const expected = crypto.scryptSync('pass', 'salt', 1, defaults);


  const testEncoding = 'latin1';

How to use crypto.getCipherInfo:

120
121
122
123
124
125
126
127
128
129
const cryptoCiphers = crypto.getCiphers();
assert(crypto.getCiphers().includes('aes-128-cbc'));
validateList(cryptoCiphers);
// Make sure all of the ciphers are supported by OpenSSL
for (const algo of cryptoCiphers) {
  const { ivLength, keyLength, mode } = crypto.getCipherInfo(algo);
  let options;
  if (mode === 'ccm')
    options = { authTagLength: 8 };
  else if (mode === 'ocb' || algo === 'chacha20-poly1305')

How to use crypto.ECDH:

89
90
91
92
93
94
95
96
97
98
99
                                            'to return a new instance when ' +
                                            'called without `new`');
}


{
  const ECDH = crypto.ECDH;
  const ecdh = ECDH('prime256v1');
  assert(ecdh instanceof ECDH, 'ECDH is expected to return a new instance ' +
                               'when called without `new`');
}

How to use crypto.RSA_PKCS1_OAEP_PADDING:

173
174
175
176
177
178
179
180
181
}
else if (algorithmType == EncryptAlgorithmType.RsaOaep) {
  if (this.keyType != KeyType.RSA)
    return SyncPromise.reject(new Error("The key type must be RSA"));

  padding = cryptoConstants.RSA_PKCS1_OAEP_PADDING;
}
else
  return SyncPromise.reject(new Error("unsupported padding scheme"));

How to use crypto.webcrypto:

-4
-3
const crypto = require('crypto');
global.crypto = crypto.webcrypto;

How to use crypto.DiffieHellmanGroup:

How to use crypto.DiffieHellman:

4
5
6
7
8
9
10
exports.createDiffieHellmanGroup = crypto.createDiffieHellmanGroup
exports.getDiffieHellman = crypto.getDiffieHellman


// createDiffieHellman
exports.createDiffieHellman = crypto.createDiffieHellman
exports.DiffieHellman = crypto.DiffieHellman

How to use crypto.randomBytesAsync:

2
3
4
5
6
7
8
9
10
11
var crypto = Promise.promisifyAll(require('crypto'));

function createKey() {
  return new Promise(function(resolve, reject) {
    co.wrap(function *() {
      var bytes = yield crypto.randomBytesAsync(33);
      var key = bytes.toString('base64').replace(/\+/g, '-').replace(/\//g, '_');
      resolve(key);
    })();
  });

How to use crypto.ecc:

75
76
77
78
79
80
81
82
83
84

exports._Local = function(pair)
{
  var self = this;
  try{
    self.key = new NodeCrypto.ecc.ECKey(NodeCrypto.ecc.ECCurves.secp160r1, pair.key, true);
    self.secret = new NodeCrypto.ecc.ECKey(NodeCrypto.ecc.ECCurves.secp160r1, pair.secret);
    if(self.key.PublicKey.toString() != pair.key.toString()) throw new Error('invalid public key data');
    if(self.secret.PrivateKey.toString() != pair.secret.toString()) throw new Error('invalid secret key data');
  }catch(E){

How to use crypto.subtle:

-3
-2
-1
// JSDom does not include a full implementation of webcrypto
const crypto = require('crypto').webcrypto;
global.crypto.subtle = crypto.subtle;

How to use crypto.getHashes:

151
152
153
154
155
156
157
158
159
160
161
assert(!crypto.getHashes().includes('SHA256'));
assert(crypto.getHashes().includes('RSA-SHA1'));
assert(!crypto.getHashes().includes('rsa-sha1'));
validateList(crypto.getHashes());
// Make sure all of the hashes are supported by OpenSSL
for (const algo of crypto.getHashes())
  crypto.createHash(algo);


// Assume that we have at least secp384r1.
assert.notStrictEqual(crypto.getCurves().length, 0);

How to use crypto.generateKeyPair:

50
51
52
53
54
55
56
57
58
59
  }
}

function genKeys() {
  return new Promise((resolve, reject) => {
    crypto.generateKeyPair(
      'rsa',
      {
        modulusLength: 2048,
      },

How to use crypto.Certificate:

189
190
191
192
193
194
195
196
197
> Stability: 0 - Deprecated

As a legacy interface, it is possible to create new instances of
the `crypto.Certificate` class as illustrated in the examples below.

#### `new crypto.Certificate()`

Instances of the `Certificate` class can be created using the `new` keyword
or by calling `crypto.Certificate()` as a function:

How to use crypto.getRandomValues:

878
879
880
881
882
883
884
885
886

// Amount
const AMOUNT = new BigNumber(Math.round(Math.random() * Number.MAX_SAFE_INTEGER));

// Identifier
const IDENTIFIER = new Identifier(Common.toHexString(Common.mergeArrays([new Uint8Array([Math.round(Math.random() * Identifier.MAX_DEPTH)]), crypto.getRandomValues(new Uint8Array(Identifier.MAX_DEPTH * Uint32Array["BYTES_PER_ELEMENT"]))])));

// Log amount
console.log("Using amount: " + AMOUNT.toFixed());

How to use crypto.createCredentials:

188
189
190
191
192
193
194
195
196
197

var self = this;
var options = this._tlsOptions;

// Wrap socket's handle
var credentials = options.credentials || crypto.createCredentials();
this.ssl = tls_wrap.wrap(this._handle, credentials.context, options.isServer);
this.server = options.server || null;

// For clients, we will always have either a given ca list or be using

How to use crypto.createSecretKey:

104
105
106
107
108
109
110
111
112
113
 * @param {string} secret the MessageBird signature key
 * @param {VerifyOptions} opts validation options
 * @returns {*} an express handler to be used as middleware
 */
function ExpressMiddlewareVerify(secret, opts = DefaultVerifyOptions) {
  const sk = createSecretKey(Buffer.from(secret, 'utf8'));

  return function (req, res, next) {
    Promise.resolve()
      .then(() => {

How to use crypto.getCiphers:

44
45
46
47
48
49
50
51
52
53
54
55
  FIPS: /not supported in FIPS mode/,
  length: /Invalid initialization vector/,
  authTagLength: /Invalid authentication tag length/
};


const ciphers = crypto.getCiphers();


const expectedWarnings = common.hasFipsCrypto ?
  [] : [
    ['Use Cipheriv for counter mode of aes-192-gcm'],

How to use crypto.default:

2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
// src/server/lib/http-secure.ts
var import_crypto = __toESM(require("crypto"));
var import_crypto_js2 = __toESM(require("crypto-js"));
var import_node_jsencrypt = __toESM(require("node-jsencrypt"));
function secure(enable = () => true) {
  const { publicKey, privateKey } = import_crypto.default.generateKeyPairSync("rsa", {
    modulusLength: 2048,
    publicKeyEncoding: {
      type: "spki",
      format: "pem"