-
Notifications
You must be signed in to change notification settings - Fork 0
/
web-crypto-sign.js
63 lines (58 loc) · 1.91 KB
/
web-crypto-sign.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
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf));
}
function str2ab(str) {
const buf = new ArrayBuffer(str.length);
const bufView = new Uint8Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
async function createKey()
{
let keyPair = await window.crypto.subtle.generateKey(
{
name: "ECDSA",
namedCurve: "P-384"
},
true,
["sign", "verify"]
);
const exported = await window.crypto.subtle.exportKey( "pkcs8", keyPair.privateKey);
const exportedAsString = ab2str(exported);
const exportedAsBase64 = window.btoa(exportedAsString);
console.log (JSON.stringify(exportedAsBase64, null, " "))
document.getElementById('password').value = exportedAsBase64;
document.getElementById('form').style.display ='block';
}
async function sign()
{
const pemContents = document.getElementById('password').value
// base64 decode the string to get the binary data
const binaryDerString = window.atob(pemContents);
// convert from a binary string to an ArrayBuffer
const binaryDer = str2ab(binaryDerString);
const privateKey = await window.crypto.subtle.importKey(
"pkcs8",
binaryDer,
{
name: "ECDSA",
namedCurve: "P-384"
},
true,
["sign"]
);
const textToSign = document.getElementById('textToSign').value
let encoded = new TextEncoder().encode(textToSign);
let signature = await window.crypto.subtle.sign(
{
name: "ECDSA",
hash: {name: "SHA-384"},
},
privateKey,
encoded
);
signatureArray = new Uint8Array(signature)
document.getElementById('signature').innerHTML = btoa(String.fromCharCode.apply(null,signatureArray))
}