Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To import a PEM public key using the Web Crypto API, you can use the following steps:

  1. Convert the PEM key to a binary format (DER or Raw)

    You can convert the PEM key to DER or Raw format using a variety of tools or libraries such as OpenSSL or a JavaScript library. Here is an example of converting a PEM key to DER using OpenSSL:

    openssl rsa -in pubkey.pem -inform PEM -outform DER -pubout -out pubkey.der
    
  2. Use the Web Crypto API to import the binary public key

    To import the binary public key, you can use the crypto.subtle.importKey() method. You need to specify the type of key, the binary data format, and the algorithm used to generate the key. Here is an example of importing a public key in DER format:

    const pubkey = await crypto.subtle.importKey(
     "spki", // The type of key
     pubkey_der, // The binary data format
     {name: "RSA-OAEP", hash: {name: "SHA-256"}}, // The algorithm used to generate the key
     true, // Whether the key is extractable (i.e., can be exported)
     ["encrypt"] // The key's purpose (can be "encrypt", "decrypt", "sign", or "verify")
    );
    

    Note that you can replace "RSA-OAEP" with another algorithm, such as "ECDSA", depending on the type of key you are importing.

Once you have imported the public key, you can use it to encrypt data or verify signatures using the Web Crypto API.