js-keygen/js-keygen.js

53 lines
1.4 KiB
JavaScript
Raw Permalink Normal View History

2018-02-13 16:41:00 +00:00
/* global encodePrivateKey, encodePublicKey */
const extractable = true;
2015-09-03 11:58:00 +00:00
function wrap(text, len) {
2018-02-13 16:41:00 +00:00
const length = len || 72;
let result = "";
for (let i = 0; i < text.length; i += length) {
result += text.slice(i, i + length);
result += "\n";
2015-09-03 11:58:00 +00:00
}
return result;
}
function rsaPrivateKey(key) {
2018-02-13 16:41:00 +00:00
return `-----BEGIN RSA PRIVATE KEY-----\n${key}-----END RSA PRIVATE KEY-----`;
2015-09-03 11:58:00 +00:00
}
2015-09-04 07:13:08 +00:00
function arrayBufferToBase64(buffer) {
2018-02-13 16:41:00 +00:00
let binary = "";
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i += 1) {
2015-09-04 07:13:08 +00:00
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
2015-09-03 11:58:00 +00:00
}
function generateKeyPair(alg, size, name) {
2018-02-13 08:30:29 +00:00
return window.crypto.subtle
.generateKey(
{
name: "RSASSA-PKCS1-v1_5",
2018-02-13 16:41:00 +00:00
modulusLength: 2048, // can be 1024, 2048, or 4096
2018-02-13 08:30:29 +00:00
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
2018-02-13 16:41:00 +00:00
hash: { name: "SHA-1" }, // can be "SHA-1", "SHA-256", "SHA-384", or "SHA-512"
2018-02-13 08:30:29 +00:00
},
extractable,
["sign", "verify"]
)
2018-02-13 08:53:20 +00:00
.then(key => {
2018-02-13 16:41:00 +00:00
const privateKey = window.crypto.subtle
2018-02-13 08:30:29 +00:00
.exportKey("jwk", key.privateKey)
.then(encodePrivateKey)
.then(wrap)
.then(rsaPrivateKey);
2015-09-03 11:58:00 +00:00
2018-02-13 16:41:00 +00:00
const publicKey = window.crypto.subtle.exportKey("jwk", key.publicKey).then(jwk => encodePublicKey(jwk, name));
2018-02-13 08:30:29 +00:00
return Promise.all([privateKey, publicKey]);
});
2015-09-04 07:13:08 +00:00
}
2018-02-13 08:45:06 +00:00
2018-02-13 16:43:03 +00:00
module.exports = { arrayBufferToBase64, generateKeyPair };