· 7 years ago · Jun 12, 2018, 10:34 PM
1/*jslint
2 browser: true,
3 devel: true
4*/
5(function () {
6 'use strict';
7 var algoEncrypt, plainText, secretKey;
8 function strToArrayBuffer(str) {
9 var buf, bufView, ii, strLen;
10 buf = new window.ArrayBuffer(str.length * 2);
11 bufView = new window.Uint16Array(buf);
12 for (ii = 0, strLen = str.length; ii < strLen; ii += 1) {
13 bufView[ii] = str.charCodeAt(ii);
14 }
15 return buf;
16 }
17 function arrayBufferToString(buf) {
18 return String.fromCharCode.apply(null, new window.Uint16Array(buf));
19 }
20 algoEncrypt = {
21 name: 'AES-CBC',
22 iv: window.crypto.getRandomValues(new window.Uint8Array(16)),
23 tagLength: 128
24 };
25 plainText = 'This is some plaintext';
26 console.log('Plain Text: ' + plainText);
27 window.crypto.subtle.generateKey({
28 name: 'AES-CBC',
29 length: 256
30 }, false, [
31 'encrypt',
32 'decrypt'
33 ]).then(function (key) {
34 secretKey = key;
35 return window.crypto.subtle.encrypt(algoEncrypt, key, strToArrayBuffer(plainText));
36 }).then(function (cipherText) {
37 console.log('Cipher Text: ' + arrayBufferToString(cipherText));
38 return window.crypto.subtle.decrypt(algoEncrypt, secretKey, cipherText);
39 }).then(function (plainText) {
40 console.log('Plain Text: ' + arrayBufferToString(plainText));
41 }).catch(function (err) {
42 console.log('Error: ' + err.message);
43 });
44}());