Ask Your Question
0

How can I use Web Crypto API to bring in a PEM public key?

asked 2023-07-08 21:10:04 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-07-08 21:38:02 +0000

qstack gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-08 21:10:04 +0000

Seen: 12 times

Last updated: Jul 08 '23