-
Notifications
You must be signed in to change notification settings - Fork 2
/
decrypt.js
228 lines (193 loc) · 5.31 KB
/
decrypt.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
var global = window;
// Unibabel
(function () {
'use strict';
function utf8ToBinaryString(str) {
var escstr = encodeURIComponent(str);
// replaces any uri escape sequence, such as %0A,
// with binary escape, such as 0x0A
var binstr = escstr.replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode(parseInt(p1, 16));
});
return binstr;
}
function utf8ToBuffer(str) {
var binstr = utf8ToBinaryString(str);
var buf = binaryStringToBuffer(binstr);
return buf;
}
function utf8ToBase64(str) {
var binstr = utf8ToBinaryString(str);
return btoa(binstr);
}
function binaryStringToUtf8(binstr) {
var escstr = binstr.replace(/(.)/g, function (m, p) {
var code = p.charCodeAt(0).toString(16).toUpperCase();
if (code.length < 2) {
code = '0' + code;
}
return '%' + code;
});
return decodeURIComponent(escstr);
}
function bufferToUtf8(buf) {
var binstr = bufferToBinaryString(buf);
return binaryStringToUtf8(binstr);
}
function base64ToUtf8(b64) {
var binstr = atob(b64);
return binaryStringToUtf8(binstr);
}
function bufferToBinaryString(buf) {
var binstr = Array.prototype.map.call(buf, function (ch) {
return String.fromCharCode(ch);
}).join('');
return binstr;
}
function bufferToBase64(arr) {
var binstr = bufferToBinaryString(arr);
return btoa(binstr);
}
function binaryStringToBuffer(binstr) {
var buf;
if ('undefined' !== typeof Uint8Array) {
buf = new Uint8Array(binstr.length);
} else {
buf = [];
}
Array.prototype.forEach.call(binstr, function (ch, i) {
buf[i] = ch.charCodeAt(0);
});
return buf;
}
function base64ToBuffer(base64) {
var binstr = atob(base64);
var buf = binaryStringToBuffer(binstr);
return buf;
}
window.Unibabel = {
utf8ToBinaryString: utf8ToBinaryString
, utf8ToBuffer: utf8ToBuffer
, utf8ToBase64: utf8ToBase64
, binaryStringToUtf8: binaryStringToUtf8
, bufferToUtf8: bufferToUtf8
, base64ToUtf8: base64ToUtf8
, bufferToBinaryString: bufferToBinaryString
, bufferToBase64: bufferToBase64
, binaryStringToBuffer: binaryStringToBuffer
, base64ToBuffer: base64ToBuffer
// compat
, strToUtf8Arr: utf8ToBuffer
, utf8ArrToStr: bufferToUtf8
, arrToBase64: bufferToBase64
, base64ToArr: base64ToBuffer
};
}());
// Takes a Pojo, returns cypher text.
function encrypt (password, dataObj) {
var salt = generateSalt()
return keyFromPassword(password, salt)
.then(function (passwordDerivedKey) {
return encryptWithKey(passwordDerivedKey, dataObj)
})
.then(function (payload) {
payload.salt = salt
return JSON.stringify(payload)
})
}
function encryptWithKey (key, dataObj) {
var data = JSON.stringify(dataObj)
var dataBuffer = Unibabel.utf8ToBuffer(data)
var vector = global.crypto.getRandomValues(new Uint8Array(16))
return global.crypto.subtle.encrypt({
name: 'AES-GCM',
iv: vector,
}, key, dataBuffer).then(function (buf) {
var buffer = new Uint8Array(buf)
var vectorStr = Unibabel.bufferToBase64(vector)
var vaultStr = Unibabel.bufferToBase64(buffer)
return {
data: vaultStr,
iv: vectorStr,
}
})
}
// Takes encrypted text, returns the restored Pojo.
function decrypt (password, text) {
const payload = JSON.parse(text)
const salt = payload.salt
return keyFromPassword(password, salt)
.then(function (key) {
return decryptWithKey(key, payload)
})
}
function decryptWithKey (key, payload) {
const encryptedData = Unibabel.base64ToBuffer(payload.data)
const vector = Unibabel.base64ToBuffer(payload.iv)
return crypto.subtle.decrypt({name: 'AES-GCM', iv: vector}, key, encryptedData)
.then(function (result) {
const decryptedData = new Uint8Array(result)
const decryptedStr = Unibabel.bufferToUtf8(decryptedData)
const decryptedObj = JSON.parse(decryptedStr)
return decryptedObj
})
.catch(function (reason) {
throw new Error('Incorrect password')
})
}
function keyFromPassword (password, salt) {
var passBuffer = Unibabel.utf8ToBuffer(password)
var saltBuffer = Unibabel.base64ToBuffer(salt)
return global.crypto.subtle.importKey(
'raw',
passBuffer,
{ name: 'PBKDF2' },
false,
['deriveBits', 'deriveKey']
).then(function (key) {
return global.crypto.subtle.deriveKey(
{ name: 'PBKDF2',
salt: saltBuffer,
iterations: 10000,
hash: 'SHA-256',
},
key,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt']
)
})
}
function serializeBufferFromStorage (str) {
var stripStr = (str.slice(0, 2) === '0x') ? str.slice(2) : str
var buf = new Uint8Array(stripStr.length / 2)
for (var i = 0; i < stripStr.length; i += 2) {
var seg = stripStr.substr(i, 2)
buf[i / 2] = parseInt(seg, 16)
}
return buf
}
// Should return a string, ready for storage, in hex format.
function serializeBufferForStorage (buffer) {
var result = '0x'
var len = buffer.length || buffer.byteLength
for (var i = 0; i < len; i++) {
result += unprefixedHex(buffer[i])
}
return result
}
function unprefixedHex (num) {
var hex = num.toString(16)
while (hex.length < 2) {
hex = '0' + hex
}
return hex
}
function generateSalt (byteCount = 32) {
var view = new Uint8Array(byteCount)
global.crypto.getRandomValues(view)
var b64encoded = btoa(String.fromCharCode.apply(null, view))
return b64encoded
}
// decrypt
// decrypt(password, vault)