forked from video-dev/hls.js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
decrypter.js
77 lines (68 loc) · 2.14 KB
/
decrypter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import AESCrypto from './aes-crypto';
import FastAESKey from './fast-aes-key';
import AESDecryptor from './aes-decryptor';
import {ErrorTypes, ErrorDetails} from '../errors';
import {logger} from '../utils/logger';
class Decrypter {
constructor(hls) {
this.hls = hls;
try {
const browserCrypto = window ? window.crypto : crypto;
this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
} catch (e) {}
this.disableWebCrypto = !this.supportsWebCrypto();
}
supportsWebCrypto() {
return this.subtle && window.location.protocol === 'https:';
}
decrypt(data, key, iv, callback) {
if (this.disableWebCrypto && this.hls.config.enableSoftwareAES) {
logger.log('decrypting by JavaScript Implementation');
if (!this.decryptor) {
this.decryptor = new AESDecryptor();
}
this.decryptor.expandKey(key);
callback(this.decryptor.decrypt(data, 0, iv));
}
else {
logger.log('decrypting by WebCrypto API');
const subtle = this.subtle;
if (this.key !== key) {
this.key = key;
this.fastAesKey = new FastAESKey(subtle,key);
}
this.fastAesKey.expandKey().
then((aesKey) => {
// decrypt using web crypto
let crypto = new AESCrypto(subtle,iv);
crypto.decrypt(data, aesKey).
then((result) => {
callback(result);
});
}).
catch ((err) => {
this.onWebCryptoError(err, data, key, iv, callback);
});
}
}
onWebCryptoError(err, data, key, iv, callback) {
let hls = this.hls;
if (hls.config.enableSoftwareAES) {
logger.log('disabling to use WebCrypto API');
this.disableWebCrypto = true;
this.decrypt(data, key, iv, callback);
}
else {
logger.error(`decrypting error : ${err.message}`);
hls.trigger(Event.ERROR, {type : ErrorTypes.MEDIA_ERROR, details : ErrorDetails.FRAG_DECRYPT_ERROR, fatal : true, reason : err.message});
}
}
destroy() {
let decryptor = this.decryptor;
if (decryptor) {
decryptor.destroy();
this.decryptor = undefined;
}
}
}
export default Decrypter;