切换风格

默认Lavender Sky Flowers Wizard Snow Beige California City Dragon Black London Sunset glow Pink Cloud

349

主题

5075

积分

25

精华

用户组 

易积分
11305
热心
102
好评
136
QQ

热心会员国庆节纪念勋章活跃会员

Java & PHP & Javascript 通用 RSA 加密 解密 (长字符串)[复制链接]
发表于 2019-12-30 23:20:36 | 显示全部楼层 |阅读模式
先给大家提前普及一下,如意验证系统1.7过些天就要发布了,本次更新将对数据进行RSA加密传输。
系统与系统的数据交互中,有些敏感数据是不能直接明文传输的,所以在发送数据之前要进行加密,在接收到数据时进行解密处理;然而由于系统与系统之间的开发语言不同。
本次需求是生成二维码是通过java生成,由php来解密。基于这类需求所以选择了RSA进行加解密。
生成RSA公私钥分成三步生成,第1、2步可以满足php的使用,由于java的私钥要转化为PKCS8格式才能使用,所以执行第3步来实现。
生成 RSA 密钥 :https://docs.open.alipay.com/291/105971/

JAVA版本加解密:

  1. import org.apache.commons.codec.binary.Base64;
  2. import org.apache.commons.lang3.ArrayUtils;

  3. import javax.crypto.Cipher;
  4. import java.security.*;
  5. import java.security.spec.PKCS8EncodedKeySpec;
  6. import java.security.spec.X509EncodedKeySpec;

  7. public class RSAUtils {

  8.     /**
  9.      * RSA最大加密明文大小
  10.      */
  11.     private static final int MAX_ENCRYPT_BLOCK = 117;

  12.     /**
  13.      * RSA最大解密密文大小
  14.      */
  15.     private static final int MAX_DECRYPT_BLOCK = 128;

  16.     public static final String SIGN_ALGORITHMS = "SHA256withRSA";

  17.     private static String ALGORITHM_RSA = "RSA";

  18.     /**
  19.      * 使用公钥将数据加密
  20.      * @param sourceData
  21.      * @param publicKey
  22.      * @return
  23.      */
  24.     public static String publicEncrypt(String sourceData, String publicKey){
  25.         return rsaEncrypt(sourceData,publicKey,false);
  26.     }

  27.     /**
  28.      * 使用私钥将数据加密
  29.      * @param sourceData
  30.      * @param privateKey
  31.      * @return
  32.      */
  33.     public static String privateEncrypt(String sourceData, String privateKey){
  34.         return rsaEncrypt(sourceData,privateKey,true);
  35.     }


  36.     /**
  37.      * 使用公钥解密
  38.      * @param encryptedData
  39.      * @param privateKey
  40.      * @return
  41.      */
  42.     public static String publicDecrypt(String encryptedData, String privateKey) {
  43.         return rsaDecrypt(encryptedData,privateKey,false);
  44.     }

  45.     /**
  46.      * 使用私钥解密
  47.      * @param encryptedData
  48.      * @param privateKey
  49.      * @return
  50.      */
  51.     public static String privateDecrypt(String encryptedData, String privateKey) {
  52.         return rsaDecrypt(encryptedData,privateKey,true);
  53.     }

  54.     protected static String rsaEncrypt(String sourceData, String key,boolean isPrivate){
  55.         try {
  56.             Key key1 = isPrivate ? loadPrivateKey(key) : loadPublicKey(key);
  57.             byte[] data = sourceData.getBytes();
  58.             byte[] dataReturn = new byte[0];
  59.             Cipher cipher = Cipher.getInstance(ALGORITHM_RSA);
  60.             cipher.init(Cipher.ENCRYPT_MODE, key1);

  61.             // 加密时超过117字节就报错。为此采用分段加密的办法来加密
  62.             StringBuilder sb = new StringBuilder();
  63.             for (int i = 0; i < data.length; i += MAX_ENCRYPT_BLOCK) {
  64.                 byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(data, i,i + MAX_ENCRYPT_BLOCK));
  65.                 sb.append(new String(doFinal));
  66.                 dataReturn = ArrayUtils.addAll(dataReturn, doFinal);
  67.             }

  68.             return Base64.encodeBase64URLSafeString(dataReturn);
  69.         } catch (Exception e) {
  70.             e.printStackTrace();
  71.             return null;
  72.         }
  73.     }

  74.     protected static String rsaDecrypt(String encryptedData, String key,boolean isPrivate){
  75.         try {
  76.             Key key1 = isPrivate ? loadPrivateKey(key) : loadPublicKey(key);
  77.             byte[] data = Base64.decodeBase64(encryptedData);

  78.             Cipher cipher = Cipher.getInstance(ALGORITHM_RSA);
  79.             cipher.init(Cipher.DECRYPT_MODE, key1);

  80.             // 解密时超过128字节就报错。为此采用分段解密的办法来解密
  81.             byte[] dataReturn = new byte[0];
  82.             for (int i = 0; i < data.length; i += MAX_DECRYPT_BLOCK) {
  83.                 byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(data, i, i + MAX_DECRYPT_BLOCK));
  84.                 dataReturn = ArrayUtils.addAll(dataReturn, doFinal);
  85.             }

  86.             return new String(dataReturn);
  87.         } catch (Exception e) {
  88.             e.printStackTrace();
  89.             return null;
  90.         }
  91.     }

  92.     /**
  93.      * 私钥加签名
  94.      * @param encryptData
  95.      * @param privateKey
  96.      * @return
  97.      */
  98.     public static String rsaSign(String encryptData, String privateKey) {
  99.         try {
  100.             Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
  101.             signature.initSign(loadPrivateKey(privateKey));
  102.             signature.update(encryptData.getBytes());
  103.             byte[] signed = signature.sign();
  104.             return Base64.encodeBase64URLSafeString(signed);
  105.         } catch (Exception e) {
  106.             e.printStackTrace();
  107.         }
  108.         return null;
  109.     }

  110.     /**
  111.      * 公钥验签
  112.      * @param encryptStr
  113.      * @param sign
  114.      * @param publicKey
  115.      * @return
  116.      * @throws Exception
  117.      */
  118.     public static boolean verifySign(String encryptStr, String sign, String publicKey)throws Exception {
  119.         try {
  120.             Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
  121.             signature.initVerify(loadPublicKey(publicKey));
  122.             signature.update(encryptStr.getBytes());
  123.             return signature.verify(Base64.decodeBase64(sign));
  124.         }  catch (NoSuchAlgorithmException e) {
  125.             throw new Exception(String.format("验证数字签名时没有[%s]此类算法", SIGN_ALGORITHMS));
  126.         } catch (InvalidKeyException e) {
  127.             throw new Exception("验证数字签名时公钥无效");
  128.         } catch (SignatureException e) {
  129.             throw new Exception("验证数字签名时出现异常");
  130.         }
  131.     }

  132.     public static PublicKey loadPublicKey(String publicKeyStr) throws Exception {
  133.         byte[] buffer = Base64.decodeBase64(publicKeyStr);
  134.         KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
  135.         X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
  136.         return keyFactory.generatePublic(keySpec);
  137.     }

  138.     public static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception {
  139.         byte[] buffer = Base64.decodeBase64(privateKeyStr);
  140.         PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
  141.         KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
  142.         return keyFactory.generatePrivate(keySpec);
  143.     }

  144.     public  static String urlsafe_encode (String encryptStr){
  145.         return encryptStr.replaceAll("\\+","-").replaceAll("/","_").replaceAll("=","").replaceAll("(\r\n|\r|\n|\n\r)","");

  146.     }

  147.     public  static String urlsafe_decode(String encryptStr){
  148.         encryptStr= encryptStr.replaceAll("-","+").replaceAll("_","/");
  149.         int mob = encryptStr.length()%4;
  150.         if(mob>0){
  151.             encryptStr+="====".substring(mob);
  152.         }
  153.         return encryptStr;
  154.     }

  155.     public  static  void main(String[ ] asdfs) throws Exception {
  156.         String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC6BSDlbRplhMMNZBKHX4xe8AwE" +
  157.                 "SpzHVfAcHHsX9FFSMuF91W3cxgT/g5n+qlLLFzCE3hWG/yX5NMAxR4mS3MlhyXKw" +
  158.                 "ko3tK9Ua691afod1lxORR3IaZ8nV7v5Bv8y4JDe4E3/f/bQIGzroWiJ0sXTcO41G" +
  159.                 "qvOw3G9leClSvjVnSwIDAQAB";
  160.         String privateKeyStr = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALoFIOVtGmWEww1k" +
  161.                 "EodfjF7wDARKnMdV8Bwcexf0UVIy4X3VbdzGBP+Dmf6qUssXMITeFYb/Jfk0wDFH" +
  162.                 "iZLcyWHJcrCSje0r1Rrr3Vp+h3WXE5FHchpnydXu/kG/zLgkN7gTf9/9tAgbOuha" +
  163.                 "InSxdNw7jUaq87Dcb2V4KVK+NWdLAgMBAAECgYBqCihhgJtOiarjBEvnrZkIOZCw" +
  164.                 "FZRfsWaJr9afph+BWw3dvH+/HYaV3YA4gwFlUlfPNgZRiTstX1u7+8q51HBa+08h" +
  165.                 "jPE8Q4GhoUY+sQ9MB8NXA6SWHNPPfMOYIeKEtKmNBdgIbtuhnob3o18rJNFIY+qC" +
  166.                 "i8djf4om93+AChmo6QJBAO31hd9qem7BnHXsxiMwS+iHlRjW9KxXva2zf+BNURSR" +
  167.                 "Z19cePReHJGE4v1C731MZlygTB5zKChQ8uZ3JLKJeX8CQQDIH4k/xbuhMb8dMdzl" +
  168.                 "AYN/CU+MgfWjlgbYjxOnTaLcbs5Mlz9v3/5I/FwqxPvzGuCjHkyh08oFfnQXvzdj" +
  169.                 "YMA1AkEApjgyOnzzZviBZXJueVgcPiKvSHmm0dg8W+Cd+72mXHqxPdCngPNYe2Ha" +
  170.                 "+VRPXDQI8LzcTwzbyUW6Vrh0/u2+2wJBAK1rZqx01VuimFLcWue4oBL+JolENXFF" +
  171.                 "GTmhAw8AIBmVjACjML3qBZmJ1vTZLtxEdlXkc9PojDCmnEPX2E+uD+ECQF2eX4EY" +
  172.                 "X95HDzQ4cm1kGQudjgfH1gZ+30DIindIHXNAOFpYeAUD7yUQP5tZO8nG38gybPJg" +
  173.                 "FoadlsSMIQIpksM=";

  174.         //加密
  175.         String data = "i like java";
  176.         String privateEncryptStr = RSAUtils.privateEncrypt(data, privateKeyStr);
  177.         String publicEncryptStr = RSAUtils.publicEncrypt(data, publicKeyStr);
  178.         String privateEncryptSign = RSAUtils.rsaSign(privateEncryptStr,privateKeyStr);
  179.         String publicEncryptSign = RSAUtils.rsaSign(publicEncryptStr,privateKeyStr);

  180.         System.out.println("source:" + data);
  181.         System.out.println("private encryptStr: " + privateEncryptStr);
  182.         System.out.println("public encryptStr: " + publicEncryptStr);
  183.         System.out.println("private encrypt sign: " + privateEncryptSign);
  184.         System.out.println("public encrypt sign: " + publicEncryptSign);
  185.         System.out.println("public decrypt:" + RSAUtils.publicDecrypt(privateEncryptStr, publicKeyStr));
  186.         System.out.println("private decrypt:" + RSAUtils.privateDecrypt(publicEncryptStr, privateKeyStr));
  187.         System.out.println("verifySign1: " + RSAUtils.verifySign(privateEncryptStr,privateEncryptSign,publicKeyStr));
  188.         System.out.println("verifySign2: " + RSAUtils.verifySign(publicEncryptStr,publicEncryptSign,publicKeyStr));

  189.         System.out.println("\r\n");
  190.         publicEncryptStr = "WopnO2LnolZ7XpOwA_ktOhfkkaQQJQgkJudk3ZH_-ob36GQFv968nE1UBXxNekA9pIHBcvcl0ZWfwFhk-kyOF2FmQvpPY9LkqiCV0T32vhJet0n93ti2PBoFILxvChjzdOgSG9M0flH78Vm696Q4mHo7VMt_XMoHDTd3Rbagvt8";
  191.         privateEncryptStr = "Fwb5BtLRveCWbx7FkXarl1zVOdwDvbDTl7gv-vPHXpj-T2wm9GlUDn3X0wnHHXkE8cqAT6PcE0g0ide6beP9_ysHMLgnC6wVqkomIKsi6C9TcGd4d6XQBjeJgdgccvDcD-7pcKrV9W-_Z7jkYkwwrjPGPd_uckEHR_cDXyOX4PU";
  192.         System.out.println("php >>>> private decrypt: " + RSAUtils.privateDecrypt(publicEncryptStr, privateKeyStr));
  193.         System.out.println("php >>>> public decrypt: " + RSAUtils.publicDecrypt(privateEncryptStr, publicKeyStr));

  194.         publicEncryptStr = "T2LFtY3dF_b6OBO07BN-3LtMSEBZqDukovDZ4HGCff8wosvlowf6IFJ3U7LFBIeHfiHBKiFuAV8-pFltCfTXtA4AwgVUnwbBMBWBfIJiLDi02ev30V-5BcYEuSF-cEdnSUd7WecrX4rHhzYLueGuj8H6c7RRbSbrJ6_3EFfU-K0";
  195.         System.out.println("js >>>> private decrypt: " + RSAUtils.privateDecrypt(publicEncryptStr, privateKeyStr));
  196.     }
  197. }
复制代码
输出如下:
  1. source: i like java
  2. private encryptStr: fHG5JMpTTF-KzrPCp827opRy3BvqmVIpIZS4gVuWqY5NeLsgoLxdrq3SaxUp_oBQ9pVqNlEiU9SIwbqJDjIqjHsCtVMOLoEdWicib_wCaoB16veKTEC4GnvviJwlS5IedH27oWGHKTTc6Ii5cLiQncjDAadvm0KCdC74yrwPqnc
  3. public encryptStr: raoQQsfN0KBfPAMRWnxr9kFPvJ6BgQ7PRBCMnz0nWsH03sD4IdlMvKpj78BHe7V7Ga1HZHyDxuJhVaJ0T5qKl8qHXzvKquzNtdMru7G4X9o8ylzkGxJLg-HYCWOrsZ77ZMaKoV9p-TCf-yMI21OpL_5JGot-XNfVVPkmg0z9FW0
  4. private encrypt sign: jlJvXY5t8KesDi3WaPr71jj2BigHLDr3b827Jl9xspbecdUjPB44Xe3sjWnzvFDLpKJGiNTvqE-Qyu3FZpG_NyI5yhVrAQgZmyYfVywmeDDsTOQYk1xP0UEfFgB0MXsFdlfSdMu5JcR5kgC5Xl5jds1b0Z2Nq7gQ-bvFJQcuHgU
  5. public encrypt sign: ngN2kQppfITyn5yAfNc1c-ofK20trKJWXIjlaJhWtm7s2jzv5rcsPY5JH06CMAIIbnKGIUcoVvMeKavAIVFb4G_h3CvXIYnxMjQL19Op-SbtyGNwT-rZzTEP8tKfxFRVm7SrHHDz2s287S3vqQz9vGEGNmgDHEdrCfHBmmoFkQA
  6. public decrypt: i like java
  7. private decrypt: i like java
  8. verifySign1: true
  9. verifySign2: true


  10. php >>>> private decrypt: i like php
  11. php >>>> public decrypt: i like php

  12. js >>>> private decrypt: i like JS
复制代码
PHP版本加解密
  1. <?php

  2. $private_key = <<<KEY
  3. -----BEGIN RSA PRIVATE KEY-----
  4. MIICXQIBAAKBgQC6BSDlbRplhMMNZBKHX4xe8AwESpzHVfAcHHsX9FFSMuF91W3c
  5. xgT/g5n+qlLLFzCE3hWG/yX5NMAxR4mS3MlhyXKwko3tK9Ua691afod1lxORR3Ia
  6. Z8nV7v5Bv8y4JDe4E3/f/bQIGzroWiJ0sXTcO41GqvOw3G9leClSvjVnSwIDAQAB
  7. AoGAagooYYCbTomq4wRL562ZCDmQsBWUX7Fmia/Wn6YfgVsN3bx/vx2Gld2AOIMB
  8. ZVJXzzYGUYk7LV9bu/vKudRwWvtPIYzxPEOBoaFGPrEPTAfDVwOklhzTz3zDmCHi
  9. hLSpjQXYCG7boZ6G96NfKyTRSGPqgovHY3+KJvd/gAoZqOkCQQDt9YXfanpuwZx1
  10. 7MYjMEvoh5UY1vSsV72ts3/gTVEUkWdfXHj0XhyRhOL9Qu99TGZcoEwecygoUPLm
  11. dySyiXl/AkEAyB+JP8W7oTG/HTHc5QGDfwlPjIH1o5YG2I8Tp02i3G7OTJc/b9/+
  12. SPxcKsT78xrgox5ModPKBX50F783Y2DANQJBAKY4Mjp882b4gWVybnlYHD4ir0h5
  13. ptHYPFvgnfu9plx6sT3Qp4DzWHth2vlUT1w0CPC83E8M28lFula4dP7tvtsCQQCt
  14. a2asdNVbophS3FrnuKAS/iaJRDVxRRk5oQMPACAZlYwAozC96gWZidb02S7cRHZV
  15. 5HPT6IwwppxD19hPrg/hAkBdnl+BGF/eRw80OHJtZBkLnY4Hx9YGft9AyIp3SB1z
  16. QDhaWHgFA+8lED+bWTvJxt/IMmzyYBaGnZbEjCECKZLD
  17. -----END RSA PRIVATE KEY-----
  18. KEY;

  19. $private8_key = <<<KEY
  20. -----BEGIN PRIVATE KEY-----
  21. MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALoFIOVtGmWEww1k
  22. EodfjF7wDARKnMdV8Bwcexf0UVIy4X3VbdzGBP+Dmf6qUssXMITeFYb/Jfk0wDFH
  23. iZLcyWHJcrCSje0r1Rrr3Vp+h3WXE5FHchpnydXu/kG/zLgkN7gTf9/9tAgbOuha
  24. InSxdNw7jUaq87Dcb2V4KVK+NWdLAgMBAAECgYBqCihhgJtOiarjBEvnrZkIOZCw
  25. FZRfsWaJr9afph+BWw3dvH+/HYaV3YA4gwFlUlfPNgZRiTstX1u7+8q51HBa+08h
  26. jPE8Q4GhoUY+sQ9MB8NXA6SWHNPPfMOYIeKEtKmNBdgIbtuhnob3o18rJNFIY+qC
  27. i8djf4om93+AChmo6QJBAO31hd9qem7BnHXsxiMwS+iHlRjW9KxXva2zf+BNURSR
  28. Z19cePReHJGE4v1C731MZlygTB5zKChQ8uZ3JLKJeX8CQQDIH4k/xbuhMb8dMdzl
  29. AYN/CU+MgfWjlgbYjxOnTaLcbs5Mlz9v3/5I/FwqxPvzGuCjHkyh08oFfnQXvzdj
  30. YMA1AkEApjgyOnzzZviBZXJueVgcPiKvSHmm0dg8W+Cd+72mXHqxPdCngPNYe2Ha
  31. +VRPXDQI8LzcTwzbyUW6Vrh0/u2+2wJBAK1rZqx01VuimFLcWue4oBL+JolENXFF
  32. GTmhAw8AIBmVjACjML3qBZmJ1vTZLtxEdlXkc9PojDCmnEPX2E+uD+ECQF2eX4EY
  33. X95HDzQ4cm1kGQudjgfH1gZ+30DIindIHXNAOFpYeAUD7yUQP5tZO8nG38gybPJg
  34. FoadlsSMIQIpksM=
  35. -----END PRIVATE KEY-----
  36. KEY;

  37. $public_key = <<<KEY
  38. -----BEGIN PUBLIC KEY-----
  39. MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC6BSDlbRplhMMNZBKHX4xe8AwE
  40. SpzHVfAcHHsX9FFSMuF91W3cxgT/g5n+qlLLFzCE3hWG/yX5NMAxR4mS3MlhyXKw
  41. ko3tK9Ua691afod1lxORR3IaZ8nV7v5Bv8y4JDe4E3/f/bQIGzroWiJ0sXTcO41G
  42. qvOw3G9leClSvjVnSwIDAQAB
  43. -----END PUBLIC KEY-----
  44. KEY;

  45. $data = 'i like php';
  46. //使用公钥将数据加密
  47. $encrypt_data = RsaUtils::publicEncrypt($data,$public_key);
  48. //使用私钥将数据解密
  49. $decrypt_data = RsaUtils::privateDecrypt($encrypt_data,$private_key);

  50. echo 'public encrypt data:'.$encrypt_data.PHP_EOL;
  51. echo 'private decrypt data:'.$decrypt_data.PHP_EOL;


  52. //使用私钥将数据加密
  53. $encrypt_data = RsaUtils::privateEncrypt($data,$private_key);
  54. //使用私钥将加密数据加签
  55. $private_encrypt_sign = RsaUtils::rsaSign($encrypt_data,$private_key);
  56. //使用公钥解签
  57. $public_check_sign = RsaUtils::verifySign($encrypt_data,$private_encrypt_sign,$public_key);
  58. //使用公钥将数据解密
  59. $decrypt_data = RsaUtils::publicDecrypt($encrypt_data,$public_key);

  60. echo 'private encrypt data: '.$encrypt_data.PHP_EOL;
  61. echo 'private encrypt sign: '.$private_encrypt_sign.PHP_EOL;
  62. echo 'public check sign: '.$public_check_sign.PHP_EOL;
  63. echo 'public decrypt data: '.$decrypt_data.PHP_EOL;



  64. //验证java加密解密方法
  65. $private_encrypt_data = 'fHG5JMpTTF-KzrPCp827opRy3BvqmVIpIZS4gVuWqY5NeLsgoLxdrq3SaxUp_oBQ9pVqNlEiU9SIwbqJDjIqjHsCtVMOLoEdWicib_wCaoB16veKTEC4GnvviJwlS5IedH27oWGHKTTc6Ii5cLiQncjDAadvm0KCdC74yrwPqnc';
  66. $public_decrypt_data = RsaUtils::publicDecrypt($private_encrypt_data,$public_key);
  67. $sign_data1 = 'jlJvXY5t8KesDi3WaPr71jj2BigHLDr3b827Jl9xspbecdUjPB44Xe3sjWnzvFDLpKJGiNTvqE-Qyu3FZpG_NyI5yhVrAQgZmyYfVywmeDDsTOQYk1xP0UEfFgB0MXsFdlfSdMu5JcR5kgC5Xl5jds1b0Z2Nq7gQ-bvFJQcuHgU';
  68. $verify_sign1 = RsaUtils::verifySign($private_encrypt_data,$sign_data1,$public_key);

  69. $public_encrypt_data = 'raoQQsfN0KBfPAMRWnxr9kFPvJ6BgQ7PRBCMnz0nWsH03sD4IdlMvKpj78BHe7V7Ga1HZHyDxuJhVaJ0T5qKl8qHXzvKquzNtdMru7G4X9o8ylzkGxJLg-HYCWOrsZ77ZMaKoV9p-TCf-yMI21OpL_5JGot-XNfVVPkmg0z9FW0';
  70. $private_decrypt_data = RsaUtils::privateDecrypt($public_encrypt_data, $private_key);
  71. $sign_data2 = 'ngN2kQppfITyn5yAfNc1c-ofK20trKJWXIjlaJhWtm7s2jzv5rcsPY5JH06CMAIIbnKGIUcoVvMeKavAIVFb4G_h3CvXIYnxMjQL19Op-SbtyGNwT-rZzTEP8tKfxFRVm7SrHHDz2s287S3vqQz9vGEGNmgDHEdrCfHBmmoFkQA';
  72. $verify_sign2 = RsaUtils::verifySign($public_encrypt_data,$sign_data2,$public_key);

  73. echo PHP_EOL;
  74. echo 'public_decrypt_data: '.$public_decrypt_data.PHP_EOL;
  75. echo 'verifySign1: '. $verify_sign1.PHP_EOL;

  76. echo 'private_decrypt_data: '.$private_decrypt_data.PHP_EOL;
  77. echo 'verifySign2: '. $verify_sign2.PHP_EOL;

  78. $public_encrypt_data = 'T2LFtY3dF_b6OBO07BN-3LtMSEBZqDukovDZ4HGCff8wosvlowf6IFJ3U7LFBIeHfiHBKiFuAV8-pFltCfTXtA4AwgVUnwbBMBWBfIJiLDi02ev30V-5BcYEuSF-cEdnSUd7WecrX4rHhzYLueGuj8H6c7RRbSbrJ6_3EFfU-K0';
  79. $private_decrypt_data = RsaUtils::privateDecrypt($public_encrypt_data,$private_key);
  80. echo PHP_EOL;
  81. echo 'private_decrypt_data: '.$private_decrypt_data.PHP_EOL;



  82. class RsaUtils{

  83.     /**
  84.      * 签名算法,SHA256WithRSA
  85.      */
  86.     private const SIGNATURE_ALGORITHM = OPENSSL_ALGO_SHA256;

  87.     /**
  88.      * RSA最大加密明文大小
  89.      */
  90.     private const MAX_ENCRYPT_BLOCK = 117;

  91.     /**
  92.      * RSA最大解密密文大小
  93.      */
  94.     private const MAX_DECRYPT_BLOCK = 128;

  95.     /**
  96.      * 使用公钥将数据加密
  97.      * @param $data string 需要加密的数据
  98.      * @param $publicKey string 公钥
  99.      * @return string 返回加密串(base64编码)
  100.      */
  101.     public static function publicEncrypt($data,$publicKey){
  102.         $data = str_split($data, self::MAX_ENCRYPT_BLOCK);

  103.         $encrypted = '';
  104.         foreach($data as & $chunk){
  105.             if(!openssl_public_encrypt($chunk, $encryptData, $publicKey)){
  106.                 return '';
  107.             }else{
  108.                 $encrypted .= $encryptData;
  109.             }
  110.         }
  111.         return self::urlSafeBase64encode($encrypted);
  112.     }

  113.     /**
  114.      * 使用私钥解密
  115.      * @param $data string 需要解密的数据
  116.      * @param $privateKey string 私钥
  117.      * @return string 返回解密串
  118.      */
  119.     public static function privateDecrypt($data,$privateKey){
  120.         $data = str_split(self::urlSafeBase64decode($data), self::MAX_DECRYPT_BLOCK);

  121.         $decrypted = '';
  122.         foreach($data as & $chunk){
  123.             if(!openssl_private_decrypt($chunk, $decryptData, $privateKey)){
  124.                 return '';
  125.             }else{
  126.                 $decrypted .= $decryptData;
  127.             }
  128.         }
  129.         return $decrypted;
  130.     }

  131.     /**
  132.      * 使用私钥将数据加密
  133.      * @param $data string 需要加密的数据
  134.      * @param $privateKey string 私钥
  135.      * @return string 返回加密串(base64编码)
  136.      */
  137.     public static function privateEncrypt($data,$privateKey){
  138.         $data = str_split($data, self::MAX_ENCRYPT_BLOCK);

  139.         $encrypted = '';
  140.         foreach($data as & $chunk){
  141.             if(!openssl_private_encrypt($chunk, $encryptData, $privateKey)){
  142.                 return '';
  143.             }else{
  144.                 $encrypted .= $encryptData;
  145.             }
  146.         }
  147.         return self::urlSafeBase64encode($encrypted);
  148.     }


  149.     /**
  150.      * 使用公钥解密
  151.      * @param $data string 需要解密的数据
  152.      * @param $publicKey string 公钥
  153.      * @return string 返回解密串
  154.      */
  155.     public static function publicDecrypt($data,$publicKey){
  156.         $data = str_split(self::urlSafeBase64decode($data), self::MAX_DECRYPT_BLOCK);

  157.         $decrypted = '';
  158.         foreach($data as & $chunk){
  159.             if(!openssl_public_decrypt($chunk, $decryptData, $publicKey)){
  160.                 return '';
  161.             }else{
  162.                 $decrypted .= $decryptData;
  163.             }
  164.         }
  165.         return $decrypted;
  166.     }


  167.     /**
  168.      * 私钥加签名
  169.      * @param $data 被加签数据
  170.      * @param $privateKey 私钥
  171.      * @return mixed|string
  172.      */
  173.     public static function rsaSign($data, $privateKey){
  174.         if(openssl_sign($data, $sign, $privateKey, self::SIGNATURE_ALGORITHM)){
  175.             return self::urlSafeBase64encode($sign);
  176.         }
  177.         return '';
  178.     }

  179.     /**
  180.      * 公钥验签
  181.      * @param $data 被加签数据
  182.      * @param $sign 签名
  183.      * @param $publicKey 公钥
  184.      * @return bool
  185.      */
  186.     public static function verifySign($data, $sign, $publicKey):bool {
  187.         return (1 == openssl_verify($data, self::urlSafeBase64decode($sign), $publicKey, self::SIGNATURE_ALGORITHM));
  188.     }

  189.     /**
  190.      * url base64编码
  191.      * @param $string
  192.      * @return mixed|string
  193.      */
  194.     public static function urlSafeBase64encode($string){
  195.         $data = str_replace(array('+','/','='), array( '-','_',''), base64_encode($string));
  196.         return $data;
  197.     }

  198.     /**
  199.      * url base64解码
  200.      * @param $string
  201.      * @return bool|string
  202.      */
  203.     public static function urlSafeBase64decode($string){
  204.         $data = str_replace(array('-','_'), array('+','/'), $string);
  205.         $mod4 = strlen($data) % 4;
  206.         if($mod4){
  207.             $data .= substr('====', $mod4);
  208.         }
  209.         return base64_decode($data);
  210.     }
  211. }
复制代码
输出如下:
  1. public encrypt data: WopnO2LnolZ7XpOwA_ktOhfkkaQQJQgkJudk3ZH_-ob36GQFv968nE1UBXxNekA9pIHBcvcl0ZWfwFhk-kyOF2FmQvpPY9LkqiCV0T32vhJet0n93ti2PBoFILxvChjzdOgSG9M0flH78Vm696Q4mHo7VMt_XMoHDTd3Rbagvt8
  2. private decrypt data: i like php
  3. public encrypt data: Fwb5BtLRveCWbx7FkXarl1zVOdwDvbDTl7gv-vPHXpj-T2wm9GlUDn3X0wnHHXkE8cqAT6PcE0g0ide6beP9_ysHMLgnC6wVqkomIKsi6C9TcGd4d6XQBjeJgdgccvDcD-7pcKrV9W-_Z7jkYkwwrjPGPd_uckEHR_cDXyOX4PU
  4. private rsa sign: T-I3KLkBEMRi9YdflyjNZxh_IhEC2mG4vFaq5FeFzs03l7ojtmf3pXFOwjz6qbHUwIJ-tjIMVammfCrYKa0AjMAX_L7-99_EUPmMvmjXS_8z0aZuY5dZPgRCBxklKem56r0qss-iSGTGsh3eivhUiHvtRTBXhtbkpjjlkkqXy-k
  5. public check sign: 1
  6. private decrypt data: i like php

  7. public_decrypt_data: i like java
  8. verifySign1: 1
  9. private_decrypt_data: i like java
  10. verifySign2: 1

  11. private_decrypt_data: i like JS
复制代码
JS版本加解密
  1. var b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  2. var b64pad = "=";

  3. var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";

  4. //整型转字符串
  5. function int2char(n) {
  6.     return BI_RM.charAt(n);
  7. }

  8. //十六进制转Base64字符串
  9. function hex2b64(h) {
  10.     var i;
  11.     var c;
  12.     var ret = "";
  13.     for (i = 0; i + 3 <= h.length; i += 3) {
  14.         c = parseInt(h.substring(i, i + 3), 16);
  15.         ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
  16.     }
  17.     if (i + 1 == h.length) {
  18.         c = parseInt(h.substring(i, i + 1), 16);
  19.         ret += b64map.charAt(c << 2);
  20.     }
  21.     else if (i + 2 == h.length) {
  22.         c = parseInt(h.substring(i, i + 2), 16);
  23.         ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4);
  24.     }
  25.     while ((ret.length & 3) > 0) {
  26.         ret += b64pad;
  27.     }
  28.     return ret;
  29. }

  30. //Base64字符串转十六进制
  31. function b64tohex(s) {
  32.     var ret = "";
  33.     var i;
  34.     var k = 0; // b64 state, 0-3
  35.     var slop = 0;
  36.     for (i = 0; i < s.length; ++i) {
  37.         if (s.charAt(i) == b64pad) {
  38.             break;
  39.         }
  40.         var v = b64map.indexOf(s.charAt(i));
  41.         if (v < 0) {
  42.             continue;
  43.         }
  44.         if (k == 0) {
  45.             ret += int2char(v >> 2);
  46.             slop = v & 3;
  47.             k = 1;
  48.         }
  49.         else if (k == 1) {
  50.             ret += int2char((slop << 2) | (v >> 4));
  51.             slop = v & 0xf;
  52.             k = 2;
  53.         }
  54.         else if (k == 2) {
  55.             ret += int2char(slop);
  56.             ret += int2char(v >> 2);
  57.             slop = v & 3;
  58.             k = 3;
  59.         }
  60.         else {
  61.             ret += int2char((slop << 2) | (v >> 4));
  62.             ret += int2char(v & 0xf);
  63.             k = 0;
  64.         }
  65.     }
  66.     if (k == 1) {
  67.         ret += int2char(slop << 2);
  68.     }
  69.     return ret;
  70. }

  71. //十六进制转字节
  72. function hexToBytes(hex) {
  73.     for (var bytes = [], c = 0; c < hex.length; c += 2)
  74.         bytes.push(parseInt(hex.substr(c, 2), 16));
  75.     return bytes;
  76. }

  77. //字节转十六进制
  78. function bytesToHex(bytes) {
  79.     for (var hex = [], i = 0; i < bytes.length; i++) {
  80.         hex.push((bytes[i] >>> 4).toString(16));
  81.         hex.push((bytes[i] & 0xF).toString(16));
  82.     }
  83.     return hex.join("");
  84. }

  85. String.prototype.replaceAllStr=function(f,e){
  86.     var reg=new RegExp(f,"g");
  87.     return this.replace(reg,e);
  88. }

  89. function urlsafeEncode(e) {
  90.     return e.replaceAllStr("\\+","-").replaceAllStr("/","_").replaceAllStr("=","");
  91. }

  92. function urlsafeDecode(e) {
  93.     e =  e.replaceAllStr("-","+").replaceAllStr("_","/");
  94.     var mob = e.length%4;
  95.     if(mob>0){
  96.         e += "====".substr(mob);
  97.     }
  98.     return e;
  99. }


  100. //长字符串加密
  101. JSEncrypt.prototype.encryptLong = function (string) {
  102.     var k = this.getKey();
  103.     //var MAX_ENCRYPT_BLOCK = (((k.n.bitLength() + 7) >> 3) - 11);
  104.     var MAX_ENCRYPT_BLOCK = 117;

  105.     try {
  106.         var lt = "";
  107.         var ct = "";
  108.         //RSA每次加密117bytes,需要辅助方法判断字符串截取位置
  109.         //1.获取字符串截取点
  110.         var bytes = new Array();
  111.         bytes.push(0);
  112.         var byteNo = 0;
  113.         var len, c;
  114.         len = string.length;

  115.         var temp = 0;
  116.         for (var i = 0; i < len; i++) {
  117.             c = string.charCodeAt(i);
  118.             if (c >= 0x010000 && c <= 0x10FFFF) {
  119.                 byteNo += 4;
  120.             } else if (c >= 0x000800 && c <= 0x00FFFF) {
  121.                 byteNo += 3;
  122.             } else if (c >= 0x000080 && c <= 0x0007FF) {
  123.                 byteNo += 2;
  124.             } else {
  125.                 byteNo += 1;
  126.             }
  127.             if ((byteNo % MAX_ENCRYPT_BLOCK) >= 114 || (byteNo % MAX_ENCRYPT_BLOCK) == 0) {
  128.                 if (byteNo - temp >= 114) {
  129.                     bytes.push(i);
  130.                     temp = byteNo;
  131.                 }
  132.             }
  133.         }

  134.         //2.截取字符串并分段加密
  135.         if (bytes.length > 1) {
  136.             for (var i = 0; i < bytes.length - 1; i++) {
  137.                 var str;
  138.                 if (i == 0) {
  139.                     str = string.substring(0, bytes[i + 1] + 1);
  140.                 } else {
  141.                     str = string.substring(bytes[i] + 1, bytes[i + 1] + 1);
  142.                 }
  143.                 var t1 = k.encrypt(str);
  144.                 ct += t1;
  145.             }
  146.             ;
  147.             if (bytes[bytes.length - 1] != string.length - 1) {
  148.                 var lastStr = string.substring(bytes[bytes.length - 1] + 1);
  149.                 ct += k.encrypt(lastStr);
  150.             }
  151.             return hex2b64(ct);
  152.         }
  153.         var t = k.encrypt(string);
  154.         var y = hex2b64(t);
  155.         return y;
  156.     } catch (ex) {
  157.         return false;
  158.     }
  159. };

  160. //长字符串解密
  161. JSEncrypt.prototype.decryptLong = function (string) {
  162.     var k = this.getKey();
  163.     // var MAX_DECRYPT_BLOCK = ((k.n.bitLength()+7)>>3);
  164.     var MAX_DECRYPT_BLOCK = 128;
  165.     try {
  166.         var ct = "";
  167.         var t1;
  168.         var bufTmp;
  169.         var hexTmp;
  170.         var str = b64tohex(string);
  171.         var buf = hexToBytes(str);
  172.         var inputLen = buf.length;
  173.         //开始长度
  174.         var offSet = 0;
  175.         //结束长度
  176.         var endOffSet = MAX_DECRYPT_BLOCK;

  177.         //分段加密
  178.         while (inputLen - offSet > 0) {
  179.             if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
  180.                 bufTmp = buf.slice(offSet, endOffSet);
  181.                 hexTmp = bytesToHex(bufTmp);
  182.                 t1 = k.decrypt(hexTmp);
  183.                 ct += t1;

  184.             } else {
  185.                 bufTmp = buf.slice(offSet, inputLen);
  186.                 hexTmp = bytesToHex(bufTmp);
  187.                 t1 = k.decrypt(hexTmp);
  188.                 ct += t1;

  189.             }
  190.             offSet += MAX_DECRYPT_BLOCK;
  191.             endOffSet += MAX_DECRYPT_BLOCK;
  192.         }
  193.         return ct;
  194.     } catch (ex) {
  195.         return false;
  196.     }
  197. };


  198. // Call this code when the page is done loading.
  199. var publicKeyStr =  "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC6BSDlbRplhMMNZBKHX4xe8AwE" +
  200.     "SpzHVfAcHHsX9FFSMuF91W3cxgT/g5n+qlLLFzCE3hWG/yX5NMAxR4mS3MlhyXKw" +
  201.     "ko3tK9Ua691afod1lxORR3IaZ8nV7v5Bv8y4JDe4E3/f/bQIGzroWiJ0sXTcO41G" +
  202.     "qvOw3G9leClSvjVnSwIDAQAB";

  203. var privateKeyStr = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALoFIOVtGmWEww1k" +
  204.     "EodfjF7wDARKnMdV8Bwcexf0UVIy4X3VbdzGBP+Dmf6qUssXMITeFYb/Jfk0wDFH" +
  205.     "iZLcyWHJcrCSje0r1Rrr3Vp+h3WXE5FHchpnydXu/kG/zLgkN7gTf9/9tAgbOuha" +
  206.     "InSxdNw7jUaq87Dcb2V4KVK+NWdLAgMBAAECgYBqCihhgJtOiarjBEvnrZkIOZCw" +
  207.     "FZRfsWaJr9afph+BWw3dvH+/HYaV3YA4gwFlUlfPNgZRiTstX1u7+8q51HBa+08h" +
  208.     "jPE8Q4GhoUY+sQ9MB8NXA6SWHNPPfMOYIeKEtKmNBdgIbtuhnob3o18rJNFIY+qC" +
  209.     "i8djf4om93+AChmo6QJBAO31hd9qem7BnHXsxiMwS+iHlRjW9KxXva2zf+BNURSR" +
  210.     "Z19cePReHJGE4v1C731MZlygTB5zKChQ8uZ3JLKJeX8CQQDIH4k/xbuhMb8dMdzl" +
  211.     "AYN/CU+MgfWjlgbYjxOnTaLcbs5Mlz9v3/5I/FwqxPvzGuCjHkyh08oFfnQXvzdj" +
  212.     "YMA1AkEApjgyOnzzZviBZXJueVgcPiKvSHmm0dg8W+Cd+72mXHqxPdCngPNYe2Ha" +
  213.     "+VRPXDQI8LzcTwzbyUW6Vrh0/u2+2wJBAK1rZqx01VuimFLcWue4oBL+JolENXFF" +
  214.     "GTmhAw8AIBmVjACjML3qBZmJ1vTZLtxEdlXkc9PojDCmnEPX2E+uD+ECQF2eX4EY" +
  215.     "X95HDzQ4cm1kGQudjgfH1gZ+30DIindIHXNAOFpYeAUD7yUQP5tZO8nG38gybPJg" +
  216.     "FoadlsSMIQIpksM=";


  217. var sourceStr = "i like JS";

  218. //公钥加密
  219. var encrypt = new JSEncrypt();
  220. encrypt.setPublicKey(publicKeyStr);
  221. var encrypted = encrypt.encryptLong(sourceStr);
  222. encrypted = urlsafeEncode(encrypted);

  223. //私钥解密
  224. var decrypt = new JSEncrypt();
  225. decrypt.setPrivateKey(privateKeyStr);
  226. var uncrypted = decrypt.decryptLong(urlsafeDecode(encrypted));

  227. console.log("public encrypted: ",encrypted);
  228. console.log("private uncrypted: ",uncrypted);
  229.   console.log("private uncrypted: ",decrypt.decryptLong(urlsafeDecode("WopnO2LnolZ7XpOwA_ktOhfkkaQQJQgkJudk3ZH_-ob36GQFv968nE1UBXxNekA9pIHBcvcl0ZWfwFhk-kyOF2FmQvpPY9LkqiCV0T32vhJet0n93ti2PBoFILxvChjzdOgSG9M0flH78Vm696Q4mHo7VMt_XMoHDTd3Rbagvt8")));
  230.   console.log("private uncrypted: ",decrypt.decryptLong(urlsafeDecode("raoQQsfN0KBfPAMRWnxr9kFPvJ6BgQ7PRBCMnz0nWsH03sD4IdlMvKpj78BHe7V7Ga1HZHyDxuJhVaJ0T5qKl8qHXzvKquzNtdMru7G4X9o8ylzkGxJLg-HYCWOrsZ77ZMaKoV9p-TCf-yMI21OpL_5JGot-XNfVVPkmg0z9FW0")));
复制代码
jsencrypt.js:
  1. (function (global, factory) {
  2.     typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3.         typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4.             (factory((global.JSEncrypt = {})));
  5. }(this, (function (exports) { 'use strict';

  6.     var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
  7.     function int2char(n) {
  8.         return BI_RM.charAt(n);
  9.     }
  10. //#region BIT_OPERATIONS
  11. // (public) this & a
  12.     function op_and(x, y) {
  13.         return x & y;
  14.     }
  15. // (public) this | a
  16.     function op_or(x, y) {
  17.         return x | y;
  18.     }
  19. // (public) this ^ a
  20.     function op_xor(x, y) {
  21.         return x ^ y;
  22.     }
  23. // (public) this & ~a
  24.     function op_andnot(x, y) {
  25.         return x & ~y;
  26.     }
  27. // return index of lowest 1-bit in x, x < 2^31
  28.     function lbit(x) {
  29.         if (x == 0) {
  30.             return -1;
  31.         }
  32.         var r = 0;
  33.         if ((x & 0xffff) == 0) {
  34.             x >>= 16;
  35.             r += 16;
  36.         }
  37.         if ((x & 0xff) == 0) {
  38.             x >>= 8;
  39.             r += 8;
  40.         }
  41.         if ((x & 0xf) == 0) {
  42.             x >>= 4;
  43.             r += 4;
  44.         }
  45.         if ((x & 3) == 0) {
  46.             x >>= 2;
  47.             r += 2;
  48.         }
  49.         if ((x & 1) == 0) {
  50.             ++r;
  51.         }
  52.         return r;
  53.     }
  54. // return number of 1 bits in x
  55.     function cbit(x) {
  56.         var r = 0;
  57.         while (x != 0) {
  58.             x &= x - 1;
  59.             ++r;
  60.         }
  61.         return r;
  62.     }
  63. //#endregion BIT_OPERATIONS

  64.     var b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  65.     var b64pad = "=";
  66.     function hex2b64(h) {
  67.         var i;
  68.         var c;
  69.         var ret = "";
  70.         for (i = 0; i + 3 <= h.length; i += 3) {
  71.             c = parseInt(h.substring(i, i + 3), 16);
  72.             ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
  73.         }
  74.         if (i + 1 == h.length) {
  75.             c = parseInt(h.substring(i, i + 1), 16);
  76.             ret += b64map.charAt(c << 2);
  77.         }
  78.         else if (i + 2 == h.length) {
  79.             c = parseInt(h.substring(i, i + 2), 16);
  80.             ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4);
  81.         }
  82.         while ((ret.length & 3) > 0) {
  83.             ret += b64pad;
  84.         }
  85.         return ret;
  86.     }
  87. // convert a base64 string to hex
  88.     function b64tohex(s) {
  89.         var ret = "";
  90.         var i;
  91.         var k = 0; // b64 state, 0-3
  92.         var slop = 0;
  93.         for (i = 0; i < s.length; ++i) {
  94.             if (s.charAt(i) == b64pad) {
  95.                 break;
  96.             }
  97.             var v = b64map.indexOf(s.charAt(i));
  98.             if (v < 0) {
  99.                 continue;
  100.             }
  101.             if (k == 0) {
  102.                 ret += int2char(v >> 2);
  103.                 slop = v & 3;
  104.                 k = 1;
  105.             }
  106.             else if (k == 1) {
  107.                 ret += int2char((slop << 2) | (v >> 4));
  108.                 slop = v & 0xf;
  109.                 k = 2;
  110.             }
  111.             else if (k == 2) {
  112.                 ret += int2char(slop);
  113.                 ret += int2char(v >> 2);
  114.                 slop = v & 3;
  115.                 k = 3;
  116.             }
  117.             else {
  118.                 ret += int2char((slop << 2) | (v >> 4));
  119.                 ret += int2char(v & 0xf);
  120.                 k = 0;
  121.             }
  122.         }
  123.         if (k == 1) {
  124.             ret += int2char(slop << 2);
  125.         }
  126.         return ret;
  127.     }

  128.     /*! *****************************************************************************
  129. Copyright (c) Microsoft Corporation. All rights reserved.
  130. Licensed under the Apache License, Version 2.0 (the "License"); you may not use
  131. this file except in compliance with the License. You may obtain a copy of the
  132. License at http://www.apache.org/licenses/LICENSE-2.0

  133. THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  134. KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  135. WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  136. MERCHANTABLITY OR NON-INFRINGEMENT.

  137. See the Apache Version 2.0 License for specific language governing permissions
  138. and limitations under the License.
  139. ***************************************************************************** */
  140.     /* global Reflect, Promise */

  141.     var extendStatics = function(d, b) {
  142.         extendStatics = Object.setPrototypeOf ||
  143.             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  144.             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  145.         return extendStatics(d, b);
  146.     };

  147.     function __extends(d, b) {
  148.         extendStatics(d, b);
  149.         function __() { this.constructor = d; }
  150.         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  151.     }

  152. // Hex JavaScript decoder
  153. // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
  154. // Permission to use, copy, modify, and/or distribute this software for any
  155. // purpose with or without fee is hereby granted, provided that the above
  156. // copyright notice and this permission notice appear in all copies.
  157. //
  158. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  159. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  160. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  161. // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  162. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  163. // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  164. // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  165.     /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
  166.     var decoder;
  167.     var Hex = {
  168.         decode: function (a) {
  169.             var i;
  170.             if (decoder === undefined) {
  171.                 var hex = "0123456789ABCDEF";
  172.                 var ignore = " \f\n\r\t\u00A0\u2028\u2029";
  173.                 decoder = {};
  174.                 for (i = 0; i < 16; ++i) {
  175.                     decoder[hex.charAt(i)] = i;
  176.                 }
  177.                 hex = hex.toLowerCase();
  178.                 for (i = 10; i < 16; ++i) {
  179.                     decoder[hex.charAt(i)] = i;
  180.                 }
  181.                 for (i = 0; i < ignore.length; ++i) {
  182.                     decoder[ignore.charAt(i)] = -1;
  183.                 }
  184.             }
  185.             var out = [];
  186.             var bits = 0;
  187.             var char_count = 0;
  188.             for (i = 0; i < a.length; ++i) {
  189.                 var c = a.charAt(i);
  190.                 if (c == "=") {
  191.                     break;
  192.                 }
  193.                 c = decoder[c];
  194.                 if (c == -1) {
  195.                     continue;
  196.                 }
  197.                 if (c === undefined) {
  198.                     throw new Error("Illegal character at offset " + i);
  199.                 }
  200.                 bits |= c;
  201.                 if (++char_count >= 2) {
  202.                     out[out.length] = bits;
  203.                     bits = 0;
  204.                     char_count = 0;
  205.                 }
  206.                 else {
  207.                     bits <<= 4;
  208.                 }
  209.             }
  210.             if (char_count) {
  211.                 throw new Error("Hex encoding incomplete: 4 bits missing");
  212.             }
  213.             return out;
  214.         }
  215.     };

  216. // Base64 JavaScript decoder
  217. // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
  218. // Permission to use, copy, modify, and/or distribute this software for any
  219. // purpose with or without fee is hereby granted, provided that the above
  220. // copyright notice and this permission notice appear in all copies.
  221. //
  222. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  223. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  224. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  225. // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  226. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  227. // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  228. // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  229.     /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
  230.     var decoder$1;
  231.     var Base64 = {
  232.         decode: function (a) {
  233.             var i;
  234.             if (decoder$1 === undefined) {
  235.                 var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  236.                 var ignore = "= \f\n\r\t\u00A0\u2028\u2029";
  237.                 decoder$1 = Object.create(null);
  238.                 for (i = 0; i < 64; ++i) {
  239.                     decoder$1[b64.charAt(i)] = i;
  240.                 }
  241.                 for (i = 0; i < ignore.length; ++i) {
  242.                     decoder$1[ignore.charAt(i)] = -1;
  243.                 }
  244.             }
  245.             var out = [];
  246.             var bits = 0;
  247.             var char_count = 0;
  248.             for (i = 0; i < a.length; ++i) {
  249.                 var c = a.charAt(i);
  250.                 if (c == "=") {
  251.                     break;
  252.                 }
  253.                 c = decoder$1[c];
  254.                 if (c == -1) {
  255.                     continue;
  256.                 }
  257.                 if (c === undefined) {
  258.                     throw new Error("Illegal character at offset " + i);
  259.                 }
  260.                 bits |= c;
  261.                 if (++char_count >= 4) {
  262.                     out[out.length] = (bits >> 16);
  263.                     out[out.length] = (bits >> 8) & 0xFF;
  264.                     out[out.length] = bits & 0xFF;
  265.                     bits = 0;
  266.                     char_count = 0;
  267.                 }
  268.                 else {
  269.                     bits <<= 6;
  270.                 }
  271.             }
  272.             switch (char_count) {
  273.                 case 1:
  274.                     throw new Error("Base64 encoding incomplete: at least 2 bits missing");
  275.                 case 2:
  276.                     out[out.length] = (bits >> 10);
  277.                     break;
  278.                 case 3:
  279.                     out[out.length] = (bits >> 16);
  280.                     out[out.length] = (bits >> 8) & 0xFF;
  281.                     break;
  282.             }
  283.             return out;
  284.         },
  285.         re: /-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/,
  286.         unarmor: function (a) {
  287.             var m = Base64.re.exec(a);
  288.             if (m) {
  289.                 if (m[1]) {
  290.                     a = m[1];
  291.                 }
  292.                 else if (m[2]) {
  293.                     a = m[2];
  294.                 }
  295.                 else {
  296.                     throw new Error("RegExp out of sync");
  297.                 }
  298.             }
  299.             return Base64.decode(a);
  300.         }
  301.     };

  302. // Big integer base-10 printing library
  303. // Copyright (c) 2014 Lapo Luchini <lapo@lapo.it>
  304. // Permission to use, copy, modify, and/or distribute this software for any
  305. // purpose with or without fee is hereby granted, provided that the above
  306. // copyright notice and this permission notice appear in all copies.
  307. //
  308. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  309. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  310. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  311. // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  312. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  313. // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  314. // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  315.     /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
  316.     var max = 10000000000000; // biggest integer that can still fit 2^53 when multiplied by 256
  317.     var Int10 = /** @class */ (function () {
  318.         function Int10(value) {
  319.             this.buf = [+value || 0];
  320.         }
  321.         Int10.prototype.mulAdd = function (m, c) {
  322.             // assert(m <= 256)
  323.             var b = this.buf;
  324.             var l = b.length;
  325.             var i;
  326.             var t;
  327.             for (i = 0; i < l; ++i) {
  328.                 t = b[i] * m + c;
  329.                 if (t < max) {
  330.                     c = 0;
  331.                 }
  332.                 else {
  333.                     c = 0 | (t / max);
  334.                     t -= c * max;
  335.                 }
  336.                 b[i] = t;
  337.             }
  338.             if (c > 0) {
  339.                 b[i] = c;
  340.             }
  341.         };
  342.         Int10.prototype.sub = function (c) {
  343.             // assert(m <= 256)
  344.             var b = this.buf;
  345.             var l = b.length;
  346.             var i;
  347.             var t;
  348.             for (i = 0; i < l; ++i) {
  349.                 t = b[i] - c;
  350.                 if (t < 0) {
  351.                     t += max;
  352.                     c = 1;
  353.                 }
  354.                 else {
  355.                     c = 0;
  356.                 }
  357.                 b[i] = t;
  358.             }
  359.             while (b[b.length - 1] === 0) {
  360.                 b.pop();
  361.             }
  362.         };
  363.         Int10.prototype.toString = function (base) {
  364.             if ((base || 10) != 10) {
  365.                 throw new Error("only base 10 is supported");
  366.             }
  367.             var b = this.buf;
  368.             var s = b[b.length - 1].toString();
  369.             for (var i = b.length - 2; i >= 0; --i) {
  370.                 s += (max + b[i]).toString().substring(1);
  371.             }
  372.             return s;
  373.         };
  374.         Int10.prototype.valueOf = function () {
  375.             var b = this.buf;
  376.             var v = 0;
  377.             for (var i = b.length - 1; i >= 0; --i) {
  378.                 v = v * max + b[i];
  379.             }
  380.             return v;
  381.         };
  382.         Int10.prototype.simplify = function () {
  383.             var b = this.buf;
  384.             return (b.length == 1) ? b[0] : this;
  385.         };
  386.         return Int10;
  387.     }());

  388. // ASN.1 JavaScript decoder
  389.     var ellipsis = "\u2026";
  390.     var reTimeS = /^(\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/;
  391.     var reTimeL = /^(\d\d\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/;
  392.     function stringCut(str, len) {
  393.         if (str.length > len) {
  394.             str = str.substring(0, len) + ellipsis;
  395.         }
  396.         return str;
  397.     }
  398.     var Stream = /** @class */ (function () {
  399.         function Stream(enc, pos) {
  400.             this.hexDigits = "0123456789ABCDEF";
  401.             if (enc instanceof Stream) {
  402.                 this.enc = enc.enc;
  403.                 this.pos = enc.pos;
  404.             }
  405.             else {
  406.                 // enc should be an array or a binary string
  407.                 this.enc = enc;
  408.                 this.pos = pos;
  409.             }
  410.         }
  411.         Stream.prototype.get = function (pos) {
  412.             if (pos === undefined) {
  413.                 pos = this.pos++;
  414.             }
  415.             if (pos >= this.enc.length) {
  416.                 throw new Error("Requesting byte offset " + pos + " on a stream of length " + this.enc.length);
  417.             }
  418.             return ("string" === typeof this.enc) ? this.enc.charCodeAt(pos) : this.enc[pos];
  419.         };
  420.         Stream.prototype.hexByte = function (b) {
  421.             return this.hexDigits.charAt((b >> 4) & 0xF) + this.hexDigits.charAt(b & 0xF);
  422.         };
  423.         Stream.prototype.hexDump = function (start, end, raw) {
  424.             var s = "";
  425.             for (var i = start; i < end; ++i) {
  426.                 s += this.hexByte(this.get(i));
  427.                 if (raw !== true) {
  428.                     switch (i & 0xF) {
  429.                         case 0x7:
  430.                             s += "  ";
  431.                             break;
  432.                         case 0xF:
  433.                             s += "\n";
  434.                             break;
  435.                         default:
  436.                             s += " ";
  437.                     }
  438.                 }
  439.             }
  440.             return s;
  441.         };
  442.         Stream.prototype.isASCII = function (start, end) {
  443.             for (var i = start; i < end; ++i) {
  444.                 var c = this.get(i);
  445.                 if (c < 32 || c > 176) {
  446.                     return false;
  447.                 }
  448.             }
  449.             return true;
  450.         };
  451.         Stream.prototype.parseStringISO = function (start, end) {
  452.             var s = "";
  453.             for (var i = start; i < end; ++i) {
  454.                 s += String.fromCharCode(this.get(i));
  455.             }
  456.             return s;
  457.         };
  458.         Stream.prototype.parseStringUTF = function (start, end) {
  459.             var s = "";
  460.             for (var i = start; i < end;) {
  461.                 var c = this.get(i++);
  462.                 if (c < 128) {
  463.                     s += String.fromCharCode(c);
  464.                 }
  465.                 else if ((c > 191) && (c < 224)) {
  466.                     s += String.fromCharCode(((c & 0x1F) << 6) | (this.get(i++) & 0x3F));
  467.                 }
  468.                 else {
  469.                     s += String.fromCharCode(((c & 0x0F) << 12) | ((this.get(i++) & 0x3F) << 6) | (this.get(i++) & 0x3F));
  470.                 }
  471.             }
  472.             return s;
  473.         };
  474.         Stream.prototype.parseStringBMP = function (start, end) {
  475.             var str = "";
  476.             var hi;
  477.             var lo;
  478.             for (var i = start; i < end;) {
  479.                 hi = this.get(i++);
  480.                 lo = this.get(i++);
  481.                 str += String.fromCharCode((hi << 8) | lo);
  482.             }
  483.             return str;
  484.         };
  485.         Stream.prototype.parseTime = function (start, end, shortYear) {
  486.             var s = this.parseStringISO(start, end);
  487.             var m = (shortYear ? reTimeS : reTimeL).exec(s);
  488.             if (!m) {
  489.                 return "Unrecognized time: " + s;
  490.             }
  491.             if (shortYear) {
  492.                 // to avoid querying the timer, use the fixed range [1970, 2069]
  493.                 // it will conform with ITU X.400 [-10, +40] sliding window until 2030
  494.                 m[1] = +m[1];
  495.                 m[1] += (+m[1] < 70) ? 2000 : 1900;
  496.             }
  497.             s = m[1] + "-" + m[2] + "-" + m[3] + " " + m[4];
  498.             if (m[5]) {
  499.                 s += ":" + m[5];
  500.                 if (m[6]) {
  501.                     s += ":" + m[6];
  502.                     if (m[7]) {
  503.                         s += "." + m[7];
  504.                     }
  505.                 }
  506.             }
  507.             if (m[8]) {
  508.                 s += " UTC";
  509.                 if (m[8] != "Z") {
  510.                     s += m[8];
  511.                     if (m[9]) {
  512.                         s += ":" + m[9];
  513.                     }
  514.                 }
  515.             }
  516.             return s;
  517.         };
  518.         Stream.prototype.parseInteger = function (start, end) {
  519.             var v = this.get(start);
  520.             var neg = (v > 127);
  521.             var pad = neg ? 255 : 0;
  522.             var len;
  523.             var s = "";
  524.             // skip unuseful bits (not allowed in DER)
  525.             while (v == pad && ++start < end) {
  526.                 v = this.get(start);
  527.             }
  528.             len = end - start;
  529.             if (len === 0) {
  530.                 return neg ? -1 : 0;
  531.             }
  532.             // show bit length of huge integers
  533.             if (len > 4) {
  534.                 s = v;
  535.                 len <<= 3;
  536.                 while (((+s ^ pad) & 0x80) == 0) {
  537.                     s = +s << 1;
  538.                     --len;
  539.                 }
  540.                 s = "(" + len + " bit)\n";
  541.             }
  542.             // decode the integer
  543.             if (neg) {
  544.                 v = v - 256;
  545.             }
  546.             var n = new Int10(v);
  547.             for (var i = start + 1; i < end; ++i) {
  548.                 n.mulAdd(256, this.get(i));
  549.             }
  550.             return s + n.toString();
  551.         };
  552.         Stream.prototype.parseBitString = function (start, end, maxLength) {
  553.             var unusedBit = this.get(start);
  554.             var lenBit = ((end - start - 1) << 3) - unusedBit;
  555.             var intro = "(" + lenBit + " bit)\n";
  556.             var s = "";
  557.             for (var i = start + 1; i < end; ++i) {
  558.                 var b = this.get(i);
  559.                 var skip = (i == end - 1) ? unusedBit : 0;
  560.                 for (var j = 7; j >= skip; --j) {
  561.                     s += (b >> j) & 1 ? "1" : "0";
  562.                 }
  563.                 if (s.length > maxLength) {
  564.                     return intro + stringCut(s, maxLength);
  565.                 }
  566.             }
  567.             return intro + s;
  568.         };
  569.         Stream.prototype.parseOctetString = function (start, end, maxLength) {
  570.             if (this.isASCII(start, end)) {
  571.                 return stringCut(this.parseStringISO(start, end), maxLength);
  572.             }
  573.             var len = end - start;
  574.             var s = "(" + len + " byte)\n";
  575.             maxLength /= 2; // we work in bytes
  576.             if (len > maxLength) {
  577.                 end = start + maxLength;
  578.             }
  579.             for (var i = start; i < end; ++i) {
  580.                 s += this.hexByte(this.get(i));
  581.             }
  582.             if (len > maxLength) {
  583.                 s += ellipsis;
  584.             }
  585.             return s;
  586.         };
  587.         Stream.prototype.parseOID = function (start, end, maxLength) {
  588.             var s = "";
  589.             var n = new Int10();
  590.             var bits = 0;
  591.             for (var i = start; i < end; ++i) {
  592.                 var v = this.get(i);
  593.                 n.mulAdd(128, v & 0x7F);
  594.                 bits += 7;
  595.                 if (!(v & 0x80)) { // finished
  596.                     if (s === "") {
  597.                         n = n.simplify();
  598.                         if (n instanceof Int10) {
  599.                             n.sub(80);
  600.                             s = "2." + n.toString();
  601.                         }
  602.                         else {
  603.                             var m = n < 80 ? n < 40 ? 0 : 1 : 2;
  604.                             s = m + "." + (n - m * 40);
  605.                         }
  606.                     }
  607.                     else {
  608.                         s += "." + n.toString();
  609.                     }
  610.                     if (s.length > maxLength) {
  611.                         return stringCut(s, maxLength);
  612.                     }
  613.                     n = new Int10();
  614.                     bits = 0;
  615.                 }
  616.             }
  617.             if (bits > 0) {
  618.                 s += ".incomplete";
  619.             }
  620.             return s;
  621.         };
  622.         return Stream;
  623.     }());
  624.     var ASN1 = /** @class */ (function () {
  625.         function ASN1(stream, header, length, tag, sub) {
  626.             if (!(tag instanceof ASN1Tag)) {
  627.                 throw new Error("Invalid tag value.");
  628.             }
  629.             this.stream = stream;
  630.             this.header = header;
  631.             this.length = length;
  632.             this.tag = tag;
  633.             this.sub = sub;
  634.         }
  635.         ASN1.prototype.typeName = function () {
  636.             switch (this.tag.tagClass) {
  637.                 case 0: // universal
  638.                     switch (this.tag.tagNumber) {
  639.                         case 0x00:
  640.                             return "EOC";
  641.                         case 0x01:
  642.                             return "BOOLEAN";
  643.                         case 0x02:
  644.                             return "INTEGER";
  645.                         case 0x03:
  646.                             return "BIT_STRING";
  647.                         case 0x04:
  648.                             return "OCTET_STRING";
  649.                         case 0x05:
  650.                             return "NULL";
  651.                         case 0x06:
  652.                             return "OBJECT_IDENTIFIER";
  653.                         case 0x07:
  654.                             return "ObjectDescriptor";
  655.                         case 0x08:
  656.                             return "EXTERNAL";
  657.                         case 0x09:
  658.                             return "REAL";
  659.                         case 0x0A:
  660.                             return "ENUMERATED";
  661.                         case 0x0B:
  662.                             return "EMBEDDED_PDV";
  663.                         case 0x0C:
  664.                             return "UTF8String";
  665.                         case 0x10:
  666.                             return "SEQUENCE";
  667.                         case 0x11:
  668.                             return "SET";
  669.                         case 0x12:
  670.                             return "NumericString";
  671.                         case 0x13:
  672.                             return "PrintableString"; // ASCII subset
  673.                         case 0x14:
  674.                             return "TeletexString"; // aka T61String
  675.                         case 0x15:
  676.                             return "VideotexString";
  677.                         case 0x16:
  678.                             return "IA5String"; // ASCII
  679.                         case 0x17:
  680.                             return "UTCTime";
  681.                         case 0x18:
  682.                             return "GeneralizedTime";
  683.                         case 0x19:
  684.                             return "GraphicString";
  685.                         case 0x1A:
  686.                             return "VisibleString"; // ASCII subset
  687.                         case 0x1B:
  688.                             return "GeneralString";
  689.                         case 0x1C:
  690.                             return "UniversalString";
  691.                         case 0x1E:
  692.                             return "BMPString";
  693.                     }
  694.                     return "Universal_" + this.tag.tagNumber.toString();
  695.                 case 1:
  696.                     return "Application_" + this.tag.tagNumber.toString();
  697.                 case 2:
  698.                     return "[" + this.tag.tagNumber.toString() + "]"; // Context
  699.                 case 3:
  700.                     return "Private_" + this.tag.tagNumber.toString();
  701.             }
  702.         };
  703.         ASN1.prototype.content = function (maxLength) {
  704.             if (this.tag === undefined) {
  705.                 return null;
  706.             }
  707.             if (maxLength === undefined) {
  708.                 maxLength = Infinity;
  709.             }
  710.             var content = this.posContent();
  711.             var len = Math.abs(this.length);
  712.             if (!this.tag.isUniversal()) {
  713.                 if (this.sub !== null) {
  714.                     return "(" + this.sub.length + " elem)";
  715.                 }
  716.                 return this.stream.parseOctetString(content, content + len, maxLength);
  717.             }
  718.             switch (this.tag.tagNumber) {
  719.                 case 0x01: // BOOLEAN
  720.                     return (this.stream.get(content) === 0) ? "false" : "true";
  721.                 case 0x02: // INTEGER
  722.                     return this.stream.parseInteger(content, content + len);
  723.                 case 0x03: // BIT_STRING
  724.                     return this.sub ? "(" + this.sub.length + " elem)" :
  725.                         this.stream.parseBitString(content, content + len, maxLength);
  726.                 case 0x04: // OCTET_STRING
  727.                     return this.sub ? "(" + this.sub.length + " elem)" :
  728.                         this.stream.parseOctetString(content, content + len, maxLength);
  729.                 // case 0x05: // NULL
  730.                 case 0x06: // OBJECT_IDENTIFIER
  731.                     return this.stream.parseOID(content, content + len, maxLength);
  732.                 // case 0x07: // ObjectDescriptor
  733.                 // case 0x08: // EXTERNAL
  734.                 // case 0x09: // REAL
  735.                 // case 0x0A: // ENUMERATED
  736.                 // case 0x0B: // EMBEDDED_PDV
  737.                 case 0x10: // SEQUENCE
  738.                 case 0x11: // SET
  739.                     if (this.sub !== null) {
  740.                         return "(" + this.sub.length + " elem)";
  741.                     }
  742.                     else {
  743.                         return "(no elem)";
  744.                     }
  745.                 case 0x0C: // UTF8String
  746.                     return stringCut(this.stream.parseStringUTF(content, content + len), maxLength);
  747.                 case 0x12: // NumericString
  748.                 case 0x13: // PrintableString
  749.                 case 0x14: // TeletexString
  750.                 case 0x15: // VideotexString
  751.                 case 0x16: // IA5String
  752.                 // case 0x19: // GraphicString
  753.                 case 0x1A: // VisibleString
  754.                     // case 0x1B: // GeneralString
  755.                     // case 0x1C: // UniversalString
  756.                     return stringCut(this.stream.parseStringISO(content, content + len), maxLength);
  757.                 case 0x1E: // BMPString
  758.                     return stringCut(this.stream.parseStringBMP(content, content + len), maxLength);
  759.                 case 0x17: // UTCTime
  760.                 case 0x18: // GeneralizedTime
  761.                     return this.stream.parseTime(content, content + len, (this.tag.tagNumber == 0x17));
  762.             }
  763.             return null;
  764.         };
  765.         ASN1.prototype.toString = function () {
  766.             return this.typeName() + "@" + this.stream.pos + "[header:" + this.header + ",length:" + this.length + ",sub:" + ((this.sub === null) ? "null" : this.sub.length) + "]";
  767.         };
  768.         ASN1.prototype.toPrettyString = function (indent) {
  769.             if (indent === undefined) {
  770.                 indent = "";
  771.             }
  772.             var s = indent + this.typeName() + " @" + this.stream.pos;
  773.             if (this.length >= 0) {
  774.                 s += "+";
  775.             }
  776.             s += this.length;
  777.             if (this.tag.tagConstructed) {
  778.                 s += " (constructed)";
  779.             }
  780.             else if ((this.tag.isUniversal() && ((this.tag.tagNumber == 0x03) || (this.tag.tagNumber == 0x04))) && (this.sub !== null)) {
  781.                 s += " (encapsulates)";
  782.             }
  783.             s += "\n";
  784.             if (this.sub !== null) {
  785.                 indent += "  ";
  786.                 for (var i = 0, max = this.sub.length; i < max; ++i) {
  787.                     s += this.sub[i].toPrettyString(indent);
  788.                 }
  789.             }
  790.             return s;
  791.         };
  792.         ASN1.prototype.posStart = function () {
  793.             return this.stream.pos;
  794.         };
  795.         ASN1.prototype.posContent = function () {
  796.             return this.stream.pos + this.header;
  797.         };
  798.         ASN1.prototype.posEnd = function () {
  799.             return this.stream.pos + this.header + Math.abs(this.length);
  800.         };
  801.         ASN1.prototype.toHexString = function () {
  802.             return this.stream.hexDump(this.posStart(), this.posEnd(), true);
  803.         };
  804.         ASN1.decodeLength = function (stream) {
  805.             var buf = stream.get();
  806.             var len = buf & 0x7F;
  807.             if (len == buf) {
  808.                 return len;
  809.             }
  810.             // no reason to use Int10, as it would be a huge buffer anyways
  811.             if (len > 6) {
  812.                 throw new Error("Length over 48 bits not supported at position " + (stream.pos - 1));
  813.             }
  814.             if (len === 0) {
  815.                 return null;
  816.             } // undefined
  817.             buf = 0;
  818.             for (var i = 0; i < len; ++i) {
  819.                 buf = (buf * 256) + stream.get();
  820.             }
  821.             return buf;
  822.         };
  823.         /**
  824.          * Retrieve the hexadecimal value (as a string) of the current ASN.1 element
  825.          * @returns {string}
  826.          * @public
  827.          */
  828.         ASN1.prototype.getHexStringValue = function () {
  829.             var hexString = this.toHexString();
  830.             var offset = this.header * 2;
  831.             var length = this.length * 2;
  832.             return hexString.substr(offset, length);
  833.         };
  834.         ASN1.decode = function (str) {
  835.             var stream;
  836.             if (!(str instanceof Stream)) {
  837.                 stream = new Stream(str, 0);
  838.             }
  839.             else {
  840.                 stream = str;
  841.             }
  842.             var streamStart = new Stream(stream);
  843.             var tag = new ASN1Tag(stream);
  844.             var len = ASN1.decodeLength(stream);
  845.             var start = stream.pos;
  846.             var header = start - streamStart.pos;
  847.             var sub = null;
  848.             var getSub = function () {
  849.                 var ret = [];
  850.                 if (len !== null) {
  851.                     // definite length
  852.                     var end = start + len;
  853.                     while (stream.pos < end) {
  854.                         ret[ret.length] = ASN1.decode(stream);
  855.                     }
  856.                     if (stream.pos != end) {
  857.                         throw new Error("Content size is not correct for container starting at offset " + start);
  858.                     }
  859.                 }
  860.                 else {
  861.                     // undefined length
  862.                     try {
  863.                         for (;;) {
  864.                             var s = ASN1.decode(stream);
  865.                             if (s.tag.isEOC()) {
  866.                                 break;
  867.                             }
  868.                             ret[ret.length] = s;
  869.                         }
  870.                         len = start - stream.pos; // undefined lengths are represented as negative values
  871.                     }
  872.                     catch (e) {
  873.                         throw new Error("Exception while decoding undefined length content: " + e);
  874.                     }
  875.                 }
  876.                 return ret;
  877.             };
  878.             if (tag.tagConstructed) {
  879.                 // must have valid content
  880.                 sub = getSub();
  881.             }
  882.             else if (tag.isUniversal() && ((tag.tagNumber == 0x03) || (tag.tagNumber == 0x04))) {
  883.                 // sometimes BitString and OctetString are used to encapsulate ASN.1
  884.                 try {
  885.                     if (tag.tagNumber == 0x03) {
  886.                         if (stream.get() != 0) {
  887.                             throw new Error("BIT STRINGs with unused bits cannot encapsulate.");
  888.                         }
  889.                     }
  890.                     sub = getSub();
  891.                     for (var i = 0; i < sub.length; ++i) {
  892.                         if (sub[i].tag.isEOC()) {
  893.                             throw new Error("EOC is not supposed to be actual content.");
  894.                         }
  895.                     }
  896.                 }
  897.                 catch (e) {
  898.                     // but silently ignore when they don't
  899.                     sub = null;
  900.                 }
  901.             }
  902.             if (sub === null) {
  903.                 if (len === null) {
  904.                     throw new Error("We can't skip over an invalid tag with undefined length at offset " + start);
  905.                 }
  906.                 stream.pos = start + Math.abs(len);
  907.             }
  908.             return new ASN1(streamStart, header, len, tag, sub);
  909.         };
  910.         return ASN1;
  911.     }());
  912.     var ASN1Tag = /** @class */ (function () {
  913.         function ASN1Tag(stream) {
  914.             var buf = stream.get();
  915.             this.tagClass = buf >> 6;
  916.             this.tagConstructed = ((buf & 0x20) !== 0);
  917.             this.tagNumber = buf & 0x1F;
  918.             if (this.tagNumber == 0x1F) { // long tag
  919.                 var n = new Int10();
  920.                 do {
  921.                     buf = stream.get();
  922.                     n.mulAdd(128, buf & 0x7F);
  923.                 } while (buf & 0x80);
  924.                 this.tagNumber = n.simplify();
  925.             }
  926.         }
  927.         ASN1Tag.prototype.isUniversal = function () {
  928.             return this.tagClass === 0x00;
  929.         };
  930.         ASN1Tag.prototype.isEOC = function () {
  931.             return this.tagClass === 0x00 && this.tagNumber === 0x00;
  932.         };
  933.         return ASN1Tag;
  934.     }());

  935. // Copyright (c) 2005  Tom Wu
  936. // Bits per digit
  937.     var dbits;
  938. // JavaScript engine analysis
  939.     var canary = 0xdeadbeefcafe;
  940.     var j_lm = ((canary & 0xffffff) == 0xefcafe);
  941. //#region
  942.     var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997];
  943.     var lplim = (1 << 26) / lowprimes[lowprimes.length - 1];
  944. //#endregion
  945. // (public) Constructor
  946.     var BigInteger = /** @class */ (function () {
  947.         function BigInteger(a, b, c) {
  948.             if (a != null) {
  949.                 if ("number" == typeof a) {
  950.                     this.fromNumber(a, b, c);
  951.                 }
  952.                 else if (b == null && "string" != typeof a) {
  953.                     this.fromString(a, 256);
  954.                 }
  955.                 else {
  956.                     this.fromString(a, b);
  957.                 }
  958.             }
  959.         }
  960.         //#region PUBLIC
  961.         // BigInteger.prototype.toString = bnToString;
  962.         // (public) return string representation in given radix
  963.         BigInteger.prototype.toString = function (b) {
  964.             if (this.s < 0) {
  965.                 return "-" + this.negate().toString(b);
  966.             }
  967.             var k;
  968.             if (b == 16) {
  969.                 k = 4;
  970.             }
  971.             else if (b == 8) {
  972.                 k = 3;
  973.             }
  974.             else if (b == 2) {
  975.                 k = 1;
  976.             }
  977.             else if (b == 32) {
  978.                 k = 5;
  979.             }
  980.             else if (b == 4) {
  981.                 k = 2;
  982.             }
  983.             else {
  984.                 return this.toRadix(b);
  985.             }
  986.             var km = (1 << k) - 1;
  987.             var d;
  988.             var m = false;
  989.             var r = "";
  990.             var i = this.t;
  991.             var p = this.DB - (i * this.DB) % k;
  992.             if (i-- > 0) {
  993.                 if (p < this.DB && (d = this[i] >> p) > 0) {
  994.                     m = true;
  995.                     r = int2char(d);
  996.                 }
  997.                 while (i >= 0) {
  998.                     if (p < k) {
  999.                         d = (this[i] & ((1 << p) - 1)) << (k - p);
  1000.                         d |= this[--i] >> (p += this.DB - k);
  1001.                     }
  1002.                     else {
  1003.                         d = (this[i] >> (p -= k)) & km;
  1004.                         if (p <= 0) {
  1005.                             p += this.DB;
  1006.                             --i;
  1007.                         }
  1008.                     }
  1009.                     if (d > 0) {
  1010.                         m = true;
  1011.                     }
  1012.                     if (m) {
  1013.                         r += int2char(d);
  1014.                     }
  1015.                 }
  1016.             }
  1017.             return m ? r : "0";
  1018.         };
  1019.         // BigInteger.prototype.negate = bnNegate;
  1020.         // (public) -this
  1021.         BigInteger.prototype.negate = function () {
  1022.             var r = nbi();
  1023.             BigInteger.ZERO.subTo(this, r);
  1024.             return r;
  1025.         };
  1026.         // BigInteger.prototype.abs = bnAbs;
  1027.         // (public) |this|
  1028.         BigInteger.prototype.abs = function () {
  1029.             return (this.s < 0) ? this.negate() : this;
  1030.         };
  1031.         // BigInteger.prototype.compareTo = bnCompareTo;
  1032.         // (public) return + if this > a, - if this < a, 0 if equal
  1033.         BigInteger.prototype.compareTo = function (a) {
  1034.             var r = this.s - a.s;
  1035.             if (r != 0) {
  1036.                 return r;
  1037.             }
  1038.             var i = this.t;
  1039.             r = i - a.t;
  1040.             if (r != 0) {
  1041.                 return (this.s < 0) ? -r : r;
  1042.             }
  1043.             while (--i >= 0) {
  1044.                 if ((r = this[i] - a[i]) != 0) {
  1045.                     return r;
  1046.                 }
  1047.             }
  1048.             return 0;
  1049.         };
  1050.         // BigInteger.prototype.bitLength = bnBitLength;
  1051.         // (public) return the number of bits in "this"
  1052.         BigInteger.prototype.bitLength = function () {
  1053.             if (this.t <= 0) {
  1054.                 return 0;
  1055.             }
  1056.             return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM));
  1057.         };
  1058.         // BigInteger.prototype.mod = bnMod;
  1059.         // (public) this mod a
  1060.         BigInteger.prototype.mod = function (a) {
  1061.             var r = nbi();
  1062.             this.abs().divRemTo(a, null, r);
  1063.             if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) {
  1064.                 a.subTo(r, r);
  1065.             }
  1066.             return r;
  1067.         };
  1068.         // BigInteger.prototype.modPowInt = bnModPowInt;
  1069.         // (public) this^e % m, 0 <= e < 2^32
  1070.         BigInteger.prototype.modPowInt = function (e, m) {
  1071.             var z;
  1072.             if (e < 256 || m.isEven()) {
  1073.                 z = new Classic(m);
  1074.             }
  1075.             else {
  1076.                 z = new Montgomery(m);
  1077.             }
  1078.             return this.exp(e, z);
  1079.         };
  1080.         // BigInteger.prototype.clone = bnClone;
  1081.         // (public)
  1082.         BigInteger.prototype.clone = function () {
  1083.             var r = nbi();
  1084.             this.copyTo(r);
  1085.             return r;
  1086.         };
  1087.         // BigInteger.prototype.intValue = bnIntValue;
  1088.         // (public) return value as integer
  1089.         BigInteger.prototype.intValue = function () {
  1090.             if (this.s < 0) {
  1091.                 if (this.t == 1) {
  1092.                     return this[0] - this.DV;
  1093.                 }
  1094.                 else if (this.t == 0) {
  1095.                     return -1;
  1096.                 }
  1097.             }
  1098.             else if (this.t == 1) {
  1099.                 return this[0];
  1100.             }
  1101.             else if (this.t == 0) {
  1102.                 return 0;
  1103.             }
  1104.             // assumes 16 < DB < 32
  1105.             return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0];
  1106.         };
  1107.         // BigInteger.prototype.byteValue = bnByteValue;
  1108.         // (public) return value as byte
  1109.         BigInteger.prototype.byteValue = function () {
  1110.             return (this.t == 0) ? this.s : (this[0] << 24) >> 24;
  1111.         };
  1112.         // BigInteger.prototype.shortValue = bnShortValue;
  1113.         // (public) return value as short (assumes DB>=16)
  1114.         BigInteger.prototype.shortValue = function () {
  1115.             return (this.t == 0) ? this.s : (this[0] << 16) >> 16;
  1116.         };
  1117.         // BigInteger.prototype.signum = bnSigNum;
  1118.         // (public) 0 if this == 0, 1 if this > 0
  1119.         BigInteger.prototype.signum = function () {
  1120.             if (this.s < 0) {
  1121.                 return -1;
  1122.             }
  1123.             else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) {
  1124.                 return 0;
  1125.             }
  1126.             else {
  1127.                 return 1;
  1128.             }
  1129.         };
  1130.         // BigInteger.prototype.toByteArray = bnToByteArray;
  1131.         // (public) convert to bigendian byte array
  1132.         BigInteger.prototype.toByteArray = function () {
  1133.             var i = this.t;
  1134.             var r = [];
  1135.             r[0] = this.s;
  1136.             var p = this.DB - (i * this.DB) % 8;
  1137.             var d;
  1138.             var k = 0;
  1139.             if (i-- > 0) {
  1140.                 if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) {
  1141.                     r[k++] = d | (this.s << (this.DB - p));
  1142.                 }
  1143.                 while (i >= 0) {
  1144.                     if (p < 8) {
  1145.                         d = (this[i] & ((1 << p) - 1)) << (8 - p);
  1146.                         d |= this[--i] >> (p += this.DB - 8);
  1147.                     }
  1148.                     else {
  1149.                         d = (this[i] >> (p -= 8)) & 0xff;
  1150.                         if (p <= 0) {
  1151.                             p += this.DB;
  1152.                             --i;
  1153.                         }
  1154.                     }
  1155.                     if ((d & 0x80) != 0) {
  1156.                         d |= -256;
  1157.                     }
  1158.                     if (k == 0 && (this.s & 0x80) != (d & 0x80)) {
  1159.                         ++k;
  1160.                     }
  1161.                     if (k > 0 || d != this.s) {
  1162.                         r[k++] = d;
  1163.                     }
  1164.                 }
  1165.             }
  1166.             return r;
  1167.         };
  1168.         // BigInteger.prototype.equals = bnEquals;
  1169.         BigInteger.prototype.equals = function (a) {
  1170.             return (this.compareTo(a) == 0);
  1171.         };
  1172.         // BigInteger.prototype.min = bnMin;
  1173.         BigInteger.prototype.min = function (a) {
  1174.             return (this.compareTo(a) < 0) ? this : a;
  1175.         };
  1176.         // BigInteger.prototype.max = bnMax;
  1177.         BigInteger.prototype.max = function (a) {
  1178.             return (this.compareTo(a) > 0) ? this : a;
  1179.         };
  1180.         // BigInteger.prototype.and = bnAnd;
  1181.         BigInteger.prototype.and = function (a) {
  1182.             var r = nbi();
  1183.             this.bitwiseTo(a, op_and, r);
  1184.             return r;
  1185.         };
  1186.         // BigInteger.prototype.or = bnOr;
  1187.         BigInteger.prototype.or = function (a) {
  1188.             var r = nbi();
  1189.             this.bitwiseTo(a, op_or, r);
  1190.             return r;
  1191.         };
  1192.         // BigInteger.prototype.xor = bnXor;
  1193.         BigInteger.prototype.xor = function (a) {
  1194.             var r = nbi();
  1195.             this.bitwiseTo(a, op_xor, r);
  1196.             return r;
  1197.         };
  1198.         // BigInteger.prototype.andNot = bnAndNot;
  1199.         BigInteger.prototype.andNot = function (a) {
  1200.             var r = nbi();
  1201.             this.bitwiseTo(a, op_andnot, r);
  1202.             return r;
  1203.         };
  1204.         // BigInteger.prototype.not = bnNot;
  1205.         // (public) ~this
  1206.         BigInteger.prototype.not = function () {
  1207.             var r = nbi();
  1208.             for (var i = 0; i < this.t; ++i) {
  1209.                 r[i] = this.DM & ~this[i];
  1210.             }
  1211.             r.t = this.t;
  1212.             r.s = ~this.s;
  1213.             return r;
  1214.         };
  1215.         // BigInteger.prototype.shiftLeft = bnShiftLeft;
  1216.         // (public) this << n
  1217.         BigInteger.prototype.shiftLeft = function (n) {
  1218.             var r = nbi();
  1219.             if (n < 0) {
  1220.                 this.rShiftTo(-n, r);
  1221.             }
  1222.             else {
  1223.                 this.lShiftTo(n, r);
  1224.             }
  1225.             return r;
  1226.         };
  1227.         // BigInteger.prototype.shiftRight = bnShiftRight;
  1228.         // (public) this >> n
  1229.         BigInteger.prototype.shiftRight = function (n) {
  1230.             var r = nbi();
  1231.             if (n < 0) {
  1232.                 this.lShiftTo(-n, r);
  1233.             }
  1234.             else {
  1235.                 this.rShiftTo(n, r);
  1236.             }
  1237.             return r;
  1238.         };
  1239.         // BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
  1240.         // (public) returns index of lowest 1-bit (or -1 if none)
  1241.         BigInteger.prototype.getLowestSetBit = function () {
  1242.             for (var i = 0; i < this.t; ++i) {
  1243.                 if (this[i] != 0) {
  1244.                     return i * this.DB + lbit(this[i]);
  1245.                 }
  1246.             }
  1247.             if (this.s < 0) {
  1248.                 return this.t * this.DB;
  1249.             }
  1250.             return -1;
  1251.         };
  1252.         // BigInteger.prototype.bitCount = bnBitCount;
  1253.         // (public) return number of set bits
  1254.         BigInteger.prototype.bitCount = function () {
  1255.             var r = 0;
  1256.             var x = this.s & this.DM;
  1257.             for (var i = 0; i < this.t; ++i) {
  1258.                 r += cbit(this[i] ^ x);
  1259.             }
  1260.             return r;
  1261.         };
  1262.         // BigInteger.prototype.testBit = bnTestBit;
  1263.         // (public) true iff nth bit is set
  1264.         BigInteger.prototype.testBit = function (n) {
  1265.             var j = Math.floor(n / this.DB);
  1266.             if (j >= this.t) {
  1267.                 return (this.s != 0);
  1268.             }
  1269.             return ((this[j] & (1 << (n % this.DB))) != 0);
  1270.         };
  1271.         // BigInteger.prototype.setBit = bnSetBit;
  1272.         // (public) this | (1<<n)
  1273.         BigInteger.prototype.setBit = function (n) {
  1274.             return this.changeBit(n, op_or);
  1275.         };
  1276.         // BigInteger.prototype.clearBit = bnClearBit;
  1277.         // (public) this & ~(1<<n)
  1278.         BigInteger.prototype.clearBit = function (n) {
  1279.             return this.changeBit(n, op_andnot);
  1280.         };
  1281.         // BigInteger.prototype.flipBit = bnFlipBit;
  1282.         // (public) this ^ (1<<n)
  1283.         BigInteger.prototype.flipBit = function (n) {
  1284.             return this.changeBit(n, op_xor);
  1285.         };
  1286.         // BigInteger.prototype.add = bnAdd;
  1287.         // (public) this + a
  1288.         BigInteger.prototype.add = function (a) {
  1289.             var r = nbi();
  1290.             this.addTo(a, r);
  1291.             return r;
  1292.         };
  1293.         // BigInteger.prototype.subtract = bnSubtract;
  1294.         // (public) this - a
  1295.         BigInteger.prototype.subtract = function (a) {
  1296.             var r = nbi();
  1297.             this.subTo(a, r);
  1298.             return r;
  1299.         };
  1300.         // BigInteger.prototype.multiply = bnMultiply;
  1301.         // (public) this * a
  1302.         BigInteger.prototype.multiply = function (a) {
  1303.             var r = nbi();
  1304.             this.multiplyTo(a, r);
  1305.             return r;
  1306.         };
  1307.         // BigInteger.prototype.divide = bnDivide;
  1308.         // (public) this / a
  1309.         BigInteger.prototype.divide = function (a) {
  1310.             var r = nbi();
  1311.             this.divRemTo(a, r, null);
  1312.             return r;
  1313.         };
  1314.         // BigInteger.prototype.remainder = bnRemainder;
  1315.         // (public) this % a
  1316.         BigInteger.prototype.remainder = function (a) {
  1317.             var r = nbi();
  1318.             this.divRemTo(a, null, r);
  1319.             return r;
  1320.         };
  1321.         // BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
  1322.         // (public) [this/a,this%a]
  1323.         BigInteger.prototype.divideAndRemainder = function (a) {
  1324.             var q = nbi();
  1325.             var r = nbi();
  1326.             this.divRemTo(a, q, r);
  1327.             return [q, r];
  1328.         };
  1329.         // BigInteger.prototype.modPow = bnModPow;
  1330.         // (public) this^e % m (HAC 14.85)
  1331.         BigInteger.prototype.modPow = function (e, m) {
  1332.             var i = e.bitLength();
  1333.             var k;
  1334.             var r = nbv(1);
  1335.             var z;
  1336.             if (i <= 0) {
  1337.                 return r;
  1338.             }
  1339.             else if (i < 18) {
  1340.                 k = 1;
  1341.             }
  1342.             else if (i < 48) {
  1343.                 k = 3;
  1344.             }
  1345.             else if (i < 144) {
  1346.                 k = 4;
  1347.             }
  1348.             else if (i < 768) {
  1349.                 k = 5;
  1350.             }
  1351.             else {
  1352.                 k = 6;
  1353.             }
  1354.             if (i < 8) {
  1355.                 z = new Classic(m);
  1356.             }
  1357.             else if (m.isEven()) {
  1358.                 z = new Barrett(m);
  1359.             }
  1360.             else {
  1361.                 z = new Montgomery(m);
  1362.             }
  1363.             // precomputation
  1364.             var g = [];
  1365.             var n = 3;
  1366.             var k1 = k - 1;
  1367.             var km = (1 << k) - 1;
  1368.             g[1] = z.convert(this);
  1369.             if (k > 1) {
  1370.                 var g2 = nbi();
  1371.                 z.sqrTo(g[1], g2);
  1372.                 while (n <= km) {
  1373.                     g[n] = nbi();
  1374.                     z.mulTo(g2, g[n - 2], g[n]);
  1375.                     n += 2;
  1376.                 }
  1377.             }
  1378.             var j = e.t - 1;
  1379.             var w;
  1380.             var is1 = true;
  1381.             var r2 = nbi();
  1382.             var t;
  1383.             i = nbits(e[j]) - 1;
  1384.             while (j >= 0) {
  1385.                 if (i >= k1) {
  1386.                     w = (e[j] >> (i - k1)) & km;
  1387.                 }
  1388.                 else {
  1389.                     w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i);
  1390.                     if (j > 0) {
  1391.                         w |= e[j - 1] >> (this.DB + i - k1);
  1392.                     }
  1393.                 }
  1394.                 n = k;
  1395.                 while ((w & 1) == 0) {
  1396.                     w >>= 1;
  1397.                     --n;
  1398.                 }
  1399.                 if ((i -= n) < 0) {
  1400.                     i += this.DB;
  1401.                     --j;
  1402.                 }
  1403.                 if (is1) { // ret == 1, don't bother squaring or multiplying it
  1404.                     g[w].copyTo(r);
  1405.                     is1 = false;
  1406.                 }
  1407.                 else {
  1408.                     while (n > 1) {
  1409.                         z.sqrTo(r, r2);
  1410.                         z.sqrTo(r2, r);
  1411.                         n -= 2;
  1412.                     }
  1413.                     if (n > 0) {
  1414.                         z.sqrTo(r, r2);
  1415.                     }
  1416.                     else {
  1417.                         t = r;
  1418.                         r = r2;
  1419.                         r2 = t;
  1420.                     }
  1421.                     z.mulTo(r2, g[w], r);
  1422.                 }
  1423.                 while (j >= 0 && (e[j] & (1 << i)) == 0) {
  1424.                     z.sqrTo(r, r2);
  1425.                     t = r;
  1426.                     r = r2;
  1427.                     r2 = t;
  1428.                     if (--i < 0) {
  1429.                         i = this.DB - 1;
  1430.                         --j;
  1431.                     }
  1432.                 }
  1433.             }
  1434.             return z.revert(r);
  1435.         };
  1436.         // BigInteger.prototype.modInverse = bnModInverse;
  1437.         // (public) 1/this % m (HAC 14.61)
  1438.         BigInteger.prototype.modInverse = function (m) {
  1439.             var ac = m.isEven();
  1440.             if ((this.isEven() && ac) || m.signum() == 0) {
  1441.                 return BigInteger.ZERO;
  1442.             }
  1443.             var u = m.clone();
  1444.             var v = this.clone();
  1445.             var a = nbv(1);
  1446.             var b = nbv(0);
  1447.             var c = nbv(0);
  1448.             var d = nbv(1);
  1449.             while (u.signum() != 0) {
  1450.                 while (u.isEven()) {
  1451.                     u.rShiftTo(1, u);
  1452.                     if (ac) {
  1453.                         if (!a.isEven() || !b.isEven()) {
  1454.                             a.addTo(this, a);
  1455.                             b.subTo(m, b);
  1456.                         }
  1457.                         a.rShiftTo(1, a);
  1458.                     }
  1459.                     else if (!b.isEven()) {
  1460.                         b.subTo(m, b);
  1461.                     }
  1462.                     b.rShiftTo(1, b);
  1463.                 }
  1464.                 while (v.isEven()) {
  1465.                     v.rShiftTo(1, v);
  1466.                     if (ac) {
  1467.                         if (!c.isEven() || !d.isEven()) {
  1468.                             c.addTo(this, c);
  1469.                             d.subTo(m, d);
  1470.                         }
  1471.                         c.rShiftTo(1, c);
  1472.                     }
  1473.                     else if (!d.isEven()) {
  1474.                         d.subTo(m, d);
  1475.                     }
  1476.                     d.rShiftTo(1, d);
  1477.                 }
  1478.                 if (u.compareTo(v) >= 0) {
  1479.                     u.subTo(v, u);
  1480.                     if (ac) {
  1481.                         a.subTo(c, a);
  1482.                     }
  1483.                     b.subTo(d, b);
  1484.                 }
  1485.                 else {
  1486.                     v.subTo(u, v);
  1487.                     if (ac) {
  1488.                         c.subTo(a, c);
  1489.                     }
  1490.                     d.subTo(b, d);
  1491.                 }
  1492.             }
  1493.             if (v.compareTo(BigInteger.ONE) != 0) {
  1494.                 return BigInteger.ZERO;
  1495.             }
  1496.             if (d.compareTo(m) >= 0) {
  1497.                 return d.subtract(m);
  1498.             }
  1499.             if (d.signum() < 0) {
  1500.                 d.addTo(m, d);
  1501.             }
  1502.             else {
  1503.                 return d;
  1504.             }
  1505.             if (d.signum() < 0) {
  1506.                 return d.add(m);
  1507.             }
  1508.             else {
  1509.                 return d;
  1510.             }
  1511.         };
  1512.         // BigInteger.prototype.pow = bnPow;
  1513.         // (public) this^e
  1514.         BigInteger.prototype.pow = function (e) {
  1515.             return this.exp(e, new NullExp());
  1516.         };
  1517.         // BigInteger.prototype.gcd = bnGCD;
  1518.         // (public) gcd(this,a) (HAC 14.54)
  1519.         BigInteger.prototype.gcd = function (a) {
  1520.             var x = (this.s < 0) ? this.negate() : this.clone();
  1521.             var y = (a.s < 0) ? a.negate() : a.clone();
  1522.             if (x.compareTo(y) < 0) {
  1523.                 var t = x;
  1524.                 x = y;
  1525.                 y = t;
  1526.             }
  1527.             var i = x.getLowestSetBit();
  1528.             var g = y.getLowestSetBit();
  1529.             if (g < 0) {
  1530.                 return x;
  1531.             }
  1532.             if (i < g) {
  1533.                 g = i;
  1534.             }
  1535.             if (g > 0) {
  1536.                 x.rShiftTo(g, x);
  1537.                 y.rShiftTo(g, y);
  1538.             }
  1539.             while (x.signum() > 0) {
  1540.                 if ((i = x.getLowestSetBit()) > 0) {
  1541.                     x.rShiftTo(i, x);
  1542.                 }
  1543.                 if ((i = y.getLowestSetBit()) > 0) {
  1544.                     y.rShiftTo(i, y);
  1545.                 }
  1546.                 if (x.compareTo(y) >= 0) {
  1547.                     x.subTo(y, x);
  1548.                     x.rShiftTo(1, x);
  1549.                 }
  1550.                 else {
  1551.                     y.subTo(x, y);
  1552.                     y.rShiftTo(1, y);
  1553.                 }
  1554.             }
  1555.             if (g > 0) {
  1556.                 y.lShiftTo(g, y);
  1557.             }
  1558.             return y;
  1559.         };
  1560.         // BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
  1561.         // (public) test primality with certainty >= 1-.5^t
  1562.         BigInteger.prototype.isProbablePrime = function (t) {
  1563.             var i;
  1564.             var x = this.abs();
  1565.             if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) {
  1566.                 for (i = 0; i < lowprimes.length; ++i) {
  1567.                     if (x[0] == lowprimes[i]) {
  1568.                         return true;
  1569.                     }
  1570.                 }
  1571.                 return false;
  1572.             }
  1573.             if (x.isEven()) {
  1574.                 return false;
  1575.             }
  1576.             i = 1;
  1577.             while (i < lowprimes.length) {
  1578.                 var m = lowprimes[i];
  1579.                 var j = i + 1;
  1580.                 while (j < lowprimes.length && m < lplim) {
  1581.                     m *= lowprimes[j++];
  1582.                 }
  1583.                 m = x.modInt(m);
  1584.                 while (i < j) {
  1585.                     if (m % lowprimes[i++] == 0) {
  1586.                         return false;
  1587.                     }
  1588.                 }
  1589.             }
  1590.             return x.millerRabin(t);
  1591.         };
  1592.         //#endregion PUBLIC
  1593.         //#region PROTECTED
  1594.         // BigInteger.prototype.copyTo = bnpCopyTo;
  1595.         // (protected) copy this to r
  1596.         BigInteger.prototype.copyTo = function (r) {
  1597.             for (var i = this.t - 1; i >= 0; --i) {
  1598.                 r[i] = this[i];
  1599.             }
  1600.             r.t = this.t;
  1601.             r.s = this.s;
  1602.         };
  1603.         // BigInteger.prototype.fromInt = bnpFromInt;
  1604.         // (protected) set from integer value x, -DV <= x < DV
  1605.         BigInteger.prototype.fromInt = function (x) {
  1606.             this.t = 1;
  1607.             this.s = (x < 0) ? -1 : 0;
  1608.             if (x > 0) {
  1609.                 this[0] = x;
  1610.             }
  1611.             else if (x < -1) {
  1612.                 this[0] = x + this.DV;
  1613.             }
  1614.             else {
  1615.                 this.t = 0;
  1616.             }
  1617.         };
  1618.         // BigInteger.prototype.fromString = bnpFromString;
  1619.         // (protected) set from string and radix
  1620.         BigInteger.prototype.fromString = function (s, b) {
  1621.             var k;
  1622.             if (b == 16) {
  1623.                 k = 4;
  1624.             }
  1625.             else if (b == 8) {
  1626.                 k = 3;
  1627.             }
  1628.             else if (b == 256) {
  1629.                 k = 8;
  1630.                 /* byte array */
  1631.             }
  1632.             else if (b == 2) {
  1633.                 k = 1;
  1634.             }
  1635.             else if (b == 32) {
  1636.                 k = 5;
  1637.             }
  1638.             else if (b == 4) {
  1639.                 k = 2;
  1640.             }
  1641.             else {
  1642.                 this.fromRadix(s, b);
  1643.                 return;
  1644.             }
  1645.             this.t = 0;
  1646.             this.s = 0;
  1647.             var i = s.length;
  1648.             var mi = false;
  1649.             var sh = 0;
  1650.             while (--i >= 0) {
  1651.                 var x = (k == 8) ? (+s[i]) & 0xff : intAt(s, i);
  1652.                 if (x < 0) {
  1653.                     if (s.charAt(i) == "-") {
  1654.                         mi = true;
  1655.                     }
  1656.                     continue;
  1657.                 }
  1658.                 mi = false;
  1659.                 if (sh == 0) {
  1660.                     this[this.t++] = x;
  1661.                 }
  1662.                 else if (sh + k > this.DB) {
  1663.                     this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh;
  1664.                     this[this.t++] = (x >> (this.DB - sh));
  1665.                 }
  1666.                 else {
  1667.                     this[this.t - 1] |= x << sh;
  1668.                 }
  1669.                 sh += k;
  1670.                 if (sh >= this.DB) {
  1671.                     sh -= this.DB;
  1672.                 }
  1673.             }
  1674.             if (k == 8 && ((+s[0]) & 0x80) != 0) {
  1675.                 this.s = -1;
  1676.                 if (sh > 0) {
  1677.                     this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh;
  1678.                 }
  1679.             }
  1680.             this.clamp();
  1681.             if (mi) {
  1682.                 BigInteger.ZERO.subTo(this, this);
  1683.             }
  1684.         };
  1685.         // BigInteger.prototype.clamp = bnpClamp;
  1686.         // (protected) clamp off excess high words
  1687.         BigInteger.prototype.clamp = function () {
  1688.             var c = this.s & this.DM;
  1689.             while (this.t > 0 && this[this.t - 1] == c) {
  1690.                 --this.t;
  1691.             }
  1692.         };
  1693.         // BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
  1694.         // (protected) r = this << n*DB
  1695.         BigInteger.prototype.dlShiftTo = function (n, r) {
  1696.             var i;
  1697.             for (i = this.t - 1; i >= 0; --i) {
  1698.                 r[i + n] = this[i];
  1699.             }
  1700.             for (i = n - 1; i >= 0; --i) {
  1701.                 r[i] = 0;
  1702.             }
  1703.             r.t = this.t + n;
  1704.             r.s = this.s;
  1705.         };
  1706.         // BigInteger.prototype.drShiftTo = bnpDRShiftTo;
  1707.         // (protected) r = this >> n*DB
  1708.         BigInteger.prototype.drShiftTo = function (n, r) {
  1709.             for (var i = n; i < this.t; ++i) {
  1710.                 r[i - n] = this[i];
  1711.             }
  1712.             r.t = Math.max(this.t - n, 0);
  1713.             r.s = this.s;
  1714.         };
  1715.         // BigInteger.prototype.lShiftTo = bnpLShiftTo;
  1716.         // (protected) r = this << n
  1717.         BigInteger.prototype.lShiftTo = function (n, r) {
  1718.             var bs = n % this.DB;
  1719.             var cbs = this.DB - bs;
  1720.             var bm = (1 << cbs) - 1;
  1721.             var ds = Math.floor(n / this.DB);
  1722.             var c = (this.s << bs) & this.DM;
  1723.             for (var i = this.t - 1; i >= 0; --i) {
  1724.                 r[i + ds + 1] = (this[i] >> cbs) | c;
  1725.                 c = (this[i] & bm) << bs;
  1726.             }
  1727.             for (var i = ds - 1; i >= 0; --i) {
  1728.                 r[i] = 0;
  1729.             }
  1730.             r[ds] = c;
  1731.             r.t = this.t + ds + 1;
  1732.             r.s = this.s;
  1733.             r.clamp();
  1734.         };
  1735.         // BigInteger.prototype.rShiftTo = bnpRShiftTo;
  1736.         // (protected) r = this >> n
  1737.         BigInteger.prototype.rShiftTo = function (n, r) {
  1738.             r.s = this.s;
  1739.             var ds = Math.floor(n / this.DB);
  1740.             if (ds >= this.t) {
  1741.                 r.t = 0;
  1742.                 return;
  1743.             }
  1744.             var bs = n % this.DB;
  1745.             var cbs = this.DB - bs;
  1746.             var bm = (1 << bs) - 1;
  1747.             r[0] = this[ds] >> bs;
  1748.             for (var i = ds + 1; i < this.t; ++i) {
  1749.                 r[i - ds - 1] |= (this[i] & bm) << cbs;
  1750.                 r[i - ds] = this[i] >> bs;
  1751.             }
  1752.             if (bs > 0) {
  1753.                 r[this.t - ds - 1] |= (this.s & bm) << cbs;
  1754.             }
  1755.             r.t = this.t - ds;
  1756.             r.clamp();
  1757.         };
  1758.         // BigInteger.prototype.subTo = bnpSubTo;
  1759.         // (protected) r = this - a
  1760.         BigInteger.prototype.subTo = function (a, r) {
  1761.             var i = 0;
  1762.             var c = 0;
  1763.             var m = Math.min(a.t, this.t);
  1764.             while (i < m) {
  1765.                 c += this[i] - a[i];
  1766.                 r[i++] = c & this.DM;
  1767.                 c >>= this.DB;
  1768.             }
  1769.             if (a.t < this.t) {
  1770.                 c -= a.s;
  1771.                 while (i < this.t) {
  1772.                     c += this[i];
  1773.                     r[i++] = c & this.DM;
  1774.                     c >>= this.DB;
  1775.                 }
  1776.                 c += this.s;
  1777.             }
  1778.             else {
  1779.                 c += this.s;
  1780.                 while (i < a.t) {
  1781.                     c -= a[i];
  1782.                     r[i++] = c & this.DM;
  1783.                     c >>= this.DB;
  1784.                 }
  1785.                 c -= a.s;
  1786.             }
  1787.             r.s = (c < 0) ? -1 : 0;
  1788.             if (c < -1) {
  1789.                 r[i++] = this.DV + c;
  1790.             }
  1791.             else if (c > 0) {
  1792.                 r[i++] = c;
  1793.             }
  1794.             r.t = i;
  1795.             r.clamp();
  1796.         };
  1797.         // BigInteger.prototype.multiplyTo = bnpMultiplyTo;
  1798.         // (protected) r = this * a, r != this,a (HAC 14.12)
  1799.         // "this" should be the larger one if appropriate.
  1800.         BigInteger.prototype.multiplyTo = function (a, r) {
  1801.             var x = this.abs();
  1802.             var y = a.abs();
  1803.             var i = x.t;
  1804.             r.t = i + y.t;
  1805.             while (--i >= 0) {
  1806.                 r[i] = 0;
  1807.             }
  1808.             for (i = 0; i < y.t; ++i) {
  1809.                 r[i + x.t] = x.am(0, y[i], r, i, 0, x.t);
  1810.             }
  1811.             r.s = 0;
  1812.             r.clamp();
  1813.             if (this.s != a.s) {
  1814.                 BigInteger.ZERO.subTo(r, r);
  1815.             }
  1816.         };
  1817.         // BigInteger.prototype.squareTo = bnpSquareTo;
  1818.         // (protected) r = this^2, r != this (HAC 14.16)
  1819.         BigInteger.prototype.squareTo = function (r) {
  1820.             var x = this.abs();
  1821.             var i = r.t = 2 * x.t;
  1822.             while (--i >= 0) {
  1823.                 r[i] = 0;
  1824.             }
  1825.             for (i = 0; i < x.t - 1; ++i) {
  1826.                 var c = x.am(i, x[i], r, 2 * i, 0, 1);
  1827.                 if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
  1828.                     r[i + x.t] -= x.DV;
  1829.                     r[i + x.t + 1] = 1;
  1830.                 }
  1831.             }
  1832.             if (r.t > 0) {
  1833.                 r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1);
  1834.             }
  1835.             r.s = 0;
  1836.             r.clamp();
  1837.         };
  1838.         // BigInteger.prototype.divRemTo = bnpDivRemTo;
  1839.         // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
  1840.         // r != q, this != m.  q or r may be null.
  1841.         BigInteger.prototype.divRemTo = function (m, q, r) {
  1842.             var pm = m.abs();
  1843.             if (pm.t <= 0) {
  1844.                 return;
  1845.             }
  1846.             var pt = this.abs();
  1847.             if (pt.t < pm.t) {
  1848.                 if (q != null) {
  1849.                     q.fromInt(0);
  1850.                 }
  1851.                 if (r != null) {
  1852.                     this.copyTo(r);
  1853.                 }
  1854.                 return;
  1855.             }
  1856.             if (r == null) {
  1857.                 r = nbi();
  1858.             }
  1859.             var y = nbi();
  1860.             var ts = this.s;
  1861.             var ms = m.s;
  1862.             var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus
  1863.             if (nsh > 0) {
  1864.                 pm.lShiftTo(nsh, y);
  1865.                 pt.lShiftTo(nsh, r);
  1866.             }
  1867.             else {
  1868.                 pm.copyTo(y);
  1869.                 pt.copyTo(r);
  1870.             }
  1871.             var ys = y.t;
  1872.             var y0 = y[ys - 1];
  1873.             if (y0 == 0) {
  1874.                 return;
  1875.             }
  1876.             var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0);
  1877.             var d1 = this.FV / yt;
  1878.             var d2 = (1 << this.F1) / yt;
  1879.             var e = 1 << this.F2;
  1880.             var i = r.t;
  1881.             var j = i - ys;
  1882.             var t = (q == null) ? nbi() : q;
  1883.             y.dlShiftTo(j, t);
  1884.             if (r.compareTo(t) >= 0) {
  1885.                 r[r.t++] = 1;
  1886.                 r.subTo(t, r);
  1887.             }
  1888.             BigInteger.ONE.dlShiftTo(ys, t);
  1889.             t.subTo(y, y); // "negative" y so we can replace sub with am later
  1890.             while (y.t < ys) {
  1891.                 y[y.t++] = 0;
  1892.             }
  1893.             while (--j >= 0) {
  1894.                 // Estimate quotient digit
  1895.                 var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2);
  1896.                 if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out
  1897.                     y.dlShiftTo(j, t);
  1898.                     r.subTo(t, r);
  1899.                     while (r[i] < --qd) {
  1900.                         r.subTo(t, r);
  1901.                     }
  1902.                 }
  1903.             }
  1904.             if (q != null) {
  1905.                 r.drShiftTo(ys, q);
  1906.                 if (ts != ms) {
  1907.                     BigInteger.ZERO.subTo(q, q);
  1908.                 }
  1909.             }
  1910.             r.t = ys;
  1911.             r.clamp();
  1912.             if (nsh > 0) {
  1913.                 r.rShiftTo(nsh, r);
  1914.             } // Denormalize remainder
  1915.             if (ts < 0) {
  1916.                 BigInteger.ZERO.subTo(r, r);
  1917.             }
  1918.         };
  1919.         // BigInteger.prototype.invDigit = bnpInvDigit;
  1920.         // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
  1921.         // justification:
  1922.         //         xy == 1 (mod m)
  1923.         //         xy =  1+km
  1924.         //   xy(2-xy) = (1+km)(1-km)
  1925.         // x[y(2-xy)] = 1-k^2m^2
  1926.         // x[y(2-xy)] == 1 (mod m^2)
  1927.         // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
  1928.         // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
  1929.         // JS multiply "overflows" differently from C/C++, so care is needed here.
  1930.         BigInteger.prototype.invDigit = function () {
  1931.             if (this.t < 1) {
  1932.                 return 0;
  1933.             }
  1934.             var x = this[0];
  1935.             if ((x & 1) == 0) {
  1936.                 return 0;
  1937.             }
  1938.             var y = x & 3; // y == 1/x mod 2^2
  1939.             y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4
  1940.             y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8
  1941.             y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16
  1942.             // last step - calculate inverse mod DV directly;
  1943.             // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
  1944.             y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits
  1945.             // we really want the negative inverse, and -DV < y < DV
  1946.             return (y > 0) ? this.DV - y : -y;
  1947.         };
  1948.         // BigInteger.prototype.isEven = bnpIsEven;
  1949.         // (protected) true iff this is even
  1950.         BigInteger.prototype.isEven = function () {
  1951.             return ((this.t > 0) ? (this[0] & 1) : this.s) == 0;
  1952.         };
  1953.         // BigInteger.prototype.exp = bnpExp;
  1954.         // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
  1955.         BigInteger.prototype.exp = function (e, z) {
  1956.             if (e > 0xffffffff || e < 1) {
  1957.                 return BigInteger.ONE;
  1958.             }
  1959.             var r = nbi();
  1960.             var r2 = nbi();
  1961.             var g = z.convert(this);
  1962.             var i = nbits(e) - 1;
  1963.             g.copyTo(r);
  1964.             while (--i >= 0) {
  1965.                 z.sqrTo(r, r2);
  1966.                 if ((e & (1 << i)) > 0) {
  1967.                     z.mulTo(r2, g, r);
  1968.                 }
  1969.                 else {
  1970.                     var t = r;
  1971.                     r = r2;
  1972.                     r2 = t;
  1973.                 }
  1974.             }
  1975.             return z.revert(r);
  1976.         };
  1977.         // BigInteger.prototype.chunkSize = bnpChunkSize;
  1978.         // (protected) return x s.t. r^x < DV
  1979.         BigInteger.prototype.chunkSize = function (r) {
  1980.             return Math.floor(Math.LN2 * this.DB / Math.log(r));
  1981.         };
  1982.         // BigInteger.prototype.toRadix = bnpToRadix;
  1983.         // (protected) convert to radix string
  1984.         BigInteger.prototype.toRadix = function (b) {
  1985.             if (b == null) {
  1986.                 b = 10;
  1987.             }
  1988.             if (this.signum() == 0 || b < 2 || b > 36) {
  1989.                 return "0";
  1990.             }
  1991.             var cs = this.chunkSize(b);
  1992.             var a = Math.pow(b, cs);
  1993.             var d = nbv(a);
  1994.             var y = nbi();
  1995.             var z = nbi();
  1996.             var r = "";
  1997.             this.divRemTo(d, y, z);
  1998.             while (y.signum() > 0) {
  1999.                 r = (a + z.intValue()).toString(b).substr(1) + r;
  2000.                 y.divRemTo(d, y, z);
  2001.             }
  2002.             return z.intValue().toString(b) + r;
  2003.         };
  2004.         // BigInteger.prototype.fromRadix = bnpFromRadix;
  2005.         // (protected) convert from radix string
  2006.         BigInteger.prototype.fromRadix = function (s, b) {
  2007.             this.fromInt(0);
  2008.             if (b == null) {
  2009.                 b = 10;
  2010.             }
  2011.             var cs = this.chunkSize(b);
  2012.             var d = Math.pow(b, cs);
  2013.             var mi = false;
  2014.             var j = 0;
  2015.             var w = 0;
  2016.             for (var i = 0; i < s.length; ++i) {
  2017.                 var x = intAt(s, i);
  2018.                 if (x < 0) {
  2019.                     if (s.charAt(i) == "-" && this.signum() == 0) {
  2020.                         mi = true;
  2021.                     }
  2022.                     continue;
  2023.                 }
  2024.                 w = b * w + x;
  2025.                 if (++j >= cs) {
  2026.                     this.dMultiply(d);
  2027.                     this.dAddOffset(w, 0);
  2028.                     j = 0;
  2029.                     w = 0;
  2030.                 }
  2031.             }
  2032.             if (j > 0) {
  2033.                 this.dMultiply(Math.pow(b, j));
  2034.                 this.dAddOffset(w, 0);
  2035.             }
  2036.             if (mi) {
  2037.                 BigInteger.ZERO.subTo(this, this);
  2038.             }
  2039.         };
  2040.         // BigInteger.prototype.fromNumber = bnpFromNumber;
  2041.         // (protected) alternate constructor
  2042.         BigInteger.prototype.fromNumber = function (a, b, c) {
  2043.             if ("number" == typeof b) {
  2044.                 // new BigInteger(int,int,RNG)
  2045.                 if (a < 2) {
  2046.                     this.fromInt(1);
  2047.                 }
  2048.                 else {
  2049.                     this.fromNumber(a, c);
  2050.                     if (!this.testBit(a - 1)) {
  2051.                         // force MSB set
  2052.                         this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);
  2053.                     }
  2054.                     if (this.isEven()) {
  2055.                         this.dAddOffset(1, 0);
  2056.                     } // force odd
  2057.                     while (!this.isProbablePrime(b)) {
  2058.                         this.dAddOffset(2, 0);
  2059.                         if (this.bitLength() > a) {
  2060.                             this.subTo(BigInteger.ONE.shiftLeft(a - 1), this);
  2061.                         }
  2062.                     }
  2063.                 }
  2064.             }
  2065.             else {
  2066.                 // new BigInteger(int,RNG)
  2067.                 var x = [];
  2068.                 var t = a & 7;
  2069.                 x.length = (a >> 3) + 1;
  2070.                 b.nextBytes(x);
  2071.                 if (t > 0) {
  2072.                     x[0] &= ((1 << t) - 1);
  2073.                 }
  2074.                 else {
  2075.                     x[0] = 0;
  2076.                 }
  2077.                 this.fromString(x, 256);
  2078.             }
  2079.         };
  2080.         // BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
  2081.         // (protected) r = this op a (bitwise)
  2082.         BigInteger.prototype.bitwiseTo = function (a, op, r) {
  2083.             var i;
  2084.             var f;
  2085.             var m = Math.min(a.t, this.t);
  2086.             for (i = 0; i < m; ++i) {
  2087.                 r[i] = op(this[i], a[i]);
  2088.             }
  2089.             if (a.t < this.t) {
  2090.                 f = a.s & this.DM;
  2091.                 for (i = m; i < this.t; ++i) {
  2092.                     r[i] = op(this[i], f);
  2093.                 }
  2094.                 r.t = this.t;
  2095.             }
  2096.             else {
  2097.                 f = this.s & this.DM;
  2098.                 for (i = m; i < a.t; ++i) {
  2099.                     r[i] = op(f, a[i]);
  2100.                 }
  2101.                 r.t = a.t;
  2102.             }
  2103.             r.s = op(this.s, a.s);
  2104.             r.clamp();
  2105.         };
  2106.         // BigInteger.prototype.changeBit = bnpChangeBit;
  2107.         // (protected) this op (1<<n)
  2108.         BigInteger.prototype.changeBit = function (n, op) {
  2109.             var r = BigInteger.ONE.shiftLeft(n);
  2110.             this.bitwiseTo(r, op, r);
  2111.             return r;
  2112.         };
  2113.         // BigInteger.prototype.addTo = bnpAddTo;
  2114.         // (protected) r = this + a
  2115.         BigInteger.prototype.addTo = function (a, r) {
  2116.             var i = 0;
  2117.             var c = 0;
  2118.             var m = Math.min(a.t, this.t);
  2119.             while (i < m) {
  2120.                 c += this[i] + a[i];
  2121.                 r[i++] = c & this.DM;
  2122.                 c >>= this.DB;
  2123.             }
  2124.             if (a.t < this.t) {
  2125.                 c += a.s;
  2126.                 while (i < this.t) {
  2127.                     c += this[i];
  2128.                     r[i++] = c & this.DM;
  2129.                     c >>= this.DB;
  2130.                 }
  2131.                 c += this.s;
  2132.             }
  2133.             else {
  2134.                 c += this.s;
  2135.                 while (i < a.t) {
  2136.                     c += a[i];
  2137.                     r[i++] = c & this.DM;
  2138.                     c >>= this.DB;
  2139.                 }
  2140.                 c += a.s;
  2141.             }
  2142.             r.s = (c < 0) ? -1 : 0;
  2143.             if (c > 0) {
  2144.                 r[i++] = c;
  2145.             }
  2146.             else if (c < -1) {
  2147.                 r[i++] = this.DV + c;
  2148.             }
  2149.             r.t = i;
  2150.             r.clamp();
  2151.         };
  2152.         // BigInteger.prototype.dMultiply = bnpDMultiply;
  2153.         // (protected) this *= n, this >= 0, 1 < n < DV
  2154.         BigInteger.prototype.dMultiply = function (n) {
  2155.             this[this.t] = this.am(0, n - 1, this, 0, 0, this.t);
  2156.             ++this.t;
  2157.             this.clamp();
  2158.         };
  2159.         // BigInteger.prototype.dAddOffset = bnpDAddOffset;
  2160.         // (protected) this += n << w words, this >= 0
  2161.         BigInteger.prototype.dAddOffset = function (n, w) {
  2162.             if (n == 0) {
  2163.                 return;
  2164.             }
  2165.             while (this.t <= w) {
  2166.                 this[this.t++] = 0;
  2167.             }
  2168.             this[w] += n;
  2169.             while (this[w] >= this.DV) {
  2170.                 this[w] -= this.DV;
  2171.                 if (++w >= this.t) {
  2172.                     this[this.t++] = 0;
  2173.                 }
  2174.                 ++this[w];
  2175.             }
  2176.         };
  2177.         // BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
  2178.         // (protected) r = lower n words of "this * a", a.t <= n
  2179.         // "this" should be the larger one if appropriate.
  2180.         BigInteger.prototype.multiplyLowerTo = function (a, n, r) {
  2181.             var i = Math.min(this.t + a.t, n);
  2182.             r.s = 0; // assumes a,this >= 0
  2183.             r.t = i;
  2184.             while (i > 0) {
  2185.                 r[--i] = 0;
  2186.             }
  2187.             for (var j = r.t - this.t; i < j; ++i) {
  2188.                 r[i + this.t] = this.am(0, a[i], r, i, 0, this.t);
  2189.             }
  2190.             for (var j = Math.min(a.t, n); i < j; ++i) {
  2191.                 this.am(0, a[i], r, i, 0, n - i);
  2192.             }
  2193.             r.clamp();
  2194.         };
  2195.         // BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
  2196.         // (protected) r = "this * a" without lower n words, n > 0
  2197.         // "this" should be the larger one if appropriate.
  2198.         BigInteger.prototype.multiplyUpperTo = function (a, n, r) {
  2199.             --n;
  2200.             var i = r.t = this.t + a.t - n;
  2201.             r.s = 0; // assumes a,this >= 0
  2202.             while (--i >= 0) {
  2203.                 r[i] = 0;
  2204.             }
  2205.             for (i = Math.max(n - this.t, 0); i < a.t; ++i) {
  2206.                 r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n);
  2207.             }
  2208.             r.clamp();
  2209.             r.drShiftTo(1, r);
  2210.         };
  2211.         // BigInteger.prototype.modInt = bnpModInt;
  2212.         // (protected) this % n, n < 2^26
  2213.         BigInteger.prototype.modInt = function (n) {
  2214.             if (n <= 0) {
  2215.                 return 0;
  2216.             }
  2217.             var d = this.DV % n;
  2218.             var r = (this.s < 0) ? n - 1 : 0;
  2219.             if (this.t > 0) {
  2220.                 if (d == 0) {
  2221.                     r = this[0] % n;
  2222.                 }
  2223.                 else {
  2224.                     for (var i = this.t - 1; i >= 0; --i) {
  2225.                         r = (d * r + this[i]) % n;
  2226.                     }
  2227.                 }
  2228.             }
  2229.             return r;
  2230.         };
  2231.         // BigInteger.prototype.millerRabin = bnpMillerRabin;
  2232.         // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
  2233.         BigInteger.prototype.millerRabin = function (t) {
  2234.             var n1 = this.subtract(BigInteger.ONE);
  2235.             var k = n1.getLowestSetBit();
  2236.             if (k <= 0) {
  2237.                 return false;
  2238.             }
  2239.             var r = n1.shiftRight(k);
  2240.             t = (t + 1) >> 1;
  2241.             if (t > lowprimes.length) {
  2242.                 t = lowprimes.length;
  2243.             }
  2244.             var a = nbi();
  2245.             for (var i = 0; i < t; ++i) {
  2246.                 // Pick bases at random, instead of starting at 2
  2247.                 a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]);
  2248.                 var y = a.modPow(r, this);
  2249.                 if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
  2250.                     var j = 1;
  2251.                     while (j++ < k && y.compareTo(n1) != 0) {
  2252.                         y = y.modPowInt(2, this);
  2253.                         if (y.compareTo(BigInteger.ONE) == 0) {
  2254.                             return false;
  2255.                         }
  2256.                     }
  2257.                     if (y.compareTo(n1) != 0) {
  2258.                         return false;
  2259.                     }
  2260.                 }
  2261.             }
  2262.             return true;
  2263.         };
  2264.         // BigInteger.prototype.square = bnSquare;
  2265.         // (public) this^2
  2266.         BigInteger.prototype.square = function () {
  2267.             var r = nbi();
  2268.             this.squareTo(r);
  2269.             return r;
  2270.         };
  2271.         //#region ASYNC
  2272.         // Public API method
  2273.         BigInteger.prototype.gcda = function (a, callback) {
  2274.             var x = (this.s < 0) ? this.negate() : this.clone();
  2275.             var y = (a.s < 0) ? a.negate() : a.clone();
  2276.             if (x.compareTo(y) < 0) {
  2277.                 var t = x;
  2278.                 x = y;
  2279.                 y = t;
  2280.             }
  2281.             var i = x.getLowestSetBit();
  2282.             var g = y.getLowestSetBit();
  2283.             if (g < 0) {
  2284.                 callback(x);
  2285.                 return;
  2286.             }
  2287.             if (i < g) {
  2288.                 g = i;
  2289.             }
  2290.             if (g > 0) {
  2291.                 x.rShiftTo(g, x);
  2292.                 y.rShiftTo(g, y);
  2293.             }
  2294.             // Workhorse of the algorithm, gets called 200 - 800 times per 512 bit keygen.
  2295.             var gcda1 = function () {
  2296.                 if ((i = x.getLowestSetBit()) > 0) {
  2297.                     x.rShiftTo(i, x);
  2298.                 }
  2299.                 if ((i = y.getLowestSetBit()) > 0) {
  2300.                     y.rShiftTo(i, y);
  2301.                 }
  2302.                 if (x.compareTo(y) >= 0) {
  2303.                     x.subTo(y, x);
  2304.                     x.rShiftTo(1, x);
  2305.                 }
  2306.                 else {
  2307.                     y.subTo(x, y);
  2308.                     y.rShiftTo(1, y);
  2309.                 }
  2310.                 if (!(x.signum() > 0)) {
  2311.                     if (g > 0) {
  2312.                         y.lShiftTo(g, y);
  2313.                     }
  2314.                     setTimeout(function () { callback(y); }, 0); // escape
  2315.                 }
  2316.                 else {
  2317.                     setTimeout(gcda1, 0);
  2318.                 }
  2319.             };
  2320.             setTimeout(gcda1, 10);
  2321.         };
  2322.         // (protected) alternate constructor
  2323.         BigInteger.prototype.fromNumberAsync = function (a, b, c, callback) {
  2324.             if ("number" == typeof b) {
  2325.                 if (a < 2) {
  2326.                     this.fromInt(1);
  2327.                 }
  2328.                 else {
  2329.                     this.fromNumber(a, c);
  2330.                     if (!this.testBit(a - 1)) {
  2331.                         this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);
  2332.                     }
  2333.                     if (this.isEven()) {
  2334.                         this.dAddOffset(1, 0);
  2335.                     }
  2336.                     var bnp_1 = this;
  2337.                     var bnpfn1_1 = function () {
  2338.                         bnp_1.dAddOffset(2, 0);
  2339.                         if (bnp_1.bitLength() > a) {
  2340.                             bnp_1.subTo(BigInteger.ONE.shiftLeft(a - 1), bnp_1);
  2341.                         }
  2342.                         if (bnp_1.isProbablePrime(b)) {
  2343.                             setTimeout(function () { callback(); }, 0); // escape
  2344.                         }
  2345.                         else {
  2346.                             setTimeout(bnpfn1_1, 0);
  2347.                         }
  2348.                     };
  2349.                     setTimeout(bnpfn1_1, 0);
  2350.                 }
  2351.             }
  2352.             else {
  2353.                 var x = [];
  2354.                 var t = a & 7;
  2355.                 x.length = (a >> 3) + 1;
  2356.                 b.nextBytes(x);
  2357.                 if (t > 0) {
  2358.                     x[0] &= ((1 << t) - 1);
  2359.                 }
  2360.                 else {
  2361.                     x[0] = 0;
  2362.                 }
  2363.                 this.fromString(x, 256);
  2364.             }
  2365.         };
  2366.         return BigInteger;
  2367.     }());
  2368. //#region REDUCERS
  2369. //#region NullExp
  2370.     var NullExp = /** @class */ (function () {
  2371.         function NullExp() {
  2372.         }
  2373.         // NullExp.prototype.convert = nNop;
  2374.         NullExp.prototype.convert = function (x) {
  2375.             return x;
  2376.         };
  2377.         // NullExp.prototype.revert = nNop;
  2378.         NullExp.prototype.revert = function (x) {
  2379.             return x;
  2380.         };
  2381.         // NullExp.prototype.mulTo = nMulTo;
  2382.         NullExp.prototype.mulTo = function (x, y, r) {
  2383.             x.multiplyTo(y, r);
  2384.         };
  2385.         // NullExp.prototype.sqrTo = nSqrTo;
  2386.         NullExp.prototype.sqrTo = function (x, r) {
  2387.             x.squareTo(r);
  2388.         };
  2389.         return NullExp;
  2390.     }());
  2391. // Modular reduction using "classic" algorithm
  2392.     var Classic = /** @class */ (function () {
  2393.         function Classic(m) {
  2394.             this.m = m;
  2395.         }
  2396.         // Classic.prototype.convert = cConvert;
  2397.         Classic.prototype.convert = function (x) {
  2398.             if (x.s < 0 || x.compareTo(this.m) >= 0) {
  2399.                 return x.mod(this.m);
  2400.             }
  2401.             else {
  2402.                 return x;
  2403.             }
  2404.         };
  2405.         // Classic.prototype.revert = cRevert;
  2406.         Classic.prototype.revert = function (x) {
  2407.             return x;
  2408.         };
  2409.         // Classic.prototype.reduce = cReduce;
  2410.         Classic.prototype.reduce = function (x) {
  2411.             x.divRemTo(this.m, null, x);
  2412.         };
  2413.         // Classic.prototype.mulTo = cMulTo;
  2414.         Classic.prototype.mulTo = function (x, y, r) {
  2415.             x.multiplyTo(y, r);
  2416.             this.reduce(r);
  2417.         };
  2418.         // Classic.prototype.sqrTo = cSqrTo;
  2419.         Classic.prototype.sqrTo = function (x, r) {
  2420.             x.squareTo(r);
  2421.             this.reduce(r);
  2422.         };
  2423.         return Classic;
  2424.     }());
  2425. //#endregion
  2426. //#region Montgomery
  2427. // Montgomery reduction
  2428.     var Montgomery = /** @class */ (function () {
  2429.         function Montgomery(m) {
  2430.             this.m = m;
  2431.             this.mp = m.invDigit();
  2432.             this.mpl = this.mp & 0x7fff;
  2433.             this.mph = this.mp >> 15;
  2434.             this.um = (1 << (m.DB - 15)) - 1;
  2435.             this.mt2 = 2 * m.t;
  2436.         }
  2437.         // Montgomery.prototype.convert = montConvert;
  2438.         // xR mod m
  2439.         Montgomery.prototype.convert = function (x) {
  2440.             var r = nbi();
  2441.             x.abs().dlShiftTo(this.m.t, r);
  2442.             r.divRemTo(this.m, null, r);
  2443.             if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) {
  2444.                 this.m.subTo(r, r);
  2445.             }
  2446.             return r;
  2447.         };
  2448.         // Montgomery.prototype.revert = montRevert;
  2449.         // x/R mod m
  2450.         Montgomery.prototype.revert = function (x) {
  2451.             var r = nbi();
  2452.             x.copyTo(r);
  2453.             this.reduce(r);
  2454.             return r;
  2455.         };
  2456.         // Montgomery.prototype.reduce = montReduce;
  2457.         // x = x/R mod m (HAC 14.32)
  2458.         Montgomery.prototype.reduce = function (x) {
  2459.             while (x.t <= this.mt2) {
  2460.                 // pad x so am has enough room later
  2461.                 x[x.t++] = 0;
  2462.             }
  2463.             for (var i = 0; i < this.m.t; ++i) {
  2464.                 // faster way of calculating u0 = x[i]*mp mod DV
  2465.                 var j = x[i] & 0x7fff;
  2466.                 var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM;
  2467.                 // use am to combine the multiply-shift-add into one call
  2468.                 j = i + this.m.t;
  2469.                 x[j] += this.m.am(0, u0, x, i, 0, this.m.t);
  2470.                 // propagate carry
  2471.                 while (x[j] >= x.DV) {
  2472.                     x[j] -= x.DV;
  2473.                     x[++j]++;
  2474.                 }
  2475.             }
  2476.             x.clamp();
  2477.             x.drShiftTo(this.m.t, x);
  2478.             if (x.compareTo(this.m) >= 0) {
  2479.                 x.subTo(this.m, x);
  2480.             }
  2481.         };
  2482.         // Montgomery.prototype.mulTo = montMulTo;
  2483.         // r = "xy/R mod m"; x,y != r
  2484.         Montgomery.prototype.mulTo = function (x, y, r) {
  2485.             x.multiplyTo(y, r);
  2486.             this.reduce(r);
  2487.         };
  2488.         // Montgomery.prototype.sqrTo = montSqrTo;
  2489.         // r = "x^2/R mod m"; x != r
  2490.         Montgomery.prototype.sqrTo = function (x, r) {
  2491.             x.squareTo(r);
  2492.             this.reduce(r);
  2493.         };
  2494.         return Montgomery;
  2495.     }());
  2496. //#endregion Montgomery
  2497. //#region Barrett
  2498. // Barrett modular reduction
  2499.     var Barrett = /** @class */ (function () {
  2500.         function Barrett(m) {
  2501.             this.m = m;
  2502.             // setup Barrett
  2503.             this.r2 = nbi();
  2504.             this.q3 = nbi();
  2505.             BigInteger.ONE.dlShiftTo(2 * m.t, this.r2);
  2506.             this.mu = this.r2.divide(m);
  2507.         }
  2508.         // Barrett.prototype.convert = barrettConvert;
  2509.         Barrett.prototype.convert = function (x) {
  2510.             if (x.s < 0 || x.t > 2 * this.m.t) {
  2511.                 return x.mod(this.m);
  2512.             }
  2513.             else if (x.compareTo(this.m) < 0) {
  2514.                 return x;
  2515.             }
  2516.             else {
  2517.                 var r = nbi();
  2518.                 x.copyTo(r);
  2519.                 this.reduce(r);
  2520.                 return r;
  2521.             }
  2522.         };
  2523.         // Barrett.prototype.revert = barrettRevert;
  2524.         Barrett.prototype.revert = function (x) {
  2525.             return x;
  2526.         };
  2527.         // Barrett.prototype.reduce = barrettReduce;
  2528.         // x = x mod m (HAC 14.42)
  2529.         Barrett.prototype.reduce = function (x) {
  2530.             x.drShiftTo(this.m.t - 1, this.r2);
  2531.             if (x.t > this.m.t + 1) {
  2532.                 x.t = this.m.t + 1;
  2533.                 x.clamp();
  2534.             }
  2535.             this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3);
  2536.             this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2);
  2537.             while (x.compareTo(this.r2) < 0) {
  2538.                 x.dAddOffset(1, this.m.t + 1);
  2539.             }
  2540.             x.subTo(this.r2, x);
  2541.             while (x.compareTo(this.m) >= 0) {
  2542.                 x.subTo(this.m, x);
  2543.             }
  2544.         };
  2545.         // Barrett.prototype.mulTo = barrettMulTo;
  2546.         // r = x*y mod m; x,y != r
  2547.         Barrett.prototype.mulTo = function (x, y, r) {
  2548.             x.multiplyTo(y, r);
  2549.             this.reduce(r);
  2550.         };
  2551.         // Barrett.prototype.sqrTo = barrettSqrTo;
  2552.         // r = x^2 mod m; x != r
  2553.         Barrett.prototype.sqrTo = function (x, r) {
  2554.             x.squareTo(r);
  2555.             this.reduce(r);
  2556.         };
  2557.         return Barrett;
  2558.     }());
  2559. //#endregion
  2560. //#endregion REDUCERS
  2561. // return new, unset BigInteger
  2562.     function nbi() { return new BigInteger(null); }
  2563.     function parseBigInt(str, r) {
  2564.         return new BigInteger(str, r);
  2565.     }
  2566. // am: Compute w_j += (x*this_i), propagate carries,
  2567. // c is initial carry, returns final carry.
  2568. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue
  2569. // We need to select the fastest one that works in this environment.
  2570. // am1: use a single mult and divide to get the high bits,
  2571. // max digit bits should be 26 because
  2572. // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
  2573.     function am1(i, x, w, j, c, n) {
  2574.         while (--n >= 0) {
  2575.             var v = x * this[i++] + w[j] + c;
  2576.             c = Math.floor(v / 0x4000000);
  2577.             w[j++] = v & 0x3ffffff;
  2578.         }
  2579.         return c;
  2580.     }
  2581. // am2 avoids a big mult-and-extract completely.
  2582. // Max digit bits should be <= 30 because we do bitwise ops
  2583. // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
  2584.     function am2(i, x, w, j, c, n) {
  2585.         var xl = x & 0x7fff;
  2586.         var xh = x >> 15;
  2587.         while (--n >= 0) {
  2588.             var l = this[i] & 0x7fff;
  2589.             var h = this[i++] >> 15;
  2590.             var m = xh * l + h * xl;
  2591.             l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff);
  2592.             c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30);
  2593.             w[j++] = l & 0x3fffffff;
  2594.         }
  2595.         return c;
  2596.     }
  2597. // Alternately, set max digit bits to 28 since some
  2598. // browsers slow down when dealing with 32-bit numbers.
  2599.     function am3(i, x, w, j, c, n) {
  2600.         var xl = x & 0x3fff;
  2601.         var xh = x >> 14;
  2602.         while (--n >= 0) {
  2603.             var l = this[i] & 0x3fff;
  2604.             var h = this[i++] >> 14;
  2605.             var m = xh * l + h * xl;
  2606.             l = xl * l + ((m & 0x3fff) << 14) + w[j] + c;
  2607.             c = (l >> 28) + (m >> 14) + xh * h;
  2608.             w[j++] = l & 0xfffffff;
  2609.         }
  2610.         return c;
  2611.     }
  2612.     if (j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
  2613.         BigInteger.prototype.am = am2;
  2614.         dbits = 30;
  2615.     }
  2616.     else if (j_lm && (navigator.appName != "Netscape")) {
  2617.         BigInteger.prototype.am = am1;
  2618.         dbits = 26;
  2619.     }
  2620.     else { // Mozilla/Netscape seems to prefer am3
  2621.         BigInteger.prototype.am = am3;
  2622.         dbits = 28;
  2623.     }
  2624.     BigInteger.prototype.DB = dbits;
  2625.     BigInteger.prototype.DM = ((1 << dbits) - 1);
  2626.     BigInteger.prototype.DV = (1 << dbits);
  2627.     var BI_FP = 52;
  2628.     BigInteger.prototype.FV = Math.pow(2, BI_FP);
  2629.     BigInteger.prototype.F1 = BI_FP - dbits;
  2630.     BigInteger.prototype.F2 = 2 * dbits - BI_FP;
  2631. // Digit conversions
  2632.     var BI_RC = [];
  2633.     var rr;
  2634.     var vv;
  2635.     rr = "0".charCodeAt(0);
  2636.     for (vv = 0; vv <= 9; ++vv) {
  2637.         BI_RC[rr++] = vv;
  2638.     }
  2639.     rr = "a".charCodeAt(0);
  2640.     for (vv = 10; vv < 36; ++vv) {
  2641.         BI_RC[rr++] = vv;
  2642.     }
  2643.     rr = "A".charCodeAt(0);
  2644.     for (vv = 10; vv < 36; ++vv) {
  2645.         BI_RC[rr++] = vv;
  2646.     }
  2647.     function intAt(s, i) {
  2648.         var c = BI_RC[s.charCodeAt(i)];
  2649.         return (c == null) ? -1 : c;
  2650.     }
  2651. // return bigint initialized to value
  2652.     function nbv(i) {
  2653.         var r = nbi();
  2654.         r.fromInt(i);
  2655.         return r;
  2656.     }
  2657. // returns bit length of the integer x
  2658.     function nbits(x) {
  2659.         var r = 1;
  2660.         var t;
  2661.         if ((t = x >>> 16) != 0) {
  2662.             x = t;
  2663.             r += 16;
  2664.         }
  2665.         if ((t = x >> 8) != 0) {
  2666.             x = t;
  2667.             r += 8;
  2668.         }
  2669.         if ((t = x >> 4) != 0) {
  2670.             x = t;
  2671.             r += 4;
  2672.         }
  2673.         if ((t = x >> 2) != 0) {
  2674.             x = t;
  2675.             r += 2;
  2676.         }
  2677.         if ((t = x >> 1) != 0) {
  2678.             x = t;
  2679.             r += 1;
  2680.         }
  2681.         return r;
  2682.     }
  2683. // "constants"
  2684.     BigInteger.ZERO = nbv(0);
  2685.     BigInteger.ONE = nbv(1);

  2686. // prng4.js - uses Arcfour as a PRNG
  2687.     var Arcfour = /** @class */ (function () {
  2688.         function Arcfour() {
  2689.             this.i = 0;
  2690.             this.j = 0;
  2691.             this.S = [];
  2692.         }
  2693.         // Arcfour.prototype.init = ARC4init;
  2694.         // Initialize arcfour context from key, an array of ints, each from [0..255]
  2695.         Arcfour.prototype.init = function (key) {
  2696.             var i;
  2697.             var j;
  2698.             var t;
  2699.             for (i = 0; i < 256; ++i) {
  2700.                 this.S[i] = i;
  2701.             }
  2702.             j = 0;
  2703.             for (i = 0; i < 256; ++i) {
  2704.                 j = (j + this.S[i] + key[i % key.length]) & 255;
  2705.                 t = this.S[i];
  2706.                 this.S[i] = this.S[j];
  2707.                 this.S[j] = t;
  2708.             }
  2709.             this.i = 0;
  2710.             this.j = 0;
  2711.         };
  2712.         // Arcfour.prototype.next = ARC4next;
  2713.         Arcfour.prototype.next = function () {
  2714.             var t;
  2715.             this.i = (this.i + 1) & 255;
  2716.             this.j = (this.j + this.S[this.i]) & 255;
  2717.             t = this.S[this.i];
  2718.             this.S[this.i] = this.S[this.j];
  2719.             this.S[this.j] = t;
  2720.             return this.S[(t + this.S[this.i]) & 255];
  2721.         };
  2722.         return Arcfour;
  2723.     }());
  2724. // Plug in your RNG constructor here
  2725.     function prng_newstate() {
  2726.         return new Arcfour();
  2727.     }
  2728. // Pool size must be a multiple of 4 and greater than 32.
  2729. // An array of bytes the size of the pool will be passed to init()
  2730.     var rng_psize = 256;

  2731. // Random number generator - requires a PRNG backend, e.g. prng4.js
  2732.     var rng_state;
  2733.     var rng_pool = null;
  2734.     var rng_pptr;
  2735. // Initialize the pool with junk if needed.
  2736.     if (rng_pool == null) {
  2737.         rng_pool = [];
  2738.         rng_pptr = 0;
  2739.         var t = void 0;
  2740.         if (window.crypto && window.crypto.getRandomValues) {
  2741.             // Extract entropy (2048 bits) from RNG if available
  2742.             var z = new Uint32Array(256);
  2743.             window.crypto.getRandomValues(z);
  2744.             for (t = 0; t < z.length; ++t) {
  2745.                 rng_pool[rng_pptr++] = z[t] & 255;
  2746.             }
  2747.         }
  2748.         // Use mouse events for entropy, if we do not have enough entropy by the time
  2749.         // we need it, entropy will be generated by Math.random.
  2750.         var onMouseMoveListener_1 = function (ev) {
  2751.             this.count = this.count || 0;
  2752.             if (this.count >= 256 || rng_pptr >= rng_psize) {
  2753.                 if (window.removeEventListener) {
  2754.                     window.removeEventListener("mousemove", onMouseMoveListener_1, false);
  2755.                 }
  2756.                 else if (window.detachEvent) {
  2757.                     window.detachEvent("onmousemove", onMouseMoveListener_1);
  2758.                 }
  2759.                 return;
  2760.             }
  2761.             try {
  2762.                 var mouseCoordinates = ev.x + ev.y;
  2763.                 rng_pool[rng_pptr++] = mouseCoordinates & 255;
  2764.                 this.count += 1;
  2765.             }
  2766.             catch (e) {
  2767.                 // Sometimes Firefox will deny permission to access event properties for some reason. Ignore.
  2768.             }
  2769.         };
  2770.         if (window.addEventListener) {
  2771.             window.addEventListener("mousemove", onMouseMoveListener_1, false);
  2772.         }
  2773.         else if (window.attachEvent) {
  2774.             window.attachEvent("onmousemove", onMouseMoveListener_1);
  2775.         }
  2776.     }
  2777.     function rng_get_byte() {
  2778.         if (rng_state == null) {
  2779.             rng_state = prng_newstate();
  2780.             // At this point, we may not have collected enough entropy.  If not, fall back to Math.random
  2781.             while (rng_pptr < rng_psize) {
  2782.                 var random = Math.floor(65536 * Math.random());
  2783.                 rng_pool[rng_pptr++] = random & 255;
  2784.             }
  2785.             rng_state.init(rng_pool);
  2786.             for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) {
  2787.                 rng_pool[rng_pptr] = 0;
  2788.             }
  2789.             rng_pptr = 0;
  2790.         }
  2791.         // TODO: allow reseeding after first request
  2792.         return rng_state.next();
  2793.     }
  2794.     var SecureRandom = /** @class */ (function () {
  2795.         function SecureRandom() {
  2796.         }
  2797.         SecureRandom.prototype.nextBytes = function (ba) {
  2798.             for (var i = 0; i < ba.length; ++i) {
  2799.                 ba[i] = rng_get_byte();
  2800.             }
  2801.         };
  2802.         return SecureRandom;
  2803.     }());

  2804. // Depends on jsbn.js and rng.js
  2805. // function linebrk(s,n) {
  2806. //   var ret = "";
  2807. //   var i = 0;
  2808. //   while(i + n < s.length) {
  2809. //     ret += s.substring(i,i+n) + "\n";
  2810. //     i += n;
  2811. //   }
  2812. //   return ret + s.substring(i,s.length);
  2813. // }
  2814. // function byte2Hex(b) {
  2815. //   if(b < 0x10)
  2816. //     return "0" + b.toString(16);
  2817. //   else
  2818. //     return b.toString(16);
  2819. // }
  2820.     function pkcs1pad1(s, n) {
  2821.         if (n < s.length + 22) {
  2822.             console.error("Message too long for RSA");
  2823.             return null;
  2824.         }
  2825.         var len = n - s.length - 6;
  2826.         var filler = "";
  2827.         for (var f = 0; f < len; f += 2) {
  2828.             filler += "ff";
  2829.         }
  2830.         var m = "0001" + filler + "00" + s;
  2831.         return parseBigInt(m, 16);
  2832.     }
  2833. // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
  2834.     function pkcs1pad2(s, n) {
  2835.         if (n < s.length + 11) { // TODO: fix for utf-8
  2836.             console.error("Message too long for RSA");
  2837.             return null;
  2838.         }
  2839.         var ba = [];
  2840.         var i = s.length - 1;
  2841.         while (i >= 0 && n > 0) {
  2842.             var c = s.charCodeAt(i--);
  2843.             if (c < 128) { // encode using utf-8
  2844.                 ba[--n] = c;
  2845.             }
  2846.             else if ((c > 127) && (c < 2048)) {
  2847.                 ba[--n] = (c & 63) | 128;
  2848.                 ba[--n] = (c >> 6) | 192;
  2849.             }
  2850.             else {
  2851.                 ba[--n] = (c & 63) | 128;
  2852.                 ba[--n] = ((c >> 6) & 63) | 128;
  2853.                 ba[--n] = (c >> 12) | 224;
  2854.             }
  2855.         }
  2856.         ba[--n] = 0;
  2857.         var rng = new SecureRandom();
  2858.         var x = [];
  2859.         while (n > 2) { // random non-zero pad
  2860.             x[0] = 0;
  2861.             while (x[0] == 0) {
  2862.                 rng.nextBytes(x);
  2863.             }
  2864.             ba[--n] = x[0];
  2865.         }
  2866.         ba[--n] = 2;
  2867.         ba[--n] = 0;
  2868.         return new BigInteger(ba);
  2869.     }
  2870. // "empty" RSA key constructor
  2871.     var RSAKey = /** @class */ (function () {
  2872.         function RSAKey() {
  2873.             this.n = null;
  2874.             this.e = 0;
  2875.             this.d = null;
  2876.             this.p = null;
  2877.             this.q = null;
  2878.             this.dmp1 = null;
  2879.             this.dmq1 = null;
  2880.             this.coeff = null;
  2881.         }
  2882.         //#region PROTECTED
  2883.         // protected
  2884.         // RSAKey.prototype.doPublic = RSADoPublic;
  2885.         // Perform raw public operation on "x": return x^e (mod n)
  2886.         RSAKey.prototype.doPublic = function (x) {
  2887.             return x.modPowInt(this.e, this.n);
  2888.         };
  2889.         // RSAKey.prototype.doPrivate = RSADoPrivate;
  2890.         // Perform raw private operation on "x": return x^d (mod n)
  2891.         RSAKey.prototype.doPrivate = function (x) {
  2892.             if (this.p == null || this.q == null) {
  2893.                 return x.modPow(this.d, this.n);
  2894.             }
  2895.             // TODO: re-calculate any missing CRT params
  2896.             var xp = x.mod(this.p).modPow(this.dmp1, this.p);
  2897.             var xq = x.mod(this.q).modPow(this.dmq1, this.q);
  2898.             while (xp.compareTo(xq) < 0) {
  2899.                 xp = xp.add(this.p);
  2900.             }
  2901.             return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq);
  2902.         };
  2903.         //#endregion PROTECTED
  2904.         //#region PUBLIC
  2905.         // RSAKey.prototype.setPublic = RSASetPublic;
  2906.         // Set the public key fields N and e from hex strings
  2907.         RSAKey.prototype.setPublic = function (N, E) {
  2908.             if (N != null && E != null && N.length > 0 && E.length > 0) {
  2909.                 this.n = parseBigInt(N, 16);
  2910.                 this.e = parseInt(E, 16);
  2911.             }
  2912.             else {
  2913.                 console.error("Invalid RSA public key");
  2914.             }
  2915.         };
  2916.         // RSAKey.prototype.encrypt = RSAEncrypt;
  2917.         // Return the PKCS#1 RSA encryption of "text" as an even-length hex string
  2918.         RSAKey.prototype.encrypt = function (text) {
  2919.             var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3);
  2920.             if (m == null) {
  2921.                 return null;
  2922.             }
  2923.             var c = this.doPublic(m);
  2924.             if (c == null) {
  2925.                 return null;
  2926.             }
  2927.             var h = c.toString(16);
  2928.             if ((h.length & 1) == 0) {
  2929.                 return h;
  2930.             }
  2931.             else {
  2932.                 return "0" + h;
  2933.             }
  2934.         };
  2935.         // RSAKey.prototype.setPrivate = RSASetPrivate;
  2936.         // Set the private key fields N, e, and d from hex strings
  2937.         RSAKey.prototype.setPrivate = function (N, E, D) {
  2938.             if (N != null && E != null && N.length > 0 && E.length > 0) {
  2939.                 this.n = parseBigInt(N, 16);
  2940.                 this.e = parseInt(E, 16);
  2941.                 this.d = parseBigInt(D, 16);
  2942.             }
  2943.             else {
  2944.                 console.error("Invalid RSA private key");
  2945.             }
  2946.         };
  2947.         // RSAKey.prototype.setPrivateEx = RSASetPrivateEx;
  2948.         // Set the private key fields N, e, d and CRT params from hex strings
  2949.         RSAKey.prototype.setPrivateEx = function (N, E, D, P, Q, DP, DQ, C) {
  2950.             if (N != null && E != null && N.length > 0 && E.length > 0) {
  2951.                 this.n = parseBigInt(N, 16);
  2952.                 this.e = parseInt(E, 16);
  2953.                 this.d = parseBigInt(D, 16);
  2954.                 this.p = parseBigInt(P, 16);
  2955.                 this.q = parseBigInt(Q, 16);
  2956.                 this.dmp1 = parseBigInt(DP, 16);
  2957.                 this.dmq1 = parseBigInt(DQ, 16);
  2958.                 this.coeff = parseBigInt(C, 16);
  2959.             }
  2960.             else {
  2961.                 console.error("Invalid RSA private key");
  2962.             }
  2963.         };
  2964.         // RSAKey.prototype.generate = RSAGenerate;
  2965.         // Generate a new random private key B bits long, using public expt E
  2966.         RSAKey.prototype.generate = function (B, E) {
  2967.             var rng = new SecureRandom();
  2968.             var qs = B >> 1;
  2969.             this.e = parseInt(E, 16);
  2970.             var ee = new BigInteger(E, 16);
  2971.             for (;;) {
  2972.                 for (;;) {
  2973.                     this.p = new BigInteger(B - qs, 1, rng);
  2974.                     if (this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) {
  2975.                         break;
  2976.                     }
  2977.                 }
  2978.                 for (;;) {
  2979.                     this.q = new BigInteger(qs, 1, rng);
  2980.                     if (this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) {
  2981.                         break;
  2982.                     }
  2983.                 }
  2984.                 if (this.p.compareTo(this.q) <= 0) {
  2985.                     var t = this.p;
  2986.                     this.p = this.q;
  2987.                     this.q = t;
  2988.                 }
  2989.                 var p1 = this.p.subtract(BigInteger.ONE);
  2990.                 var q1 = this.q.subtract(BigInteger.ONE);
  2991.                 var phi = p1.multiply(q1);
  2992.                 if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
  2993.                     this.n = this.p.multiply(this.q);
  2994.                     this.d = ee.modInverse(phi);
  2995.                     this.dmp1 = this.d.mod(p1);
  2996.                     this.dmq1 = this.d.mod(q1);
  2997.                     this.coeff = this.q.modInverse(this.p);
  2998.                     break;
  2999.                 }
  3000.             }
  3001.         };
  3002.         // RSAKey.prototype.decrypt = RSADecrypt;
  3003.         // Return the PKCS#1 RSA decryption of "ctext".
  3004.         // "ctext" is an even-length hex string and the output is a plain string.
  3005.         RSAKey.prototype.decrypt = function (ctext) {
  3006.             var c = parseBigInt(ctext, 16);
  3007.             var m = this.doPrivate(c);
  3008.             if (m == null) {
  3009.                 return null;
  3010.             }
  3011.             return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3);
  3012.         };
  3013.         // Generate a new random private key B bits long, using public expt E
  3014.         RSAKey.prototype.generateAsync = function (B, E, callback) {
  3015.             var rng = new SecureRandom();
  3016.             var qs = B >> 1;
  3017.             this.e = parseInt(E, 16);
  3018.             var ee = new BigInteger(E, 16);
  3019.             var rsa = this;
  3020.             // These functions have non-descript names because they were originally for(;;) loops.
  3021.             // I don't know about cryptography to give them better names than loop1-4.
  3022.             var loop1 = function () {
  3023.                 var loop4 = function () {
  3024.                     if (rsa.p.compareTo(rsa.q) <= 0) {
  3025.                         var t = rsa.p;
  3026.                         rsa.p = rsa.q;
  3027.                         rsa.q = t;
  3028.                     }
  3029.                     var p1 = rsa.p.subtract(BigInteger.ONE);
  3030.                     var q1 = rsa.q.subtract(BigInteger.ONE);
  3031.                     var phi = p1.multiply(q1);
  3032.                     if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
  3033.                         rsa.n = rsa.p.multiply(rsa.q);
  3034.                         rsa.d = ee.modInverse(phi);
  3035.                         rsa.dmp1 = rsa.d.mod(p1);
  3036.                         rsa.dmq1 = rsa.d.mod(q1);
  3037.                         rsa.coeff = rsa.q.modInverse(rsa.p);
  3038.                         setTimeout(function () { callback(); }, 0); // escape
  3039.                     }
  3040.                     else {
  3041.                         setTimeout(loop1, 0);
  3042.                     }
  3043.                 };
  3044.                 var loop3 = function () {
  3045.                     rsa.q = nbi();
  3046.                     rsa.q.fromNumberAsync(qs, 1, rng, function () {
  3047.                         rsa.q.subtract(BigInteger.ONE).gcda(ee, function (r) {
  3048.                             if (r.compareTo(BigInteger.ONE) == 0 && rsa.q.isProbablePrime(10)) {
  3049.                                 setTimeout(loop4, 0);
  3050.                             }
  3051.                             else {
  3052.                                 setTimeout(loop3, 0);
  3053.                             }
  3054.                         });
  3055.                     });
  3056.                 };
  3057.                 var loop2 = function () {
  3058.                     rsa.p = nbi();
  3059.                     rsa.p.fromNumberAsync(B - qs, 1, rng, function () {
  3060.                         rsa.p.subtract(BigInteger.ONE).gcda(ee, function (r) {
  3061.                             if (r.compareTo(BigInteger.ONE) == 0 && rsa.p.isProbablePrime(10)) {
  3062.                                 setTimeout(loop3, 0);
  3063.                             }
  3064.                             else {
  3065.                                 setTimeout(loop2, 0);
  3066.                             }
  3067.                         });
  3068.                     });
  3069.                 };
  3070.                 setTimeout(loop2, 0);
  3071.             };
  3072.             setTimeout(loop1, 0);
  3073.         };
  3074.         RSAKey.prototype.sign = function (text, digestMethod, digestName) {
  3075.             var header = getDigestHeader(digestName);
  3076.             var digest = header + digestMethod(text).toString();
  3077.             var m = pkcs1pad1(digest, this.n.bitLength() / 4);
  3078.             if (m == null) {
  3079.                 return null;
  3080.             }
  3081.             var c = this.doPrivate(m);
  3082.             if (c == null) {
  3083.                 return null;
  3084.             }
  3085.             var h = c.toString(16);
  3086.             if ((h.length & 1) == 0) {
  3087.                 return h;
  3088.             }
  3089.             else {
  3090.                 return "0" + h;
  3091.             }
  3092.         };
  3093.         RSAKey.prototype.verify = function (text, signature, digestMethod) {
  3094.             var c = parseBigInt(signature, 16);
  3095.             var m = this.doPublic(c);
  3096.             if (m == null) {
  3097.                 return null;
  3098.             }
  3099.             var unpadded = m.toString(16).replace(/^1f+00/, "");
  3100.             var digest = removeDigestHeader(unpadded);
  3101.             return digest == digestMethod(text).toString();
  3102.         };
  3103.         return RSAKey;
  3104.     }());
  3105. // Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext
  3106.     function pkcs1unpad2(d, n) {
  3107.         var b = d.toByteArray();
  3108.         var i = 0;
  3109.         while (i < b.length && b[i] == 0) {
  3110.             ++i;
  3111.         }
  3112.         if (b.length - i != n - 1 || b[i] != 2) {
  3113.             return null;
  3114.         }
  3115.         ++i;
  3116.         while (b[i] != 0) {
  3117.             if (++i >= b.length) {
  3118.                 return null;
  3119.             }
  3120.         }
  3121.         var ret = "";
  3122.         while (++i < b.length) {
  3123.             var c = b[i] & 255;
  3124.             if (c < 128) { // utf-8 decode
  3125.                 ret += String.fromCharCode(c);
  3126.             }
  3127.             else if ((c > 191) && (c < 224)) {
  3128.                 ret += String.fromCharCode(((c & 31) << 6) | (b[i + 1] & 63));
  3129.                 ++i;
  3130.             }
  3131.             else {
  3132.                 ret += String.fromCharCode(((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63));
  3133.                 i += 2;
  3134.             }
  3135.         }
  3136.         return ret;
  3137.     }
  3138. // https://tools.ietf.org/html/rfc3447#page-43
  3139.     var DIGEST_HEADERS = {
  3140.         md2: "3020300c06082a864886f70d020205000410",
  3141.         md5: "3020300c06082a864886f70d020505000410",
  3142.         sha1: "3021300906052b0e03021a05000414",
  3143.         sha224: "302d300d06096086480165030402040500041c",
  3144.         sha256: "3031300d060960864801650304020105000420",
  3145.         sha384: "3041300d060960864801650304020205000430",
  3146.         sha512: "3051300d060960864801650304020305000440",
  3147.         ripemd160: "3021300906052b2403020105000414",
  3148.     };
  3149.     function getDigestHeader(name) {
  3150.         return DIGEST_HEADERS[name] || "";
  3151.     }
  3152.     function removeDigestHeader(str) {
  3153.         for (var name_1 in DIGEST_HEADERS) {
  3154.             if (DIGEST_HEADERS.hasOwnProperty(name_1)) {
  3155.                 var header = DIGEST_HEADERS[name_1];
  3156.                 var len = header.length;
  3157.                 if (str.substr(0, len) == header) {
  3158.                     return str.substr(len);
  3159.                 }
  3160.             }
  3161.         }
  3162.         return str;
  3163.     }
  3164. // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
  3165. // function RSAEncryptB64(text) {
  3166. //  var h = this.encrypt(text);
  3167. //  if(h) return hex2b64(h); else return null;
  3168. // }
  3169. // public
  3170. // RSAKey.prototype.encrypt_b64 = RSAEncryptB64;

  3171.     /*!
  3172. Copyright (c) 2011, Yahoo! Inc. All rights reserved.
  3173. Code licensed under the BSD License:
  3174. http://developer.yahoo.com/yui/license.html
  3175. version: 2.9.0
  3176. */
  3177.     var YAHOO = {};
  3178.     YAHOO.lang = {
  3179.         /**
  3180.          * Utility to set up the prototype, constructor and superclass properties to
  3181.          * support an inheritance strategy that can chain constructors and methods.
  3182.          * Static members will not be inherited.
  3183.          *
  3184.          * @method extend
  3185.          * @static
  3186.          * @param {Function} subc   the object to modify
  3187.          * @param {Function} superc the object to inherit
  3188.          * @param {Object} overrides  additional properties/methods to add to the
  3189.          *                              subclass prototype.  These will override the
  3190.          *                              matching items obtained from the superclass
  3191.          *                              if present.
  3192.          */
  3193.         extend: function(subc, superc, overrides) {
  3194.             if (! superc || ! subc) {
  3195.                 throw new Error("YAHOO.lang.extend failed, please check that " +
  3196.                     "all dependencies are included.");
  3197.             }

  3198.             var F = function() {};
  3199.             F.prototype = superc.prototype;
  3200.             subc.prototype = new F();
  3201.             subc.prototype.constructor = subc;
  3202.             subc.superclass = superc.prototype;

  3203.             if (superc.prototype.constructor == Object.prototype.constructor) {
  3204.                 superc.prototype.constructor = superc;
  3205.             }

  3206.             if (overrides) {
  3207.                 var i;
  3208.                 for (i in overrides) {
  3209.                     subc.prototype[i] = overrides[i];
  3210.                 }

  3211.                 /*
  3212.              * IE will not enumerate native functions in a derived object even if the
  3213.              * function was overridden.  This is a workaround for specific functions
  3214.              * we care about on the Object prototype.
  3215.              * @property _IEEnumFix
  3216.              * @param {Function} r  the object to receive the augmentation
  3217.              * @param {Function} s  the object that supplies the properties to augment
  3218.              * @static
  3219.              * @private
  3220.              */
  3221.                 var _IEEnumFix = function() {},
  3222.                     ADD = ["toString", "valueOf"];
  3223.                 try {
  3224.                     if (/MSIE/.test(navigator.userAgent)) {
  3225.                         _IEEnumFix = function(r, s) {
  3226.                             for (i = 0; i < ADD.length; i = i + 1) {
  3227.                                 var fname = ADD[i], f = s[fname];
  3228.                                 if (typeof f === 'function' && f != Object.prototype[fname]) {
  3229.                                     r[fname] = f;
  3230.                                 }
  3231.                             }
  3232.                         };
  3233.                     }
  3234.                 } catch (ex) {}            _IEEnumFix(subc.prototype, overrides);
  3235.             }
  3236.         }
  3237.     };

  3238.     /* asn1-1.0.13.js (c) 2013-2017 Kenji Urushima | kjur.github.com/jsrsasign/license
  3239. */

  3240.     /**
  3241.      * @fileOverview
  3242.      * @name asn1-1.0.js
  3243.      * @author Kenji Urushima kenji.urushima@gmail.com
  3244.      * @version asn1 1.0.13 (2017-Jun-02)
  3245.      * @since jsrsasign 2.1
  3246.      * @license <a href="https://kjur.github.io/jsrsasign/license/">MIT License</a>
  3247.      */

  3248.     /**
  3249.      * kjur's class library name space
  3250.      * <p>
  3251.      * This name space provides following name spaces:
  3252.      * <ul>
  3253.      * <li>{@link KJUR.asn1} - ASN.1 primitive hexadecimal encoder</li>
  3254.      * <li>{@link KJUR.asn1.x509} - ASN.1 structure for X.509 certificate and CRL</li>
  3255.      * <li>{@link KJUR.crypto} - Java Cryptographic Extension(JCE) style MessageDigest/Signature
  3256.      * class and utilities</li>
  3257.      * </ul>
  3258.      * </p>
  3259.      * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2.
  3260.      * @name KJUR
  3261.      * @namespace kjur's class library name space
  3262.      */
  3263.     var KJUR = {};

  3264.     /**
  3265.      * kjur's ASN.1 class library name space
  3266.      * <p>
  3267.      * This is ITU-T X.690 ASN.1 DER encoder class library and
  3268.      * class structure and methods is very similar to
  3269.      * org.bouncycastle.asn1 package of
  3270.      * well known BouncyCaslte Cryptography Library.
  3271.      * <h4>PROVIDING ASN.1 PRIMITIVES</h4>
  3272.      * Here are ASN.1 DER primitive classes.
  3273.      * <ul>
  3274.      * <li>0x01 {@link KJUR.asn1.DERBoolean}</li>
  3275.      * <li>0x02 {@link KJUR.asn1.DERInteger}</li>
  3276.      * <li>0x03 {@link KJUR.asn1.DERBitString}</li>
  3277.      * <li>0x04 {@link KJUR.asn1.DEROctetString}</li>
  3278.      * <li>0x05 {@link KJUR.asn1.DERNull}</li>
  3279.      * <li>0x06 {@link KJUR.asn1.DERObjectIdentifier}</li>
  3280.      * <li>0x0a {@link KJUR.asn1.DEREnumerated}</li>
  3281.      * <li>0x0c {@link KJUR.asn1.DERUTF8String}</li>
  3282.      * <li>0x12 {@link KJUR.asn1.DERNumericString}</li>
  3283.      * <li>0x13 {@link KJUR.asn1.DERPrintableString}</li>
  3284.      * <li>0x14 {@link KJUR.asn1.DERTeletexString}</li>
  3285.      * <li>0x16 {@link KJUR.asn1.DERIA5String}</li>
  3286.      * <li>0x17 {@link KJUR.asn1.DERUTCTime}</li>
  3287.      * <li>0x18 {@link KJUR.asn1.DERGeneralizedTime}</li>
  3288.      * <li>0x30 {@link KJUR.asn1.DERSequence}</li>
  3289.      * <li>0x31 {@link KJUR.asn1.DERSet}</li>
  3290.      * </ul>
  3291.      * <h4>OTHER ASN.1 CLASSES</h4>
  3292.      * <ul>
  3293.      * <li>{@link KJUR.asn1.ASN1Object}</li>
  3294.      * <li>{@link KJUR.asn1.DERAbstractString}</li>
  3295.      * <li>{@link KJUR.asn1.DERAbstractTime}</li>
  3296.      * <li>{@link KJUR.asn1.DERAbstractStructured}</li>
  3297.      * <li>{@link KJUR.asn1.DERTaggedObject}</li>
  3298.      * </ul>
  3299.      * <h4>SUB NAME SPACES</h4>
  3300.      * <ul>
  3301.      * <li>{@link KJUR.asn1.cades} - CAdES long term signature format</li>
  3302.      * <li>{@link KJUR.asn1.cms} - Cryptographic Message Syntax</li>
  3303.      * <li>{@link KJUR.asn1.csr} - Certificate Signing Request (CSR/PKCS#10)</li>
  3304.      * <li>{@link KJUR.asn1.tsp} - RFC 3161 Timestamping Protocol Format</li>
  3305.      * <li>{@link KJUR.asn1.x509} - RFC 5280 X.509 certificate and CRL</li>
  3306.      * </ul>
  3307.      * </p>
  3308.      * NOTE: Please ignore method summary and document of this namespace.
  3309.      * This caused by a bug of jsdoc2.
  3310.      * @name KJUR.asn1
  3311.      * @namespace
  3312.      */
  3313.     if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) KJUR.asn1 = {};

  3314.     /**
  3315.      * ASN1 utilities class
  3316.      * @name KJUR.asn1.ASN1Util
  3317.      * @class ASN1 utilities class
  3318.      * @since asn1 1.0.2
  3319.      */
  3320.     KJUR.asn1.ASN1Util = new function() {
  3321.         this.integerToByteHex = function(i) {
  3322.             var h = i.toString(16);
  3323.             if ((h.length % 2) == 1) h = '0' + h;
  3324.             return h;
  3325.         };
  3326.         this.bigIntToMinTwosComplementsHex = function(bigIntegerValue) {
  3327.             var h = bigIntegerValue.toString(16);
  3328.             if (h.substr(0, 1) != '-') {
  3329.                 if (h.length % 2 == 1) {
  3330.                     h = '0' + h;
  3331.                 } else {
  3332.                     if (! h.match(/^[0-7]/)) {
  3333.                         h = '00' + h;
  3334.                     }
  3335.                 }
  3336.             } else {
  3337.                 var hPos = h.substr(1);
  3338.                 var xorLen = hPos.length;
  3339.                 if (xorLen % 2 == 1) {
  3340.                     xorLen += 1;
  3341.                 } else {
  3342.                     if (! h.match(/^[0-7]/)) {
  3343.                         xorLen += 2;
  3344.                     }
  3345.                 }
  3346.                 var hMask = '';
  3347.                 for (var i = 0; i < xorLen; i++) {
  3348.                     hMask += 'f';
  3349.                 }
  3350.                 var biMask = new BigInteger(hMask, 16);
  3351.                 var biNeg = biMask.xor(bigIntegerValue).add(BigInteger.ONE);
  3352.                 h = biNeg.toString(16).replace(/^-/, '');
  3353.             }
  3354.             return h;
  3355.         };
  3356.         /**
  3357.          * get PEM string from hexadecimal data and header string
  3358.          * @name getPEMStringFromHex
  3359.          * @memberOf KJUR.asn1.ASN1Util
  3360.          * @function
  3361.          * @param {String} dataHex hexadecimal string of PEM body
  3362.          * @param {String} pemHeader PEM header string (ex. 'RSA PRIVATE KEY')
  3363.          * @return {String} PEM formatted string of input data
  3364.          * @description
  3365.          * This method converts a hexadecimal string to a PEM string with
  3366.          * a specified header. Its line break will be CRLF("\r\n").
  3367.          * @example
  3368.          * var pem  = KJUR.asn1.ASN1Util.getPEMStringFromHex('616161', 'RSA PRIVATE KEY');
  3369.          * // value of pem will be:
  3370.          * -----BEGIN PRIVATE KEY-----
  3371.          * YWFh
  3372.          * -----END PRIVATE KEY-----
  3373.          */
  3374.         this.getPEMStringFromHex = function(dataHex, pemHeader) {
  3375.             return hextopem(dataHex, pemHeader);
  3376.         };

  3377.         /**
  3378.          * generate ASN1Object specifed by JSON parameters
  3379.          * @name newObject
  3380.          * @memberOf KJUR.asn1.ASN1Util
  3381.          * @function
  3382.          * @param {Array} param JSON parameter to generate ASN1Object
  3383.          * @return {KJUR.asn1.ASN1Object} generated object
  3384.          * @since asn1 1.0.3
  3385.          * @description
  3386.          * generate any ASN1Object specified by JSON param
  3387.          * including ASN.1 primitive or structured.
  3388.          * Generally 'param' can be described as follows:
  3389.          * <blockquote>
  3390.          * {TYPE-OF-ASNOBJ: ASN1OBJ-PARAMETER}
  3391.          * </blockquote>
  3392.          * 'TYPE-OF-ASN1OBJ' can be one of following symbols:
  3393.          * <ul>
  3394.          * <li>'bool' - DERBoolean</li>
  3395.          * <li>'int' - DERInteger</li>
  3396.          * <li>'bitstr' - DERBitString</li>
  3397.          * <li>'octstr' - DEROctetString</li>
  3398.          * <li>'null' - DERNull</li>
  3399.          * <li>'oid' - DERObjectIdentifier</li>
  3400.          * <li>'enum' - DEREnumerated</li>
  3401.          * <li>'utf8str' - DERUTF8String</li>
  3402.          * <li>'numstr' - DERNumericString</li>
  3403.          * <li>'prnstr' - DERPrintableString</li>
  3404.          * <li>'telstr' - DERTeletexString</li>
  3405.          * <li>'ia5str' - DERIA5String</li>
  3406.          * <li>'utctime' - DERUTCTime</li>
  3407.          * <li>'gentime' - DERGeneralizedTime</li>
  3408.          * <li>'seq' - DERSequence</li>
  3409.          * <li>'set' - DERSet</li>
  3410.          * <li>'tag' - DERTaggedObject</li>
  3411.          * </ul>
  3412.          * @example
  3413.          * newObject({'prnstr': 'aaa'});
  3414.          * newObject({'seq': [{'int': 3}, {'prnstr': 'aaa'}]})
  3415.          * // ASN.1 Tagged Object
  3416.          * newObject({'tag': {'tag': 'a1',
  3417.          *                    'explicit': true,
  3418.          *                    'obj': {'seq': [{'int': 3}, {'prnstr': 'aaa'}]}}});
  3419.          * // more simple representation of ASN.1 Tagged Object
  3420.          * newObject({'tag': ['a1',
  3421.          *                    true,
  3422.          *                    {'seq': [
  3423.          *                      {'int': 3},
  3424.          *                      {'prnstr': 'aaa'}]}
  3425.          *                   ]});
  3426.          */
  3427.         this.newObject = function(param) {
  3428.             var _KJUR = KJUR,
  3429.                 _KJUR_asn1 = _KJUR.asn1,
  3430.                 _DERBoolean = _KJUR_asn1.DERBoolean,
  3431.                 _DERInteger = _KJUR_asn1.DERInteger,
  3432.                 _DERBitString = _KJUR_asn1.DERBitString,
  3433.                 _DEROctetString = _KJUR_asn1.DEROctetString,
  3434.                 _DERNull = _KJUR_asn1.DERNull,
  3435.                 _DERObjectIdentifier = _KJUR_asn1.DERObjectIdentifier,
  3436.                 _DEREnumerated = _KJUR_asn1.DEREnumerated,
  3437.                 _DERUTF8String = _KJUR_asn1.DERUTF8String,
  3438.                 _DERNumericString = _KJUR_asn1.DERNumericString,
  3439.                 _DERPrintableString = _KJUR_asn1.DERPrintableString,
  3440.                 _DERTeletexString = _KJUR_asn1.DERTeletexString,
  3441.                 _DERIA5String = _KJUR_asn1.DERIA5String,
  3442.                 _DERUTCTime = _KJUR_asn1.DERUTCTime,
  3443.                 _DERGeneralizedTime = _KJUR_asn1.DERGeneralizedTime,
  3444.                 _DERSequence = _KJUR_asn1.DERSequence,
  3445.                 _DERSet = _KJUR_asn1.DERSet,
  3446.                 _DERTaggedObject = _KJUR_asn1.DERTaggedObject,
  3447.                 _newObject = _KJUR_asn1.ASN1Util.newObject;

  3448.             var keys = Object.keys(param);
  3449.             if (keys.length != 1)
  3450.                 throw "key of param shall be only one.";
  3451.             var key = keys[0];

  3452.             if (":bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:".indexOf(":" + key + ":") == -1)
  3453.                 throw "undefined key: " + key;

  3454.             if (key == "bool")    return new _DERBoolean(param[key]);
  3455.             if (key == "int")     return new _DERInteger(param[key]);
  3456.             if (key == "bitstr")  return new _DERBitString(param[key]);
  3457.             if (key == "octstr")  return new _DEROctetString(param[key]);
  3458.             if (key == "null")    return new _DERNull(param[key]);
  3459.             if (key == "oid")     return new _DERObjectIdentifier(param[key]);
  3460.             if (key == "enum")    return new _DEREnumerated(param[key]);
  3461.             if (key == "utf8str") return new _DERUTF8String(param[key]);
  3462.             if (key == "numstr")  return new _DERNumericString(param[key]);
  3463.             if (key == "prnstr")  return new _DERPrintableString(param[key]);
  3464.             if (key == "telstr")  return new _DERTeletexString(param[key]);
  3465.             if (key == "ia5str")  return new _DERIA5String(param[key]);
  3466.             if (key == "utctime") return new _DERUTCTime(param[key]);
  3467.             if (key == "gentime") return new _DERGeneralizedTime(param[key]);

  3468.             if (key == "seq") {
  3469.                 var paramList = param[key];
  3470.                 var a = [];
  3471.                 for (var i = 0; i < paramList.length; i++) {
  3472.                     var asn1Obj = _newObject(paramList[i]);
  3473.                     a.push(asn1Obj);
  3474.                 }
  3475.                 return new _DERSequence({'array': a});
  3476.             }

  3477.             if (key == "set") {
  3478.                 var paramList = param[key];
  3479.                 var a = [];
  3480.                 for (var i = 0; i < paramList.length; i++) {
  3481.                     var asn1Obj = _newObject(paramList[i]);
  3482.                     a.push(asn1Obj);
  3483.                 }
  3484.                 return new _DERSet({'array': a});
  3485.             }

  3486.             if (key == "tag") {
  3487.                 var tagParam = param[key];
  3488.                 if (Object.prototype.toString.call(tagParam) === '[object Array]' &&
  3489.                     tagParam.length == 3) {
  3490.                     var obj = _newObject(tagParam[2]);
  3491.                     return new _DERTaggedObject({tag: tagParam[0],
  3492.                         explicit: tagParam[1],
  3493.                         obj: obj});
  3494.                 } else {
  3495.                     var newParam = {};
  3496.                     if (tagParam.explicit !== undefined)
  3497.                         newParam.explicit = tagParam.explicit;
  3498.                     if (tagParam.tag !== undefined)
  3499.                         newParam.tag = tagParam.tag;
  3500.                     if (tagParam.obj === undefined)
  3501.                         throw "obj shall be specified for 'tag'.";
  3502.                     newParam.obj = _newObject(tagParam.obj);
  3503.                     return new _DERTaggedObject(newParam);
  3504.                 }
  3505.             }
  3506.         };

  3507.         /**
  3508.          * get encoded hexadecimal string of ASN1Object specifed by JSON parameters
  3509.          * @name jsonToASN1HEX
  3510.          * @memberOf KJUR.asn1.ASN1Util
  3511.          * @function
  3512.          * @param {Array} param JSON parameter to generate ASN1Object
  3513.          * @return hexadecimal string of ASN1Object
  3514.          * @since asn1 1.0.4
  3515.          * @description
  3516.          * As for ASN.1 object representation of JSON object,
  3517.          * please see {@link newObject}.
  3518.          * @example
  3519.          * jsonToASN1HEX({'prnstr': 'aaa'});
  3520.          */
  3521.         this.jsonToASN1HEX = function(param) {
  3522.             var asn1Obj = this.newObject(param);
  3523.             return asn1Obj.getEncodedHex();
  3524.         };
  3525.     };

  3526.     /**
  3527.      * get dot noted oid number string from hexadecimal value of OID
  3528.      * @name oidHexToInt
  3529.      * @memberOf KJUR.asn1.ASN1Util
  3530.      * @function
  3531.      * @param {String} hex hexadecimal value of object identifier
  3532.      * @return {String} dot noted string of object identifier
  3533.      * @since jsrsasign 4.8.3 asn1 1.0.7
  3534.      * @description
  3535.      * This static method converts from hexadecimal string representation of
  3536.      * ASN.1 value of object identifier to oid number string.
  3537.      * @example
  3538.      * KJUR.asn1.ASN1Util.oidHexToInt('550406') → "2.5.4.6"
  3539.      */
  3540.     KJUR.asn1.ASN1Util.oidHexToInt = function(hex) {
  3541.         var s = "";
  3542.         var i01 = parseInt(hex.substr(0, 2), 16);
  3543.         var i0 = Math.floor(i01 / 40);
  3544.         var i1 = i01 % 40;
  3545.         var s = i0 + "." + i1;

  3546.         var binbuf = "";
  3547.         for (var i = 2; i < hex.length; i += 2) {
  3548.             var value = parseInt(hex.substr(i, 2), 16);
  3549.             var bin = ("00000000" + value.toString(2)).slice(- 8);
  3550.             binbuf = binbuf + bin.substr(1, 7);
  3551.             if (bin.substr(0, 1) == "0") {
  3552.                 var bi = new BigInteger(binbuf, 2);
  3553.                 s = s + "." + bi.toString(10);
  3554.                 binbuf = "";
  3555.             }
  3556.         }
  3557.         return s;
  3558.     };

  3559.     /**
  3560.      * get hexadecimal value of object identifier from dot noted oid value
  3561.      * @name oidIntToHex
  3562.      * @memberOf KJUR.asn1.ASN1Util
  3563.      * @function
  3564.      * @param {String} oidString dot noted string of object identifier
  3565.      * @return {String} hexadecimal value of object identifier
  3566.      * @since jsrsasign 4.8.3 asn1 1.0.7
  3567.      * @description
  3568.      * This static method converts from object identifier value string.
  3569.      * to hexadecimal string representation of it.
  3570.      * @example
  3571.      * KJUR.asn1.ASN1Util.oidIntToHex("2.5.4.6") → "550406"
  3572.      */
  3573.     KJUR.asn1.ASN1Util.oidIntToHex = function(oidString) {
  3574.         var itox = function(i) {
  3575.             var h = i.toString(16);
  3576.             if (h.length == 1) h = '0' + h;
  3577.             return h;
  3578.         };

  3579.         var roidtox = function(roid) {
  3580.             var h = '';
  3581.             var bi = new BigInteger(roid, 10);
  3582.             var b = bi.toString(2);
  3583.             var padLen = 7 - b.length % 7;
  3584.             if (padLen == 7) padLen = 0;
  3585.             var bPad = '';
  3586.             for (var i = 0; i < padLen; i++) bPad += '0';
  3587.             b = bPad + b;
  3588.             for (var i = 0; i < b.length - 1; i += 7) {
  3589.                 var b8 = b.substr(i, 7);
  3590.                 if (i != b.length - 7) b8 = '1' + b8;
  3591.                 h += itox(parseInt(b8, 2));
  3592.             }
  3593.             return h;
  3594.         };

  3595.         if (! oidString.match(/^[0-9.]+$/)) {
  3596.             throw "malformed oid string: " + oidString;
  3597.         }
  3598.         var h = '';
  3599.         var a = oidString.split('.');
  3600.         var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
  3601.         h += itox(i0);
  3602.         a.splice(0, 2);
  3603.         for (var i = 0; i < a.length; i++) {
  3604.             h += roidtox(a[i]);
  3605.         }
  3606.         return h;
  3607.     };


  3608. // ********************************************************************
  3609. //  Abstract ASN.1 Classes
  3610. // ********************************************************************

  3611. // ********************************************************************

  3612.     /**
  3613.      * base class for ASN.1 DER encoder object
  3614.      * @name KJUR.asn1.ASN1Object
  3615.      * @class base class for ASN.1 DER encoder object
  3616.      * @property {Boolean} isModified flag whether internal data was changed
  3617.      * @property {String} hTLV hexadecimal string of ASN.1 TLV
  3618.      * @property {String} hT hexadecimal string of ASN.1 TLV tag(T)
  3619.      * @property {String} hL hexadecimal string of ASN.1 TLV length(L)
  3620.      * @property {String} hV hexadecimal string of ASN.1 TLV value(V)
  3621.      * @description
  3622.      */
  3623.     KJUR.asn1.ASN1Object = function() {
  3624.         var hV = '';

  3625.         /**
  3626.          * get hexadecimal ASN.1 TLV length(L) bytes from TLV value(V)
  3627.          * @name getLengthHexFromValue
  3628.          * @memberOf KJUR.asn1.ASN1Object#
  3629.          * @function
  3630.          * @return {String} hexadecimal string of ASN.1 TLV length(L)
  3631.          */
  3632.         this.getLengthHexFromValue = function() {
  3633.             if (typeof this.hV == "undefined" || this.hV == null) {
  3634.                 throw "this.hV is null or undefined.";
  3635.             }
  3636.             if (this.hV.length % 2 == 1) {
  3637.                 throw "value hex must be even length: n=" + hV.length + ",v=" + this.hV;
  3638.             }
  3639.             var n = this.hV.length / 2;
  3640.             var hN = n.toString(16);
  3641.             if (hN.length % 2 == 1) {
  3642.                 hN = "0" + hN;
  3643.             }
  3644.             if (n < 128) {
  3645.                 return hN;
  3646.             } else {
  3647.                 var hNlen = hN.length / 2;
  3648.                 if (hNlen > 15) {
  3649.                     throw "ASN.1 length too long to represent by 8x: n = " + n.toString(16);
  3650.                 }
  3651.                 var head = 128 + hNlen;
  3652.                 return head.toString(16) + hN;
  3653.             }
  3654.         };

  3655.         /**
  3656.          * get hexadecimal string of ASN.1 TLV bytes
  3657.          * @name getEncodedHex
  3658.          * @memberOf KJUR.asn1.ASN1Object#
  3659.          * @function
  3660.          * @return {String} hexadecimal string of ASN.1 TLV
  3661.          */
  3662.         this.getEncodedHex = function() {
  3663.             if (this.hTLV == null || this.isModified) {
  3664.                 this.hV = this.getFreshValueHex();
  3665.                 this.hL = this.getLengthHexFromValue();
  3666.                 this.hTLV = this.hT + this.hL + this.hV;
  3667.                 this.isModified = false;
  3668.                 //alert("first time: " + this.hTLV);
  3669.             }
  3670.             return this.hTLV;
  3671.         };

  3672.         /**
  3673.          * get hexadecimal string of ASN.1 TLV value(V) bytes
  3674.          * @name getValueHex
  3675.          * @memberOf KJUR.asn1.ASN1Object#
  3676.          * @function
  3677.          * @return {String} hexadecimal string of ASN.1 TLV value(V) bytes
  3678.          */
  3679.         this.getValueHex = function() {
  3680.             this.getEncodedHex();
  3681.             return this.hV;
  3682.         };

  3683.         this.getFreshValueHex = function() {
  3684.             return '';
  3685.         };
  3686.     };

  3687. // == BEGIN DERAbstractString ================================================
  3688.     /**
  3689.      * base class for ASN.1 DER string classes
  3690.      * @name KJUR.asn1.DERAbstractString
  3691.      * @class base class for ASN.1 DER string classes
  3692.      * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  3693.      * @property {String} s internal string of value
  3694.      * @extends KJUR.asn1.ASN1Object
  3695.      * @description
  3696.      * <br/>
  3697.      * As for argument 'params' for constructor, you can specify one of
  3698.      * following properties:
  3699.      * <ul>
  3700.      * <li>str - specify initial ASN.1 value(V) by a string</li>
  3701.      * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  3702.      * </ul>
  3703.      * NOTE: 'params' can be omitted.
  3704.      */
  3705.     KJUR.asn1.DERAbstractString = function(params) {
  3706.         KJUR.asn1.DERAbstractString.superclass.constructor.call(this);

  3707.         /**
  3708.          * get string value of this string object
  3709.          * @name getString
  3710.          * @memberOf KJUR.asn1.DERAbstractString#
  3711.          * @function
  3712.          * @return {String} string value of this string object
  3713.          */
  3714.         this.getString = function() {
  3715.             return this.s;
  3716.         };

  3717.         /**
  3718.          * set value by a string
  3719.          * @name setString
  3720.          * @memberOf KJUR.asn1.DERAbstractString#
  3721.          * @function
  3722.          * @param {String} newS value by a string to set
  3723.          */
  3724.         this.setString = function(newS) {
  3725.             this.hTLV = null;
  3726.             this.isModified = true;
  3727.             this.s = newS;
  3728.             this.hV = stohex(this.s);
  3729.         };

  3730.         /**
  3731.          * set value by a hexadecimal string
  3732.          * @name setStringHex
  3733.          * @memberOf KJUR.asn1.DERAbstractString#
  3734.          * @function
  3735.          * @param {String} newHexString value by a hexadecimal string to set
  3736.          */
  3737.         this.setStringHex = function(newHexString) {
  3738.             this.hTLV = null;
  3739.             this.isModified = true;
  3740.             this.s = null;
  3741.             this.hV = newHexString;
  3742.         };

  3743.         this.getFreshValueHex = function() {
  3744.             return this.hV;
  3745.         };

  3746.         if (typeof params != "undefined") {
  3747.             if (typeof params == "string") {
  3748.                 this.setString(params);
  3749.             } else if (typeof params['str'] != "undefined") {
  3750.                 this.setString(params['str']);
  3751.             } else if (typeof params['hex'] != "undefined") {
  3752.                 this.setStringHex(params['hex']);
  3753.             }
  3754.         }
  3755.     };
  3756.     YAHOO.lang.extend(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object);
  3757. // == END   DERAbstractString ================================================

  3758. // == BEGIN DERAbstractTime ==================================================
  3759.     /**
  3760.      * base class for ASN.1 DER Generalized/UTCTime class
  3761.      * @name KJUR.asn1.DERAbstractTime
  3762.      * @class base class for ASN.1 DER Generalized/UTCTime class
  3763.      * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
  3764.      * @extends KJUR.asn1.ASN1Object
  3765.      * @description
  3766.      * @see KJUR.asn1.ASN1Object - superclass
  3767.      */
  3768.     KJUR.asn1.DERAbstractTime = function(params) {
  3769.         KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);

  3770.         // --- PRIVATE METHODS --------------------
  3771.         this.localDateToUTC = function(d) {
  3772.             utc = d.getTime() + (d.getTimezoneOffset() * 60000);
  3773.             var utcDate = new Date(utc);
  3774.             return utcDate;
  3775.         };

  3776.         /*
  3777.      * format date string by Data object
  3778.      * @name formatDate
  3779.      * @memberOf KJUR.asn1.AbstractTime;
  3780.      * @param {Date} dateObject
  3781.      * @param {string} type 'utc' or 'gen'
  3782.      * @param {boolean} withMillis flag for with millisections or not
  3783.      * @description
  3784.      * 'withMillis' flag is supported from asn1 1.0.6.
  3785.      */
  3786.         this.formatDate = function(dateObject, type, withMillis) {
  3787.             var pad = this.zeroPadding;
  3788.             var d = this.localDateToUTC(dateObject);
  3789.             var year = String(d.getFullYear());
  3790.             if (type == 'utc') year = year.substr(2, 2);
  3791.             var month = pad(String(d.getMonth() + 1), 2);
  3792.             var day = pad(String(d.getDate()), 2);
  3793.             var hour = pad(String(d.getHours()), 2);
  3794.             var min = pad(String(d.getMinutes()), 2);
  3795.             var sec = pad(String(d.getSeconds()), 2);
  3796.             var s = year + month + day + hour + min + sec;
  3797.             if (withMillis === true) {
  3798.                 var millis = d.getMilliseconds();
  3799.                 if (millis != 0) {
  3800.                     var sMillis = pad(String(millis), 3);
  3801.                     sMillis = sMillis.replace(/[0]+$/, "");
  3802.                     s = s + "." + sMillis;
  3803.                 }
  3804.             }
  3805.             return s + "Z";
  3806.         };

  3807.         this.zeroPadding = function(s, len) {
  3808.             if (s.length >= len) return s;
  3809.             return new Array(len - s.length + 1).join('0') + s;
  3810.         };

  3811.         // --- PUBLIC METHODS --------------------
  3812.         /**
  3813.          * get string value of this string object
  3814.          * @name getString
  3815.          * @memberOf KJUR.asn1.DERAbstractTime#
  3816.          * @function
  3817.          * @return {String} string value of this time object
  3818.          */
  3819.         this.getString = function() {
  3820.             return this.s;
  3821.         };

  3822.         /**
  3823.          * set value by a string
  3824.          * @name setString
  3825.          * @memberOf KJUR.asn1.DERAbstractTime#
  3826.          * @function
  3827.          * @param {String} newS value by a string to set such like "130430235959Z"
  3828.          */
  3829.         this.setString = function(newS) {
  3830.             this.hTLV = null;
  3831.             this.isModified = true;
  3832.             this.s = newS;
  3833.             this.hV = stohex(newS);
  3834.         };

  3835.         /**
  3836.          * set value by a Date object
  3837.          * @name setByDateValue
  3838.          * @memberOf KJUR.asn1.DERAbstractTime#
  3839.          * @function
  3840.          * @param {Integer} year year of date (ex. 2013)
  3841.          * @param {Integer} month month of date between 1 and 12 (ex. 12)
  3842.          * @param {Integer} day day of month
  3843.          * @param {Integer} hour hours of date
  3844.          * @param {Integer} min minutes of date
  3845.          * @param {Integer} sec seconds of date
  3846.          */
  3847.         this.setByDateValue = function(year, month, day, hour, min, sec) {
  3848.             var dateObject = new Date(Date.UTC(year, month - 1, day, hour, min, sec, 0));
  3849.             this.setByDate(dateObject);
  3850.         };

  3851.         this.getFreshValueHex = function() {
  3852.             return this.hV;
  3853.         };
  3854.     };
  3855.     YAHOO.lang.extend(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object);
  3856. // == END   DERAbstractTime ==================================================

  3857. // == BEGIN DERAbstractStructured ============================================
  3858.     /**
  3859.      * base class for ASN.1 DER structured class
  3860.      * @name KJUR.asn1.DERAbstractStructured
  3861.      * @class base class for ASN.1 DER structured class
  3862.      * @property {Array} asn1Array internal array of ASN1Object
  3863.      * @extends KJUR.asn1.ASN1Object
  3864.      * @description
  3865.      * @see KJUR.asn1.ASN1Object - superclass
  3866.      */
  3867.     KJUR.asn1.DERAbstractStructured = function(params) {
  3868.         KJUR.asn1.DERAbstractString.superclass.constructor.call(this);

  3869.         /**
  3870.          * set value by array of ASN1Object
  3871.          * @name setByASN1ObjectArray
  3872.          * @memberOf KJUR.asn1.DERAbstractStructured#
  3873.          * @function
  3874.          * @param {array} asn1ObjectArray array of ASN1Object to set
  3875.          */
  3876.         this.setByASN1ObjectArray = function(asn1ObjectArray) {
  3877.             this.hTLV = null;
  3878.             this.isModified = true;
  3879.             this.asn1Array = asn1ObjectArray;
  3880.         };

  3881.         /**
  3882.          * append an ASN1Object to internal array
  3883.          * @name appendASN1Object
  3884.          * @memberOf KJUR.asn1.DERAbstractStructured#
  3885.          * @function
  3886.          * @param {ASN1Object} asn1Object to add
  3887.          */
  3888.         this.appendASN1Object = function(asn1Object) {
  3889.             this.hTLV = null;
  3890.             this.isModified = true;
  3891.             this.asn1Array.push(asn1Object);
  3892.         };

  3893.         this.asn1Array = new Array();
  3894.         if (typeof params != "undefined") {
  3895.             if (typeof params['array'] != "undefined") {
  3896.                 this.asn1Array = params['array'];
  3897.             }
  3898.         }
  3899.     };
  3900.     YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object);


  3901. // ********************************************************************
  3902. //  ASN.1 Object Classes
  3903. // ********************************************************************

  3904. // ********************************************************************
  3905.     /**
  3906.      * class for ASN.1 DER Boolean
  3907.      * @name KJUR.asn1.DERBoolean
  3908.      * @class class for ASN.1 DER Boolean
  3909.      * @extends KJUR.asn1.ASN1Object
  3910.      * @description
  3911.      * @see KJUR.asn1.ASN1Object - superclass
  3912.      */
  3913.     KJUR.asn1.DERBoolean = function() {
  3914.         KJUR.asn1.DERBoolean.superclass.constructor.call(this);
  3915.         this.hT = "01";
  3916.         this.hTLV = "0101ff";
  3917.     };
  3918.     YAHOO.lang.extend(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object);

  3919. // ********************************************************************
  3920.     /**
  3921.      * class for ASN.1 DER Integer
  3922.      * @name KJUR.asn1.DERInteger
  3923.      * @class class for ASN.1 DER Integer
  3924.      * @extends KJUR.asn1.ASN1Object
  3925.      * @description
  3926.      * <br/>
  3927.      * As for argument 'params' for constructor, you can specify one of
  3928.      * following properties:
  3929.      * <ul>
  3930.      * <li>int - specify initial ASN.1 value(V) by integer value</li>
  3931.      * <li>bigint - specify initial ASN.1 value(V) by BigInteger object</li>
  3932.      * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  3933.      * </ul>
  3934.      * NOTE: 'params' can be omitted.
  3935.      */
  3936.     KJUR.asn1.DERInteger = function(params) {
  3937.         KJUR.asn1.DERInteger.superclass.constructor.call(this);
  3938.         this.hT = "02";

  3939.         /**
  3940.          * set value by Tom Wu's BigInteger object
  3941.          * @name setByBigInteger
  3942.          * @memberOf KJUR.asn1.DERInteger#
  3943.          * @function
  3944.          * @param {BigInteger} bigIntegerValue to set
  3945.          */
  3946.         this.setByBigInteger = function(bigIntegerValue) {
  3947.             this.hTLV = null;
  3948.             this.isModified = true;
  3949.             this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
  3950.         };

  3951.         /**
  3952.          * set value by integer value
  3953.          * @name setByInteger
  3954.          * @memberOf KJUR.asn1.DERInteger
  3955.          * @function
  3956.          * @param {Integer} integer value to set
  3957.          */
  3958.         this.setByInteger = function(intValue) {
  3959.             var bi = new BigInteger(String(intValue), 10);
  3960.             this.setByBigInteger(bi);
  3961.         };

  3962.         /**
  3963.          * set value by integer value
  3964.          * @name setValueHex
  3965.          * @memberOf KJUR.asn1.DERInteger#
  3966.          * @function
  3967.          * @param {String} hexadecimal string of integer value
  3968.          * @description
  3969.          * <br/>
  3970.          * NOTE: Value shall be represented by minimum octet length of
  3971.          * two's complement representation.
  3972.          * @example
  3973.          * new KJUR.asn1.DERInteger(123);
  3974.          * new KJUR.asn1.DERInteger({'int': 123});
  3975.          * new KJUR.asn1.DERInteger({'hex': '1fad'});
  3976.          */
  3977.         this.setValueHex = function(newHexString) {
  3978.             this.hV = newHexString;
  3979.         };

  3980.         this.getFreshValueHex = function() {
  3981.             return this.hV;
  3982.         };

  3983.         if (typeof params != "undefined") {
  3984.             if (typeof params['bigint'] != "undefined") {
  3985.                 this.setByBigInteger(params['bigint']);
  3986.             } else if (typeof params['int'] != "undefined") {
  3987.                 this.setByInteger(params['int']);
  3988.             } else if (typeof params == "number") {
  3989.                 this.setByInteger(params);
  3990.             } else if (typeof params['hex'] != "undefined") {
  3991.                 this.setValueHex(params['hex']);
  3992.             }
  3993.         }
  3994.     };
  3995.     YAHOO.lang.extend(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object);

  3996. // ********************************************************************
  3997.     /**
  3998.      * class for ASN.1 DER encoded BitString primitive
  3999.      * @name KJUR.asn1.DERBitString
  4000.      * @class class for ASN.1 DER encoded BitString primitive
  4001.      * @extends KJUR.asn1.ASN1Object
  4002.      * @description
  4003.      * <br/>
  4004.      * As for argument 'params' for constructor, you can specify one of
  4005.      * following properties:
  4006.      * <ul>
  4007.      * <li>bin - specify binary string (ex. '10111')</li>
  4008.      * <li>array - specify array of boolean (ex. [true,false,true,true])</li>
  4009.      * <li>hex - specify hexadecimal string of ASN.1 value(V) including unused bits</li>
  4010.      * <li>obj - specify {@link KJUR.asn1.ASN1Util.newObject}
  4011.      * argument for "BitString encapsulates" structure.</li>
  4012.      * </ul>
  4013.      * NOTE1: 'params' can be omitted.<br/>
  4014.      * NOTE2: 'obj' parameter have been supported since
  4015.      * asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).<br/>
  4016.      * @example
  4017.      * // default constructor
  4018.      * o = new KJUR.asn1.DERBitString();
  4019.      * // initialize with binary string
  4020.      * o = new KJUR.asn1.DERBitString({bin: "1011"});
  4021.      * // initialize with boolean array
  4022.      * o = new KJUR.asn1.DERBitString({array: [true,false,true,true]});
  4023.      * // initialize with hexadecimal string (04 is unused bits)
  4024.      * o = new KJUR.asn1.DEROctetString({hex: "04bac0"});
  4025.      * // initialize with ASN1Util.newObject argument for encapsulated
  4026.      * o = new KJUR.asn1.DERBitString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}});
  4027.      * // above generates a ASN.1 data like this:
  4028.      * // BIT STRING, encapsulates {
  4029.      * //   SEQUENCE {
  4030.      * //     INTEGER 3
  4031.      * //     PrintableString 'aaa'
  4032.      * //     }
  4033.      * //   }
  4034.      */
  4035.     KJUR.asn1.DERBitString = function(params) {
  4036.         if (params !== undefined && typeof params.obj !== "undefined") {
  4037.             var o = KJUR.asn1.ASN1Util.newObject(params.obj);
  4038.             params.hex = "00" + o.getEncodedHex();
  4039.         }
  4040.         KJUR.asn1.DERBitString.superclass.constructor.call(this);
  4041.         this.hT = "03";

  4042.         /**
  4043.          * set ASN.1 value(V) by a hexadecimal string including unused bits
  4044.          * @name setHexValueIncludingUnusedBits
  4045.          * @memberOf KJUR.asn1.DERBitString#
  4046.          * @function
  4047.          * @param {String} newHexStringIncludingUnusedBits
  4048.          */
  4049.         this.setHexValueIncludingUnusedBits = function(newHexStringIncludingUnusedBits) {
  4050.             this.hTLV = null;
  4051.             this.isModified = true;
  4052.             this.hV = newHexStringIncludingUnusedBits;
  4053.         };

  4054.         /**
  4055.          * set ASN.1 value(V) by unused bit and hexadecimal string of value
  4056.          * @name setUnusedBitsAndHexValue
  4057.          * @memberOf KJUR.asn1.DERBitString#
  4058.          * @function
  4059.          * @param {Integer} unusedBits
  4060.          * @param {String} hValue
  4061.          */
  4062.         this.setUnusedBitsAndHexValue = function(unusedBits, hValue) {
  4063.             if (unusedBits < 0 || 7 < unusedBits) {
  4064.                 throw "unused bits shall be from 0 to 7: u = " + unusedBits;
  4065.             }
  4066.             var hUnusedBits = "0" + unusedBits;
  4067.             this.hTLV = null;
  4068.             this.isModified = true;
  4069.             this.hV = hUnusedBits + hValue;
  4070.         };

  4071.         /**
  4072.          * set ASN.1 DER BitString by binary string<br/>
  4073.          * @name setByBinaryString
  4074.          * @memberOf KJUR.asn1.DERBitString#
  4075.          * @function
  4076.          * @param {String} binaryString binary value string (i.e. '10111')
  4077.          * @description
  4078.          * Its unused bits will be calculated automatically by length of
  4079.          * 'binaryValue'. <br/>
  4080.          * NOTE: Trailing zeros '0' will be ignored.
  4081.          * @example
  4082.          * o = new KJUR.asn1.DERBitString();
  4083.          * o.setByBooleanArray("01011");
  4084.          */
  4085.         this.setByBinaryString = function(binaryString) {
  4086.             binaryString = binaryString.replace(/0+$/, '');
  4087.             var unusedBits = 8 - binaryString.length % 8;
  4088.             if (unusedBits == 8) unusedBits = 0;
  4089.             for (var i = 0; i <= unusedBits; i++) {
  4090.                 binaryString += '0';
  4091.             }
  4092.             var h = '';
  4093.             for (var i = 0; i < binaryString.length - 1; i += 8) {
  4094.                 var b = binaryString.substr(i, 8);
  4095.                 var x = parseInt(b, 2).toString(16);
  4096.                 if (x.length == 1) x = '0' + x;
  4097.                 h += x;
  4098.             }
  4099.             this.hTLV = null;
  4100.             this.isModified = true;
  4101.             this.hV = '0' + unusedBits + h;
  4102.         };

  4103.         /**
  4104.          * set ASN.1 TLV value(V) by an array of boolean<br/>
  4105.          * @name setByBooleanArray
  4106.          * @memberOf KJUR.asn1.DERBitString#
  4107.          * @function
  4108.          * @param {array} booleanArray array of boolean (ex. [true, false, true])
  4109.          * @description
  4110.          * NOTE: Trailing falses will be ignored in the ASN.1 DER Object.
  4111.          * @example
  4112.          * o = new KJUR.asn1.DERBitString();
  4113.          * o.setByBooleanArray([false, true, false, true, true]);
  4114.          */
  4115.         this.setByBooleanArray = function(booleanArray) {
  4116.             var s = '';
  4117.             for (var i = 0; i < booleanArray.length; i++) {
  4118.                 if (booleanArray[i] == true) {
  4119.                     s += '1';
  4120.                 } else {
  4121.                     s += '0';
  4122.                 }
  4123.             }
  4124.             this.setByBinaryString(s);
  4125.         };

  4126.         /**
  4127.          * generate an array of falses with specified length<br/>
  4128.          * @name newFalseArray
  4129.          * @memberOf KJUR.asn1.DERBitString
  4130.          * @function
  4131.          * @param {Integer} nLength length of array to generate
  4132.          * @return {array} array of boolean falses
  4133.          * @description
  4134.          * This static method may be useful to initialize boolean array.
  4135.          * @example
  4136.          * o = new KJUR.asn1.DERBitString();
  4137.          * o.newFalseArray(3) → [false, false, false]
  4138.          */
  4139.         this.newFalseArray = function(nLength) {
  4140.             var a = new Array(nLength);
  4141.             for (var i = 0; i < nLength; i++) {
  4142.                 a[i] = false;
  4143.             }
  4144.             return a;
  4145.         };

  4146.         this.getFreshValueHex = function() {
  4147.             return this.hV;
  4148.         };

  4149.         if (typeof params != "undefined") {
  4150.             if (typeof params == "string" && params.toLowerCase().match(/^[0-9a-f]+$/)) {
  4151.                 this.setHexValueIncludingUnusedBits(params);
  4152.             } else if (typeof params['hex'] != "undefined") {
  4153.                 this.setHexValueIncludingUnusedBits(params['hex']);
  4154.             } else if (typeof params['bin'] != "undefined") {
  4155.                 this.setByBinaryString(params['bin']);
  4156.             } else if (typeof params['array'] != "undefined") {
  4157.                 this.setByBooleanArray(params['array']);
  4158.             }
  4159.         }
  4160.     };
  4161.     YAHOO.lang.extend(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object);

  4162. // ********************************************************************
  4163.     /**
  4164.      * class for ASN.1 DER OctetString<br/>
  4165.      * @name KJUR.asn1.DEROctetString
  4166.      * @class class for ASN.1 DER OctetString
  4167.      * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  4168.      * @extends KJUR.asn1.DERAbstractString
  4169.      * @description
  4170.      * This class provides ASN.1 OctetString simple type.<br/>
  4171.      * Supported "params" attributes are:
  4172.      * <ul>
  4173.      * <li>str - to set a string as a value</li>
  4174.      * <li>hex - to set a hexadecimal string as a value</li>
  4175.      * <li>obj - to set a encapsulated ASN.1 value by JSON object
  4176.      * which is defined in {@link KJUR.asn1.ASN1Util.newObject}</li>
  4177.      * </ul>
  4178.      * NOTE: A parameter 'obj' have been supported
  4179.      * for "OCTET STRING, encapsulates" structure.
  4180.      * since asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).
  4181.      * @see KJUR.asn1.DERAbstractString - superclass
  4182.      * @example
  4183.      * // default constructor
  4184.      * o = new KJUR.asn1.DEROctetString();
  4185.      * // initialize with string
  4186.      * o = new KJUR.asn1.DEROctetString({str: "aaa"});
  4187.      * // initialize with hexadecimal string
  4188.      * o = new KJUR.asn1.DEROctetString({hex: "616161"});
  4189.      * // initialize with ASN1Util.newObject argument
  4190.      * o = new KJUR.asn1.DEROctetString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}});
  4191.      * // above generates a ASN.1 data like this:
  4192.      * // OCTET STRING, encapsulates {
  4193.      * //   SEQUENCE {
  4194.      * //     INTEGER 3
  4195.      * //     PrintableString 'aaa'
  4196.      * //     }
  4197.      * //   }
  4198.      */
  4199.     KJUR.asn1.DEROctetString = function(params) {
  4200.         if (params !== undefined && typeof params.obj !== "undefined") {
  4201.             var o = KJUR.asn1.ASN1Util.newObject(params.obj);
  4202.             params.hex = o.getEncodedHex();
  4203.         }
  4204.         KJUR.asn1.DEROctetString.superclass.constructor.call(this, params);
  4205.         this.hT = "04";
  4206.     };
  4207.     YAHOO.lang.extend(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString);

  4208. // ********************************************************************
  4209.     /**
  4210.      * class for ASN.1 DER Null
  4211.      * @name KJUR.asn1.DERNull
  4212.      * @class class for ASN.1 DER Null
  4213.      * @extends KJUR.asn1.ASN1Object
  4214.      * @description
  4215.      * @see KJUR.asn1.ASN1Object - superclass
  4216.      */
  4217.     KJUR.asn1.DERNull = function() {
  4218.         KJUR.asn1.DERNull.superclass.constructor.call(this);
  4219.         this.hT = "05";
  4220.         this.hTLV = "0500";
  4221.     };
  4222.     YAHOO.lang.extend(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object);

  4223. // ********************************************************************
  4224.     /**
  4225.      * class for ASN.1 DER ObjectIdentifier
  4226.      * @name KJUR.asn1.DERObjectIdentifier
  4227.      * @class class for ASN.1 DER ObjectIdentifier
  4228.      * @param {Array} params associative array of parameters (ex. {'oid': '2.5.4.5'})
  4229.      * @extends KJUR.asn1.ASN1Object
  4230.      * @description
  4231.      * <br/>
  4232.      * As for argument 'params' for constructor, you can specify one of
  4233.      * following properties:
  4234.      * <ul>
  4235.      * <li>oid - specify initial ASN.1 value(V) by a oid string (ex. 2.5.4.13)</li>
  4236.      * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  4237.      * </ul>
  4238.      * NOTE: 'params' can be omitted.
  4239.      */
  4240.     KJUR.asn1.DERObjectIdentifier = function(params) {
  4241.         var itox = function(i) {
  4242.             var h = i.toString(16);
  4243.             if (h.length == 1) h = '0' + h;
  4244.             return h;
  4245.         };
  4246.         var roidtox = function(roid) {
  4247.             var h = '';
  4248.             var bi = new BigInteger(roid, 10);
  4249.             var b = bi.toString(2);
  4250.             var padLen = 7 - b.length % 7;
  4251.             if (padLen == 7) padLen = 0;
  4252.             var bPad = '';
  4253.             for (var i = 0; i < padLen; i++) bPad += '0';
  4254.             b = bPad + b;
  4255.             for (var i = 0; i < b.length - 1; i += 7) {
  4256.                 var b8 = b.substr(i, 7);
  4257.                 if (i != b.length - 7) b8 = '1' + b8;
  4258.                 h += itox(parseInt(b8, 2));
  4259.             }
  4260.             return h;
  4261.         };

  4262.         KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this);
  4263.         this.hT = "06";

  4264.         /**
  4265.          * set value by a hexadecimal string
  4266.          * @name setValueHex
  4267.          * @memberOf KJUR.asn1.DERObjectIdentifier#
  4268.          * @function
  4269.          * @param {String} newHexString hexadecimal value of OID bytes
  4270.          */
  4271.         this.setValueHex = function(newHexString) {
  4272.             this.hTLV = null;
  4273.             this.isModified = true;
  4274.             this.s = null;
  4275.             this.hV = newHexString;
  4276.         };

  4277.         /**
  4278.          * set value by a OID string<br/>
  4279.          * @name setValueOidString
  4280.          * @memberOf KJUR.asn1.DERObjectIdentifier#
  4281.          * @function
  4282.          * @param {String} oidString OID string (ex. 2.5.4.13)
  4283.          * @example
  4284.          * o = new KJUR.asn1.DERObjectIdentifier();
  4285.          * o.setValueOidString("2.5.4.13");
  4286.          */
  4287.         this.setValueOidString = function(oidString) {
  4288.             if (! oidString.match(/^[0-9.]+$/)) {
  4289.                 throw "malformed oid string: " + oidString;
  4290.             }
  4291.             var h = '';
  4292.             var a = oidString.split('.');
  4293.             var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
  4294.             h += itox(i0);
  4295.             a.splice(0, 2);
  4296.             for (var i = 0; i < a.length; i++) {
  4297.                 h += roidtox(a[i]);
  4298.             }
  4299.             this.hTLV = null;
  4300.             this.isModified = true;
  4301.             this.s = null;
  4302.             this.hV = h;
  4303.         };

  4304.         /**
  4305.          * set value by a OID name
  4306.          * @name setValueName
  4307.          * @memberOf KJUR.asn1.DERObjectIdentifier#
  4308.          * @function
  4309.          * @param {String} oidName OID name (ex. 'serverAuth')
  4310.          * @since 1.0.1
  4311.          * @description
  4312.          * OID name shall be defined in 'KJUR.asn1.x509.OID.name2oidList'.
  4313.          * Otherwise raise error.
  4314.          * @example
  4315.          * o = new KJUR.asn1.DERObjectIdentifier();
  4316.          * o.setValueName("serverAuth");
  4317.          */
  4318.         this.setValueName = function(oidName) {
  4319.             var oid = KJUR.asn1.x509.OID.name2oid(oidName);
  4320.             if (oid !== '') {
  4321.                 this.setValueOidString(oid);
  4322.             } else {
  4323.                 throw "DERObjectIdentifier oidName undefined: " + oidName;
  4324.             }
  4325.         };

  4326.         this.getFreshValueHex = function() {
  4327.             return this.hV;
  4328.         };

  4329.         if (params !== undefined) {
  4330.             if (typeof params === "string") {
  4331.                 if (params.match(/^[0-2].[0-9.]+$/)) {
  4332.                     this.setValueOidString(params);
  4333.                 } else {
  4334.                     this.setValueName(params);
  4335.                 }
  4336.             } else if (params.oid !== undefined) {
  4337.                 this.setValueOidString(params.oid);
  4338.             } else if (params.hex !== undefined) {
  4339.                 this.setValueHex(params.hex);
  4340.             } else if (params.name !== undefined) {
  4341.                 this.setValueName(params.name);
  4342.             }
  4343.         }
  4344.     };
  4345.     YAHOO.lang.extend(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object);

  4346. // ********************************************************************
  4347.     /**
  4348.      * class for ASN.1 DER Enumerated
  4349.      * @name KJUR.asn1.DEREnumerated
  4350.      * @class class for ASN.1 DER Enumerated
  4351.      * @extends KJUR.asn1.ASN1Object
  4352.      * @description
  4353.      * <br/>
  4354.      * As for argument 'params' for constructor, you can specify one of
  4355.      * following properties:
  4356.      * <ul>
  4357.      * <li>int - specify initial ASN.1 value(V) by integer value</li>
  4358.      * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  4359.      * </ul>
  4360.      * NOTE: 'params' can be omitted.
  4361.      * @example
  4362.      * new KJUR.asn1.DEREnumerated(123);
  4363.      * new KJUR.asn1.DEREnumerated({int: 123});
  4364.      * new KJUR.asn1.DEREnumerated({hex: '1fad'});
  4365.      */
  4366.     KJUR.asn1.DEREnumerated = function(params) {
  4367.         KJUR.asn1.DEREnumerated.superclass.constructor.call(this);
  4368.         this.hT = "0a";

  4369.         /**
  4370.          * set value by Tom Wu's BigInteger object
  4371.          * @name setByBigInteger
  4372.          * @memberOf KJUR.asn1.DEREnumerated#
  4373.          * @function
  4374.          * @param {BigInteger} bigIntegerValue to set
  4375.          */
  4376.         this.setByBigInteger = function(bigIntegerValue) {
  4377.             this.hTLV = null;
  4378.             this.isModified = true;
  4379.             this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
  4380.         };

  4381.         /**
  4382.          * set value by integer value
  4383.          * @name setByInteger
  4384.          * @memberOf KJUR.asn1.DEREnumerated#
  4385.          * @function
  4386.          * @param {Integer} integer value to set
  4387.          */
  4388.         this.setByInteger = function(intValue) {
  4389.             var bi = new BigInteger(String(intValue), 10);
  4390.             this.setByBigInteger(bi);
  4391.         };

  4392.         /**
  4393.          * set value by integer value
  4394.          * @name setValueHex
  4395.          * @memberOf KJUR.asn1.DEREnumerated#
  4396.          * @function
  4397.          * @param {String} hexadecimal string of integer value
  4398.          * @description
  4399.          * <br/>
  4400.          * NOTE: Value shall be represented by minimum octet length of
  4401.          * two's complement representation.
  4402.          */
  4403.         this.setValueHex = function(newHexString) {
  4404.             this.hV = newHexString;
  4405.         };

  4406.         this.getFreshValueHex = function() {
  4407.             return this.hV;
  4408.         };

  4409.         if (typeof params != "undefined") {
  4410.             if (typeof params['int'] != "undefined") {
  4411.                 this.setByInteger(params['int']);
  4412.             } else if (typeof params == "number") {
  4413.                 this.setByInteger(params);
  4414.             } else if (typeof params['hex'] != "undefined") {
  4415.                 this.setValueHex(params['hex']);
  4416.             }
  4417.         }
  4418.     };
  4419.     YAHOO.lang.extend(KJUR.asn1.DEREnumerated, KJUR.asn1.ASN1Object);

  4420. // ********************************************************************
  4421.     /**
  4422.      * class for ASN.1 DER UTF8String
  4423.      * @name KJUR.asn1.DERUTF8String
  4424.      * @class class for ASN.1 DER UTF8String
  4425.      * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  4426.      * @extends KJUR.asn1.DERAbstractString
  4427.      * @description
  4428.      * @see KJUR.asn1.DERAbstractString - superclass
  4429.      */
  4430.     KJUR.asn1.DERUTF8String = function(params) {
  4431.         KJUR.asn1.DERUTF8String.superclass.constructor.call(this, params);
  4432.         this.hT = "0c";
  4433.     };
  4434.     YAHOO.lang.extend(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString);

  4435. // ********************************************************************
  4436.     /**
  4437.      * class for ASN.1 DER NumericString
  4438.      * @name KJUR.asn1.DERNumericString
  4439.      * @class class for ASN.1 DER NumericString
  4440.      * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  4441.      * @extends KJUR.asn1.DERAbstractString
  4442.      * @description
  4443.      * @see KJUR.asn1.DERAbstractString - superclass
  4444.      */
  4445.     KJUR.asn1.DERNumericString = function(params) {
  4446.         KJUR.asn1.DERNumericString.superclass.constructor.call(this, params);
  4447.         this.hT = "12";
  4448.     };
  4449.     YAHOO.lang.extend(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString);

  4450. // ********************************************************************
  4451.     /**
  4452.      * class for ASN.1 DER PrintableString
  4453.      * @name KJUR.asn1.DERPrintableString
  4454.      * @class class for ASN.1 DER PrintableString
  4455.      * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  4456.      * @extends KJUR.asn1.DERAbstractString
  4457.      * @description
  4458.      * @see KJUR.asn1.DERAbstractString - superclass
  4459.      */
  4460.     KJUR.asn1.DERPrintableString = function(params) {
  4461.         KJUR.asn1.DERPrintableString.superclass.constructor.call(this, params);
  4462.         this.hT = "13";
  4463.     };
  4464.     YAHOO.lang.extend(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString);

  4465. // ********************************************************************
  4466.     /**
  4467.      * class for ASN.1 DER TeletexString
  4468.      * @name KJUR.asn1.DERTeletexString
  4469.      * @class class for ASN.1 DER TeletexString
  4470.      * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  4471.      * @extends KJUR.asn1.DERAbstractString
  4472.      * @description
  4473.      * @see KJUR.asn1.DERAbstractString - superclass
  4474.      */
  4475.     KJUR.asn1.DERTeletexString = function(params) {
  4476.         KJUR.asn1.DERTeletexString.superclass.constructor.call(this, params);
  4477.         this.hT = "14";
  4478.     };
  4479.     YAHOO.lang.extend(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString);

  4480. // ********************************************************************
  4481.     /**
  4482.      * class for ASN.1 DER IA5String
  4483.      * @name KJUR.asn1.DERIA5String
  4484.      * @class class for ASN.1 DER IA5String
  4485.      * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  4486.      * @extends KJUR.asn1.DERAbstractString
  4487.      * @description
  4488.      * @see KJUR.asn1.DERAbstractString - superclass
  4489.      */
  4490.     KJUR.asn1.DERIA5String = function(params) {
  4491.         KJUR.asn1.DERIA5String.superclass.constructor.call(this, params);
  4492.         this.hT = "16";
  4493.     };
  4494.     YAHOO.lang.extend(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString);

  4495. // ********************************************************************
  4496.     /**
  4497.      * class for ASN.1 DER UTCTime
  4498.      * @name KJUR.asn1.DERUTCTime
  4499.      * @class class for ASN.1 DER UTCTime
  4500.      * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
  4501.      * @extends KJUR.asn1.DERAbstractTime
  4502.      * @description
  4503.      * <br/>
  4504.      * As for argument 'params' for constructor, you can specify one of
  4505.      * following properties:
  4506.      * <ul>
  4507.      * <li>str - specify initial ASN.1 value(V) by a string (ex.'130430235959Z')</li>
  4508.      * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  4509.      * <li>date - specify Date object.</li>
  4510.      * </ul>
  4511.      * NOTE: 'params' can be omitted.
  4512.      * <h4>EXAMPLES</h4>
  4513.      * @example
  4514.      * d1 = new KJUR.asn1.DERUTCTime();
  4515.      * d1.setString('130430125959Z');
  4516.      *
  4517.      * d2 = new KJUR.asn1.DERUTCTime({'str': '130430125959Z'});
  4518.      * d3 = new KJUR.asn1.DERUTCTime({'date': new Date(Date.UTC(2015, 0, 31, 0, 0, 0, 0))});
  4519.      * d4 = new KJUR.asn1.DERUTCTime('130430125959Z');
  4520.      */
  4521.     KJUR.asn1.DERUTCTime = function(params) {
  4522.         KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params);
  4523.         this.hT = "17";

  4524.         /**
  4525.          * set value by a Date object<br/>
  4526.          * @name setByDate
  4527.          * @memberOf KJUR.asn1.DERUTCTime#
  4528.          * @function
  4529.          * @param {Date} dateObject Date object to set ASN.1 value(V)
  4530.          * @example
  4531.          * o = new KJUR.asn1.DERUTCTime();
  4532.          * o.setByDate(new Date("2016/12/31"));
  4533.          */
  4534.         this.setByDate = function(dateObject) {
  4535.             this.hTLV = null;
  4536.             this.isModified = true;
  4537.             this.date = dateObject;
  4538.             this.s = this.formatDate(this.date, 'utc');
  4539.             this.hV = stohex(this.s);
  4540.         };

  4541.         this.getFreshValueHex = function() {
  4542.             if (typeof this.date == "undefined" && typeof this.s == "undefined") {
  4543.                 this.date = new Date();
  4544.                 this.s = this.formatDate(this.date, 'utc');
  4545.                 this.hV = stohex(this.s);
  4546.             }
  4547.             return this.hV;
  4548.         };

  4549.         if (params !== undefined) {
  4550.             if (params.str !== undefined) {
  4551.                 this.setString(params.str);
  4552.             } else if (typeof params == "string" && params.match(/^[0-9]{12}Z$/)) {
  4553.                 this.setString(params);
  4554.             } else if (params.hex !== undefined) {
  4555.                 this.setStringHex(params.hex);
  4556.             } else if (params.date !== undefined) {
  4557.                 this.setByDate(params.date);
  4558.             }
  4559.         }
  4560.     };
  4561.     YAHOO.lang.extend(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime);

  4562. // ********************************************************************
  4563.     /**
  4564.      * class for ASN.1 DER GeneralizedTime
  4565.      * @name KJUR.asn1.DERGeneralizedTime
  4566.      * @class class for ASN.1 DER GeneralizedTime
  4567.      * @param {Array} params associative array of parameters (ex. {'str': '20130430235959Z'})
  4568.      * @property {Boolean} withMillis flag to show milliseconds or not
  4569.      * @extends KJUR.asn1.DERAbstractTime
  4570.      * @description
  4571.      * <br/>
  4572.      * As for argument 'params' for constructor, you can specify one of
  4573.      * following properties:
  4574.      * <ul>
  4575.      * <li>str - specify initial ASN.1 value(V) by a string (ex.'20130430235959Z')</li>
  4576.      * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  4577.      * <li>date - specify Date object.</li>
  4578.      * <li>millis - specify flag to show milliseconds (from 1.0.6)</li>
  4579.      * </ul>
  4580.      * NOTE1: 'params' can be omitted.
  4581.      * NOTE2: 'withMillis' property is supported from asn1 1.0.6.
  4582.      */
  4583.     KJUR.asn1.DERGeneralizedTime = function(params) {
  4584.         KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params);
  4585.         this.hT = "18";
  4586.         this.withMillis = false;

  4587.         /**
  4588.          * set value by a Date object
  4589.          * @name setByDate
  4590.          * @memberOf KJUR.asn1.DERGeneralizedTime#
  4591.          * @function
  4592.          * @param {Date} dateObject Date object to set ASN.1 value(V)
  4593.          * @example
  4594.          * When you specify UTC time, use 'Date.UTC' method like this:<br/>
  4595.          * o1 = new DERUTCTime();
  4596.          * o1.setByDate(date);
  4597.          *
  4598.          * date = new Date(Date.UTC(2015, 0, 31, 23, 59, 59, 0)); #2015JAN31 23:59:59
  4599.          */
  4600.         this.setByDate = function(dateObject) {
  4601.             this.hTLV = null;
  4602.             this.isModified = true;
  4603.             this.date = dateObject;
  4604.             this.s = this.formatDate(this.date, 'gen', this.withMillis);
  4605.             this.hV = stohex(this.s);
  4606.         };

  4607.         this.getFreshValueHex = function() {
  4608.             if (this.date === undefined && this.s === undefined) {
  4609.                 this.date = new Date();
  4610.                 this.s = this.formatDate(this.date, 'gen', this.withMillis);
  4611.                 this.hV = stohex(this.s);
  4612.             }
  4613.             return this.hV;
  4614.         };

  4615.         if (params !== undefined) {
  4616.             if (params.str !== undefined) {
  4617.                 this.setString(params.str);
  4618.             } else if (typeof params == "string" && params.match(/^[0-9]{14}Z$/)) {
  4619.                 this.setString(params);
  4620.             } else if (params.hex !== undefined) {
  4621.                 this.setStringHex(params.hex);
  4622.             } else if (params.date !== undefined) {
  4623.                 this.setByDate(params.date);
  4624.             }
  4625.             if (params.millis === true) {
  4626.                 this.withMillis = true;
  4627.             }
  4628.         }
  4629.     };
  4630.     YAHOO.lang.extend(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime);

  4631. // ********************************************************************
  4632.     /**
  4633.      * class for ASN.1 DER Sequence
  4634.      * @name KJUR.asn1.DERSequence
  4635.      * @class class for ASN.1 DER Sequence
  4636.      * @extends KJUR.asn1.DERAbstractStructured
  4637.      * @description
  4638.      * <br/>
  4639.      * As for argument 'params' for constructor, you can specify one of
  4640.      * following properties:
  4641.      * <ul>
  4642.      * <li>array - specify array of ASN1Object to set elements of content</li>
  4643.      * </ul>
  4644.      * NOTE: 'params' can be omitted.
  4645.      */
  4646.     KJUR.asn1.DERSequence = function(params) {
  4647.         KJUR.asn1.DERSequence.superclass.constructor.call(this, params);
  4648.         this.hT = "30";
  4649.         this.getFreshValueHex = function() {
  4650.             var h = '';
  4651.             for (var i = 0; i < this.asn1Array.length; i++) {
  4652.                 var asn1Obj = this.asn1Array[i];
  4653.                 h += asn1Obj.getEncodedHex();
  4654.             }
  4655.             this.hV = h;
  4656.             return this.hV;
  4657.         };
  4658.     };
  4659.     YAHOO.lang.extend(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured);

  4660. // ********************************************************************
  4661.     /**
  4662.      * class for ASN.1 DER Set
  4663.      * @name KJUR.asn1.DERSet
  4664.      * @class class for ASN.1 DER Set
  4665.      * @extends KJUR.asn1.DERAbstractStructured
  4666.      * @description
  4667.      * <br/>
  4668.      * As for argument 'params' for constructor, you can specify one of
  4669.      * following properties:
  4670.      * <ul>
  4671.      * <li>array - specify array of ASN1Object to set elements of content</li>
  4672.      * <li>sortflag - flag for sort (default: true). ASN.1 BER is not sorted in 'SET OF'.</li>
  4673.      * </ul>
  4674.      * NOTE1: 'params' can be omitted.<br/>
  4675.      * NOTE2: sortflag is supported since 1.0.5.
  4676.      */
  4677.     KJUR.asn1.DERSet = function(params) {
  4678.         KJUR.asn1.DERSet.superclass.constructor.call(this, params);
  4679.         this.hT = "31";
  4680.         this.sortFlag = true; // item shall be sorted only in ASN.1 DER
  4681.         this.getFreshValueHex = function() {
  4682.             var a = new Array();
  4683.             for (var i = 0; i < this.asn1Array.length; i++) {
  4684.                 var asn1Obj = this.asn1Array[i];
  4685.                 a.push(asn1Obj.getEncodedHex());
  4686.             }
  4687.             if (this.sortFlag == true) a.sort();
  4688.             this.hV = a.join('');
  4689.             return this.hV;
  4690.         };

  4691.         if (typeof params != "undefined") {
  4692.             if (typeof params.sortflag != "undefined" &&
  4693.                 params.sortflag == false)
  4694.                 this.sortFlag = false;
  4695.         }
  4696.     };
  4697.     YAHOO.lang.extend(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured);

  4698. // ********************************************************************
  4699.     /**
  4700.      * class for ASN.1 DER TaggedObject
  4701.      * @name KJUR.asn1.DERTaggedObject
  4702.      * @class class for ASN.1 DER TaggedObject
  4703.      * @extends KJUR.asn1.ASN1Object
  4704.      * @description
  4705.      * <br/>
  4706.      * Parameter 'tagNoNex' is ASN.1 tag(T) value for this object.
  4707.      * For example, if you find '[1]' tag in a ASN.1 dump,
  4708.      * 'tagNoHex' will be 'a1'.
  4709.      * <br/>
  4710.      * As for optional argument 'params' for constructor, you can specify *ANY* of
  4711.      * following properties:
  4712.      * <ul>
  4713.      * <li>explicit - specify true if this is explicit tag otherwise false
  4714.      *     (default is 'true').</li>
  4715.      * <li>tag - specify tag (default is 'a0' which means [0])</li>
  4716.      * <li>obj - specify ASN1Object which is tagged</li>
  4717.      * </ul>
  4718.      * @example
  4719.      * d1 = new KJUR.asn1.DERUTF8String({'str':'a'});
  4720.      * d2 = new KJUR.asn1.DERTaggedObject({'obj': d1});
  4721.      * hex = d2.getEncodedHex();
  4722.      */
  4723.     KJUR.asn1.DERTaggedObject = function(params) {
  4724.         KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);
  4725.         this.hT = "a0";
  4726.         this.hV = '';
  4727.         this.isExplicit = true;
  4728.         this.asn1Object = null;

  4729.         /**
  4730.          * set value by an ASN1Object
  4731.          * @name setString
  4732.          * @memberOf KJUR.asn1.DERTaggedObject#
  4733.          * @function
  4734.          * @param {Boolean} isExplicitFlag flag for explicit/implicit tag
  4735.          * @param {Integer} tagNoHex hexadecimal string of ASN.1 tag
  4736.          * @param {ASN1Object} asn1Object ASN.1 to encapsulate
  4737.          */
  4738.         this.setASN1Object = function(isExplicitFlag, tagNoHex, asn1Object) {
  4739.             this.hT = tagNoHex;
  4740.             this.isExplicit = isExplicitFlag;
  4741.             this.asn1Object = asn1Object;
  4742.             if (this.isExplicit) {
  4743.                 this.hV = this.asn1Object.getEncodedHex();
  4744.                 this.hTLV = null;
  4745.                 this.isModified = true;
  4746.             } else {
  4747.                 this.hV = null;
  4748.                 this.hTLV = asn1Object.getEncodedHex();
  4749.                 this.hTLV = this.hTLV.replace(/^../, tagNoHex);
  4750.                 this.isModified = false;
  4751.             }
  4752.         };

  4753.         this.getFreshValueHex = function() {
  4754.             return this.hV;
  4755.         };

  4756.         if (typeof params != "undefined") {
  4757.             if (typeof params['tag'] != "undefined") {
  4758.                 this.hT = params['tag'];
  4759.             }
  4760.             if (typeof params['explicit'] != "undefined") {
  4761.                 this.isExplicit = params['explicit'];
  4762.             }
  4763.             if (typeof params['obj'] != "undefined") {
  4764.                 this.asn1Object = params['obj'];
  4765.                 this.setASN1Object(this.isExplicit, this.hT, this.asn1Object);
  4766.             }
  4767.         }
  4768.     };
  4769.     YAHOO.lang.extend(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object);

  4770.     /**
  4771.      * Create a new JSEncryptRSAKey that extends Tom Wu's RSA key object.
  4772.      * This object is just a decorator for parsing the key parameter
  4773.      * @param {string|Object} key - The key in string format, or an object containing
  4774.      * the parameters needed to build a RSAKey object.
  4775.      * @constructor
  4776.      */
  4777.     var JSEncryptRSAKey = /** @class */ (function (_super) {
  4778.         __extends(JSEncryptRSAKey, _super);
  4779.         function JSEncryptRSAKey(key) {
  4780.             var _this = _super.call(this) || this;
  4781.             // Call the super constructor.
  4782.             //  RSAKey.call(this);
  4783.             // If a key key was provided.
  4784.             if (key) {
  4785.                 // If this is a string...
  4786.                 if (typeof key === "string") {
  4787.                     _this.parseKey(key);
  4788.                 }
  4789.                 else if (JSEncryptRSAKey.hasPrivateKeyProperty(key) ||
  4790.                     JSEncryptRSAKey.hasPublicKeyProperty(key)) {
  4791.                     // Set the values for the key.
  4792.                     _this.parsePropertiesFrom(key);
  4793.                 }
  4794.             }
  4795.             return _this;
  4796.         }
  4797.         /**
  4798.          * Method to parse a pem encoded string containing both a public or private key.
  4799.          * The method will translate the pem encoded string in a der encoded string and
  4800.          * will parse private key and public key parameters. This method accepts public key
  4801.          * in the rsaencryption pkcs #1 format (oid: 1.2.840.113549.1.1.1).
  4802.          *
  4803.          * @todo Check how many rsa formats use the same format of pkcs #1.
  4804.          *
  4805.          * The format is defined as:
  4806.          * PublicKeyInfo ::= SEQUENCE {
  4807.          *   algorithm       AlgorithmIdentifier,
  4808.          *   PublicKey       BIT STRING
  4809.          * }
  4810.          * Where AlgorithmIdentifier is:
  4811.          * AlgorithmIdentifier ::= SEQUENCE {
  4812.          *   algorithm       OBJECT IDENTIFIER,     the OID of the enc algorithm
  4813.          *   parameters      ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
  4814.          * }
  4815.          * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
  4816.          * RSAPublicKey ::= SEQUENCE {
  4817.          *   modulus           INTEGER,  -- n
  4818.          *   publicExponent    INTEGER   -- e
  4819.          * }
  4820.          * it's possible to examine the structure of the keys obtained from openssl using
  4821.          * an asn.1 dumper as the one used here to parse the components: http://lapo.it/asn1js/
  4822.          * @argument {string} pem the pem encoded string, can include the BEGIN/END header/footer
  4823.          * @private
  4824.          */
  4825.         JSEncryptRSAKey.prototype.parseKey = function (pem) {
  4826.             try {
  4827.                 var modulus = 0;
  4828.                 var public_exponent = 0;
  4829.                 var reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/;
  4830.                 var der = reHex.test(pem) ? Hex.decode(pem) : Base64.unarmor(pem);
  4831.                 var asn1 = ASN1.decode(der);
  4832.                 // Fixes a bug with OpenSSL 1.0+ private keys
  4833.                 if (asn1.sub.length === 3) {
  4834.                     asn1 = asn1.sub[2].sub[0];
  4835.                 }
  4836.                 if (asn1.sub.length === 9) {
  4837.                     // Parse the private key.
  4838.                     modulus = asn1.sub[1].getHexStringValue(); // bigint
  4839.                     this.n = parseBigInt(modulus, 16);
  4840.                     public_exponent = asn1.sub[2].getHexStringValue(); // int
  4841.                     this.e = parseInt(public_exponent, 16);
  4842.                     var private_exponent = asn1.sub[3].getHexStringValue(); // bigint
  4843.                     this.d = parseBigInt(private_exponent, 16);
  4844.                     var prime1 = asn1.sub[4].getHexStringValue(); // bigint
  4845.                     this.p = parseBigInt(prime1, 16);
  4846.                     var prime2 = asn1.sub[5].getHexStringValue(); // bigint
  4847.                     this.q = parseBigInt(prime2, 16);
  4848.                     var exponent1 = asn1.sub[6].getHexStringValue(); // bigint
  4849.                     this.dmp1 = parseBigInt(exponent1, 16);
  4850.                     var exponent2 = asn1.sub[7].getHexStringValue(); // bigint
  4851.                     this.dmq1 = parseBigInt(exponent2, 16);
  4852.                     var coefficient = asn1.sub[8].getHexStringValue(); // bigint
  4853.                     this.coeff = parseBigInt(coefficient, 16);
  4854.                 }
  4855.                 else if (asn1.sub.length === 2) {
  4856.                     // Parse the public key.
  4857.                     var bit_string = asn1.sub[1];
  4858.                     var sequence = bit_string.sub[0];
  4859.                     modulus = sequence.sub[0].getHexStringValue();
  4860.                     this.n = parseBigInt(modulus, 16);
  4861.                     public_exponent = sequence.sub[1].getHexStringValue();
  4862.                     this.e = parseInt(public_exponent, 16);
  4863.                 }
  4864.                 else {
  4865.                     return false;
  4866.                 }
  4867.                 return true;
  4868.             }
  4869.             catch (ex) {
  4870.                 return false;
  4871.             }
  4872.         };
  4873.         /**
  4874.          * Translate rsa parameters in a hex encoded string representing the rsa key.
  4875.          *
  4876.          * The translation follow the ASN.1 notation :
  4877.          * RSAPrivateKey ::= SEQUENCE {
  4878.          *   version           Version,
  4879.          *   modulus           INTEGER,  -- n
  4880.          *   publicExponent    INTEGER,  -- e
  4881.          *   privateExponent   INTEGER,  -- d
  4882.          *   prime1            INTEGER,  -- p
  4883.          *   prime2            INTEGER,  -- q
  4884.          *   exponent1         INTEGER,  -- d mod (p1)
  4885.          *   exponent2         INTEGER,  -- d mod (q-1)
  4886.          *   coefficient       INTEGER,  -- (inverse of q) mod p
  4887.          * }
  4888.          * @returns {string}  DER Encoded String representing the rsa private key
  4889.          * @private
  4890.          */
  4891.         JSEncryptRSAKey.prototype.getPrivateBaseKey = function () {
  4892.             var options = {
  4893.                 array: [
  4894.                     new KJUR.asn1.DERInteger({ int: 0 }),
  4895.                     new KJUR.asn1.DERInteger({ bigint: this.n }),
  4896.                     new KJUR.asn1.DERInteger({ int: this.e }),
  4897.                     new KJUR.asn1.DERInteger({ bigint: this.d }),
  4898.                     new KJUR.asn1.DERInteger({ bigint: this.p }),
  4899.                     new KJUR.asn1.DERInteger({ bigint: this.q }),
  4900.                     new KJUR.asn1.DERInteger({ bigint: this.dmp1 }),
  4901.                     new KJUR.asn1.DERInteger({ bigint: this.dmq1 }),
  4902.                     new KJUR.asn1.DERInteger({ bigint: this.coeff })
  4903.                 ]
  4904.             };
  4905.             var seq = new KJUR.asn1.DERSequence(options);
  4906.             return seq.getEncodedHex();
  4907.         };
  4908.         /**
  4909.          * base64 (pem) encoded version of the DER encoded representation
  4910.          * @returns {string} pem encoded representation without header and footer
  4911.          * @public
  4912.          */
  4913.         JSEncryptRSAKey.prototype.getPrivateBaseKeyB64 = function () {
  4914.             return hex2b64(this.getPrivateBaseKey());
  4915.         };
  4916.         /**
  4917.          * Translate rsa parameters in a hex encoded string representing the rsa public key.
  4918.          * The representation follow the ASN.1 notation :
  4919.          * PublicKeyInfo ::= SEQUENCE {
  4920.          *   algorithm       AlgorithmIdentifier,
  4921.          *   PublicKey       BIT STRING
  4922.          * }
  4923.          * Where AlgorithmIdentifier is:
  4924.          * AlgorithmIdentifier ::= SEQUENCE {
  4925.          *   algorithm       OBJECT IDENTIFIER,     the OID of the enc algorithm
  4926.          *   parameters      ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
  4927.          * }
  4928.          * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
  4929.          * RSAPublicKey ::= SEQUENCE {
  4930.          *   modulus           INTEGER,  -- n
  4931.          *   publicExponent    INTEGER   -- e
  4932.          * }
  4933.          * @returns {string} DER Encoded String representing the rsa public key
  4934.          * @private
  4935.          */
  4936.         JSEncryptRSAKey.prototype.getPublicBaseKey = function () {
  4937.             var first_sequence = new KJUR.asn1.DERSequence({
  4938.                 array: [
  4939.                     new KJUR.asn1.DERObjectIdentifier({ oid: "1.2.840.113549.1.1.1" }),
  4940.                     new KJUR.asn1.DERNull()
  4941.                 ]
  4942.             });
  4943.             var second_sequence = new KJUR.asn1.DERSequence({
  4944.                 array: [
  4945.                     new KJUR.asn1.DERInteger({ bigint: this.n }),
  4946.                     new KJUR.asn1.DERInteger({ int: this.e })
  4947.                 ]
  4948.             });
  4949.             var bit_string = new KJUR.asn1.DERBitString({
  4950.                 hex: "00" + second_sequence.getEncodedHex()
  4951.             });
  4952.             var seq = new KJUR.asn1.DERSequence({
  4953.                 array: [
  4954.                     first_sequence,
  4955.                     bit_string
  4956.                 ]
  4957.             });
  4958.             return seq.getEncodedHex();
  4959.         };
  4960.         /**
  4961.          * base64 (pem) encoded version of the DER encoded representation
  4962.          * @returns {string} pem encoded representation without header and footer
  4963.          * @public
  4964.          */
  4965.         JSEncryptRSAKey.prototype.getPublicBaseKeyB64 = function () {
  4966.             return hex2b64(this.getPublicBaseKey());
  4967.         };
  4968.         /**
  4969.          * wrap the string in block of width chars. The default value for rsa keys is 64
  4970.          * characters.
  4971.          * @param {string} str the pem encoded string without header and footer
  4972.          * @param {Number} [width=64] - the length the string has to be wrapped at
  4973.          * @returns {string}
  4974.          * @private
  4975.          */
  4976.         JSEncryptRSAKey.wordwrap = function (str, width) {
  4977.             width = width || 64;
  4978.             if (!str) {
  4979.                 return str;
  4980.             }
  4981.             var regex = "(.{1," + width + "})( +|$\n?)|(.{1," + width + "})";
  4982.             return str.match(RegExp(regex, "g")).join("\n");
  4983.         };
  4984.         /**
  4985.          * Retrieve the pem encoded private key
  4986.          * @returns {string} the pem encoded private key with header/footer
  4987.          * @public
  4988.          */
  4989.         JSEncryptRSAKey.prototype.getPrivateKey = function () {
  4990.             var key = "-----BEGIN RSA PRIVATE KEY-----\n";
  4991.             key += JSEncryptRSAKey.wordwrap(this.getPrivateBaseKeyB64()) + "\n";
  4992.             key += "-----END RSA PRIVATE KEY-----";
  4993.             return key;
  4994.         };
  4995.         /**
  4996.          * Retrieve the pem encoded public key
  4997.          * @returns {string} the pem encoded public key with header/footer
  4998.          * @public
  4999.          */
  5000.         JSEncryptRSAKey.prototype.getPublicKey = function () {
  5001.             var key = "-----BEGIN PUBLIC KEY-----\n";
  5002.             key += JSEncryptRSAKey.wordwrap(this.getPublicBaseKeyB64()) + "\n";
  5003.             key += "-----END PUBLIC KEY-----";
  5004.             return key;
  5005.         };
  5006.         /**
  5007.          * Check if the object contains the necessary parameters to populate the rsa modulus
  5008.          * and public exponent parameters.
  5009.          * @param {Object} [obj={}] - An object that may contain the two public key
  5010.          * parameters
  5011.          * @returns {boolean} true if the object contains both the modulus and the public exponent
  5012.          * properties (n and e)
  5013.          * @todo check for types of n and e. N should be a parseable bigInt object, E should
  5014.          * be a parseable integer number
  5015.          * @private
  5016.          */
  5017.         JSEncryptRSAKey.hasPublicKeyProperty = function (obj) {
  5018.             obj = obj || {};
  5019.             return (obj.hasOwnProperty("n") &&
  5020.                 obj.hasOwnProperty("e"));
  5021.         };
  5022.         /**
  5023.          * Check if the object contains ALL the parameters of an RSA key.
  5024.          * @param {Object} [obj={}] - An object that may contain nine rsa key
  5025.          * parameters
  5026.          * @returns {boolean} true if the object contains all the parameters needed
  5027.          * @todo check for types of the parameters all the parameters but the public exponent
  5028.          * should be parseable bigint objects, the public exponent should be a parseable integer number
  5029.          * @private
  5030.          */
  5031.         JSEncryptRSAKey.hasPrivateKeyProperty = function (obj) {
  5032.             obj = obj || {};
  5033.             return (obj.hasOwnProperty("n") &&
  5034.                 obj.hasOwnProperty("e") &&
  5035.                 obj.hasOwnProperty("d") &&
  5036.                 obj.hasOwnProperty("p") &&
  5037.                 obj.hasOwnProperty("q") &&
  5038.                 obj.hasOwnProperty("dmp1") &&
  5039.                 obj.hasOwnProperty("dmq1") &&
  5040.                 obj.hasOwnProperty("coeff"));
  5041.         };
  5042.         /**
  5043.          * Parse the properties of obj in the current rsa object. Obj should AT LEAST
  5044.          * include the modulus and public exponent (n, e) parameters.
  5045.          * @param {Object} obj - the object containing rsa parameters
  5046.          * @private
  5047.          */
  5048.         JSEncryptRSAKey.prototype.parsePropertiesFrom = function (obj) {
  5049.             this.n = obj.n;
  5050.             this.e = obj.e;
  5051.             if (obj.hasOwnProperty("d")) {
  5052.                 this.d = obj.d;
  5053.                 this.p = obj.p;
  5054.                 this.q = obj.q;
  5055.                 this.dmp1 = obj.dmp1;
  5056.                 this.dmq1 = obj.dmq1;
  5057.                 this.coeff = obj.coeff;
  5058.             }
  5059.         };
  5060.         return JSEncryptRSAKey;
  5061.     }(RSAKey));

  5062.     /**
  5063.      *
  5064.      * @param {Object} [options = {}] - An object to customize JSEncrypt behaviour
  5065.      * possible parameters are:
  5066.      * - default_key_size        {number}  default: 1024 the key size in bit
  5067.      * - default_public_exponent {string}  default: '010001' the hexadecimal representation of the public exponent
  5068.      * - log                     {boolean} default: false whether log warn/error or not
  5069.      * @constructor
  5070.      */
  5071.     var JSEncrypt = /** @class */ (function () {
  5072.         function JSEncrypt(options) {
  5073.             options = options || {};
  5074.             this.default_key_size = parseInt(options.default_key_size, 10) || 1024;
  5075.             this.default_public_exponent = options.default_public_exponent || "010001"; // 65537 default openssl public exponent for rsa key type
  5076.             this.log = options.log || false;
  5077.             // The private and public key.
  5078.             this.key = null;
  5079.         }
  5080.         /**
  5081.          * Method to set the rsa key parameter (one method is enough to set both the public
  5082.          * and the private key, since the private key contains the public key paramenters)
  5083.          * Log a warning if logs are enabled
  5084.          * @param {Object|string} key the pem encoded string or an object (with or without header/footer)
  5085.          * @public
  5086.          */
  5087.         JSEncrypt.prototype.setKey = function (key) {
  5088.             if (this.log && this.key) {
  5089.                 console.warn("A key was already set, overriding existing.");
  5090.             }
  5091.             this.key = new JSEncryptRSAKey(key);
  5092.         };
  5093.         /**
  5094.          * Proxy method for setKey, for api compatibility
  5095.          * @see setKey
  5096.          * @public
  5097.          */
  5098.         JSEncrypt.prototype.setPrivateKey = function (privkey) {
  5099.             // Create the key.
  5100.             this.setKey(privkey);
  5101.         };
  5102.         /**
  5103.          * Proxy method for setKey, for api compatibility
  5104.          * @see setKey
  5105.          * @public
  5106.          */
  5107.         JSEncrypt.prototype.setPublicKey = function (pubkey) {
  5108.             // Sets the public key.
  5109.             this.setKey(pubkey);
  5110.         };
  5111.         /**
  5112.          * Proxy method for RSAKey object's decrypt, decrypt the string using the private
  5113.          * components of the rsa key object. Note that if the object was not set will be created
  5114.          * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
  5115.          * @param {string} str base64 encoded crypted string to decrypt
  5116.          * @return {string} the decrypted string
  5117.          * @public
  5118.          */
  5119.         JSEncrypt.prototype.decrypt = function (str) {
  5120.             // Return the decrypted string.
  5121.             try {
  5122.                 return this.getKey().decrypt(b64tohex(str));
  5123.             }
  5124.             catch (ex) {
  5125.                 return false;
  5126.             }
  5127.         };
  5128.         /**
  5129.          * Proxy method for RSAKey object's encrypt, encrypt the string using the public
  5130.          * components of the rsa key object. Note that if the object was not set will be created
  5131.          * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
  5132.          * @param {string} str the string to encrypt
  5133.          * @return {string} the encrypted string encoded in base64
  5134.          * @public
  5135.          */
  5136.         JSEncrypt.prototype.encrypt = function (str) {
  5137.             // Return the encrypted string.
  5138.             try {
  5139.                 return hex2b64(this.getKey().encrypt(str));
  5140.             }
  5141.             catch (ex) {
  5142.                 return false;
  5143.             }
  5144.         };
  5145.         /**
  5146.          * Proxy method for RSAKey object's sign.
  5147.          * @param {string} str the string to sign
  5148.          * @param {function} digestMethod hash method
  5149.          * @param {string} digestName the name of the hash algorithm
  5150.          * @return {string} the signature encoded in base64
  5151.          * @public
  5152.          */
  5153.         JSEncrypt.prototype.sign = function (str, digestMethod, digestName) {
  5154.             // return the RSA signature of 'str' in 'hex' format.
  5155.             try {
  5156.                 return hex2b64(this.getKey().sign(str, digestMethod, digestName));
  5157.             }
  5158.             catch (ex) {
  5159.                 return false;
  5160.             }
  5161.         };
  5162.         /**
  5163.          * Proxy method for RSAKey object's verify.
  5164.          * @param {string} str the string to verify
  5165.          * @param {string} signature the signature encoded in base64 to compare the string to
  5166.          * @param {function} digestMethod hash method
  5167.          * @return {boolean} whether the data and signature match
  5168.          * @public
  5169.          */
  5170.         JSEncrypt.prototype.verify = function (str, signature, digestMethod) {
  5171.             // Return the decrypted 'digest' of the signature.
  5172.             try {
  5173.                 return this.getKey().verify(str, b64tohex(signature), digestMethod);
  5174.             }
  5175.             catch (ex) {
  5176.                 return false;
  5177.             }
  5178.         };
  5179.         /**
  5180.          * Getter for the current JSEncryptRSAKey object. If it doesn't exists a new object
  5181.          * will be created and returned
  5182.          * @param {callback} [cb] the callback to be called if we want the key to be generated
  5183.          * in an async fashion
  5184.          * @returns {JSEncryptRSAKey} the JSEncryptRSAKey object
  5185.          * @public
  5186.          */
  5187.         JSEncrypt.prototype.getKey = function (cb) {
  5188.             // Only create new if it does not exist.
  5189.             if (!this.key) {
  5190.                 // Get a new private key.
  5191.                 this.key = new JSEncryptRSAKey();
  5192.                 if (cb && {}.toString.call(cb) === "[object Function]") {
  5193.                     this.key.generateAsync(this.default_key_size, this.default_public_exponent, cb);
  5194.                     return;
  5195.                 }
  5196.                 // Generate the key.
  5197.                 this.key.generate(this.default_key_size, this.default_public_exponent);
  5198.             }
  5199.             return this.key;
  5200.         };
  5201.         /**
  5202.          * Returns the pem encoded representation of the private key
  5203.          * If the key doesn't exists a new key will be created
  5204.          * @returns {string} pem encoded representation of the private key WITH header and footer
  5205.          * @public
  5206.          */
  5207.         JSEncrypt.prototype.getPrivateKey = function () {
  5208.             // Return the private representation of this key.
  5209.             return this.getKey().getPrivateKey();
  5210.         };
  5211.         /**
  5212.          * Returns the pem encoded representation of the private key
  5213.          * If the key doesn't exists a new key will be created
  5214.          * @returns {string} pem encoded representation of the private key WITHOUT header and footer
  5215.          * @public
  5216.          */
  5217.         JSEncrypt.prototype.getPrivateKeyB64 = function () {
  5218.             // Return the private representation of this key.
  5219.             return this.getKey().getPrivateBaseKeyB64();
  5220.         };
  5221.         /**
  5222.          * Returns the pem encoded representation of the public key
  5223.          * If the key doesn't exists a new key will be created
  5224.          * @returns {string} pem encoded representation of the public key WITH header and footer
  5225.          * @public
  5226.          */
  5227.         JSEncrypt.prototype.getPublicKey = function () {
  5228.             // Return the private representation of this key.
  5229.             return this.getKey().getPublicKey();
  5230.         };
  5231.         /**
  5232.          * Returns the pem encoded representation of the public key
  5233.          * If the key doesn't exists a new key will be created
  5234.          * @returns {string} pem encoded representation of the public key WITHOUT header and footer
  5235.          * @public
  5236.          */
  5237.         JSEncrypt.prototype.getPublicKeyB64 = function () {
  5238.             // Return the private representation of this key.
  5239.             return this.getKey().getPublicBaseKeyB64();
  5240.         };
  5241.         JSEncrypt.version = "3.0.0-rc.1";
  5242.         return JSEncrypt;
  5243.     }());

  5244.     window.JSEncrypt = JSEncrypt;

  5245.     exports.JSEncrypt = JSEncrypt;
  5246.     exports.default = JSEncrypt;

  5247.     Object.defineProperty(exports, '__esModule', { value: true });

  5248. })));
复制代码
输出如下:
  1. public encrypted:  T2LFtY3dF_b6OBO07BN-3LtMSEBZqDukovDZ4HGCff8wosvlowf6IFJ3U7LFBIeHfiHBKiFuAV8-pFltCfTXtA4AwgVUnwbBMBWBfIJiLDi02ev30V-5BcYEuSF-cEdnSUd7WecrX4rHhzYLueGuj8H6c7RRbSbrJ6_3EFfU-K0
  2. private uncrypted:  i like JS
  3. private uncrypted:  i like php
  4. private uncrypted:  i like java
复制代码


易如意中文编程学习交流论坛有你更精彩~
回复

使用道具 举报

17

主题

1640

积分

0

精华

用户组 

易积分
1805
热心
1
好评
3

活跃会员热心会员

发表于 2019-12-31 08:03:45 | 显示全部楼层
支持版主。。。。。
易如意中文编程学习交流论坛有你更精彩~
回复

使用道具 举报

11

主题

479

积分

0

精华

用户组 

易积分
1528
热心
0
好评
0

活跃会员

发表于 2019-12-31 08:51:59 | 显示全部楼层
支持版主
易如意中文编程学习交流论坛没你也精彩~
回复

使用道具 举报

63

主题

837

积分

0

精华

用户组 

易积分
19759
热心
0
好评
2
QQ
发表于 2019-12-31 09:29:03 来自手机 | 显示全部楼层
必须支持
易如意中文编程学习交流论坛有你更精彩~
回复

使用道具 举报

3

主题

493

积分

0

精华

用户组 

易积分
2405
热心
0
好评
0
发表于 2019-12-31 10:36:44 | 显示全部楼层
进来看看了解一下
易如意中文编程学习交流论坛有你更精彩~
回复

使用道具 举报

63

主题

837

积分

0

精华

用户组 

易积分
19759
热心
0
好评
2
QQ
发表于 2019-12-31 23:32:19 来自手机 | 显示全部楼层
我想问一下,是不是卡密模式也一起出来了
易如意中文编程学习交流论坛有你更精彩~
回复

使用道具 举报

3

主题

21

积分

0

精华

用户组 

易积分
11
热心
0
好评
0
发表于 2020-1-10 00:16:32 | 显示全部楼层
2222222222222222222
易如意中文编程学习交流论坛有你更精彩~
回复

使用道具 举报

2

主题

26

积分

0

精华

用户组 

易积分
61
热心
0
好评
0
发表于 2020-4-2 11:59:56 | 显示全部楼层
非常好的帖子,感谢帮助!
易如意中文编程学习交流论坛有你更精彩~
回复

使用道具 举报

2

主题

26

积分

0

精华

用户组 

易积分
61
热心
0
好评
0
发表于 2020-5-5 18:42:26 | 显示全部楼层
下载下俩学习学习
易如意中文编程学习交流论坛有你更精彩~
回复

使用道具 举报

QQ|sitemap|免责声明|RGB颜色对照表|手机版|小黑屋| 易如意 - E4A中文编程学习交流论坛

GMT+8, 2024-4-24 04:20 , Processed in 0.087602 second(s), 33 queries .

Powered by Discuz! X3.4

© 2001-2018 eruyi.cn

返回顶部