pacote com.ylsoft.cert; importar java.io.file; importar java.io.fileInputStream; importar java.io.fileOutputStream; importar java.io.ioexception; importação java.Security.InvalKeyException; import java.security.keyPair; importação java.securge.Securght.Securge.InCeartKeyexception; importação.SeCegurMer.SeCurity.InCurity.InCegurge.EctkeNeMerk.SeCurity.InCegurge.EckeTke.Securgity.InCeartKeReNeCury.Securgity.InCeartKeReNeMerk.Secury.Securge.Securge.Securgy.InCegurge; java.Security.KeyStoreException; importar java.security.nosuchalgorithMexception; importar java.security.nosuchprovidexception; importar java.Security.PrivateKey; importação java.Security.Secrendom; importação.Secture; Java.Security.UnRecoverableKeyException; importar java.Security.Cert.Certificate; importar java.Security.Cert.CertificateException; importar java.Security.Cert.x509Certificate; import java.util.date; importação.util.util.Vector; sun.security.util.ObjectIdentifier; importar sun.security.x509.algoritmid; importar sol.security.x509.CertandKeyGen; importar sun.security.x509.CertificatealGorithmid; importar sun.security.x509.Certificate Extensions; sun.security.x509.CertificateValidity; importar sol.x509.Certificatex509Key; importar sun.security.x509.ExtendedKeySageExtension; importação; sun.security.x509.SubjectKeyIdIdierextension; importar sol.security.x509.x500Name; importar sol.security.x509.x500signer; importar sun.security.x509.x509CertImpl; importar sol. Administrador * */public class GenX509Cert {/** 提供强加密随机数生成器 (rng) * */private Securerendom sr; public genx509Cert () lança NosuchalgorithMexception, noschProvidexception {// 返回实现指定随机数生成器 (rng) 算法的 SecureRandom 对象。sr = sticurance.grender.geninininInTr. CreateCert (Certificado X509Certificate, PrivateKey RootPrivKey, Keypair KP) lança CertificateException, IoException, InvalidKeyException, NosuchalgorithMexception, NosuchProvidException, SignatureException {// X.509 V1 证书的抽象类。此类提供了一种访问 X.509 V1 证书所有属性的标准方式。Tyte, certificado {// x.509 v1 证书的抽象类。此类提供了一种访问 x.509 v1 证书所有属性的标准方式。tete X509CERTIMPL Classe representa um x.509 certificado.x509CertImpl x509CertImpl = new X509CertImpl (certbytes); // A classe X509Certinfo representa X.509CertInFoTInFoTInFoTInFoTInFoTInFoTInFoTInFoCoTInFo X509CertinFo = (X.509 x509CertImpl.get ("x509.info"); // Esta classe define o atributo x509Key para o certificado.x509Certinfo.set ("key", novo certificadox509Key (KP.getPublic ()); // Esta classe define o atributo do atributo para o atributo do certificado (certificado)); Certatextensions (); CertateExtensions.set ("sujeito X500Name ("cn = rootca, ou = hackwp, o = wp, l = bj, s = bj, c = cn"); x509Certinfo.set ("issuer.dname", emsUer); // constrói um nome de uma string convencionalmente, como // "Cn = dana" (RFC 1779 ou RFC // 2253 Style) .x500name sujeito = novo x500Name ("cn = scriptx, ou = wps, o = wps, l = bj, st = bj, c = cn"); x509Certinfo.set (signot.dname ", sujeito) // Assinatura.getInstance ("md5withrsa"); // 初始化这个用于签名的对象。如果使用其他参数再次调用此方法 , 此调用的结果将无效。Signature.initsign (kp.getprivate ()); // Esta classe fornece uma ligação entre um objeto de assinatura e um signo de sinalização e signs de sinaturs. emissuer); // Esta classe identifica algoritmos, como transformações criptográficas, // cada uma das quais pode estar associada a parâmetros.algorithmid algorithmid = signer.getalgorithmid (); // Esta classe define o algoritmo para o certificado.x509CertInfo.set (Algorithmid para o certificado.x509CertInFo.set (ALGorithmid para o certificado.x509CertInfo.set (ALGorithmid, para o certificado.x509CertInFo.set (ALGorithmid para o certificado.x509CertInFo.setMetmen. Certatealgorithmid (algoritmida)); // 开始时间 date bdate = new date (); // 结束时间 date edate = new date (); // 天 小时 分 秒 毫秒 edate.setTime (bdate.gettime () + 3650 * 24l * 60l 60l * 1000l); válido. 证书的有效时间 certificado de certificação CertateValidity = nova certificado de certificação (bdate, edate); x509Certinfo.set ("validade", certificado de certificação); // Esta classe define o atributo SerialNumber para o certificado. CertificadoSerialNumber ((int) (new Date (). GetTime ()/ 1000l))); // 设置序列号域, esta classe define a versão do x509 certificado.Certificatevertion cv = new Certertition (certificado de certificação.v3); x509Certinfo.Set (x509Certinfo.version, cv3); cv3;如果要添加用户扩展信息 则比较麻烦 首先要确定 versão 必须是 v3 否则不行 */objectIdentifier oid = new ObjectIdentifier (new int [] {2, 5, 29, 15}); // 生成扩展域的 id 是个 int 数组 第 1 位最大 2 第 2 位最大 39 最多可以几位不明 .... string userdata = " userData.Length (); // 数据总长 17 位 byte f = 0x04; byte [] bs = novo byte [userData.length () + 2]; bs [0] = f; bs [1] = l; para (int i = 2; i <bs.length; i++) {bs[i] = (byte) userData.charAt(i - 2);}Extension ext = new Extension(oid, true, bs);// 生成一个extension对象 参数分别为 oid,是否关键扩展,byte[]型的内容值// 其中内容的格式比较怪异 第一位是flag 这里取4暂时没出错 估计用来说明数据的用处的 第2位是后面的实际数据的长度,然后就是数据// 密钥用法KeyUsageExtension keyUsage = new KeyusageExtension (); Keyusage.set (keyusageExtension.digital_signature, true); keyusage.set (keyusageextension.non_repudiation, true); keyusage.set (keyUStension.DATA_IPER.ENCIPHERMENT, TRUE); ObjectIdentifier (new int [] {1, 3, 6, 1,5, 5, 7, 3, 3}); vetor <jectIdentifier> vkeyoid = novo vetor <jectIdentifier> (); vkeyoid.add (ekeyoid); atendimento Certatextensions (); Exts.set ("Keyusage", Keyusage); Exts.set ("ExtendedKeyUsage", ExkeyUsage); // 如果有多个 Extensão 则都放入 Certificate Extensões 类中 , x509Certinfo.Set (x509CERTInfo.IntSet, Exts); X509CERTIMPL (X509CERTINFO); X509CERTIMPL1.SIGN (ROOTPRIVKEY, "MD5WITHRSA"); // 使用另一个证书的私钥来签名此证书 这里使用 MD5 散列 用 RSA 来加密 BASE64ENCODER BASE64 = NOVO BASE64 (NOVONENCODER (); FileOuttStream FosS = File ("f: //scriptx.crt")); base64.encodeBuffer (x509CertImpl1.getEncoded (), fos); tente {certificado [] certchain = {x509CertImpl1}; savepfx ("scriptX", kp.getprivate (), "2}; Certchain, "f: //scriptx.pfx"); FileInputStream in = new FileInputStream ("f: //scriptx.pfx"); keystore inputKeystore = keystore.getInstance ("pkcs12"); inputKeystore.load (em, "12346". inputKeystore.getCertificate ("scriptX"); system.out.print (cert.getpublicKey ()); privateKey privk = (privateKey) inputKeystore.getKey ("scriptx", "123456" .toCharArray (); fileoutstream Privkfos = new FileOutStream (novo (new) File ("f: //scriptx.pvk")); privkfos.write (privk.getEncoded ()); system.out.print (privk); // base64.encode (key.getEncoded (), privkfos); in.close ();} catch (exceção e) {// todo autocos);生成文件 x509CertImpl1.Verify (certificado.getPublicKey (), null);}/** * 保存此根证书信息 Keystore Informações pessoais Exchange * * @param Alias * @param privky * @param pwd * @param Certchain * @param filepath * @THETKY Exceção */public Void Savepfx (String Allia FILEPATH) lança exceção {// 此类表示密钥和证书的存储设施。// 返回指定类型的 KeyStore 对象。此方法从首选 Provedor 开始遍历已注册安全提供者列表。返回一个封装 keyStorsPi // 实现的新 keystore 对象 , 该实现取自第一个支持指定类型的 Provedor。KeyStore outputKeyStore = KeyStore.getInsTance ("PKCS12"); System.out.println ("KeyStore 类型" OUTIRNSORE. keystore (例如 , 驻留在硬件标记设备上的 keystore) 或检验 // keystore 数据的完整性。如果没有指定用于完整性检验的密码 , 则不会执行完整性检验。如果要创建空 // keystore , 或者不能从流中初始化 KeyStore , 则传递 nulo 作为 fluxo 的参数。注意 , 如果此 如果此 如果此 如果此 如果此 如果此 如果此 如果此 如果此 如果此 如果此 如果此 如果此 如果此 已经被加载 已经被加载 已经被加载 那么它将被重新初始化 , 并再次从给定输入流中加载。outputkeystore.load (null pwd.tarArray (); Java.security.privateKey , 则它必须附带证明相应公钥的证书链。如果底层 keystore 实现的类型为 // jks , 则必须根据 pkcs #8 标准中的定义将 key 编码为 // criptografadoPrivateKeyInfo 。如果给定别名已经存在 , 则与别名关联的 Keystore // 信息将被给定密钥 (还可能包括证书链) 重写。outputkeystore.setKeyentry (alias, private; Keystore.privateKeyEntry pke = new // keystore.privateKeyEntry (kp.getprivate (), certchain); // keystore.passwordProtection senha = new // keystore.passkerSProtection ("123456". FileOutputStream (filepath); // 将此 keystore 存储到给定输出流 , 并用给定密码保护其完整性。OutputKeyStore.store (out, pwd.toCharArray ()); out.close ();} public void saveJks (alias de string, privateKey Privkey, string pwd, certificado [] Certificado, stringjks, string file) Slows {StringKey Exceptkey, String Pwd, certificado [] Certificado [] UTNCHAIN, String Filepath) Slows Slows { Keystore.getInstance ("jks"); system.out.println (outputKeystore.getType ()); outputKeystore.load (null, pwd.toCharArray ()); outputKeystore.setKeyEntry (alias, privkey, pwd.TotarArray (), CertChain); Keystore.privateKeyEntry (kp.getprivate (), certchain); // keystore.passwordProtection senha = new // keystore.passwordProtection ("123456" .toCharArray ()); // outputKeystore.Setentry ("scriptX", standra); FileOutputStream(filepath);outputKeyStore.store(out, pwd.toCharArray());out.close();}/** * 颁布根证书,自己作为CA * * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws InvalidKeyException * @throws IOException * @throws CertificateException * @throws SignatureException * @throws UnrecoverableKeyException */public void createRootCA() throws NoSuchAlgorithmException,NoSuchProviderException, InvalidKeyException, IOException,CertificateException, SignatureException, UnrecoverableKeyException {// 参数分别为公钥算法、签名算法 providername(因为不知道确切的 只好使用null 既使用默认的provider)// Generate a pair of keys, and provide access to them.CertandKeyGen CAK = new CertandKeyGen ("RSA", "Md5Withrsa", NULL); // Define a fonte de números aleatórios usados ao gerar keys.cak.setrandom (sr); // gera um par de teclas públicas/privadas aleatórias, com um tamanho de tecla dado.Cak.GeNeate (1024); "CN = Dave, OU = Javasoft, O = Microsystems Sun, C = US". (RFC 1779 ou RFC // 2253 Style) X500Name Assunto = novo x500Name ("CN = rootca, ou = hackwp, o = wp, l = bj, s = bj, c = cn"); // retorna um certificado X.509v3 auto-assinado para a chave pública. O certificado // é imediatamente válido. Sem extensões.// Esses certificados normalmente são usados para identificar um "certificado // autoridade" (CA). Consequentemente, eles nem sempre serão aceitos por // por outras partes. No entanto, esses certificados também são úteis quando você // está inicializando sua infraestrutura de segurança ou implantando o sistema // protótipos. 自签名的根证书 x509Certificate certificado = cak.getSelfCertificate (sujeito, new Date (), 3650 * 24l * 60l); cak.getPrivateKey (), "123456", certs, "f: //rootca.pfx");} catch (Exceção e) {e.printStacktrace ();} // 后一个 long 型参数代表从现在开始的有效期 ((如果不想从现在开始算 可以在后面改这个域) base64etr base64 = new Base64 mais novo; File ("f: //rootca.crt")); // fos.write (certificado.getEncoded ()); // 生成 (保存) Cert 文件 base64 加密 当然也可以不加密 base64.EncodeBffer (certificado.GETENCODED (), fos); fos.close ();} vid sinCert (sinCext (), fos); fos.close ();} vid sinCert (sinalização ng. IoException, UnCoverableKeyException, InvalidKeyException, NosuchProvidexception, SignatureException {try {Keystore ks = keystore.getInstance ("pkcs12"); FileInputStream Ksfis = new FileInputream ("FERMED] "123456".toCharArray();char[] keyPwd = "123456".toCharArray();// 从给定输入流中加载此 KeyStore。ks.load(ksfis, storePwd);ksfis.close();// 返回与给定别名关联的密钥(私钥),并用给定密码来恢复它。必须已经通过调用 setKeyEntry,或者以// PrivateKeyEntry// 或 SecretKeyEntry 为参数的 setEntry 关联密钥与别名。PrivateKey privK = (PrivateKey) ks.getKey ("rootca", teclado); // 返回与给定别名关联的证书。如果给定的别名标识通过调用 setCertificateEntry 创建的条目 , 或者通过调用以 // TrustedCertificateEntry 为参数的 setentry // 创建的条目 , 则返回包含在该条目中的可信证书。如果给定的别名标识通过调用 SetkeyEntry 创建的条目 , 或者通过调用以 // privateentry 为参数的 Setentry 创建的条目 创建的条目 ,tkeyentry 创建的条目 , 或者通过调用以 // privateentry 为参数的 Setentry 创建的条目 , ,tkeyTerry 创建的条目 , 或者通过调用以 // private. ks.getCertificate ("rootca"); createCert (certificado, privk, genkey ());} catch (keystoreException e) {// TODO GENERATO AUTOMENTADO BLOCKE.printStackTrace ();}} public KeyPair Genkey () lança nosuchalGorithMexception {}} KeyPair () lança o noschalgorithmException {} {KeyPair KeyPair () lança nosuxos KeypairGenerator.getInstance ("rsa"); kpg.initialize (1024, sr); system.out.print (kpg.getalgorithm ()); keypair kp = kpg.GeNeateKeypair (); retornar kp;} estático público maid Main (string [] Genx509Cert (); GCERT.CRESEROOTCA (); GCERT.SIGNCERT ();} Catch (Exceção e) {// TODO GENERATO AUTOGERATO Blocke.printStacktrace ();}}}以上这篇纯 Java 实现数字证书生成签名的简单实例就是小编分享给大家的全部内容了 , 希望能给大家一个参考 , 也希望大家多多支持武林网。