node/test/parallel/test-crypto-publicDecrypt-fails-first-time.js
James M Snell 761de815c5
test: move crypto related common utilities in common/crypto
Since `common/crypto` already exists, it makes sense to keep
crypto-related utilities there. The only exception being
common.hasCrypto which is needed up front to determine
if tests should be skipped.

Eliminate the redundant check in hasFipsCrypto and just
use crypto.getFips() directly where needed.

PR-URL: https://github.com/nodejs/node/pull/56714
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
2025-01-25 00:58:32 +00:00

46 lines
1.2 KiB
JavaScript

'use strict';
const common = require('../common');
// Test for https://github.com/nodejs/node/issues/40814
if (!common.hasCrypto) {
common.skip('missing crypto');
}
const { hasOpenSSL3 } = require('../common/crypto');
if (!hasOpenSSL3) {
common.skip('only openssl3'); // https://github.com/nodejs/node/pull/42793#issuecomment-1107491901
}
const assert = require('assert');
const crypto = require('crypto');
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-128-ecb',
passphrase: 'abcdef'
}
});
assert.notStrictEqual(privateKey.toString(), '');
const msg = 'The quick brown fox jumps over the lazy dog';
const encryptedString = crypto.privateEncrypt({
key: privateKey,
passphrase: 'abcdef'
}, Buffer.from(msg)).toString('base64');
const decryptedString = crypto.publicDecrypt(publicKey, Buffer.from(encryptedString, 'base64')).toString();
console.log(`Encrypted: ${encryptedString}`);
console.log(`Decrypted: ${decryptedString}`);
assert.notStrictEqual(encryptedString, '');
assert.strictEqual(decryptedString, msg);