1 /* keyutil-1.2.3.js (c) 2013-2021 Kenji Urushima | kjur.github.com/jsrsasign/license
  2  */
  3 /*
  4  * keyutil.js - key utility for PKCS#1/5/8 PEM, RSA/DSA/ECDSA key object
  5  *
  6  * Copyright (c) 2013-2020 Kenji Urushima (kenji.urushima@gmail.com)
  7  *
  8  * This software is licensed under the terms of the MIT License.
  9  * https://kjur.github.io/jsrsasign/license
 10  *
 11  * The above copyright and license notice shall be 
 12  * included in all copies or substantial portions of the Software.
 13  */
 14 /**
 15  * @fileOverview
 16  * @name keyutil-1.0.js
 17  * @author Kenji Urushima kenji.urushima@gmail.com
 18  * @version jsrsasign 10.1.6 keyutil 1.2.3 (2021-Feb-08)
 19  * @since jsrsasign 4.1.4
 20  * @license <a href="https://kjur.github.io/jsrsasign/license/">MIT License</a>
 21  */
 22 
 23 /**
 24  * @name KEYUTIL
 25  * @class class for RSA/ECC/DSA key utility
 26  * @description 
 27  * <br/>
 28  * {@link KEYUTIL} class is an update of former {@link PKCS5PKEY} class.
 29  * {@link KEYUTIL} class has following features:
 30  * <dl>
 31  * <dt><b>key loading - {@link KEYUTIL.getKey}</b>
 32  * <dd>
 33  * <ul>
 34  * <li>supports RSAKey and KJUR.crypto.{ECDSA,DSA} key object</li>
 35  * <li>supports private key and public key</li>
 36  * <li>supports encrypted and plain private key</li>
 37  * <li>supports PKCS#1, PKCS#5 and PKCS#8 key</li>
 38  * <li>supports public key in X.509 certificate</li>
 39  * <li>key represented by JSON object</li>
 40  * </ul>
 41  * NOTE1: Encrypted PKCS#8 only supports PBKDF2/HmacSHA1/3DES <br/>
 42  * NOTE2: Encrypted PKCS#5 supports DES-CBC, DES-EDE3-CBC, AES-{128,192.256}-CBC <br/>
 43  *
 44  * <dt><b>exporting key - {@link KEYUTIL.getPEM}</b>
 45  * <dd>
 46  * {@link KEYUTIL.getPEM} method supports following formats:
 47  * <ul>
 48  * <li>supports RSA/EC/DSA keys</li>
 49  * <li>PKCS#1 plain RSA/EC/DSA private key</li>
 50  * <li>PKCS#5 encrypted RSA/EC/DSA private key with DES-CBC, DES-EDE3-CBC, AES-{128,192.256}-CBC</li>
 51  * <li>PKCS#8 plain RSA/EC/DSA private key</li>
 52  * <li>PKCS#8 encrypted RSA/EC/DSA private key with PBKDF2_HmacSHA1_3DES</li>
 53  * </ul>
 54  *
 55  * <dt><b>keypair generation - {@link KEYUTIL.generateKeypair}</b>
 56  * <ul>
 57  * <li>generate key pair of {@link RSAKey} or {@link KJUR.crypto.ECDSA}.</li>
 58  * <li>generate private key and convert it to PKCS#5 encrypted private key.</li>
 59  * </ul>
 60  * NOTE: {@link KJUR.crypto.DSA} is not yet supported.
 61  * </dl>
 62  * 
 63  * @example
 64  * // 1. loading PEM private key
 65  * var key = KEYUTIL.getKey(pemPKCS1PrivateKey);
 66  * var key = KEYUTIL.getKey(pemPKCS5EncryptedPrivateKey, "passcode");
 67  * var key = KEYUTIL.getKey(pemPKCS5PlainRsaDssEcPrivateKey);
 68  * var key = KEYUTIL.getKey(pemPKC85PlainPrivateKey);
 69  * var key = KEYUTIL.getKey(pemPKC85EncryptedPrivateKey, "passcode");
 70  * // 2. loading PEM public key
 71  * var key = KEYUTIL.getKey(pemPKCS8PublicKey);
 72  * var key = KEYUTIL.getKey(pemX509Certificate);
 73  * // 3. exporting private key
 74  * var pem = KEYUTIL.getPEM(privateKeyObj, "PKCS1PRV");
 75  * var pem = KEYUTIL.getPEM(privateKeyObj, "PKCS5PRV", "passcode"); // DES-EDE3-CBC by default
 76  * var pem = KEYUTIL.getPEM(privateKeyObj, "PKCS5PRV", "passcode", "DES-CBC");
 77  * var pem = KEYUTIL.getPEM(privateKeyObj, "PKCS8PRV");
 78  * var pem = KEYUTIL.getPEM(privateKeyObj, "PKCS8PRV", "passcode");
 79  * // 4. exporting public key
 80  * var pem = KEYUTIL.getPEM(publicKeyObj);
 81  */
 82 var KEYUTIL = function() {
 83     // *****************************************************************
 84     // *** PRIVATE PROPERTIES AND METHODS *******************************
 85     // *****************************************************************
 86     // shared key decryption ------------------------------------------
 87     var decryptAES = function(dataHex, keyHex, ivHex) {
 88         return decryptGeneral(CryptoJS.AES, dataHex, keyHex, ivHex);
 89     };
 90 
 91     var decrypt3DES = function(dataHex, keyHex, ivHex) {
 92         return decryptGeneral(CryptoJS.TripleDES, dataHex, keyHex, ivHex);
 93     };
 94 
 95     var decryptDES = function(dataHex, keyHex, ivHex) {
 96         return decryptGeneral(CryptoJS.DES, dataHex, keyHex, ivHex);
 97     };
 98 
 99     var decryptGeneral = function(f, dataHex, keyHex, ivHex) {
100         var data = CryptoJS.enc.Hex.parse(dataHex);
101         var key = CryptoJS.enc.Hex.parse(keyHex);
102         var iv = CryptoJS.enc.Hex.parse(ivHex);
103         var encrypted = {};
104         encrypted.key = key;
105         encrypted.iv = iv;
106         encrypted.ciphertext = data;
107         var decrypted = f.decrypt(encrypted, key, { iv: iv });
108         return CryptoJS.enc.Hex.stringify(decrypted);
109     };
110 
111     // shared key decryption ------------------------------------------
112     var encryptAES = function(dataHex, keyHex, ivHex) {
113         return encryptGeneral(CryptoJS.AES, dataHex, keyHex, ivHex);
114     };
115 
116     var encrypt3DES = function(dataHex, keyHex, ivHex) {
117         return encryptGeneral(CryptoJS.TripleDES, dataHex, keyHex, ivHex);
118     };
119 
120     var encryptDES = function(dataHex, keyHex, ivHex) {
121         return encryptGeneral(CryptoJS.DES, dataHex, keyHex, ivHex);
122     };
123 
124     var encryptGeneral = function(f, dataHex, keyHex, ivHex) {
125         var data = CryptoJS.enc.Hex.parse(dataHex);
126         var key = CryptoJS.enc.Hex.parse(keyHex);
127         var iv = CryptoJS.enc.Hex.parse(ivHex);
128         var encryptedHex = f.encrypt(data, key, { iv: iv });
129         var encryptedWA = CryptoJS.enc.Hex.parse(encryptedHex.toString());
130         var encryptedB64 = CryptoJS.enc.Base64.stringify(encryptedWA);
131         return encryptedB64;
132     };
133 
134     // other methods and properties ----------------------------------------
135     var ALGLIST = {
136         'AES-256-CBC':  { 'proc': decryptAES,  'eproc': encryptAES,  keylen: 32, ivlen: 16 },
137         'AES-192-CBC':  { 'proc': decryptAES,  'eproc': encryptAES,  keylen: 24, ivlen: 16 },
138         'AES-128-CBC':  { 'proc': decryptAES,  'eproc': encryptAES,  keylen: 16, ivlen: 16 },
139         'DES-EDE3-CBC': { 'proc': decrypt3DES, 'eproc': encrypt3DES, keylen: 24, ivlen: 8 },
140         'DES-CBC':      { 'proc': decryptDES,  'eproc': encryptDES,  keylen: 8,  ivlen: 8 }
141     };
142 
143     var getFuncByName = function(algName) {
144         return ALGLIST[algName]['proc'];
145     };
146 
147     var _generateIvSaltHex = function(numBytes) {
148         var wa = CryptoJS.lib.WordArray.random(numBytes);
149         var hex = CryptoJS.enc.Hex.stringify(wa);
150         return hex;
151     };
152 
153     var _parsePKCS5PEM = function(sPKCS5PEM) {
154         var info = {};
155         var matchResult1 = sPKCS5PEM.match(new RegExp("DEK-Info: ([^,]+),([0-9A-Fa-f]+)", "m"));
156         if (matchResult1) {
157             info.cipher = matchResult1[1];
158             info.ivsalt = matchResult1[2];
159         }
160         var matchResult2 = sPKCS5PEM.match(new RegExp("-----BEGIN ([A-Z]+) PRIVATE KEY-----"));
161         if (matchResult2) {
162             info.type = matchResult2[1];
163         }
164         var i1 = -1;
165         var lenNEWLINE = 0;
166         if (sPKCS5PEM.indexOf("\r\n\r\n") != -1) {
167             i1 = sPKCS5PEM.indexOf("\r\n\r\n");
168             lenNEWLINE = 2;
169         }
170         if (sPKCS5PEM.indexOf("\n\n") != -1) {
171             i1 = sPKCS5PEM.indexOf("\n\n");
172             lenNEWLINE = 1;
173         }
174         var i2 = sPKCS5PEM.indexOf("-----END");
175         if (i1 != -1 && i2 != -1) {
176             var s = sPKCS5PEM.substring(i1 + lenNEWLINE * 2, i2 - lenNEWLINE);
177             s = s.replace(/\s+/g, '');
178             info.data = s;
179         }
180         return info;
181     };
182 
183     var _getKeyAndUnusedIvByPasscodeAndIvsalt = function(algName, passcode, ivsaltHex) {
184         //alert("ivsaltHex(2) = " + ivsaltHex);
185         var saltHex = ivsaltHex.substring(0, 16);
186         //alert("salt = " + saltHex);
187         
188         var salt = CryptoJS.enc.Hex.parse(saltHex);
189         var data = CryptoJS.enc.Utf8.parse(passcode);
190         //alert("salt = " + salt);
191         //alert("data = " + data);
192 
193         var nRequiredBytes = ALGLIST[algName]['keylen'] + ALGLIST[algName]['ivlen'];
194         var hHexValueJoined = '';
195         var hLastValue = null;
196         //alert("nRequiredBytes = " + nRequiredBytes);
197         for (;;) {
198             var h = CryptoJS.algo.MD5.create();
199             if (hLastValue != null) {
200                 h.update(hLastValue);
201             }
202             h.update(data);
203             h.update(salt);
204             hLastValue = h.finalize();
205             hHexValueJoined = hHexValueJoined + CryptoJS.enc.Hex.stringify(hLastValue);
206             //alert("joined = " + hHexValueJoined);
207             if (hHexValueJoined.length >= nRequiredBytes * 2) {
208                 break;
209             }
210         }
211         var result = {};
212         result.keyhex = hHexValueJoined.substr(0, ALGLIST[algName]['keylen'] * 2);
213         result.ivhex = hHexValueJoined.substr(ALGLIST[algName]['keylen'] * 2, ALGLIST[algName]['ivlen'] * 2);
214         return result;
215     };
216 
217     /*
218      * @param {String} privateKeyB64 base64 string of encrypted private key
219      * @param {String} sharedKeyAlgName algorithm name of shared key encryption
220      * @param {String} sharedKeyHex hexadecimal string of shared key to encrypt
221      * @param {String} ivsaltHex hexadecimal string of IV and salt
222      * @param {String} hexadecimal string of decrypted private key
223      */
224     var _decryptKeyB64 = function(privateKeyB64, sharedKeyAlgName, sharedKeyHex, ivsaltHex) {
225         var privateKeyWA = CryptoJS.enc.Base64.parse(privateKeyB64);
226         var privateKeyHex = CryptoJS.enc.Hex.stringify(privateKeyWA);
227         var f = ALGLIST[sharedKeyAlgName]['proc'];
228         var decryptedKeyHex = f(privateKeyHex, sharedKeyHex, ivsaltHex);
229         return decryptedKeyHex;
230     };
231     
232     /*
233      * @param {String} privateKeyHex hexadecimal string of private key
234      * @param {String} sharedKeyAlgName algorithm name of shared key encryption
235      * @param {String} sharedKeyHex hexadecimal string of shared key to encrypt
236      * @param {String} ivsaltHex hexadecimal string of IV and salt
237      * @param {String} base64 string of encrypted private key
238      */
239     var _encryptKeyHex = function(privateKeyHex, sharedKeyAlgName, sharedKeyHex, ivsaltHex) {
240         var f = ALGLIST[sharedKeyAlgName]['eproc'];
241         var encryptedKeyB64 = f(privateKeyHex, sharedKeyHex, ivsaltHex);
242         return encryptedKeyB64;
243     };
244 
245     // *****************************************************************
246     // *** PUBLIC PROPERTIES AND METHODS *******************************
247     // *****************************************************************
248     return {
249         // -- UTILITY METHODS ------------------------------------------------------------
250         /**
251          * decrypt private key by shared key
252          * @name version
253          * @memberOf KEYUTIL
254          * @property {String} version
255          * @description version string of KEYUTIL class
256          */
257         version: "1.0.0",
258 
259         /**
260          * parse PEM formatted passcode protected PKCS#5 private key
261          * @name parsePKCS5PEM
262          * @memberOf KEYUTIL
263          * @function
264          * @param {String} sEncryptedPEM PEM formatted protected passcode protected PKCS#5 private key
265          * @return {Hash} hash of key information
266          * @description
267          * Resulted hash has following attributes.
268          * <ul>
269          * <li>cipher - symmetric key algorithm name (ex. 'DES-EBE3-CBC', 'AES-256-CBC')</li>
270          * <li>ivsalt - IV used for decrypt. Its heading 8 bytes will be used for passcode salt.</li>
271          * <li>type - asymmetric key algorithm name of private key described in PEM header.</li>
272          * <li>data - base64 encoded encrypted private key.</li>
273          * </ul>
274          *
275          */
276         parsePKCS5PEM: function(sPKCS5PEM) {
277             return _parsePKCS5PEM(sPKCS5PEM);
278         },
279 
280         /**
281          * the same function as OpenSSL EVP_BytsToKey to generate shared key and IV
282          * @name getKeyAndUnusedIvByPasscodeAndIvsalt
283          * @memberOf KEYUTIL
284          * @function
285          * @param {String} algName name of symmetric key algorithm (ex. 'DES-EBE3-CBC')
286          * @param {String} passcode passcode to decrypt private key (ex. 'password')
287          * @param {String} hexadecimal string of IV. heading 8 bytes will be used for passcode salt
288          * @return {Hash} hash of key and unused IV (ex. {keyhex:2fe3..., ivhex:3fad..})
289          */
290         getKeyAndUnusedIvByPasscodeAndIvsalt: function(algName, passcode, ivsaltHex) {
291             return _getKeyAndUnusedIvByPasscodeAndIvsalt(algName, passcode, ivsaltHex);
292         },
293 
294         decryptKeyB64: function(privateKeyB64, sharedKeyAlgName, sharedKeyHex, ivsaltHex) {
295             return _decryptKeyB64(privateKeyB64, sharedKeyAlgName, sharedKeyHex, ivsaltHex);
296         },
297 
298         /**
299          * decrypt PEM formatted protected PKCS#5 private key with passcode
300          * @name getDecryptedKeyHex
301          * @memberOf KEYUTIL
302          * @function
303          * @param {String} sEncryptedPEM PEM formatted protected passcode protected PKCS#5 private key
304          * @param {String} passcode passcode to decrypt private key (ex. 'password')
305          * @return {String} hexadecimal string of decrypted RSA priavte key
306          */
307         getDecryptedKeyHex: function(sEncryptedPEM, passcode) {
308             // 1. parse pem
309             var info = _parsePKCS5PEM(sEncryptedPEM);
310             var publicKeyAlgName = info.type;
311             var sharedKeyAlgName = info.cipher;
312             var ivsaltHex = info.ivsalt;
313             var privateKeyB64 = info.data;
314             //alert("ivsaltHex = " + ivsaltHex);
315 
316             // 2. generate shared key
317             var sharedKeyInfo = _getKeyAndUnusedIvByPasscodeAndIvsalt(sharedKeyAlgName, passcode, ivsaltHex);
318             var sharedKeyHex = sharedKeyInfo.keyhex;
319             //alert("sharedKeyHex = " + sharedKeyHex);
320 
321             // 3. decrypt private key
322             var decryptedKey = _decryptKeyB64(privateKeyB64, sharedKeyAlgName, sharedKeyHex, ivsaltHex);
323             return decryptedKey;
324         },
325 
326         /*
327          * get PEM formatted encrypted PKCS#5 private key from hexadecimal string of plain private key
328          * @name getEncryptedPKCS5PEMFromPrvKeyHex
329          * @memberOf KEYUTIL
330          * @function
331          * @param {String} pemHeadAlg algorithm name in the pem header (i.e. RSA,EC or DSA)
332          * @param {String} hPrvKey hexadecimal string of plain private key
333          * @param {String} passcode pass code to protect private key (ex. password)
334          * @param {String} sharedKeyAlgName algorithm name to protect private key (ex. AES-256-CBC)
335          * @param {String} ivsaltHex hexadecimal string of IV and salt
336          * @return {String} string of PEM formatted encrypted PKCS#5 private key
337          * @since pkcs5pkey 1.0.2
338          * @description
339          * <br/>
340          * generate PEM formatted encrypted PKCS#5 private key by hexadecimal string encoded
341          * ASN.1 object of plain RSA private key.
342          * Following arguments can be omitted.
343          * <ul>
344          * <li>alg - AES-256-CBC will be used if omitted.</li>
345          * <li>ivsaltHex - automatically generate IV and salt which length depends on algorithm</li>
346          * </ul>
347          * NOTE1: DES-CBC, DES-EDE3-CBC, AES-{128,192.256}-CBC algorithm are supported.
348          * @example
349          * var pem = 
350          *   KEYUTIL.getEncryptedPKCS5PEMFromPrvKeyHex(plainKeyHex, "password");
351          * var pem2 = 
352          *   KEYUTIL.getEncryptedPKCS5PEMFromPrvKeyHex(plainKeyHex, "password", "AES-128-CBC");
353          * var pem3 = 
354          *   KEYUTIL.getEncryptedPKCS5PEMFromPrvKeyHex(plainKeyHex, "password", "AES-128-CBC", "1f3d02...");
355          */
356         getEncryptedPKCS5PEMFromPrvKeyHex: function(pemHeadAlg, hPrvKey, passcode, sharedKeyAlgName, ivsaltHex) {
357             var sPEM = "";
358 
359             // 1. set sharedKeyAlgName if undefined (default AES-256-CBC)
360             if (typeof sharedKeyAlgName == "undefined" || sharedKeyAlgName == null) {
361                 sharedKeyAlgName = "AES-256-CBC";
362             }
363             if (typeof ALGLIST[sharedKeyAlgName] == "undefined")
364                 throw "KEYUTIL unsupported algorithm: " + sharedKeyAlgName;
365 
366             // 2. set ivsaltHex if undefined
367             if (typeof ivsaltHex == "undefined" || ivsaltHex == null) {
368                 var ivlen = ALGLIST[sharedKeyAlgName]['ivlen'];
369                 var randIV = _generateIvSaltHex(ivlen);
370                 ivsaltHex = randIV.toUpperCase();
371             }
372 
373             // 3. get shared key
374             //alert("ivsalthex=" + ivsaltHex);
375             var sharedKeyInfo = _getKeyAndUnusedIvByPasscodeAndIvsalt(sharedKeyAlgName, passcode, ivsaltHex);
376             var sharedKeyHex = sharedKeyInfo.keyhex;
377             // alert("sharedKeyHex = " + sharedKeyHex);
378 
379             // 3. get encrypted Key in Base64
380             var encryptedKeyB64 = _encryptKeyHex(hPrvKey, sharedKeyAlgName, sharedKeyHex, ivsaltHex);
381 
382             var pemBody = encryptedKeyB64.replace(/(.{64})/g, "$1\r\n");
383             var sPEM = "-----BEGIN " + pemHeadAlg + " PRIVATE KEY-----\r\n";
384             sPEM += "Proc-Type: 4,ENCRYPTED\r\n";
385             sPEM += "DEK-Info: " + sharedKeyAlgName + "," + ivsaltHex + "\r\n";
386             sPEM += "\r\n";
387             sPEM += pemBody;
388             sPEM += "\r\n-----END " + pemHeadAlg + " PRIVATE KEY-----\r\n";
389 
390             return sPEM;
391         },
392 
393         // === PKCS8 ===============================================================
394 
395         /**
396          * generate PBKDF2 key hexstring with specified passcode and information
397          * @name parseHexOfEncryptedPKCS8
398          * @memberOf KEYUTIL
399          * @function
400          * @param {String} passcode passcode to decrypto private key
401          * @return {Array} info associative array of PKCS#8 parameters
402          * @since pkcs5pkey 1.0.3
403          * @description
404          * The associative array which is returned by this method has following properties:
405          * <ul>
406          * <li>info.pbkdf2Salt - hexadecimal string of PBKDF2 salt</li>
407          * <li>info.pkbdf2Iter - iteration count</li>
408          * <li>info.ciphertext - hexadecimal string of encrypted private key</li>
409          * <li>info.encryptionSchemeAlg - encryption algorithm name (currently TripleDES only)</li>
410          * <li>info.encryptionSchemeIV - initial vector for encryption algorithm</li>
411          * </ul>
412          * Currently, this method only supports PKCS#5v2.0 with PBES2/PBDKF2 of HmacSHA1 and TripleDES.
413          * <ul>
414          * <li>keyDerivationFunc = pkcs5PBKDF2 with HmacSHA1</li>
415          * <li>encryptionScheme = des-EDE3-CBC(i.e. TripleDES</li>
416          * </ul>
417          * @example
418          * // to convert plain PKCS#5 private key to encrypted PKCS#8 private
419          * // key with PBKDF2 with TripleDES
420          * % openssl pkcs8 -in plain_p5.pem -topk8 -v2 -des3 -out encrypted_p8.pem
421          */
422         parseHexOfEncryptedPKCS8: function(sHEX) {
423 	    var _ASN1HEX = ASN1HEX;
424 	    var _getChildIdx = _ASN1HEX.getChildIdx;
425 	    var _getV = _ASN1HEX.getV;
426             var info = {};
427             
428             var a0 = _getChildIdx(sHEX, 0);
429             if (a0.length != 2)
430                 throw "malformed format: SEQUENCE(0).items != 2: " + a0.length;
431 
432             // 1. ciphertext
433             info.ciphertext = _getV(sHEX, a0[1]);
434 
435             // 2. pkcs5PBES2
436             var a0_0 = _getChildIdx(sHEX, a0[0]); 
437             if (a0_0.length != 2)
438                 throw "malformed format: SEQUENCE(0.0).items != 2: " + a0_0.length;
439 
440             // 2.1 check if pkcs5PBES2(1 2 840 113549 1 5 13)
441             if (_getV(sHEX, a0_0[0]) != "2a864886f70d01050d")
442                 throw "this only supports pkcs5PBES2";
443 
444             // 2.2 pkcs5PBES2 param
445             var a0_0_1 = _getChildIdx(sHEX, a0_0[1]); 
446             if (a0_0.length != 2)
447                 throw "malformed format: SEQUENCE(0.0.1).items != 2: " + a0_0_1.length;
448 
449             // 2.2.1 encryptionScheme
450             var a0_0_1_1 = _getChildIdx(sHEX, a0_0_1[1]); 
451             if (a0_0_1_1.length != 2)
452                 throw "malformed format: SEQUENCE(0.0.1.1).items != 2: " + a0_0_1_1.length;
453             if (_getV(sHEX, a0_0_1_1[0]) != "2a864886f70d0307")
454                 throw "this only supports TripleDES";
455             info.encryptionSchemeAlg = "TripleDES";
456 
457             // 2.2.1.1 IV of encryptionScheme
458             info.encryptionSchemeIV = _getV(sHEX, a0_0_1_1[1]);
459 
460             // 2.2.2 keyDerivationFunc
461             var a0_0_1_0 = _getChildIdx(sHEX, a0_0_1[0]); 
462             if (a0_0_1_0.length != 2)
463                 throw "malformed format: SEQUENCE(0.0.1.0).items != 2: " + a0_0_1_0.length;
464             if (_getV(sHEX, a0_0_1_0[0]) != "2a864886f70d01050c")
465                 throw "this only supports pkcs5PBKDF2";
466 
467             // 2.2.2.1 pkcs5PBKDF2 param
468             var a0_0_1_0_1 = _getChildIdx(sHEX, a0_0_1_0[1]); 
469             if (a0_0_1_0_1.length < 2)
470                 throw "malformed format: SEQUENCE(0.0.1.0.1).items < 2: " + a0_0_1_0_1.length;
471 
472             // 2.2.2.1.1 PBKDF2 salt
473             info.pbkdf2Salt = _getV(sHEX, a0_0_1_0_1[0]);
474 
475             // 2.2.2.1.2 PBKDF2 iter
476             var iterNumHex = _getV(sHEX, a0_0_1_0_1[1]);
477             try {
478                 info.pbkdf2Iter = parseInt(iterNumHex, 16);
479             } catch(ex) {
480                 throw "malformed format pbkdf2Iter: " + iterNumHex;
481             }
482 
483             return info;
484         },
485 
486         /**
487          * generate PBKDF2 key hexstring with specified passcode and information
488          * @name getPBKDF2KeyHexFromParam
489          * @memberOf KEYUTIL
490          * @function
491          * @param {Array} info result of {@link parseHexOfEncryptedPKCS8} which has preference of PKCS#8 file
492          * @param {String} passcode passcode to decrypto private key
493          * @return {String} hexadecimal string of PBKDF2 key
494          * @since pkcs5pkey 1.0.3
495          * @description
496          * As for info, this uses following properties:
497          * <ul>
498          * <li>info.pbkdf2Salt - hexadecimal string of PBKDF2 salt</li>
499          * <li>info.pkbdf2Iter - iteration count</li>
500          * </ul>
501          * Currently, this method only supports PKCS#5v2.0 with PBES2/PBDKF2 of HmacSHA1 and TripleDES.
502          * <ul>
503          * <li>keyDerivationFunc = pkcs5PBKDF2 with HmacSHA1</li>
504          * <li>encryptionScheme = des-EDE3-CBC(i.e. TripleDES</li>
505          * </ul>
506          * @example
507          * // to convert plain PKCS#5 private key to encrypted PKCS#8 private
508          * // key with PBKDF2 with TripleDES
509          * % openssl pkcs8 -in plain_p5.pem -topk8 -v2 -des3 -out encrypted_p8.pem
510          */
511         getPBKDF2KeyHexFromParam: function(info, passcode) {
512             var pbkdf2SaltWS = CryptoJS.enc.Hex.parse(info.pbkdf2Salt);
513             var pbkdf2Iter = info.pbkdf2Iter;
514             var pbkdf2KeyWS = CryptoJS.PBKDF2(passcode, 
515                                               pbkdf2SaltWS, 
516                                               { keySize: 192/32, iterations: pbkdf2Iter });
517             var pbkdf2KeyHex = CryptoJS.enc.Hex.stringify(pbkdf2KeyWS);
518             return pbkdf2KeyHex;
519         },
520 
521         /*
522          * read PEM formatted encrypted PKCS#8 private key and returns hexadecimal string of plain PKCS#8 private key
523          * @name getPlainPKCS8HexFromEncryptedPKCS8PEM
524          * @memberOf KEYUTIL
525          * @function
526          * @param {String} pkcs8PEM PEM formatted encrypted PKCS#8 private key
527          * @param {String} passcode passcode to decrypto private key
528          * @return {String} hexadecimal string of plain PKCS#8 private key
529          * @since pkcs5pkey 1.0.3
530          * @description
531          * Currently, this method only supports PKCS#5v2.0 with PBES2/PBDKF2 of HmacSHA1 and TripleDES.
532          * <ul>
533          * <li>keyDerivationFunc = pkcs5PBKDF2 with HmacSHA1</li>
534          * <li>encryptionScheme = des-EDE3-CBC(i.e. TripleDES</li>
535          * </ul>
536          * @example
537          * // to convert plain PKCS#5 private key to encrypted PKCS#8 private
538          * // key with PBKDF2 with TripleDES
539          * % openssl pkcs8 -in plain_p5.pem -topk8 -v2 -des3 -out encrypted_p8.pem
540          */
541         _getPlainPKCS8HexFromEncryptedPKCS8PEM: function(pkcs8PEM, passcode) {
542             // 1. derHex - PKCS#8 private key encrypted by PBKDF2
543             var derHex = pemtohex(pkcs8PEM, "ENCRYPTED PRIVATE KEY");
544             // 2. info - PKCS#5 PBES info
545             var info = this.parseHexOfEncryptedPKCS8(derHex);
546             // 3. hKey - PBKDF2 key
547             var pbkdf2KeyHex = KEYUTIL.getPBKDF2KeyHexFromParam(info, passcode);
548             // 4. decrypt ciphertext by PBKDF2 key
549             var encrypted = {};
550             encrypted.ciphertext = CryptoJS.enc.Hex.parse(info.ciphertext);
551             var pbkdf2KeyWS = CryptoJS.enc.Hex.parse(pbkdf2KeyHex);
552             var des3IVWS = CryptoJS.enc.Hex.parse(info.encryptionSchemeIV);
553             var decWS = CryptoJS.TripleDES.decrypt(encrypted, pbkdf2KeyWS, { iv: des3IVWS });
554             var decHex = CryptoJS.enc.Hex.stringify(decWS);
555             return decHex;
556         },
557 
558         /**
559          * get RSAKey/ECDSA private key object from encrypted PEM PKCS#8 private key
560          * @name getKeyFromEncryptedPKCS8PEM
561          * @memberOf KEYUTIL
562          * @function
563          * @param {String} pkcs8PEM string of PEM formatted PKCS#8 private key
564          * @param {String} passcode passcode string to decrypt key
565          * @return {Object} RSAKey or KJUR.crypto.ECDSA private key object
566          * @since pkcs5pkey 1.0.5
567          */
568         getKeyFromEncryptedPKCS8PEM: function(pkcs8PEM, passcode) {
569             var prvKeyHex = this._getPlainPKCS8HexFromEncryptedPKCS8PEM(pkcs8PEM, passcode);
570             var key = this.getKeyFromPlainPrivatePKCS8Hex(prvKeyHex);
571             return key;
572         },
573 
574         /**
575          * parse hexadecimal string of plain PKCS#8 private key
576          * @name parsePlainPrivatePKCS8Hex
577          * @memberOf KEYUTIL
578          * @function
579          * @param {String} pkcs8PrvHex hexadecimal string of PKCS#8 plain private key
580          * @return {Array} associative array of parsed key
581          * @since pkcs5pkey 1.0.5
582          * @description
583          * Resulted associative array has following properties:
584          * <ul>
585          * <li>algoid - hexadecimal string of OID of asymmetric key algorithm</li>
586          * <li>algparam - hexadecimal string of OID of ECC curve name or null</li>
587          * <li>keyidx - string starting index of key in pkcs8PrvHex</li>
588          * </ul>
589          */
590         parsePlainPrivatePKCS8Hex: function(pkcs8PrvHex) {
591 	    var _ASN1HEX = ASN1HEX;
592 	    var _getChildIdx = _ASN1HEX.getChildIdx;
593 	    var _getV = _ASN1HEX.getV;
594             var result = {};
595             result.algparam = null;
596 
597             // 1. sequence
598             if (pkcs8PrvHex.substr(0, 2) != "30")
599                 throw new Error("malformed plain PKCS8 private key(code:001)");
600 	        // not sequence
601 
602             var a1 = _getChildIdx(pkcs8PrvHex, 0);
603             if (a1.length < 3)
604                 throw new Error("malformed plain PKCS8 private key(code:002)");
605                 // less elements
606 
607             // 2. AlgID
608             if (pkcs8PrvHex.substr(a1[1], 2) != "30")
609                 throw new Error("malformed PKCS8 private key(code:003)");
610                 // AlgId not sequence
611 
612             var a2 = _getChildIdx(pkcs8PrvHex, a1[1]);
613             if (a2.length != 2)
614                 throw new Error("malformed PKCS8 private key(code:004)");
615                 // AlgId not have two elements
616 
617             // 2.1. AlgID OID
618             if (pkcs8PrvHex.substr(a2[0], 2) != "06")
619                 throw new Error("malformed PKCS8 private key(code:005)");
620                 // AlgId.oid is not OID
621 
622             result.algoid = _getV(pkcs8PrvHex, a2[0]);
623 
624             // 2.2. AlgID param
625             if (pkcs8PrvHex.substr(a2[1], 2) == "06") {
626                 result.algparam = _getV(pkcs8PrvHex, a2[1]);
627             }
628 
629             // 3. Key index
630             if (pkcs8PrvHex.substr(a1[2], 2) != "04")
631                 throw new Error("malformed PKCS8 private key(code:006)");
632                 // not octet string
633 
634             result.keyidx = _ASN1HEX.getVidx(pkcs8PrvHex, a1[2]);
635 
636             return result;
637         },
638 
639         /**
640          * get RSAKey/ECDSA private key object from PEM plain PEM PKCS#8 private key
641          * @name getKeyFromPlainPrivatePKCS8PEM
642          * @memberOf KEYUTIL
643          * @function
644          * @param {String} pkcs8PEM string of plain PEM formatted PKCS#8 private key
645          * @return {Object} RSAKey or KJUR.crypto.ECDSA private key object
646          * @since pkcs5pkey 1.0.5
647          */
648         getKeyFromPlainPrivatePKCS8PEM: function(prvKeyPEM) {
649             var prvKeyHex = pemtohex(prvKeyPEM, "PRIVATE KEY");
650             var key = this.getKeyFromPlainPrivatePKCS8Hex(prvKeyHex);
651             return key;
652         },
653 
654         /**
655          * get RSAKey/DSA/ECDSA private key object from HEX plain PEM PKCS#8 private key
656          * @name getKeyFromPlainPrivatePKCS8Hex
657          * @memberOf KEYUTIL
658          * @function
659          * @param {String} prvKeyHex hexadecimal string of plain PKCS#8 private key
660          * @return {Object} RSAKey or KJUR.crypto.{DSA,ECDSA} private key object
661          * @since pkcs5pkey 1.0.5
662          */
663         getKeyFromPlainPrivatePKCS8Hex: function(prvKeyHex) {
664             var p8 = this.parsePlainPrivatePKCS8Hex(prvKeyHex);
665 	    var key;
666             
667             if (p8.algoid == "2a864886f70d010101") { // RSA
668 		key = new RSAKey();
669 	    } else if (p8.algoid == "2a8648ce380401") { // DSA
670 		key = new KJUR.crypto.DSA();
671             } else if (p8.algoid == "2a8648ce3d0201") { // ECC
672                 key = new KJUR.crypto.ECDSA();
673             } else {
674                 throw "unsupported private key algorithm";
675             }
676 
677 	    key.readPKCS8PrvKeyHex(prvKeyHex);
678 	    return key;
679         },
680 
681         // === PKCS8 RSA Public Key ================================================
682 
683         /*
684          * get RSAKey/DSA/ECDSA public key object from hexadecimal string of PKCS#8 public key
685          * @name _getKeyFromPublicPKCS8Hex
686          * @memberOf KEYUTIL
687          * @function
688          * @param {String} pkcsPub8Hex hexadecimal string of PKCS#8 public key
689          * @return {Object} RSAKey or KJUR.crypto.{ECDSA,DSA} private key object
690          * @since pkcs5pkey 1.0.5
691          */
692         _getKeyFromPublicPKCS8Hex: function(h) {
693 	    var key;
694 	    var hOID = ASN1HEX.getVbyList(h, 0, [0, 0], "06");
695 
696 	    if (hOID === "2a864886f70d010101") {    // oid=RSA
697 		key = new RSAKey();
698 	    } else if (hOID === "2a8648ce380401") { // oid=DSA
699 		key = new KJUR.crypto.DSA();
700 	    } else if (hOID === "2a8648ce3d0201") { // oid=ECPUB
701 		key = new KJUR.crypto.ECDSA();
702 	    } else {
703 		throw "unsupported PKCS#8 public key hex";
704 	    }
705 	    key.readPKCS8PubKeyHex(h);
706 	    return key;
707 	},
708 
709         /**
710          * parse hexadecimal string of plain PKCS#8 private key
711          * @name parsePublicRawRSAKeyHex
712          * @memberOf KEYUTIL
713          * @function
714          * @param {String} pubRawRSAHex hexadecimal string of ASN.1 encoded PKCS#8 public key
715          * @return {Array} associative array of parsed key
716          * @since pkcs5pkey 1.0.5
717          * @description
718          * Resulted associative array has following properties:
719          * <ul>
720          * <li>n - hexadecimal string of public key
721          * <li>e - hexadecimal string of public exponent
722          * </ul>
723          */
724         parsePublicRawRSAKeyHex: function(pubRawRSAHex) {
725 	    var _ASN1HEX = ASN1HEX;
726 	    var _getChildIdx = _ASN1HEX.getChildIdx;
727 	    var _getV = _ASN1HEX.getV;
728             var result = {};
729             
730             // 1. Sequence
731             if (pubRawRSAHex.substr(0, 2) != "30")
732                 throw "malformed RSA key(code:001)"; // not sequence
733             
734             var a1 = _getChildIdx(pubRawRSAHex, 0);
735             if (a1.length != 2)
736                 throw "malformed RSA key(code:002)"; // not 2 items in seq
737 
738             // 2. public key "N"
739             if (pubRawRSAHex.substr(a1[0], 2) != "02")
740                 throw "malformed RSA key(code:003)"; // 1st item is not integer
741 
742             result.n = _getV(pubRawRSAHex, a1[0]);
743 
744             // 3. public key "E"
745             if (pubRawRSAHex.substr(a1[1], 2) != "02")
746                 throw "malformed RSA key(code:004)"; // 2nd item is not integer
747 
748             result.e = _getV(pubRawRSAHex, a1[1]);
749 
750             return result;
751         },
752 
753         /**
754          * parse hexadecimal string of PKCS#8 RSA/EC/DSA public key
755          * @name parsePublicPKCS8Hex
756          * @memberOf KEYUTIL
757          * @function
758          * @param {String} pkcs8PubHex hexadecimal string of PKCS#8 public key
759          * @return {Hash} hash of key information
760          * @description
761          * Resulted hash has following attributes.
762          * <ul>
763          * <li>algoid - hexadecimal string of OID of asymmetric key algorithm</li>
764          * <li>algparam - hexadecimal string of OID of ECC curve name, parameter SEQUENCE of DSA or null</li>
765          * <li>key - hexadecimal string of public key</li>
766          * </ul>
767          */
768         parsePublicPKCS8Hex: function(pkcs8PubHex) {
769 	    var _ASN1HEX = ASN1HEX;
770 	    var _getChildIdx = _ASN1HEX.getChildIdx;
771 	    var _getV = _ASN1HEX.getV;
772             var result = {};
773             result.algparam = null;
774 
775             // 1. AlgID and Key bit string
776             var a1 = _getChildIdx(pkcs8PubHex, 0);
777             if (a1.length != 2)
778                 throw "outer DERSequence shall have 2 elements: " + a1.length;
779 
780             // 2. AlgID
781             var idxAlgIdTLV = a1[0];
782             if (pkcs8PubHex.substr(idxAlgIdTLV, 2) != "30")
783                 throw "malformed PKCS8 public key(code:001)"; // AlgId not sequence
784 
785             var a2 = _getChildIdx(pkcs8PubHex, idxAlgIdTLV);
786             if (a2.length != 2)
787                 throw "malformed PKCS8 public key(code:002)"; // AlgId not have two elements
788 
789             // 2.1. AlgID OID
790             if (pkcs8PubHex.substr(a2[0], 2) != "06")
791                 throw "malformed PKCS8 public key(code:003)"; // AlgId.oid is not OID
792 
793             result.algoid = _getV(pkcs8PubHex, a2[0]);
794 
795             // 2.2. AlgID param
796             if (pkcs8PubHex.substr(a2[1], 2) == "06") { // OID for EC
797                 result.algparam = _getV(pkcs8PubHex, a2[1]);
798             } else if (pkcs8PubHex.substr(a2[1], 2) == "30") { // SEQ for DSA
799                 result.algparam = {};
800                 result.algparam.p = _ASN1HEX.getVbyList(pkcs8PubHex, a2[1], [0], "02");
801                 result.algparam.q = _ASN1HEX.getVbyList(pkcs8PubHex, a2[1], [1], "02");
802                 result.algparam.g = _ASN1HEX.getVbyList(pkcs8PubHex, a2[1], [2], "02");
803             }
804 
805             // 3. Key
806             if (pkcs8PubHex.substr(a1[1], 2) != "03")
807                 throw "malformed PKCS8 public key(code:004)"; // Key is not bit string
808 
809             result.key = _getV(pkcs8PubHex, a1[1]).substr(2);
810             
811             // 4. return result assoc array
812             return result;
813         },
814     };
815 }();
816 
817 // -- MAJOR PUBLIC METHODS -------------------------------------------------------
818 /**
819  * get private or public key object from any arguments
820  * @name getKey
821  * @memberOf KEYUTIL
822  * @function
823  * @static
824  * @param {Object} param parameter to get key object. see description in detail.
825  * @param {String} passcode (OPTION) parameter to get key object. see description in detail.
826  * @param {String} hextype (OPTOIN) parameter to get key object. see description in detail.
827  * @return {Object} {@link RSAKey}, {@link KJUR.crypto.ECDSA} or {@link KJUR.crypto.ECDSA} object
828  * @since keyutil 1.0.0
829  * @description
830  * This method gets private or public key object({@link RSAKey}, {@link KJUR.crypto.DSA} or {@link KJUR.crypto.ECDSA})
831  * for RSA, DSA and ECC.
832  * Arguments for this methods depends on a key format you specify.
833  * Following key representations are supported.
834  * <ul>
835  * <li>ECC private/public key object(as is): param=KJUR.crypto.ECDSA</li>
836  * <li>DSA private/public key object(as is): param=KJUR.crypto.DSA</li>
837  * <li>RSA private/public key object(as is): param=RSAKey </li>
838  * <li>ECC private key parameters: param={d: d, curve: curveName}</li>
839  * <li>RSA private key parameters: param={n: n, e: e, d: d, p: p, q: q, dp: dp, dq: dq, co: co}<br/>
840  * NOTE: Each value shall be hexadecimal string of key spec.</li>
841  * <li>DSA private key parameters: param={p: p, q: q, g: g, y: y, x: x}<br/>
842  * NOTE: Each value shall be hexadecimal string of key spec.</li>
843  * <li>ECC public key parameters: param={xy: xy, curve: curveName}<br/>
844  * NOTE: ECC public key 'xy' shall be concatination of "04", x-bytes-hex and y-bytes-hex.</li>
845  * <li>DSA public key parameters: param={p: p, q: q, g: g, y: y}<br/>
846  * NOTE: Each value shall be hexadecimal string of key spec.</li>
847  * <li>RSA public key parameters: param={n: n, e: e} </li>
848  * <li>X.509v1/v3 PEM certificate (RSA/DSA/ECC): param=pemString</li>
849  * <li>PKCS#8 hexadecimal RSA/ECC public key: param=pemString, null, "pkcs8pub"</li>
850  * <li>PKCS#8 PEM RSA/DSA/ECC public key: param=pemString</li>
851  * <li>PKCS#5 plain hexadecimal RSA private key: param=hexString, null, "pkcs5prv"</li>
852  * <li>PKCS#5 plain PEM RSA/DSA/EC private key: param=pemString</li>
853  * <li>PKCS#8 plain PEM RSA/EC private key: param=pemString</li>
854  * <li>PKCS#5 encrypted PEM RSA/DSA/EC private key: param=pemString, passcode</li>
855  * <li>PKCS#8 encrypted PEM RSA/EC private key: param=pemString, passcode</li>
856  * </ul>
857  * Please note following limitation on encrypted keys:
858  * <ul>
859  * <li>Encrypted PKCS#8 only supports PBKDF2/HmacSHA1/3DES</li>
860  * <li>Encrypted PKCS#5 supports DES-CBC, DES-EDE3-CBC, AES-{128,192.256}-CBC</li>
861  * <li>JWT plain ECC private/public key</li>
862  * <li>JWT plain RSA public key</li>
863  * <li>JWT plain RSA private key with P/Q/DP/DQ/COEFF</li>
864  * <li>JWT plain RSA private key without P/Q/DP/DQ/COEFF (since jsrsasign 5.0.0)</li>
865  * </ul>
866  * NOTE1: <a href="https://tools.ietf.org/html/rfc7517">RFC 7517 JSON Web Key(JWK)</a> support for RSA/ECC private/public key from jsrsasign 4.8.1.<br/>
867  * NOTE2: X509v1 support is added since jsrsasign 5.0.11.
868  * 
869  * <h5>EXAMPLE</h5>
870  * @example
871  * // 1. loading private key from PEM string
872  * keyObj = KEYUTIL.getKey("-----BEGIN RSA PRIVATE KEY...");
873  * keyObj = KEYUTIL.getKey("-----BEGIN RSA PRIVATE KEY..., "passcode");
874  * keyObj = KEYUTIL.getKey("-----BEGIN PRIVATE KEY...");
875  * keyObj = KEYUTIL.getKey("-----BEGIN PRIVATE KEY...", "passcode");
876  * keyObj = KEYUTIL.getKey("-----BEGIN EC PARAMETERS...-----BEGIN EC PRIVATE KEY...");
877  * // 2. loading public key from PEM string
878  * keyObj = KEYUTIL.getKey("-----BEGIN PUBLIC KEY...");
879  * keyObj = KEYUTIL.getKey("-----BEGIN X509 CERTIFICATE...");
880  * // 3. loading hexadecimal PKCS#5/PKCS#8 key
881  * keyObj = KEYUTIL.getKey("308205c1...", null, "pkcs8pub");
882  * keyObj = KEYUTIL.getKey("3082048b...", null, "pkcs5prv");
883  * // 4. loading JSON Web Key(JWK)
884  * keyObj = KEYUTIL.getKey({kty: "RSA", n: "0vx7...", e: "AQAB"});
885  * keyObj = KEYUTIL.getKey({kty: "EC", crv: "P-256", 
886  *                          x: "MKBC...", y: "4Etl6...", d: "870Mb..."});
887  * // 5. bare hexadecimal key
888  * keyObj = KEYUTIL.getKey({n: "75ab..", e: "010001"});
889  */
890 KEYUTIL.getKey = function(param, passcode, hextype) {
891     var _ASN1HEX = ASN1HEX,
892 	_getChildIdx = _ASN1HEX.getChildIdx,
893 	_getV = _ASN1HEX.getV,
894 	_getVbyList = _ASN1HEX.getVbyList,
895 	_KJUR_crypto = KJUR.crypto,
896 	_KJUR_crypto_ECDSA = _KJUR_crypto.ECDSA,
897 	_KJUR_crypto_DSA = _KJUR_crypto.DSA,
898 	_RSAKey = RSAKey,
899 	_pemtohex = pemtohex,
900 	_KEYUTIL = KEYUTIL;
901 
902     // 1. by key RSAKey/KJUR.crypto.ECDSA/KJUR.crypto.DSA object
903     if (typeof _RSAKey != 'undefined' && param instanceof _RSAKey)
904         return param;
905     if (typeof _KJUR_crypto_ECDSA != 'undefined' && param instanceof _KJUR_crypto_ECDSA)
906         return param;
907     if (typeof _KJUR_crypto_DSA != 'undefined' && param instanceof _KJUR_crypto_DSA)
908         return param;
909 
910     // 2. by parameters of key
911 
912     // 2.1. bare ECC
913     // 2.1.1. bare ECC public key by hex values
914     if (param.curve !== undefined &&
915 	param.xy !== undefined && param.d === undefined) {
916         return new _KJUR_crypto_ECDSA({pub: param.xy, curve: param.curve});
917     }
918 
919     // 2.1.2. bare ECC private key by hex values
920     if (param.curve !== undefined && param.d !== undefined) {
921         return new _KJUR_crypto_ECDSA({prv: param.d, curve: param.curve});
922     }
923 
924     // 2.2. bare RSA
925     // 2.2.1. bare RSA public key by hex values
926     if (param.kty === undefined &&
927 	param.n !== undefined && param.e !== undefined &&
928         param.d === undefined) {
929         var key = new _RSAKey();
930         key.setPublic(param.n, param.e);
931         return key;
932     }
933 
934     // 2.2.2. bare RSA private key with P/Q/DP/DQ/COEFF by hex values
935     if (param.kty === undefined &&
936 	param.n !== undefined &&
937 	param.e !== undefined &&
938 	param.d !== undefined &&
939         param.p !== undefined &&
940 	param.q !== undefined &&
941         param.dp !== undefined &&
942 	param.dq !== undefined &&
943 	param.co !== undefined &&
944         param.qi === undefined) {
945         var key = new _RSAKey();
946         key.setPrivateEx(param.n, param.e, param.d, param.p, param.q,
947                          param.dp, param.dq, param.co);
948         return key;
949     }
950 
951     // 2.2.3. bare RSA public key without P/Q/DP/DQ/COEFF by hex values
952     if (param.kty === undefined &&
953 	param.n !== undefined &&
954 	param.e !== undefined &&
955 	param.d !== undefined &&
956         param.p === undefined) {
957         var key = new _RSAKey();
958         key.setPrivate(param.n, param.e, param.d);
959         return key;
960     }
961 
962     // 2.3. bare DSA
963     // 2.3.1. bare DSA public key by hex values
964     if (param.p !== undefined && param.q !== undefined &&
965 	param.g !== undefined &&
966         param.y !== undefined && param.x === undefined) {
967         var key = new _KJUR_crypto_DSA();
968         key.setPublic(param.p, param.q, param.g, param.y);
969         return key;
970     }
971 
972     // 2.3.2. bare DSA private key by hex values
973     if (param.p !== undefined && param.q !== undefined &&
974 	param.g !== undefined &&
975         param.y !== undefined && param.x !== undefined) {
976         var key = new _KJUR_crypto_DSA();
977         key.setPrivate(param.p, param.q, param.g, param.y, param.x);
978         return key;
979     }
980 
981     // 3. JWK
982     // 3.1. JWK RSA
983     // 3.1.1. JWK RSA public key by b64u values
984     if (param.kty === "RSA" &&
985 	param.n !== undefined &&
986 	param.e !== undefined &&
987 	param.d === undefined) {
988 	var key = new _RSAKey();
989 	key.setPublic(b64utohex(param.n), b64utohex(param.e));
990 	return key;
991     }
992 
993     // 3.1.2. JWK RSA private key with p/q/dp/dq/coeff by b64u values
994     if (param.kty === "RSA" &&
995 	param.n !== undefined &&
996 	param.e !== undefined &&
997 	param.d !== undefined &&
998 	param.p !== undefined &&
999 	param.q !== undefined &&
1000 	param.dp !== undefined &&
1001 	param.dq !== undefined &&
1002 	param.qi !== undefined) {
1003 	var key = new _RSAKey();
1004         key.setPrivateEx(b64utohex(param.n),
1005 			 b64utohex(param.e),
1006 			 b64utohex(param.d),
1007 			 b64utohex(param.p),
1008 			 b64utohex(param.q),
1009                          b64utohex(param.dp),
1010 			 b64utohex(param.dq),
1011 			 b64utohex(param.qi));
1012 	return key;
1013     }
1014 
1015     // 3.1.3. JWK RSA private key without p/q/dp/dq/coeff by b64u
1016     //        since jsrsasign 5.0.0 keyutil 1.0.11
1017     if (param.kty === "RSA" &&
1018 	param.n !== undefined &&
1019 	param.e !== undefined &&
1020 	param.d !== undefined) {
1021 	var key = new _RSAKey();
1022         key.setPrivate(b64utohex(param.n),
1023 		       b64utohex(param.e),
1024 		       b64utohex(param.d));
1025 	return key;
1026     }
1027 
1028     // 3.2. JWK ECC
1029     // 3.2.1. JWK ECC public key by b64u values
1030     if (param.kty === "EC" &&
1031 	param.crv !== undefined &&
1032 	param.x !== undefined &&
1033 	param.y !== undefined &&
1034         param.d === undefined) {
1035 	var ec = new _KJUR_crypto_ECDSA({"curve": param.crv});
1036 	var charlen = ec.ecparams.keylen / 4;
1037         var hX   = ("0000000000" + b64utohex(param.x)).slice(- charlen);
1038         var hY   = ("0000000000" + b64utohex(param.y)).slice(- charlen);
1039         var hPub = "04" + hX + hY;
1040 	ec.setPublicKeyHex(hPub);
1041 	return ec;
1042     }
1043 
1044     // 3.2.2. JWK ECC private key by b64u values
1045     if (param.kty === "EC" &&
1046 	param.crv !== undefined &&
1047 	param.x !== undefined &&
1048 	param.y !== undefined &&
1049         param.d !== undefined) {
1050 	var ec = new _KJUR_crypto_ECDSA({"curve": param.crv});
1051 	var charlen = ec.ecparams.keylen / 4;
1052         var hX   = ("0000000000" + b64utohex(param.x)).slice(- charlen);
1053         var hY   = ("0000000000" + b64utohex(param.y)).slice(- charlen);
1054         var hPub = "04" + hX + hY;
1055         var hPrv = ("0000000000" + b64utohex(param.d)).slice(- charlen);
1056 	ec.setPublicKeyHex(hPub);
1057 	ec.setPrivateKeyHex(hPrv);
1058 	return ec;
1059     }
1060     
1061     // 4. (plain) hexadecimal data
1062     // 4.1. get private key by PKCS#5 plain RSA/DSA/ECDSA hexadecimal string
1063     if (hextype === "pkcs5prv") {
1064 	var h = param, _ASN1HEX = ASN1HEX, a, key;
1065 	a = _getChildIdx(h, 0);
1066 	if (a.length === 9) {        // RSA (INT x 9)
1067 	    key = new _RSAKey();
1068             key.readPKCS5PrvKeyHex(h);
1069 	} else if (a.length === 6) { // DSA (INT x 6)
1070 	    key = new _KJUR_crypto_DSA();
1071 	    key.readPKCS5PrvKeyHex(h);
1072 	} else if (a.length > 2 &&   // ECDSA (INT, OCT prv, [0] curve, [1] pub)
1073 		   h.substr(a[1], 2) === "04") {
1074 	    key = new _KJUR_crypto_ECDSA();
1075 	    key.readPKCS5PrvKeyHex(h);
1076 	} else {
1077 	    throw "unsupported PKCS#1/5 hexadecimal key";
1078 	}
1079 
1080         return key;
1081     }
1082 
1083     // 4.2. get private key by PKCS#8 plain RSA/DSA/ECDSA hexadecimal string
1084     if (hextype === "pkcs8prv") {
1085 	var key = _KEYUTIL.getKeyFromPlainPrivatePKCS8Hex(param);
1086         return key;
1087     }
1088 
1089     // 4.3. get public key by PKCS#8 RSA/DSA/ECDSA hexadecimal string
1090     if (hextype === "pkcs8pub") {
1091         return _KEYUTIL._getKeyFromPublicPKCS8Hex(param);
1092     }
1093 
1094     // 4.4. get public key by X.509 hexadecimal string for RSA/DSA/ECDSA
1095     if (hextype === "x509pub") {
1096         return X509.getPublicKeyFromCertHex(param);
1097     }
1098 
1099     // 5. by PEM certificate (-----BEGIN ... CERTIFICATE----)
1100     if (param.indexOf("-END CERTIFICATE-", 0) != -1 ||
1101         param.indexOf("-END X509 CERTIFICATE-", 0) != -1 ||
1102         param.indexOf("-END TRUSTED CERTIFICATE-", 0) != -1) {
1103         return X509.getPublicKeyFromCertPEM(param);
1104     }
1105 
1106     // 6. public key by PKCS#8 PEM string
1107     if (param.indexOf("-END PUBLIC KEY-") != -1) {
1108         var pubKeyHex = pemtohex(param, "PUBLIC KEY");
1109         return _KEYUTIL._getKeyFromPublicPKCS8Hex(pubKeyHex);
1110     }
1111     
1112     // 8.1 private key by plain PKCS#5 PEM RSA string 
1113     //    getKey("-----BEGIN RSA PRIVATE KEY-...")
1114     if (param.indexOf("-END RSA PRIVATE KEY-") != -1 &&
1115         param.indexOf("4,ENCRYPTED") == -1) {
1116         var hex = _pemtohex(param, "RSA PRIVATE KEY");
1117         return _KEYUTIL.getKey(hex, null, "pkcs5prv");
1118     }
1119 
1120     // 8.2. private key by plain PKCS#5 PEM DSA string
1121     if (param.indexOf("-END DSA PRIVATE KEY-") != -1 &&
1122         param.indexOf("4,ENCRYPTED") == -1) {
1123 
1124         var hKey = _pemtohex(param, "DSA PRIVATE KEY");
1125         var p = _getVbyList(hKey, 0, [1], "02");
1126         var q = _getVbyList(hKey, 0, [2], "02");
1127         var g = _getVbyList(hKey, 0, [3], "02");
1128         var y = _getVbyList(hKey, 0, [4], "02");
1129         var x = _getVbyList(hKey, 0, [5], "02");
1130         var key = new _KJUR_crypto_DSA();
1131         key.setPrivate(new BigInteger(p, 16),
1132                        new BigInteger(q, 16),
1133                        new BigInteger(g, 16),
1134                        new BigInteger(y, 16),
1135                        new BigInteger(x, 16));
1136         return key;
1137     }
1138 
1139     // 8.3. private key by plain PKCS#5 PEM EC string
1140     if (param.indexOf("-END EC PRIVATE KEY-") != -1 &&
1141         param.indexOf("4,ENCRYPTED") == -1) {
1142         var hex = _pemtohex(param, "EC PRIVATE KEY");
1143         return _KEYUTIL.getKey(hex, null, "pkcs5prv");
1144     }
1145 
1146     // 10. private key by plain PKCS#8 PEM ECC/RSA string
1147     if (param.indexOf("-END PRIVATE KEY-") != -1) {
1148         return _KEYUTIL.getKeyFromPlainPrivatePKCS8PEM(param);
1149     }
1150 
1151     // 11.1 private key by encrypted PKCS#5 PEM RSA string
1152     if (param.indexOf("-END RSA PRIVATE KEY-") != -1 &&
1153         param.indexOf("4,ENCRYPTED") != -1) {
1154         var hPKey = _KEYUTIL.getDecryptedKeyHex(param, passcode);
1155         var rsaKey = new RSAKey();
1156         rsaKey.readPKCS5PrvKeyHex(hPKey);
1157         return rsaKey;
1158     }
1159 
1160     // 11.2. private key by encrypted PKCS#5 PEM ECDSA string
1161     if (param.indexOf("-END EC PRIVATE KEY-") != -1 &&
1162         param.indexOf("4,ENCRYPTED") != -1) {
1163         var hKey = _KEYUTIL.getDecryptedKeyHex(param, passcode);
1164 
1165         var key = _getVbyList(hKey, 0, [1], "04");
1166         var curveNameOidHex = _getVbyList(hKey, 0, [2,0], "06");
1167         var pubkey = _getVbyList(hKey, 0, [3,0], "03").substr(2);
1168         var curveName = "";
1169 
1170         if (KJUR.crypto.OID.oidhex2name[curveNameOidHex] !== undefined) {
1171             curveName = KJUR.crypto.OID.oidhex2name[curveNameOidHex];
1172         } else {
1173             throw "undefined OID(hex) in KJUR.crypto.OID: " + curveNameOidHex;
1174         }
1175 
1176         var ec = new _KJUR_crypto_ECDSA({'curve': curveName});
1177         ec.setPublicKeyHex(pubkey);
1178         ec.setPrivateKeyHex(key);
1179         ec.isPublic = false;
1180         return ec;
1181     }
1182 
1183     // 11.3. private key by encrypted PKCS#5 PEM DSA string
1184     if (param.indexOf("-END DSA PRIVATE KEY-") != -1 &&
1185         param.indexOf("4,ENCRYPTED") != -1) {
1186         var hKey = _KEYUTIL.getDecryptedKeyHex(param, passcode);
1187         var p = _getVbyList(hKey, 0, [1], "02");
1188         var q = _getVbyList(hKey, 0, [2], "02");
1189         var g = _getVbyList(hKey, 0, [3], "02");
1190         var y = _getVbyList(hKey, 0, [4], "02");
1191         var x = _getVbyList(hKey, 0, [5], "02");
1192         var key = new _KJUR_crypto_DSA();
1193         key.setPrivate(new BigInteger(p, 16),
1194                        new BigInteger(q, 16),
1195                        new BigInteger(g, 16),
1196                        new BigInteger(y, 16),
1197                        new BigInteger(x, 16));
1198         return key;
1199     }
1200 
1201     // 11. private key by encrypted PKCS#8 hexadecimal RSA/ECDSA string
1202     if (param.indexOf("-END ENCRYPTED PRIVATE KEY-") != -1) {
1203         return _KEYUTIL.getKeyFromEncryptedPKCS8PEM(param, passcode);
1204     }
1205 
1206     throw new Error("not supported argument");
1207 };
1208 
1209 /**
1210  * @name generateKeypair
1211  * @memberOf KEYUTIL
1212  * @function
1213  * @static
1214  * @param {String} alg 'RSA' or 'EC'
1215  * @param {Object} keylenOrCurve key length for RSA or curve name for EC
1216  * @return {Array} associative array of keypair which has prvKeyObj and pubKeyObj parameters
1217  * @since keyutil 1.0.1
1218  * @description
1219  * This method generates a key pair of public key algorithm.
1220  * The result will be an associative array which has following
1221  * parameters:
1222  * <ul>
1223  * <li>prvKeyObj - RSAKey or ECDSA object of private key</li>
1224  * <li>pubKeyObj - RSAKey or ECDSA object of public key</li>
1225  * </ul>
1226  * NOTE1: As for RSA algoirthm, public exponent has fixed
1227  * value '0x10001'.
1228  * NOTE2: As for EC algorithm, supported names of curve are
1229  * secp256r1, secp256k1 and secp384r1.
1230  * NOTE3: DSA is not supported yet.
1231  * @example
1232  * var rsaKeypair = KEYUTIL.generateKeypair("RSA", 1024);
1233  * var ecKeypair = KEYUTIL.generateKeypair("EC", "secp256r1");
1234  *
1235  */
1236 KEYUTIL.generateKeypair = function(alg, keylenOrCurve) {
1237     if (alg == "RSA") {
1238         var keylen = keylenOrCurve;
1239         var prvKey = new RSAKey();
1240         prvKey.generate(keylen, '10001');
1241         prvKey.isPrivate = true;
1242         prvKey.isPublic = true;
1243         
1244         var pubKey = new RSAKey();
1245         var hN = prvKey.n.toString(16);
1246         var hE = prvKey.e.toString(16);
1247         pubKey.setPublic(hN, hE);
1248         pubKey.isPrivate = false;
1249         pubKey.isPublic = true;
1250         
1251         var result = {};
1252         result.prvKeyObj = prvKey;
1253         result.pubKeyObj = pubKey;
1254         return result;
1255     } else if (alg == "EC") {
1256         var curve = keylenOrCurve;
1257         var ec = new KJUR.crypto.ECDSA({curve: curve});
1258         var keypairHex = ec.generateKeyPairHex();
1259 
1260         var prvKey = new KJUR.crypto.ECDSA({curve: curve});
1261         prvKey.setPublicKeyHex(keypairHex.ecpubhex);
1262         prvKey.setPrivateKeyHex(keypairHex.ecprvhex);
1263         prvKey.isPrivate = true;
1264         prvKey.isPublic = false;
1265 
1266         var pubKey = new KJUR.crypto.ECDSA({curve: curve});
1267         pubKey.setPublicKeyHex(keypairHex.ecpubhex);
1268         pubKey.isPrivate = false;
1269         pubKey.isPublic = true;
1270 
1271         var result = {};
1272         result.prvKeyObj = prvKey;
1273         result.pubKeyObj = pubKey;
1274         return result;
1275     } else {
1276         throw "unknown algorithm: " + alg;
1277     }
1278 };
1279 
1280 /**
1281  * get PEM formatted private or public key file from a RSA/ECDSA/DSA key object
1282  * @name getPEM
1283  * @memberOf KEYUTIL
1284  * @function
1285  * @static
1286  * @param {Object} keyObjOrHex key object {@link RSAKey}, {@link KJUR.crypto.ECDSA} or {@link KJUR.crypto.DSA} to encode to
1287  * @param {String} formatType (OPTION) output format type of "PKCS1PRV", "PKCS5PRV" or "PKCS8PRV" for private key
1288  * @param {String} passwd (OPTION) password to protect private key
1289  * @param {String} encAlg (OPTION) encryption algorithm for PKCS#5. currently supports DES-CBC, DES-EDE3-CBC and AES-{128,192,256}-CBC
1290  * @param {String} hexType (OPTION) type of hex string (ex. pkcs5prv, pkcs8prv)
1291  * @param {String} ivsaltHex hexadecimal string of IV and salt (default generated random IV)
1292  * @since keyutil 1.0.4
1293  * @description
1294  * <dl>
1295  * <dt><b>NOTE1:</b>
1296  * <dd>
1297  * PKCS#5 encrypted private key protection algorithm supports DES-CBC, 
1298  * DES-EDE3-CBC and AES-{128,192,256}-CBC
1299  * <dt><b>NOTE2:</b>
1300  * <dd>
1301  * OpenSSL supports
1302  * <dt><b>NOTE3:</b>
1303  * <dd>
1304  * Parameter "ivsaltHex" supported since jsrsasign 8.0.0 keyutil 1.2.0.
1305  * </dl>
1306  * @example
1307  * KEUUTIL.getPEM(publicKey) => generates PEM PKCS#8 public key 
1308  * KEUUTIL.getPEM(privateKey, "PKCS1PRV") => generates PEM PKCS#1 plain private key
1309  * KEUUTIL.getPEM(privateKey, "PKCS5PRV", "pass") => generates PEM PKCS#5 encrypted private key 
1310  *                                                          with DES-EDE3-CBC (DEFAULT)
1311  * KEUUTIL.getPEM(privateKey, "PKCS5PRV", "pass", "DES-CBC") => generates PEM PKCS#5 encrypted 
1312  *                                                                 private key with DES-CBC
1313  * KEUUTIL.getPEM(privateKey, "PKCS8PRV") => generates PEM PKCS#8 plain private key
1314  * KEUUTIL.getPEM(privateKey, "PKCS8PRV", "pass") => generates PEM PKCS#8 encrypted private key
1315  *                                                      with PBKDF2_HmacSHA1_3DES
1316  */
1317 KEYUTIL.getPEM = function(keyObjOrHex, formatType, passwd, encAlg, hexType, ivsaltHex) {
1318     var _KJUR = KJUR,
1319 	_KJUR_asn1 = _KJUR.asn1,
1320 	_DERObjectIdentifier = _KJUR_asn1.DERObjectIdentifier,
1321 	_DERInteger = _KJUR_asn1.DERInteger,
1322 	_newObject = _KJUR_asn1.ASN1Util.newObject,
1323 	_KJUR_asn1_x509 = _KJUR_asn1.x509,
1324 	_SubjectPublicKeyInfo = _KJUR_asn1_x509.SubjectPublicKeyInfo,
1325 	_KJUR_crypto = _KJUR.crypto,
1326 	_DSA = _KJUR_crypto.DSA,
1327 	_ECDSA = _KJUR_crypto.ECDSA,
1328 	_RSAKey = RSAKey;
1329 
1330     function _rsaprv2asn1obj(keyObjOrHex) {
1331         var asn1Obj = _newObject({
1332             "seq": [
1333                 {"int": 0 },
1334                 {"int": {"bigint": keyObjOrHex.n}},
1335                 {"int": keyObjOrHex.e},
1336                 {"int": {"bigint": keyObjOrHex.d}},
1337                 {"int": {"bigint": keyObjOrHex.p}},
1338                 {"int": {"bigint": keyObjOrHex.q}},
1339                 {"int": {"bigint": keyObjOrHex.dmp1}},
1340                 {"int": {"bigint": keyObjOrHex.dmq1}},
1341                 {"int": {"bigint": keyObjOrHex.coeff}}
1342             ]
1343         });
1344         return asn1Obj;
1345     };
1346 
1347     function _ecdsaprv2asn1obj(keyObjOrHex) {
1348         var asn1Obj2 = _newObject({
1349             "seq": [
1350                 {"int": 1 },
1351                 {"octstr": {"hex": keyObjOrHex.prvKeyHex}},
1352                 {"tag": ['a0', true, {'oid': {'name': keyObjOrHex.curveName}}]},
1353                 {"tag": ['a1', true, {'bitstr': {'hex': '00' + keyObjOrHex.pubKeyHex}}]}
1354             ]
1355         });
1356         return asn1Obj2;
1357     };
1358 
1359     function _dsaprv2asn1obj(keyObjOrHex) {
1360         var asn1Obj = _newObject({
1361             "seq": [
1362                 {"int": 0 },
1363                 {"int": {"bigint": keyObjOrHex.p}},
1364                 {"int": {"bigint": keyObjOrHex.q}},
1365                 {"int": {"bigint": keyObjOrHex.g}},
1366                 {"int": {"bigint": keyObjOrHex.y}},
1367                 {"int": {"bigint": keyObjOrHex.x}}
1368             ]
1369         });
1370         return asn1Obj;
1371     };
1372 
1373     // 1. public key
1374 
1375     // x. PEM PKCS#8 public key of RSA/ECDSA/DSA public key object
1376     if (((_RSAKey !== undefined && keyObjOrHex instanceof _RSAKey) ||
1377          (_DSA !== undefined    && keyObjOrHex instanceof _DSA) ||
1378          (_ECDSA !== undefined  && keyObjOrHex instanceof _ECDSA)) &&
1379         keyObjOrHex.isPublic == true &&
1380         (formatType === undefined || formatType == "PKCS8PUB")) {
1381         var asn1Obj = new _SubjectPublicKeyInfo(keyObjOrHex);
1382         var asn1Hex = asn1Obj.getEncodedHex();
1383         return hextopem(asn1Hex, "PUBLIC KEY");
1384     }
1385     
1386     // 2. private
1387 
1388     // x. PEM PKCS#1 plain private key of RSA private key object
1389     if (formatType == "PKCS1PRV" &&
1390         _RSAKey !== undefined &&
1391         keyObjOrHex instanceof _RSAKey &&
1392         (passwd === undefined || passwd == null) &&
1393         keyObjOrHex.isPrivate  == true) {
1394 
1395         var asn1Obj = _rsaprv2asn1obj(keyObjOrHex);
1396         var asn1Hex = asn1Obj.getEncodedHex();
1397         return hextopem(asn1Hex, "RSA PRIVATE KEY");
1398     }
1399 
1400     // x. PEM PKCS#1 plain private key of ECDSA private key object
1401     if (formatType == "PKCS1PRV" &&
1402         _ECDSA !== undefined &&
1403         keyObjOrHex instanceof _ECDSA &&
1404         (passwd === undefined || passwd == null) &&
1405         keyObjOrHex.isPrivate  == true) {
1406 
1407         var asn1Obj1 = 
1408 	    new _DERObjectIdentifier({'name': keyObjOrHex.curveName});
1409         var asn1Hex1 = asn1Obj1.getEncodedHex();
1410         var asn1Obj2 = _ecdsaprv2asn1obj(keyObjOrHex);
1411         var asn1Hex2 = asn1Obj2.getEncodedHex();
1412 
1413         var s = "";
1414         s += hextopem(asn1Hex1, "EC PARAMETERS");
1415         s += hextopem(asn1Hex2, "EC PRIVATE KEY");
1416         return s;
1417     }
1418 
1419     // x. PEM PKCS#1 plain private key of DSA private key object
1420     if (formatType == "PKCS1PRV" &&
1421         _DSA !== undefined &&
1422         keyObjOrHex instanceof _DSA &&
1423         (passwd === undefined || passwd == null) &&
1424         keyObjOrHex.isPrivate  == true) {
1425 
1426         var asn1Obj = _dsaprv2asn1obj(keyObjOrHex);
1427         var asn1Hex = asn1Obj.getEncodedHex();
1428         return hextopem(asn1Hex, "DSA PRIVATE KEY");
1429     }
1430 
1431     // 3. private
1432 
1433     // x. PEM PKCS#5 encrypted private key of RSA private key object
1434     if (formatType == "PKCS5PRV" &&
1435         _RSAKey !== undefined &&
1436         keyObjOrHex instanceof _RSAKey &&
1437         (passwd !== undefined && passwd != null) &&
1438         keyObjOrHex.isPrivate  == true) {
1439 
1440         var asn1Obj = _rsaprv2asn1obj(keyObjOrHex);
1441         var asn1Hex = asn1Obj.getEncodedHex();
1442 
1443         if (encAlg === undefined) encAlg = "DES-EDE3-CBC";
1444         return this.getEncryptedPKCS5PEMFromPrvKeyHex("RSA", asn1Hex, passwd, encAlg, ivsaltHex);
1445     }
1446 
1447     // x. PEM PKCS#5 encrypted private key of ECDSA private key object
1448     if (formatType == "PKCS5PRV" &&
1449         _ECDSA !== undefined &&
1450         keyObjOrHex instanceof _ECDSA &&
1451         (passwd !== undefined && passwd != null) &&
1452         keyObjOrHex.isPrivate  == true) {
1453 
1454         var asn1Obj = _ecdsaprv2asn1obj(keyObjOrHex);
1455         var asn1Hex = asn1Obj.getEncodedHex();
1456 
1457         if (encAlg === undefined) encAlg = "DES-EDE3-CBC";
1458         return this.getEncryptedPKCS5PEMFromPrvKeyHex("EC", asn1Hex, passwd, encAlg, ivsaltHex);
1459     }
1460 
1461     // x. PEM PKCS#5 encrypted private key of DSA private key object
1462     if (formatType == "PKCS5PRV" &&
1463         _DSA !== undefined &&
1464         keyObjOrHex instanceof _DSA &&
1465         (passwd !== undefined && passwd != null) &&
1466         keyObjOrHex.isPrivate  == true) {
1467 
1468         var asn1Obj = _dsaprv2asn1obj(keyObjOrHex);
1469         var asn1Hex = asn1Obj.getEncodedHex();
1470 
1471         if (encAlg === undefined) encAlg = "DES-EDE3-CBC";
1472         return this.getEncryptedPKCS5PEMFromPrvKeyHex("DSA", asn1Hex, passwd, encAlg, ivsaltHex);
1473     }
1474 
1475     // x. ======================================================================
1476 
1477     var _getEncryptedPKCS8 = function(plainKeyHex, passcode) {
1478         var info = _getEencryptedPKCS8Info(plainKeyHex, passcode);
1479         //alert("iv=" + info.encryptionSchemeIV);
1480         //alert("info.ciphertext2[" + info.ciphertext.length + "=" + info.ciphertext);
1481         var asn1Obj = new _newObject({
1482             "seq": [
1483                 {"seq": [
1484                     {"oid": {"name": "pkcs5PBES2"}},
1485                     {"seq": [
1486                         {"seq": [
1487                             {"oid": {"name": "pkcs5PBKDF2"}},
1488                             {"seq": [
1489                                 {"octstr": {"hex": info.pbkdf2Salt}},
1490                                 {"int": info.pbkdf2Iter}
1491                             ]}
1492                         ]},
1493                         {"seq": [
1494                             {"oid": {"name": "des-EDE3-CBC"}},
1495                             {"octstr": {"hex": info.encryptionSchemeIV}}
1496                         ]}
1497                     ]}
1498                 ]},
1499                 {"octstr": {"hex": info.ciphertext}}
1500             ]
1501         });
1502         return asn1Obj.getEncodedHex();
1503     };
1504 
1505     var _getEencryptedPKCS8Info = function(plainKeyHex, passcode) {
1506         var pbkdf2Iter = 100;
1507         var pbkdf2SaltWS = CryptoJS.lib.WordArray.random(8);
1508         var encryptionSchemeAlg = "DES-EDE3-CBC";
1509         var encryptionSchemeIVWS = CryptoJS.lib.WordArray.random(8);
1510         // PBKDF2 key
1511         var pbkdf2KeyWS = CryptoJS.PBKDF2(passcode, 
1512                                           pbkdf2SaltWS, { "keySize": 192/32,
1513                                                           "iterations": pbkdf2Iter });
1514         // ENCRYPT
1515         var plainKeyWS = CryptoJS.enc.Hex.parse(plainKeyHex);
1516         var encryptedKeyHex = 
1517             CryptoJS.TripleDES.encrypt(plainKeyWS, pbkdf2KeyWS, { "iv": encryptionSchemeIVWS }) + "";
1518 
1519         //alert("encryptedKeyHex=" + encryptedKeyHex);
1520 
1521         var info = {};
1522         info.ciphertext = encryptedKeyHex;
1523         //alert("info.ciphertext=" + info.ciphertext);
1524         info.pbkdf2Salt = CryptoJS.enc.Hex.stringify(pbkdf2SaltWS);
1525         info.pbkdf2Iter = pbkdf2Iter;
1526         info.encryptionSchemeAlg = encryptionSchemeAlg;
1527         info.encryptionSchemeIV = CryptoJS.enc.Hex.stringify(encryptionSchemeIVWS);
1528         return info;
1529     };
1530 
1531     // x. PEM PKCS#8 plain private key of RSA private key object
1532     if (formatType == "PKCS8PRV" &&
1533         _RSAKey != undefined &&
1534         keyObjOrHex instanceof _RSAKey &&
1535         keyObjOrHex.isPrivate  == true) {
1536 
1537         var keyObj = _rsaprv2asn1obj(keyObjOrHex);
1538         var keyHex = keyObj.getEncodedHex();
1539 
1540         var asn1Obj = _newObject({
1541             "seq": [
1542                 {"int": 0},
1543                 {"seq": [{"oid": {"name": "rsaEncryption"}},{"null": true}]},
1544                 {"octstr": {"hex": keyHex}}
1545             ]
1546         });
1547         var asn1Hex = asn1Obj.getEncodedHex();
1548 
1549         if (passwd === undefined || passwd == null) {
1550             return hextopem(asn1Hex, "PRIVATE KEY");
1551         } else {
1552             var asn1Hex2 = _getEncryptedPKCS8(asn1Hex, passwd);
1553             return hextopem(asn1Hex2, "ENCRYPTED PRIVATE KEY");
1554         }
1555     }
1556 
1557     // x. PEM PKCS#8 plain private key of ECDSA private key object
1558     if (formatType == "PKCS8PRV" &&
1559         _ECDSA !== undefined &&
1560         keyObjOrHex instanceof _ECDSA &&
1561         keyObjOrHex.isPrivate  == true) {
1562 
1563         var keyObj = new _newObject({
1564             "seq": [
1565                 {"int": 1},
1566                 {"octstr": {"hex": keyObjOrHex.prvKeyHex}},
1567                 {"tag": ['a1', true, {"bitstr": {"hex": "00" + keyObjOrHex.pubKeyHex}}]}
1568             ]
1569         });
1570         var keyHex = keyObj.getEncodedHex();
1571 
1572         var asn1Obj = _newObject({
1573             "seq": [
1574                 {"int": 0},
1575                 {"seq": [
1576                     {"oid": {"name": "ecPublicKey"}},
1577                     {"oid": {"name": keyObjOrHex.curveName}}
1578                 ]},
1579                 {"octstr": {"hex": keyHex}}
1580             ]
1581         });
1582 
1583         var asn1Hex = asn1Obj.getEncodedHex();
1584         if (passwd === undefined || passwd == null) {
1585             return hextopem(asn1Hex, "PRIVATE KEY");
1586         } else {
1587             var asn1Hex2 = _getEncryptedPKCS8(asn1Hex, passwd);
1588             return hextopem(asn1Hex2, "ENCRYPTED PRIVATE KEY");
1589         }
1590     }
1591 
1592     // x. PEM PKCS#8 plain private key of DSA private key object
1593     if (formatType == "PKCS8PRV" &&
1594         _DSA !== undefined &&
1595         keyObjOrHex instanceof _DSA &&
1596         keyObjOrHex.isPrivate  == true) {
1597 
1598         var keyObj = new _DERInteger({'bigint': keyObjOrHex.x});
1599         var keyHex = keyObj.getEncodedHex();
1600 
1601         var asn1Obj = _newObject({
1602             "seq": [
1603                 {"int": 0},
1604                 {"seq": [
1605                     {"oid": {"name": "dsa"}},
1606                     {"seq": [
1607                         {"int": {"bigint": keyObjOrHex.p}},
1608                         {"int": {"bigint": keyObjOrHex.q}},
1609                         {"int": {"bigint": keyObjOrHex.g}}
1610                     ]}
1611                 ]},
1612                 {"octstr": {"hex": keyHex}}
1613             ]
1614         });
1615 
1616         var asn1Hex = asn1Obj.getEncodedHex();
1617         if (passwd === undefined || passwd == null) {
1618             return hextopem(asn1Hex, "PRIVATE KEY");
1619         } else {
1620             var asn1Hex2 = _getEncryptedPKCS8(asn1Hex, passwd);
1621             return hextopem(asn1Hex2, "ENCRYPTED PRIVATE KEY");
1622         }
1623     }
1624 
1625     throw new Error("unsupported object nor format");
1626 };
1627 
1628 // -- PUBLIC METHODS FOR CSR --------------------------------------------------
1629 
1630 /**
1631  * get RSAKey/DSA/ECDSA public key object from PEM formatted PKCS#10 CSR string
1632  * @name getKeyFromCSRPEM
1633  * @memberOf KEYUTIL
1634  * @function
1635  * @param {String} csrPEM PEM formatted PKCS#10 CSR string
1636  * @return {Object} RSAKey/DSA/ECDSA public key object
1637  * @since keyutil 1.0.5
1638  */
1639 KEYUTIL.getKeyFromCSRPEM = function(csrPEM) {
1640     var csrHex = pemtohex(csrPEM, "CERTIFICATE REQUEST");
1641     var key = KEYUTIL.getKeyFromCSRHex(csrHex);
1642     return key;
1643 };
1644 
1645 /**
1646  * get RSAKey/DSA/ECDSA public key object from hexadecimal string of PKCS#10 CSR
1647  * @name getKeyFromCSRHex
1648  * @memberOf KEYUTIL
1649  * @function
1650  * @param {String} csrHex hexadecimal string of PKCS#10 CSR
1651  * @return {Object} RSAKey/DSA/ECDSA public key object
1652  * @since keyutil 1.0.5
1653  */
1654 KEYUTIL.getKeyFromCSRHex = function(csrHex) {
1655     var info = KEYUTIL.parseCSRHex(csrHex);
1656     var key = KEYUTIL.getKey(info.p8pubkeyhex, null, "pkcs8pub");
1657     return key;
1658 };
1659 
1660 /**
1661  * parse hexadecimal string of PKCS#10 CSR (certificate signing request)
1662  * @name parseCSRHex
1663  * @memberOf KEYUTIL
1664  * @function
1665  * @param {String} csrHex hexadecimal string of PKCS#10 CSR
1666  * @return {Array} associative array of parsed CSR
1667  * @since keyutil 1.0.5
1668  * @description
1669  * Resulted associative array has following properties:
1670  * <ul>
1671  * <li>p8pubkeyhex - hexadecimal string of subject public key in PKCS#8</li>
1672  * </ul>
1673  */
1674 KEYUTIL.parseCSRHex = function(csrHex) {
1675     var _ASN1HEX = ASN1HEX;
1676     var _getChildIdx = _ASN1HEX.getChildIdx;
1677     var _getTLV = _ASN1HEX.getTLV;
1678     var result = {};
1679     var h = csrHex;
1680 
1681     // 1. sequence
1682     if (h.substr(0, 2) != "30")
1683         throw "malformed CSR(code:001)"; // not sequence
1684 
1685     var a1 = _getChildIdx(h, 0);
1686     if (a1.length < 1)
1687         throw "malformed CSR(code:002)"; // short length
1688 
1689     // 2. 2nd sequence
1690     if (h.substr(a1[0], 2) != "30")
1691         throw "malformed CSR(code:003)"; // not sequence
1692 
1693     var a2 = _getChildIdx(h, a1[0]);
1694     if (a2.length < 3)
1695         throw "malformed CSR(code:004)"; // 2nd seq short elem
1696 
1697     result.p8pubkeyhex = _getTLV(h, a2[2]);
1698 
1699     return result;
1700 };
1701 
1702 // -- OTHER STATIC PUBLIC METHODS  --------------------------------------------
1703 
1704 /**
1705  * get key ID by public key object for subject or authority key identifier
1706  * @name getKeyID
1707  * @memberof KEYUTIL
1708  * @function
1709  * @static
1710  * @param {Object} obj RSAKey/KJUR.crypto.ECDSA,DSA public key object or public key PEM string
1711  * @return hexadecimal string of public key identifier
1712  * @since keyutil 1.2.2 jsrsasign 5.0.16
1713  * @description
1714  * This static method generates a key identifier from a public key
1715  * by the method described in 
1716  * <a href="https://tools.ietf.org/html/rfc5280#section-4.2.1.2"
1717  * target="_blank">RFC 5280 4.2.1.2. Subject Key Identifier (1)</a>.
1718  * @example
1719  * pubkeyobj = KEYUTIL.getKey(...);
1720  * KEYTUTIL.getKey(pubkeyobj) → "a612..."
1721  */
1722 KEYUTIL.getKeyID = function(obj) {
1723     var _KEYUTIL = KEYUTIL;
1724     var _ASN1HEX = ASN1HEX;
1725 
1726     if (typeof obj  === "string" && obj.indexOf("BEGIN ") != -1) {
1727 	obj = _KEYUTIL.getKey(obj);
1728     }
1729 
1730     var p8hex = pemtohex(_KEYUTIL.getPEM(obj));
1731     var idx = _ASN1HEX.getIdxbyList(p8hex, 0, [1]); // BITSTRING
1732     var hV = _ASN1HEX.getV(p8hex, idx).substring(2); // value without unused bit
1733     return KJUR.crypto.Util.hashHex(hV, "sha1");
1734 }
1735 
1736 /**
1737  * convert from RSAKey/KJUR.crypto.ECDSA public/private key object to RFC 7517 JSON Web Key(JWK)
1738  * @name getJWKFromKey
1739  * @memberOf KEYUTIL
1740  * @function
1741  * @static
1742  * @param {Object} RSAKey/KJUR.crypto.ECDSA public/private key object
1743  * @return {Object} JWK object
1744  * @since keyutil 1.0.13 jsrsasign 5.0.14
1745  * @description
1746  * This static method convert from RSAKey/KJUR.crypto.ECDSA public/private key object 
1747  * to RFC 7517 JSON Web Key(JWK)
1748  * @example
1749  * kp1 = KEYUTIL.generateKeypair("EC", "P-256");
1750  * jwkPrv1 = KEYUTIL.getJWKFromKey(kp1.prvKeyObj);
1751  * jwkPub1 = KEYUTIL.getJWKFromKey(kp1.pubKeyObj);
1752  *
1753  * kp2 = KEYUTIL.generateKeypair("RSA", 2048);
1754  * jwkPrv2 = KEYUTIL.getJWKFromKey(kp2.prvKeyObj);
1755  * jwkPub2 = KEYUTIL.getJWKFromKey(kp2.pubKeyObj);
1756  *
1757  * // if you need RFC 7638 JWK thumprint as kid do like this:
1758  * jwkPub2.kid = KJUR.jws.JWS.getJWKthumbprint(jwkPub2);
1759  */
1760 KEYUTIL.getJWKFromKey = function(keyObj) {
1761     var jwk = {};
1762     if (keyObj instanceof RSAKey && keyObj.isPrivate) {
1763 	jwk.kty = "RSA";
1764 	jwk.n = hextob64u(keyObj.n.toString(16));
1765 	jwk.e = hextob64u(keyObj.e.toString(16));
1766 	jwk.d = hextob64u(keyObj.d.toString(16));
1767 	jwk.p = hextob64u(keyObj.p.toString(16));
1768 	jwk.q = hextob64u(keyObj.q.toString(16));
1769 	jwk.dp = hextob64u(keyObj.dmp1.toString(16));
1770 	jwk.dq = hextob64u(keyObj.dmq1.toString(16));
1771 	jwk.qi = hextob64u(keyObj.coeff.toString(16));
1772 	return jwk;
1773     } else if (keyObj instanceof RSAKey && keyObj.isPublic) {
1774 	jwk.kty = "RSA";
1775 	jwk.n = hextob64u(keyObj.n.toString(16));
1776 	jwk.e = hextob64u(keyObj.e.toString(16));
1777 	return jwk;
1778     } else if (keyObj instanceof KJUR.crypto.ECDSA && keyObj.isPrivate) {
1779 	var name = keyObj.getShortNISTPCurveName();
1780 	if (name !== "P-256" && name !== "P-384")
1781 	    throw "unsupported curve name for JWT: " + name;
1782 	var xy = keyObj.getPublicKeyXYHex();
1783 	jwk.kty = "EC";
1784 	jwk.crv =  name;
1785 	jwk.x = hextob64u(xy.x);
1786 	jwk.y = hextob64u(xy.y);
1787 	jwk.d = hextob64u(keyObj.prvKeyHex);
1788 	return jwk;
1789     } else if (keyObj instanceof KJUR.crypto.ECDSA && keyObj.isPublic) {
1790 	var name = keyObj.getShortNISTPCurveName();
1791 	if (name !== "P-256" && name !== "P-384")
1792 	    throw "unsupported curve name for JWT: " + name;
1793 	var xy = keyObj.getPublicKeyXYHex();
1794 	jwk.kty = "EC";
1795 	jwk.crv =  name;
1796 	jwk.x = hextob64u(xy.x);
1797 	jwk.y = hextob64u(xy.y);
1798 	return jwk;
1799     }
1800     throw "not supported key object";
1801 };
1802 
1803 
1804