-
Notifications
You must be signed in to change notification settings - Fork 11
/
common.js
90 lines (78 loc) · 2.25 KB
/
common.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
class MozCommon {
constructor() {
}
ord(c){
/* return an ordinal for a character
*/
return c.charCodeAt(0);
}
chr(c){
/* return a character for a given ordinal
*/
return String.fromCharCode(c);
}
toUrlBase64(data) {
/* Convert a binary array into a URL safe base64 string
*/
return btoa(data)
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=/g, "")
}
fromUrlBase64(data) {
/* return a binary array from a URL safe base64 string
*/
return atob((data + "====".substr(data.length % 4))
.replace(/\-/g, "+")
.replace(/\_/g, "/"));
}
strToArray(str) {
/* convert a string into a ByteArray
*
* TextEncoders would be faster, but have a habit of altering
* byte order
*/
let split = str.split("");
let reply = new Uint8Array(split.length);
for (let i in split) {
reply[i] = this.ord(split[i]);
}
return reply;
}
arrayToStr(array) {
/* convert a ByteArray into a string
*/
return String.fromCharCode.apply(null, new Uint8Array(array));
}
rawToJWK(raw, ops) {
/* convert a URL safe base64 raw key to jwk format
*/
if (typeof(raw) == "string") {
raw = this.strToArray(this.fromUrlBase64(raw));
}
// Raw is supposed to start with a 0x04, but some libraries don't. sigh.
if (raw.length == 65 && raw[0] != 4) {
throw new Error('ERR_PUB_KEY');
}
raw = raw.slice(-64);
let x = this.toUrlBase64(this.arrayToStr(raw.slice(0,32)));
let y = this.toUrlBase64(this.arrayToSTr(raw.slice(32,64)));
// Convert to a JWK and import it.
let jwk = {
crv: "P-256",
ext: true,
key_ops: ops,
kty: "EC",
x: x,
y, y
};
return jwk
}
JWKToRaw(jwk) {
/* Convert a JWK object to a "raw" URL Safe base64 string
*/
let xv = this.fromUrlBase64(jwk.x);
let yv = this.fromUrlBase64(jwk.y);
return this.toUrlBase64("\x04" + xv + yv);
}
}