UNPKG

pkijs

Version:

Public Key Infrastructure (PKI) is the basis of how identity and key management is performed on the web today. PKIjs is a pure JavaScript library implementing the formats that are used in PKI applications. It is built on WebCrypto and aspires to make it p

295 lines (250 loc) 11.3 kB
<!-- Copyright (c) 2014, GMO GlobalSign All rights reserved. Author 2014, Yury Strozhevsky <www.strozhevsky.com>. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --> <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>How to create new X.509 certificate</title> <script type="text/javascript" src="org/pkijs/common.js"></script> <script type="text/javascript" src="org/pkijs/asn1.js"></script> <script type="text/javascript" src="org/pkijs/x509_schema.js"></script> <script type="text/javascript" src="org/pkijs/x509_simpl.js"></script> <style type="text/css"> * { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; overflow:auto; } html,body { width:100%; max-width:100%; margin:0; padding:0; border-style:none; } body * { font-family:"Trebuchet MS", Arial, Helvetica, sans-serif; } textarea { width:100%; height:300px; resize:none; } div#cert_div { position:relative; display:block; left:50%; width:700px; margin-left:-350px; margin-top:20px; margin-bottom:10px; } </style> <script type="text/javascript"> //********************************************************************************* function formatPEM(pem_string) { /// <summary>Format string in order to have each line with length equal to 63</summary> /// <param name="pem_string">String to format</param> var string_length = pem_string.length; var result_string = ""; for(var i = 0, count = 0; i < string_length; i++, count++) { if(count > 63) { result_string = result_string + "\r\n"; count = 0; } result_string = result_string + pem_string[i]; } return result_string; } //********************************************************************************* function create_new_certificate() { // #region Initial variables var sequence = Promise.resolve(); var cert_simpl = new org.pkijs.simpl.CERT(); var publicKey; var privateKey; // #endregion // #region Get a "crypto" extension var crypto = org.pkijs.getCrypto(); if(typeof crypto == "undefined") { alert("No WebCrypto extension found"); return; } // #endregion // #region Put a static values cert_simpl.serialNumber = new org.pkijs.asn1.INTEGER({ value: 1 }); cert_simpl.issuer.types_and_values.push(new org.pkijs.simpl.ATTR_TYPE_AND_VALUE({ type: "2.5.4.6", // Country name value: new org.pkijs.asn1.PRINTABLESTRING({ value: "RU" }) })); cert_simpl.issuer.types_and_values.push(new org.pkijs.simpl.ATTR_TYPE_AND_VALUE({ type: "2.5.4.3", // Common name value: new org.pkijs.asn1.PRINTABLESTRING({ value: "Test" }) })); cert_simpl.subject.types_and_values.push(new org.pkijs.simpl.ATTR_TYPE_AND_VALUE({ type: "2.5.4.6", // Country name value: new org.pkijs.asn1.PRINTABLESTRING({ value: "RU" }) })); cert_simpl.subject.types_and_values.push(new org.pkijs.simpl.ATTR_TYPE_AND_VALUE({ type: "2.5.4.3", // Common name value: new org.pkijs.asn1.PRINTABLESTRING({ value: "Test" }) })); cert_simpl.notBefore.value = new Date(2013, 01, 01); cert_simpl.notAfter.value = new Date(2016, 01, 01); cert_simpl.extensions = new Array(); // Extensions are not a part of certificate by default, it's an optional array // #region "BasicConstraints" extension var basic_constr = new org.pkijs.simpl.x509.BasicConstraints({ cA: true, pathLenConstraint: 3 }); cert_simpl.extensions.push(new org.pkijs.simpl.EXTENSION({ extnID: "2.5.29.19", critical: false, extnValue: basic_constr.toSchema().toBER(false), parsedValue: basic_constr // Parsed value for well-known extensions })); // #endregion // #region "KeyUsage" extension var bit_array = new ArrayBuffer(1); var bit_view = new Uint8Array(bit_array); bit_view[0] = bit_view[0] | 0x02; // Key usage "cRLSign" flag bit_view[0] = bit_view[0] | 0x04; // Key usage "keyCertSign" flag var key_usage = new org.pkijs.asn1.BITSTRING({ value_hex: bit_array }); cert_simpl.extensions.push(new org.pkijs.simpl.EXTENSION({ extnID: "2.5.29.15", critical: false, extnValue: key_usage.toBER(false), parsedValue: key_usage // Parsed value for well-known extensions })); // #endregion cert_simpl.signatureAlgorithm.algorithm_id = "1.2.840.113549.1.1.5"; // RSA + SHA-1 cert_simpl.signature.algorithm_id = cert_simpl.signatureAlgorithm.algorithm_id; // Must be the same value // #endregion // #region Create a new key pair sequence = sequence.then( function() { return crypto.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), hash: { name: "sha-1" } }, true, ["encrypt", "decrypt", "sign", "verify"]); } ); // #endregion // #region Store new key in an interim variables sequence = sequence.then( function(keyPair) { publicKey = keyPair.publicKey; privateKey = keyPair.privateKey; }, function(error) { alert("Error during key generation: " + error); } ); // #endregion // #region Exporting public key into "subjectPublicKeyInfo" value of certificate sequence = sequence.then( function() { return cert_simpl.subjectPublicKeyInfo.importKey(publicKey); } ); // #endregion // #region Signing final certificate sequence = sequence.then( function() { return cert_simpl.sign(privateKey); }, function(error) { alert("Error during exporting public key: " + error); } ); // #endregion // #region Encode and store certificate sequence = sequence.then( function() { var cert_simpl_encoded = cert_simpl.toSchema(true).toBER(false); var cert_simpl_string = String.fromCharCode.apply(null, new Uint8Array(cert_simpl_encoded)); var result_string = "-----BEGIN CERTIFICATE-----\r\n"; result_string = result_string + formatPEM(window.btoa(cert_simpl_string)); result_string = result_string + "\r\n-----END CERTIFICATE-----\r\n"; document.getElementById("new_certificate").innerHTML = result_string; alert("Certificate created successfully!"); }, function(error) { alert("Error during signing: " + error); } ); // #endregion // #region Exporting private key sequence = sequence.then( function() { return crypto.exportKey("pkcs8", privateKey); } ); // #endregion sequence.then( function(result) { var private_key_string = String.fromCharCode.apply(null, new Uint8Array(result)); var result_string = document.getElementById("new_certificate").innerHTML; result_string = result_string + "\r\n-----BEGIN PRIVATE KEY-----\r\n"; result_string = result_string + formatPEM(window.btoa(private_key_string)); result_string = result_string + "\r\n-----END PRIVATE KEY-----"; document.getElementById("new_certificate").innerHTML = result_string; alert("Private key exported successfully!"); }, function(error) { alert("Error during exporting of private key: " + error); } ); } //********************************************************************************* </script> </head> <body onload="create_new_certificate()"> <div id="cert_div"> <label for="new_certificate" style="font-weight:bold">BASE-64 encoded new certificate + PKCS#8 private key:</label> <textarea id="new_certificate">New encoded certificate will be put here</textarea> </div> </body> </html>