admin管理员组文章数量:1433532
I was wondering how to encrypt and decrypt a video with WebCrypto API using AES and a custom key. I have only found this code and only indicates how to encrypt the video but not how to decrypt it, also uses a random key. Thank you in advance.
function processFile(evt) {
var file = evt.target.files[0],
reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result,
iv = crypto.getRandomValues(new Uint8Array(16));
crypto.subtle.generateKey({ 'name': 'AES-CBC', 'length': 256 }, false, ['encrypt', 'decrypt'])
.then(key => crypto.subtle.encrypt({ 'name': 'AES-CBC', iv }, key, data) )
.then(encrypted => {
console.log(encrypted);
alert('The encrypted data is ' + encrypted.byteLength + ' bytes long'); // encrypted is an ArrayBuffer
})
.catch(console.error);
}
reader.readAsArrayBuffer(file);
}
I was wondering how to encrypt and decrypt a video with WebCrypto API using AES and a custom key. I have only found this code and only indicates how to encrypt the video but not how to decrypt it, also uses a random key. Thank you in advance.
function processFile(evt) {
var file = evt.target.files[0],
reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result,
iv = crypto.getRandomValues(new Uint8Array(16));
crypto.subtle.generateKey({ 'name': 'AES-CBC', 'length': 256 }, false, ['encrypt', 'decrypt'])
.then(key => crypto.subtle.encrypt({ 'name': 'AES-CBC', iv }, key, data) )
.then(encrypted => {
console.log(encrypted);
alert('The encrypted data is ' + encrypted.byteLength + ' bytes long'); // encrypted is an ArrayBuffer
})
.catch(console.error);
}
reader.readAsArrayBuffer(file);
}
Share
Improve this question
asked May 24, 2018 at 14:47
asiertaasierta
3176 silver badges16 bronze badges
2 Answers
Reset to default 2You will find plete examples of how to generate keys, import keys, encrypt and decrypt using AES-GCM here : https://github./diafygi/webcrypto-examples/blob/master/README.md#aes-gcm
You should use GCM as it is an authenticated mode of encryption. There is no stream interface for WebCrypto so you will have to process in chunks, otherwise it’s very straight forward.
You likely want to use ECDH to exchange the AES key. That same page has examples for that as well.
here's a demo that decrypts and plays HLS video using aes-256-cbc:
https://kaizhu256.github.io/node-demo-hls-encrypted/index.html
it was acplished by hacking the ajax-call in hls.js (https://github./video-dev/hls.js/blob/v0.8.9/dist/hls.js) to decrypt the xhr.response before passing it to video-playback:
--- assets.hls.v0.8.9.js 2018-08-04 03:59:42.000000000 +0700
+++ assets.hls.v0.8.9.crypto.js 2018-08-04 03:59:42.000000000 +0700
@@ -1,3 +1,97 @@
+var local;
+(function () {
+ (function () {
+ local = local || {};
+ local.base64ToBuffer = function (b64, mode) {
+ /*
+ * this function will convert b64 to Uint8Array
+ * https://gist.github./wang-bin/7332335
+ */
+ /*globals Uint8Array*/
+ var bff, byte, chr, ii, jj, map64, mod4;
+ b64 = b64 || '';
+ bff = new Uint8Array(b64.length); // 3/4
+ byte = 0;
+ jj = 0;
+ map64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
+ mod4 = 0;
+ for (ii = 0; ii < b64.length; ii += 1) {
+ chr = map64.indexOf(b64[ii]);
+ if (chr >= 0) {
+ mod4 %= 4;
+ if (mod4 === 0) {
+ byte = chr;
+ } else {
+ byte = byte * 64 + chr;
+ bff[jj] = 255 & (byte >> ((-2 * (mod4 + 1)) & 6));
+ jj += 1;
+ }
+ mod4 += 1;
+ }
+ }
+ // optimization - create resized-view of bff
+ bff = bff.subarray(0, jj);
+ // mode !== 'string'
+ if (mode !== 'string') {
+ return bff;
+ }
+ // mode === 'string' - browser js-env
+ if (typeof window === 'object' && window && typeof window.TextDecoder === 'function') {
+ return new window.TextDecoder().decode(bff);
+ }
+ // mode === 'string' - node js-env
+ Object.setPrototypeOf(bff, Buffer.prototype);
+ return String(bff);
+ };
+ local.cryptoAes256CbcByteDecrypt = function (key, data, onError, mode) {
+ /*
+ * this function will aes-256-cbc decrypt with the hex-key, Uint8Array data
+ * example usage:
+ key = '0000000000000000000000000000000000000000000000000000000000000000';
+ local.cryptoAes256CbcByteEncrypt(key, new Uint8Array([1,2,3]), function (error, data) {
+ console.assert(!error, error);
+ local.cryptoAes256CbcByteDecrypt(key, data, console.log);
+ });
+ */
+ /*globals Uint8Array*/
+ var cipher, crypto, ii, iv, tmp;
+ // init key
+ tmp = key;
+ key = new Uint8Array(32);
+ for (ii = 0; ii < key.length; ii += 2) {
+ key[ii] = parseInt(tmp.slice(2 * ii, 2 * ii + 2), 16);
+ }
+ // base64
+ if (mode === 'base64') {
+ data = local.base64ToBuffer(data);
+ }
+ if (!(data instanceof Uint8Array)) {
+ data = new Uint8Array(data);
+ }
+ // init iv
+ iv = data.subarray(0, 16);
+ // optimization - create resized-view of data
+ data = data.subarray(16);
+ crypto = typeof window === 'object' && window.crypto;
+ /* istanbul ignore next */
+ if (!(crypto && crypto.subtle && typeof crypto.subtle.importKey === 'function')) {
+ setTimeout(function () {
+ crypto = require('crypto');
+ cipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
+ onError(null, Buffer.concat([cipher.update(data), cipher.final()]));
+ });
+ return;
+ }
+ crypto.subtle.importKey('raw', key, {
+ name: 'AES-CBC'
+ }, false, ['decrypt']).then(function (key) {
+ crypto.subtle.decrypt({ iv: iv, name: 'AES-CBC' }, key, data).then(function (data) {
+ onError(null, new Uint8Array(data));
+ }).catch(onError);
+ }).catch(onError);
+ };
+ }());
+}());
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
@@ -10919,6 +11013,22 @@
}
stats.loaded = stats.total = len;
var response = { url: xhr.responseURL, data: data };
+ if (data && window.modeMediaEncrypted && window.mediaEncryptedKey) {
+ var self = this;
+ local.cryptoAes256CbcByteDecrypt(
+ window.mediaEncryptedKey,
+ data,
+ function (error, data) {
+ response.data = typeof xhr.response === 'string'
+ ? new TextDecoder().decode(data)
+ : data;
+ stats.loaded = stats.total = data.byteLength;
+ self.callbacks.onSuccess(response, stats, context, xhr);
+ },
+ typeof xhr.response === 'string' && 'base64'
+ );
+ return;
+ }
this.callbacks.onSuccess(response, stats, context, xhr);
} else {
// if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
本文标签: javascriptEncrypt and decrypt a video with WebCrypto API using AES and a custom keyStack Overflow
版权声明:本文标题:javascript - Encrypt and decrypt a video with WebCrypto API using AES and a custom key - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745616297a2666421.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论