kevin parra
kevin parra

Reputation: 436

Encrypt something using SubtleCrypto and then decrypt it using crypto module

Currently I have a request to change our client code from using nodejs crypto module to SubtleCrypto web API. The problem is, I am encrypting something using SubtleCrypto and asymmetric encryption (using public and private), but when I send the encrypted data to the server (which is using crypto module and I can't change it), I got an error like this:

Error:02000079:rsa routines::oaep decoding error

How can I encrypt something using subtle.encrypt method and decrypt it using crypto.privateDecrypt method?

My encryption code looks like this:

const encryptedArrayBuffer = await webcryptoAPI.subtle.encrypt(
    {
      name: 'RSA-OAEP',
    },
    key,
    encoded
  );

I expected the decryption works, but it looks like a compatibility problem between the two libraries.

This is the code I have on the client side (Next app). I don't have access to the BE server but I know they use crypto.privateDecrypt

const ASYMMETRIC_ALGORITHM = 'RSA-OAEP';
const ENCODING = 'base64';

async function importAsymmetricPublicKey(secretKey) {
  try {
    const publicKeyPEM = secretKey
      .replace(/-----BEGIN PUBLIC KEY-----/, '')
      .replace(/-----END PUBLIC KEY-----/, '');

    const publicKeyBase64 = publicKeyPEM.replace(/\r\n|\n|\r/g, '');

    return await webcryptoAPI.subtle.importKey(
      'spki',
      Buffer.from(publicKeyBase64, ENCODING),
      { name: ASYMMETRIC_ALGORITHM, hash: 'SHA-256', modulusLength: 4096 },
      true,
      ['encrypt']
    );
  } catch (error) {
    console.log('[importAsymmetricPublicKey]: ', error);
  }
}

async function asymmetricEncryptStringKey(publicKey, generatedKey) {
  const key = await importAsymmetricPublicKey(publicKey);


  let encoded = encodeMessage(generatedKey);
  const encryptedArrayBuffer = await webcryptoAPI.subtle.encrypt(
    {
      name: ASYMMETRIC_ALGORITHM,
    },
    key,
    encoded
  );

  return Buffer.from(encryptedArrayBuffer);
}

Upvotes: 0

Views: 1189

Answers (1)

kevin parra
kevin parra

Reputation: 436

The problem with my current approach was I was using the wrong hash type. You have to use SHA1 as @Topaco mentioned.

Upvotes: 0

Related Questions