패키지 com.ylsoft.cert; import java.io.file; import java.io.fileInputStream; import java.io.fileoutputStream; import java.io.ioexception; import java.security.invalidkeyexception; import java.security.keypair; importme java.security java.security.keystore; import java.security.keystoreexception; import java.security.nosuchalgorithmexception; import java.security.nosuchproviderexception; import java.security.privatekey; import java.security. securerandom; java.security.signaturexception; import java.security.uncoverablekeyException; import java.security.cert.certificate; import java.security.cert.certificateexception; import java.security.cert.x509certificate; import java.util.date; java.util.vector; Sun.Misc.Base64Encoder; import Sun.Security.util.ObjectIndifier; import Sun.Security.x509.AlgorithMID; import Sun.Security.x509.CertandKeyGen; import Sun.Security.x509.certificatealgorithMid; import Sun.Security.x509.certificateextensions; Sun.security.x509.certificateserialNumber; import sun.security.x509.certificatevalidity; import sun.security.x509.certificateversion; import sun.security.x509.certificatex509key; import sun.security.x509.extendedkeyusageextension; import sun.security.x509.extrension; Sun.Security.x509. KeyEndifier; import Sun.Security.x509. KeyUsageExtension; import Sun.security.x509.subjectKeyIntifierextension; import sun.security.x509.x500name; import sun.security.x509.x500signer; import sun.security.x509.certimpl; import sun.security.x509.x509certinfo;/** * 首先生成 ca 的根证书, 然后有 ca 的根证书签署生成 scriptx 的证书 * * @author 관리자 * */public class genx509cert {/** 提供强加密随机数生成器 (rng) * */private securerandom sr; public genx509cert () Throws nosuchalexemence, nosuch recemence返回实现指定随机数生成器 (rng) 算法的 securerandom 对象。Sr = securerandom.getInstance ( "sha1prng", "sun");} public void createCert (x509Certificate 인증서, 개인 키 루트 프리 브리, 키프 에어 KP) throws replicateException, IOException, InvalidKeyException, nosuchalexemention, nosuchalexemention SignatureException {// x.509 V1 X.509 V1 证书所有属性的标准方式。BYTE CERTBYTES [] = eTRICERTIATE.GETENCODED (); // x509CertImpl 클래스는 X.509 reatifate.x509Certimpl x509Certimpl = new x509Certimpl (certbytes); // x509certinfo Classent X.509 인증을 나타냅니다. information.x509certinfo x509certinfo = (x509certinfo) x509certimpl.get ( "x509.info"); // this 클래스는 인증서의 x509key 속성을 정의합니다 .x509certinfo.set ( "키", 새로운 인증서 5509key (kp.getpublic ()); attrictecertificateextensions atricationextensions = new arpertyextensions (); chertorextensions.set ( "subjectkeyEdifier", new subjectKeyIntifierextension ((new keyskeyNifier (kp.getPublic ()).设置 발행자 er x500name 발행자 = new x500name ( "cn = rootca, ou = hackwp, o = wp, l = bj, s = bj, c = cn"); x509certinfo.set ( "vissuer.dname", vissuer); // a 이름에서 구성된 문자열, // "cn = j d, // o = Sun Microsystems, c = us ". (RFC 1779 또는 RFC // 2253 스타일) .x500name 주제 = New x500name ( "CN = ScriptX, OU = WPS, O = WPS, L = BJ, ST = BJ, C = CN"; x509CertInfo.Set ( "Subject.dname", Subject); // 此 서명 gonatuature SIGNATURATUR signature.getInstance ( "Md5withrsa"); // 初始化这个用于签名的对象。如果使用其他参数再次调用此方法 初始化这个用于签名的对象。如果使用其他参数再次调用此方法 初始化这个用于签名的对象。如果使用其他参数再次调用此方法 初始化这个用于签名的对象。如果使用其他参数再次调用此方法, 此调用的结果将无效。signature.initsign (kp.getPrivate ()); //이 클래스는 서명 객체와 Authenticated X.500 이름 (X.509 인증 체인) 사이의 바인딩을 제공합니다. //이 클래스는 암호화 변환과 같은 알고리즘을 식별합니다. // 각각 매개 변수와 관련 될 수있는 각각은 AlgorithMid = signer.getalgorithmid (); //이 클래스가 인증서에 대한 알고리즘을 정의합니다. atricatialgorithmid (algorithmid)); // 开始时间 开始时间 date bdate = new date (); // 结束时间 날짜 edate = new 날짜 = 새로운 날짜 (); // 天 天 小时 分 秒 毫秒 毫秒 毫秒 毫秒 adate.settime () + 3650 * 24l * 60L * 60L * 1000L); 유효한. 인증서 erialnumber ((int) (new date (). gettime ()/ 1000l))); // 设置序列号域,이 클래스는 x509 인증서 버전을 정의합니다 .certificateversion cv = new chertientversion (charnectateversion.v3); x509certinfo.set (x509certinfo.version, cv); // v1, v2, v2, v2, v2, v2, v2, v2, v2, v2, v2, v2, v2.以上是证书的基本信息 以上是证书的基本信息 以上是证书的基本信息 则比较麻烦 如果要添加用户扩展信息 버전 必须是 v3 否则不行 */ObjectIndifier OID = 새로운 대변인 (new int [] {] {2, 5, 29, 15}); // 生成扩展域的 ID 是个 int 数组 第 1 位最大 2 第 2 位最大 39 最多可以几位不明 .... 문자열 userData = "디지털 서명, 비 반복, 비판적 흡입문 (encippherment) (f0). userData.length (); // 数据总长 17 位 byte f = 0x04; byte [] bs = new Byte [userData.length () + 2]; bs [0] = f; bs [1] = l; for (int i = 2; i <bs.length; i ++) {bs [i] = (byte) userdata.charat (i -2);} extension ext = new Extension (oid, true, bs); // 生成一个 生成一个 生成一个 生成一个 生成一个 生成一个 对象 对象 参数分别为 oid, 是否关键扩展, byte [] 型的内容值 第一位是 第一位是 flag 这里取 4 暂时没出错 估计用来说明数据的用处的 第 第 2 位是后面的实际数据的长度 位是后面的实际数据的长度 位是后面的实际数据的长度 keyusage = keyusage keyUsageExtension (); keyusage.set (keyusageExtension.digital_Signature, true); keyusage.set (keyusageextension.non_repudiation, true); keyusage.set (keyusageextension.key_encipherment, keyusage.set (keyUsageExtension.data_encipherment, true); // eke ekeideor); ObjectIndifier (New int [] {] {1, 3, 6, 1,5, 5, 7, 3, 3}); 벡터 <객관화 자> vkeyoid = new 벡터 <objectidentifier> (); vkeyoid.add (ekeyoid); ExtendedKeyUseExtension ExkeyUsage = new ExtendKeyUseExtension (vkeyOid); New extensions = 새로운 ExtendKeyusageExtension (vkeyoid); explicateextensions (); exts.set ( "keyusage", keyusage); exts.set ( "extendekeusage", exkeyUsage); // 如果有多个 如果有多个 如果有多个 extension 则都放入 atriptionextensions 类中, x509certinfo.set (x509certinfo.extensions, exts); x509cert x509cert x509cert x509cert x509cert x509cert x509cert x509cert. x509certimpl (x509certinfo); x509certimpl1.sign (rootprivkey, "md5withrsa"); // 使用另一个证书的私钥来签名此证书 这里使用 md5 散列 用 用 rsa 来加密 rsa 来加密 base64 encoder base64 = 새로운 Base64 Encoder (); fileoutputstream fos = new FileoutputStream (새로운 파일 아웃 푸트 스트림) file ( "f : //scriptx.crt"); base64.encodebuffer (x509certimpl1.getencoded (), fos); try {reateral [] certchain = {x509certimpl1}; savepfx ( "scriptx", kp.getprivate (), "123456", certchain, "f : //scriptx.pfx"); fileInputStream in = new FileInputStream ( "f : //scriptx.pfx"); keystore inputKeyStore = keystore.getInstance ( "PKCS12"); inputKeyStore.Load (in, ",", "); inputkeyStore.getCertificate ( "scriptx"); System.out.print (cert.getPublickey ()); privatekey jubk = (privatekey) inputkeyStore.getKey ( "scriptx", "123456".toCharray (); fileoutputStream jubfos = new FileOutputStream (new file ( "f : //scriptx.pvk")); prodkfos.write (weflk.getencoded ()); system.out.print (probk); // base64.encode (key.getencoded (), probkfos);生成文件 x509certimpl1.verify (reative.getPublickey (), null);};}/** * keystore 개인 정보 교환 * * @param alias * @param privkey * @param pwd * @param certchain * @param filepath */public void savepfx (string privkey, string pwd, string). FilePath)는 예외를 {// 此类表示密钥和证书的存储设施。 此类表示密钥和证书的存储设施。// 返回指定类型的 Keystore 对象。此方法从首选 keystorespi // 实现的新 keystore 对象 对象 对象 对象 对象 keystore 对象 对象 对象 对象 对象 对象 keystore 对象 对象 对象 对象 对象 对象 keystore = keystore.getInstance ( "pkcs12"); system.out.println ( "keystore 类型 类型 : ar 从给定输入流中加载此 从给定输入流中加载此 the 从给定输入流中加载此 the 从给定输入流中加载此 the 从给定输入流中加载此 the the the the keystore.getinstance ("pkcs12 "); keystore (((, 驻留在硬件标记设备上的 keystore) 或检验 // keystore 数据的完整性。如果没有指定用于完整性检验的密码, 则不会执行完整性检验。如果要创建空 // keystore, 或者不能从流中初始化 keystore +, 则传递 null 作为 作为 스트림 的参数。注意, 如果此 keystore // 已经被加载 已经被加载, 那么它将被重新初始化, 并再次从给定输入流中加载。outputkeystore.load (null, pwd.tocharray ()); // 将给定密钥 已经被保护 分配给给定别名。如果受保护密钥的类型为 分配给给定别名。如果受保护密钥的类型为 // // java.security.privatekey, 则它必须附带证明相应公钥的证书链。如果底层 keystore 实现的类型为 // jks, jks, 则必须根据 pkcs #8 标准中的定义将 key 标准中的定义将 key 编码为 // ecryptedPrivateKeyInfo 。如果给定别名已经存在, 则与别名关联的 keystore // 信息将被给定密钥 信息将被给定密钥 (还可能包括证书链) 重写。outputkeystore.setKeyEntry (alias, privkey, privkey, pwd.to charArray); keystore.privatekeyEntry pke = new // keystore.privateKeyEntry (kp.getPrivate (), certchain); // keystore.PasswordProtection password = new // keystore.passwordProtection ( "123456".ToCharray ()); // outputkeyStore.setEntry ( "ScriptX", popportx "; FileOutputStream (FilePath); // 将此 keystore 存储到给定输出流 存储到给定输出流, 并用给定密码保护其完整性。outputkeyStore.store (out, pwd.tochararray ()); out.close ();} public void savejks (문자열 별명, 개인 키 프리 키, 스트링, 인증서 [] certchain, 문자열 파일) 예외 {keystore outputkeystore = keystore.getInstance ( "jks"); system.out.println (outputkeyStore.getType ()); outputKeyStore.load (null, pwd.tochararray ()); outputKeyStore.setKeyEntry (Alias, Privkey, pwd.tochararray (), Certchain.private. keystore.privateKeyEntry (kp.getPrivate (), certchain); // keystore.passwordProtection password = new // keystore.passwordProtection ( "123456".tocharray ()); // outputKeyStore.Stentry ( "scriptx", pke, password); fileOutputStream out = new fileoutputStream (filepath); outputkeyStore.store (out, pwd.tocharray ()); out.close ();}/** * 颁布根证书 * 颁布根证书 颁布根证书, 自己作为 ca * * @throws nosuchalgorithmexception * @throws nosuchproviderexception * @throws invalidkeexcemption * @ThroweNception * @Throwestemence * @Throwestemence * @Throwestrows * @Throwescateception * @throws SignatureException * @throws UnrecoverableKeyException */public void createRootCA() throws NoSuchAlgorithmException,NoSuchProviderException, InvalidKeyException, IOException,CertificateException, SignatureException, UnrecoverableKeyException {// 参数分别为公钥算法、签名算法 providername(因为不知道确切的 只好使用null 既使用默认的provider)// Generate a pair of Keys 및 그들에게 액세스 할 수 있습니다 .certandkeygen cak = new certandkeygen ( "rsa", "md5withrsa", null); // keys.cak.setrandom (sr)을 생성 할 때 사용되는 임의의 숫자 소스를 설정합니다. // "cn = dave, ou = javasoft, o = sun microsystems, c = us"와 같은 문자열. (RFC 1779 또는 RFC // 2253 스타일) x500name 주제 = New x500name ( "CN = Rootca, OU = Hackwp, O = WP, L = BJ, S = BJ, C = CN"; // 공개 키에 대한 자체 서명 X.509V3 인증서를 반환합니다. // 인증서는 즉시 유효합니다. 내선이 없음 .// 이러한 인증서는 일반적으로 "인증서 // 권위"(CA)를 식별하는 데 사용됩니다. 따라서, 그들은 항상 다른 당사자들에 의해 받아 들여지는 것은 아닙니다. 그러나 이러한 인증서는 // 보안 인프라를 부트 스트랩하거나 시스템을 배포 할 때 유용합니다. // 프로토 타입. cak.getPrivatekey (), "123456", certs, "f : //rootca.pfx");} catch (예외 e) {e.printstacktrace ();} // 后一个 long 型参数代表从现在开始的有效期 单位为秒 单位为秒 单位为秒 可以在后面改这个域))))); New Base64 ENDEDER (); PILEOUTPERSTREAM FOS (new PileoutpepputStream) file ( "f : //rootca.crt"); // fos.write (chertorate.getEncoded ()); // 生成 (保存 保存) rect 文件 base64 加密 当然也可以不加密 当然也可以不加密 base64.encodebuffer (repistivate.getEncoded (), fos.close (); public void Shipcert () NosucheLecemence, nosucheLecemence, public void Sipcert () ioException, uncoververableKeyException, InvalidKeyException, nosuchProviderException, signatureException {try {keystore ks = keystore.getInstance ( "pkcs12"); fileInputStream ksfis = new fileInputStream ( "f : //rootca.pfx"; "123456".tocharray (); char [] kyypwd = "123456".toChararray (); // 从给定输入流中加载此 keystore。ks.load (ksfis, storepwd); ksfis.close (); // 返回与给定别名关联的密钥 (私钥), 并用给定密码来恢复它。必须已经通过调用 并用给定密码来恢复它。必须已经通过调用 setkeyentry, 或者以 或者以 或者以 或者以 为参数的 seteNtry gectyEntry // = (privatekey) ks.getKey ( "rootca", kyypwd); // 返回与给定别名关联的证书。如果给定的别名标识通过调用 setCertificateEntry 创建的条目 创建的条目, 或者通过调用以 // trustEdCertIficateEntry 为参数的 setentry // 创建的条目 创建的条目, 则返回包含在该条目中的可信证书。如果给定的别名标识通过调用 setKeyEntry 创建的条目, 或者通过调用以 // privateKeyEntry 为参数的 setentry 创建的条目 创建的条目, 则返回该条目中证书链的第一个元素。x509certificate pritiattate = (x509certificate). ks. getCertificate ( "rootca"); CreateCert (인증서, pribk, genkey ());} catch (keystoreException e) {// todo 자동 생성 캐치 블록 .printstacktrace ();}} public keypair genkey () wrows nosuchalgorithmexection {keypairgencection vpg = kyypairgenerator.getInstance ( "rsa"); kpg.initialize (1024, sr); system.out.print (kpg.getalgorithm ()); kyypair kp = kpg.generatekeypair (); return kp;} public static void main (try {genx509cert gcert = new) {genx509cert gcert = genx509cert (); gcert.createrootca (); gcert.signcert ();} catch (예외 e) {// todo auto-auto-auto-auto-receated catch blocke.printstacktrace ();}}}以上这篇纯 Java a a, 希望能给大家一个参考, 也希望大家多多支持武林网。