0

I'm trying to use crypto module in js and subtleCrypto to encode a string with a public key. I want to give the public key as a string but my code in subtle crypto throws error that "parameter 2 is not of type 'CryptoKey'. here's my code:

const handleEncodeClick = () => {
 const crypto = window.crypto.subtle;
 crypto.encrypt({name: "RSA-OAEP"}, publicKey, new TextEncoder().encode(myMsg))
  .then(encrypted => {
   setEncoded(new Uint8Array(encrypted));
  })
  .catch(err => {
   console.log(err);
  });
 };
isherwood
  • 58,414
  • 16
  • 114
  • 157
m0j1
  • 4,067
  • 8
  • 31
  • 54
  • As the error message states, the key must be of type `CryptoKey`. For this the key has to be imported with `importKey()`. The details of the import depend on the format/encoding of your key, which you did not specify. Post this info or a test key. – Topaco Jan 12 '23 at 16:46
  • Thanks @Topaco, As I said I want to have the key not imported from a wallet but from a text field, and it seems to be it needs to be converted, but don't know how. – m0j1 Jan 12 '23 at 17:28
  • It is not about importing from a wallet. WebCrypto uses the `CryptoKey` type for keys internally. Therefore **each** key must be converted/imported to this type (using `importKey()`). The import depends on the format and encoding of the key. Without this information, the question cannot be answered, or can only be answered flatly with: Import your key with `importKey()`. – Topaco Jan 12 '23 at 17:52
  • Thanks again @Topaco, Sorry if it was not clear, I'm not very experienced in this field. The key I want to encode my message with is a crypto wallet address (public key) which I want to receive it from the user in a text box. – m0j1 Jan 12 '23 at 18:28
  • Since it seems to be about crypto currencies, the key is probably an EC key not an RSA key. It is not clear what you actually mean by encryption in this context. Have a look at [this link](https://river.com/learn/how-bitcoin-uses-cryptography/) and describe in more detail what you actually want to achieve. – Topaco Jan 12 '23 at 18:50
  • Thanks again @Topaco, What I want to achieve is I want to encrypt a string using another person's public key (in this case address) and make it so that only the other person with his/her private key can decrypt it. – m0j1 Jan 12 '23 at 19:05
  • 1
    *...I want to encrypt a string using another person's public key...* EC (unlike RSA) is not used for *direct* encryption (it is used for signatures and key agreement). You should get more familiar with the subject, currently it looks like what you want is not possible (at least not as easy as you think). A good starting point is the linked post that gives an overview of the role of cryptography in crypto currencies. – Topaco Jan 12 '23 at 19:23

0 Answers0