Using NodeJS v16/v17, I am trying to encrypt a data with Crypto.publicEncrypt() using a certificate public key(pem). Code snippet is added below:
const pkey = '-----BEGIN CERTIFICATE-----
<Encoding>
-----END CERTIFICATE-----'
const pubPemKey = crypto.createPublicKey(pkey)
const pubPemKeyStr = pubPemKey.export({ type: 'spki', format: 'pem' })
console.log(pubPemKeyStr)
const encryptedData = crypto.publicEncrypt(pubPemKeyStr,
Buffer.from ('test'))
On executing, am getting below error:
node:internal/crypto/cipher:79
return method(data, format, type, passphrase, buffer, padding, oaepHash,
^
Error: error:0608B096:digital envelope routines:EVP_PKEY_encrypt_init:operation not supported for this
keytype
at Object.publicEncrypt (node:internal/crypto/cipher:79:12)
at Object.<anonymous> (/home/jdoodle.js:28:30)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47 {
library: 'digital envelope routines',
function: 'EVP_PKEY_encrypt_init',
reason: 'operation not supported for this keytype',
code: 'ERR_OSSL_EVP_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE'
}
I have tried passing the key as a keyobject also but not successful. like : const encryptedKey = crypto.publicEncrypt({ key: pkey, padding: crypto.constants.RSA_PKCS1_PADDING }, Buffer.from(plainText))
Please provide input that can help to resolve this issue ...
Thanks in advance Sree