-
Notifications
You must be signed in to change notification settings - Fork 1
/
generate.html
78 lines (70 loc) · 2.5 KB
/
generate.html
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
<html>
<head>
<style>
input, textarea {
display: block;
width: 100%;
}
#private {background: palevioletred;}
#public {background: lightgreen;}
</style>
</head>
<body>
<input type="button" id="generate" value="generate keypair">
This is your PUBLIC key. Send it to sender and ask them to use <a href="encrypt.html">encrypt.html</a> to encrypt a message for you.
<textarea id="public" readonly onfocus="this.select();"></textarea>
This is your <b>PRIVATE</b> key. Do <b>not</b> send it to anyone! Instead, save it and use <a href="decrypt.html">decrypt.html</a> to decrypt an encrypted message.
<textarea id="private" readonly onfocus="this.select();"></textarea>
Note: These two keys form a pair: messages encrypted with above public key can be decrypted <b>only</b> with above private key.
<script>
function $(s){return document.querySelector(s)};
function bin2text(bin){return btoa(String.fromCharCode(...new Uint8Array(bin)));}
function autosize(textarea){textarea.style.height = "";textarea.style.height = textarea.scrollHeight +3 + "px"};
$('#generate').onclick=function(){
window.crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 1024, //can be 1024, 2048, or 4096
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: {name: "SHA-256"}, //can be "SHA-1", "SHA-256", "SHA-384", or "SHA-512"
},
true, //whether the key is extractable (i.e. can be used in exportKey)
["encrypt", "decrypt"] //must be ["encrypt", "decrypt"] or ["wrapKey", "unwrapKey"]
)
.then(function(key){
//returns a keypair object
window.crypto.subtle.exportKey(
"pkcs8", //can be "jwk" (public or private), "spki" (public only), or "pkcs8" (private only)
key.privateKey //can be a publicKey or privateKey, as long as extractable was true
)
.then(function(keydata){
//returns the exported key data
console.log('private',keydata);
// $('#private').value=keydata.n;
$('#private').value=bin2text(keydata);
autosize($('#private'));
})
.catch(function(err){
console.error(err);
});
window.crypto.subtle.exportKey(
"spki", //can be "jwk" (public or private), "spki" (public only), or "pkcs8" (private only)
key.publicKey //can be a publicKey or privateKey, as long as extractable was true
)
.then(function(keydata){
//returns the exported key data
console.log('public',keydata);
$('#public').value=bin2text(keydata);
autosize($('#public'));
})
.catch(function(err){
console.error(err);
});
})
.catch(function(err){
console.error(err);
});
}
</script>
</body>
</html>