invisal / god_crypto

Pure Javascript/Typescript Crypto Implementation for Deno. AES, RSA, HMAC, and TOTP
MIT License
93 stars 16 forks source link

Use promises to reduce errors #41

Closed HPaulson closed 1 year ago

HPaulson commented 2 years ago

In functions such as RSA.parseKey & RSA.importKey, it's likely a smarter idea to implement Promises so developers can catch errors more effectively. Currently, passing an invalid key into one of these functions returns a type error from the following function:

export function rsa_import_key(
  key: string | JSONWebKey,
  format: RSAImportKeyFormat,
): RSAKeyParams {
  const finalFormat = format === "auto" ? detect_format(key) : format;

  if (finalFormat === "jwk") return rsa_import_jwk(key as JSONWebKey);
  if (finalFormat === "pem") return rsa_import_pem(key as string);

  throw new TypeError("Unsupported key format");
}

This is bad practice, especially if the developer is passing on a user-provided public key. A better implementation would be to use a Promise and reject if the key format is invalid, which would then allow the end developer to handle such error and pass it off to the user with .catch().