title: Encrypt and Decrypt with RSA OAEP
body: <p>I'm using Web Crypto, more specifically these examples: <a href="https://github.com/diafygi/webcrypto-examples/#rsa-oaep" rel="nofollow noreferrer">https://github.com/diafygi/webcrypto-examples/#rsa-oaep</a></p>
  
  <p>My main goal is to encrypt a string with my public key and decrypt it with my private key. </p>
  
  <p>The public key encryption works well but when I try to decrypt the encrypted string with the private key, it returns the following error: <code>OperationError</code> and a empty string as well.</p>
  
  <p>I'm using the following functions:</p>
  
  <pre><code>function encryptDataWithPublicKey(data, key) {
      data = stringToArrayBuffer(data);
      return window.crypto.subtle.encrypt(
      {
          name: "RSA-OAEP",
          //label: Uint8Array([...]) //optional
      },
      key, //from generateKey or importKey above
      data //ArrayBuffer of data you want to encrypt
  );
  }
  
  
  function decryptDataWithPrivateKey(data, key) {
      data = stringToArrayBuffer(data);
      return window.crypto.subtle.decrypt(
          {
              name: "RSA-OAEP",
              //label: Uint8Array([...]) //optional
          },
          key, //from generateKey or importKey above
          data //ArrayBuffer of data you want to encrypt
      );
  }
  
  function stringToArrayBuffer(str){
      var buf = new ArrayBuffer(str.length);
      var bufView = new Uint8Array(buf);
      for (var i=0, strLen=str.length; i&lt;strLen; i++) {
          bufView[i] = str.charCodeAt(i);
      }
      return buf;
  }
  </code></pre>
  
  <p><strong>UPDATE</strong></p>
  
  <pre><code>var data = "example";
  encryptDataWithPublicKey(data, publicKey).then((result) =&gt; {
      var rdata = arrayBufferToString(result);
      return decryptDataWithPrivateKey(rdata, privateKey).then((result) =&gt; {
          var result = arrayBufferToString(result);
      });
  });
  
  function arrayBufferToString(str){
      var byteArray = new Uint8Array(str);
      var byteString = '';
      for(var i=0; i &lt; byteArray.byteLength; i++) {
          byteString += String.fromCodePoint(byteArray[i]);
      }
      return byteString;
  }
  </code></pre>