How to use the createPublicKey function from crypto

Find comprehensive JavaScript crypto.createPublicKey code examples handpicked from public code repositorys.

crypto.createPublicKey is a method in Node.js that creates a public key object for asymmetric cryptography.

57
58
59
60
61
62
63
64
65
66
// Show the result as a base64-encoded string
console.log('Message:', message)
console.log('Signature:', signature.toString('base64'))

// Load the public key from file, which we'll use to verify the signature
const publicKeyObject = crypto.createPublicKey(
    fs.readFileSync('public-ed25519.pem')
)

// Verify the signature
fork icon10
star icon28
watch icon7

+ 3 other calls in file

174
175
176
177
178
179
180
181
182
183
case 'public':
  return i(this).pem
default:
  if (needsPublic) {
    if (!('pub' in i(this))) {
      i(this).pub = createPublicKey(this)
    }

    return i(this).pub.asInput()
  }
fork icon279
star icon0
watch icon1

+ 3 other calls in file

How does crypto.createPublicKey work?

crypto.createPublicKey is a method in Node.js's crypto module that creates a public key object from a key in PEM format or an object that contains the key's data and format. When called with a PEM-encoded public key, it returns a crypto.KeyObject that can be used for various cryptographic operations, such as encryption or verification. If called with an object, it expects a type property to specify the type of key and a key property to contain the key's data in binary format. It supports different public key types, such as RSA or ECDSA, and can throw errors for invalid input.

123
124
125
126
127
128
129
130
131
132
133
}


const verifySignature = (message, signature, testMode) => {
    try {
        const key = trimPemKey(testMode ? csobConfig.TEST_PRODUCTION_PUB : csobConfig.PRODUCTION_PUB);
        const publicKeyToVerify = crypto.createPublicKey(key);
        const verify = crypto.createVerify('RSA-SHA256');
        verify.update(message);
        return verify.verify(publicKeyToVerify, signature, 'base64');
    } catch (error) {
fork icon0
star icon0
watch icon1

71
72
73
74
75
76
77
78
79
80
81
       'y/0tmLIsHxLIn+WK9CANqMbCWoP4I178BQaqhiOBkNyNZ0ndqA==\n' +
       '-----END PRIVATE KEY-----',
  format: 'pem'
});


const bobPublicKey = crypto.createPublicKey({
  key: '-----BEGIN PUBLIC KEY-----\n' +
       'MIIBoDCB1QYJKoZIhvcNAQMBMIHHAoHBAP//////////yQ/aoiFowjTExmKLgNwc\n' +
       '0SkCTgiKZ8x0Agu+pjsTmyJRSgh5jjQE3e+VGbPNOkMbMCsKbfJfFDdP4TVtbVHC\n' +
       'ReSFtXZiXn7G9ExC6aY37WsL/1y29Aa37e44a/taiZ+lrp8kEXxLH+ZJKGZR7ORb\n' +
fork icon0
star icon0
watch icon0

+ 23 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
const crypto = require("crypto");

const publicKey = `-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE9hUaJ8U6WIOY6yGg/L+Jzv+f8C6
Lz6ZODjM9eOv+8JcWYlSgxEcEdOgyxHx8GJSPgk4jzOen9H5mP8mFKG+w==
-----END PUBLIC KEY-----`;

const publicKeyObj = crypto.createPublicKey(publicKey);
console.log(publicKeyObj);

This will output a publicKeyObj which can be used to verify signatures, encrypt data, and more.

83
84
85
86
87
88
89
90
91
92
const nodePrivateKey = nodeCrypto.createPrivateKey({
  key: Buffer.concat([PRIVATE_KEY_DER_PREFIX, privKey]),
  format: "der",
  type: "pkcs8",
});
const nodePublicKey = nodeCrypto.createPublicKey({
  key: Buffer.concat([PUBLIC_KEY_DER_PREFIX, pubKey]),
  format: "der",
  type: "spki",
});
fork icon0
star icon0
watch icon0

+ 4 other calls in file

116
117
118
119
120
121
122
123
124
125
  return done(new JsonWebTokenError('please specify "none" in "algorithms" to verify unsigned tokens'));
}

if (secretOrPublicKey != null && !(secretOrPublicKey instanceof KeyObject)) {
  try {
    secretOrPublicKey = createPublicKey(secretOrPublicKey);
  } catch (_) {
    try {
      secretOrPublicKey = createSecretKey(typeof secretOrPublicKey === 'string' ? Buffer.from(secretOrPublicKey) : secretOrPublicKey);
    } catch (_) {
fork icon0
star icon0
watch icon0

165
166
167
168
169
170
171
172
173
    code: "xxxx",
    message: "keyStore error",
  };
}

//const publicKeyObject = crypto.createPublicKey(publicKeyString);
// created token pair
//const tokens = await createTokenPair({ userId: newShop._id, email }, publicKeyObject, privateKey)
//console.log('Created Token Success::', tokens)
fork icon0
star icon0
watch icon0

153
154
155
156
157
158
159
160
161
162

if (!publicKeyString) {
    throw new BadRequestError('publicKeyString error')
}

const publicKeyObject = crypto.createPublicKey(publicKeyString)

const tokens = await createTokenPair({ userId: newShop._id, email }, publicKeyObject, privateKey)

return {
fork icon0
star icon0
watch icon0

451
452
453
454
455
456
457
458
459
}

{
  const data = Buffer.from('Hello world');
  const privKeyObj = crypto.createPrivateKey(pair.private);
  const pubKeyObj = crypto.createPublicKey(pair.public);

  const sig = crypto.sign(algo, data, privKeyObj);
  assert.strictEqual(sig.length, pair.sigLen);
fork icon0
star icon0
watch icon0

35
36
37
38
39
40
41
42
43
44
		format: 'pem'
	}
});

const publicKeyString = await KeyTokenService.create({ userId: newShop._id, publicKey });
const publicKeyObj = crypto.createPublicKey(publicKeyString);

const tokens = await createTokenPair({ userId: newShop._id, email }, publicKeyObj, privateKey);

return {
fork icon0
star icon0
watch icon0

370
371
372
373
374
375
376
377
378
379
380
    assert.deepStrictEqual(uncompressed, Buffer.from(spki));
  }
})().then(common.mustCall());


{
  const rsaPublic = crypto.createPublicKey(
    fixtures.readKey('rsa_public_2048.pem'));
  const rsaPrivate = crypto.createPrivateKey(
    fixtures.readKey('rsa_private_2048.pem'));

fork icon0
star icon0
watch icon0

530
531
532
533
534
535
536
537
538
539
540
  });
  await Promise.all(variations);
})().then(common.mustCall());


{
  const ecPublic = crypto.createPublicKey(
    fixtures.readKey('ec_p256_public.pem'));
  const ecPrivate = crypto.createPrivateKey(
    fixtures.readKey('ec_p256_private.pem'));

fork icon0
star icon0
watch icon0