encrypt method

Encrypts buffer's data using the algorithm and key parameters.

IE11

 

Syntax

var retVal = SubtleCrypto.encrypt(algorithm, key, buffer);

Parameters

algorithm [in]

Type: any

A valid algorithm object.

key [in]

Type: Key

A valid Key object.

buffer [in, optional]

Type: ArrayBufferView

An ArrayBufferView object containing the data to encrypt. If this parameter is specified, the returned operation will immediately complete and return with the encrypted data. Otherwise, the caller is expected to perform the following tasks:

  1. Provide data through any number of calls to the process method of the CryptoOperation object returned by this (encrypt) method.
  2. Call the finish method (on this same CryptoOperation object) when done entering data via the process method.

Once the above two steps are completed, the operation will be completed and the encrypted data returned.

Return value

Type: CryptoOperation

A CryptoOperation object that can encrypt data (see below example).

Remarks

The encrypt method supports the following cryptographic algorithms:

  • AES-CBC
  • AES-GCM
  • RSAES-PKCS1-v1_5
  • RSA-OAEP

Examples

Example 1


<!DOCTYPE html>

<html>
<head>
  <title>encrypt</title>
</head>

<body>
  <h1>encrypt Method</h1>
  <p>
    Open <a href="http://msdn.microsoft.com/en-us/library/ie/gg589512(v=vs.85).aspx">F12 Tools</a> (press F12) to see the
    results of this demo in the <a href="http://msdn.microsoft.com/en-us/library/ie/dn255006(v=vs.85).aspx">Console</a>.
  </p>
  <script>
    "use strict;"

    var pubKey;
    var privKey;
    var data = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); // Data to encrypt.
    var encryptedData;
    var decryptedData;
    var crypto = window.msCrypto;

    if (crypto.subtle) {
      var genOp = crypto.subtle.generateKey({
        name: "RSAES-PKCS1-v1_5",
        modulusLength: 2048,
        publicExponent: new Uint8Array([0x01, 0x00, 0x01])
      }, true, ["encrypt", "decrypt"]);


      genOp.onerror = function (e) { console.log("genOp.onerror event handler fired."); }
      genOp.oncomplete = function (e) {
        pubKey = e.target.result.publicKey;
        privKey = e.target.result.privateKey;

        if (pubKey && privKey) {
          console.log("generateKey RSAES-PKCS1-v1_5: PASS");
        }
        else {
          console.error("generateKey RSAES-PKCS1-v1_5: FAIL");
        }

        var encryptOp = crypto.subtle.encrypt({ name: "RSAES-PKCS1-v1_5" }, pubKey, data);
        encryptOp.onerror = function (evt) { console.error("encryptOp.onerror event handler fired."); }

        encryptOp.oncomplete = function (evt) {
          encryptedData = new Uint8Array(evt.target.result);

          if (encryptedData != data) {
            console.log("Encrypted RSAES-PKCS1-v1_5: PASS");
          }
          else {
            console.error("Encrypted RSAES-PKCS1-v1_5: FAIL");
          }

          var decryptOp = crypto.subtle.decrypt({ name: "RSAES-PKCS1-v1_5" }, privKey, encryptedData);
          decryptOp.onerror = function (evt) {
            console.log("decryptOp.onerror event handler fired.");
          } // decryptOp.onerror
          decryptOp.oncomplete = function (evt) {
            decryptedData = new Uint8Array(evt.target.result);

            var bEqual = false;
            for (var i = 0, j = 0; (i < decryptedData.length && j < data.length) ; i++, j++) {
              if (data[j] == decryptedData[i])
                bEqual = true;
              else
                bEqual = false;
            } // for

            if (bEqual) {
              console.log("Decrypt of RSAES-PKCS1-v1_5: PASS");
            }
            else {
              console.error("Decrypt of RSAES-PKCS1-v1_5: FAIL");
            } // if-else
          }; // decryptOp.oncomplete
        }; // encryptOp.oncomplete
      }; // genOp.oncomplete
    } // if (crypto.subtle)
    else {
      document.getElementsByTagName('body')[0].innerHTML = "<h2>Web Cryptography API not supported - please update your browser.</h2>";
    } // if-else
  </script>
</body>
</html>

Example 2


<!DOCTYPE html>

<html>
<head>
  <title>encrypt</title>
</head>

<body>
  <h1>encrypt Method</h1>
  <p>
    Open <a href="http://msdn.microsoft.com/en-us/library/ie/gg589512(v=vs.85).aspx">F12 Tools</a> (press F12) to see the
    results of this demo in the <a href="http://msdn.microsoft.com/en-us/library/ie/dn255006(v=vs.85).aspx">Console</a>.
  </p>
  <script>
    "use strict";

    var globals = { // Contains all global variables.
      password: new Uint8Array([8, 6, 7, 5, 3, 0, 9]), // Password.
      data: new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) // Data to encrypt.
    };

    var crypto = window.msCrypto;

    if (crypto.subtle) {
      encryptData(globals.password, globals.data);
    }
    else {
      document.getElementsByTagName('body')[0].innerHTML = "<h2>Web Cryptography API not supported - please update your browser.</h2>";
    } // if-else

    function encryptData(password, data) {
      console.log("Initial data: " + Array.prototype.join.call(data, " "));
      var digestOp = crypto.subtle.digest({ name: "SHA-256" }, password);

      digestOp.oncomplete = function (evt1) {
        var digestHash = evt1.target.result;
        console.log("Digest hash created.");

        var importKeyOp = crypto.subtle.importKey("raw", digestHash, { name: "AES-CBC" }, true, ['encrypt']);

        importKeyOp.oncomplete = function (evt2) {
          console.log("Digest key created.");

          var digestKey = evt2.target.result;
          var salt = crypto.getRandomValues(new Uint8Array(16));
          var aesAlgorithmEncrypt = {
            name: "AES-CBC",
            iv: salt
          };

          var encryptOp = crypto.subtle.encrypt(aesAlgorithmEncrypt, digestKey, data);

          encryptOp.oncomplete = function (evt3) {
            var ciphertextArrayBuffer = evt3.target.result; // In the cryptographic world, there's plaintext and ciphertext.
            console.log("Encrypted text: " + (new DataView(ciphertextArrayBuffer)).getUint8(0));
          }; // encryptOp.oncomplete

          encryptOp.onerror = function () {
            console.error("Encryption failed using new API.");

            aesAlgorithmEncrypt = {
              name: "AES-CBC",
              param: { iv: salt }
            };

            var encryptOp2 = crypto.subtle.encrypt(aesAlgorithmEncrypt, digestKey, data);

            encryptOp2.oncomplete = function (evt4) {
              var cipherTextArrayBuffer = evt4.target.result;
              console.log("Encrypted text:" + (new DataView(ciphertextArrayBuffer)).getUint8(0));
            }; // encryptOp2.oncomplete

            encryptOp2.onerror = function () { console.error("Encryption failed using old API."); };
          }; // encryptOp.onerror
        }; // importKeyOp.oncomplete

        importKeyOp.onerror = function () { console.error("Digest key failed."); };
      }; // digestOp.oncomplete

      digestOp.onerror = function () { console.error("Digest hash failed."); };
    } // encryptData
  </script>
</body>
</html>

See also

SubtleCrypto

 

 

Show:
© 2014 Microsoft