包com.ylsoft.cert; import java.io.file; import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.io.ioexception; import java.security.invalidey.invalidkeyexception; import java java.security.keypiair emptimenter; quient juava.security.security.security.security.security.security; java.security.KeyStore;import java.security.KeyStoreException;import java.security.NoSuchAlgorithmException;import java.security.NoSuchProviderException;import java.security.PrivateKey;import java.security.SecureRandom;import java.security.Signature;import java.security.SignatureException;import java.security.UnrecoverableKeyException;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.objectIdentifier; import sun.security.x509.algorithmid; intim sun.security.x509.CertificateExtensions;import 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.Extension;import sun.security.x509.KeyIdentifier;import sun.security.x509.KeyUsageExtension;import sun.security.x509.SubjectKeyIdentifierExtension;import sun.security.x509.X500Name;import sun.security.x509.X500Signer;import sun.security.x509.x509certimpl;进口太阳。xecurity.x509.x5099certinfo;/** ** * ca的根证书,caca的根证书签署生成ca的根证书签署生成ca的根证书签署生成scriptx的证书 * @author管理员 * */public class class class genx509cert genx509cert {/**********(rng) Nosuchalgorithmexception,nosuchproviderexception {//返回实现指定随机数生成器(rng)secureerandom = secureerandom = secureerandom.getInstance(“ sha1prng”,“ sun”,“ sun”);} public void crotsecert(x509certificate Certifate certical carthificate Certification,x509certificate Certifice citial,PrivateKey rootprivkey,keypair kp kp) IOEXEXPEPTION,无效的Keyexception,NosuchalGorithMexception,NosuchprovidErexception,signature exception {// X.509 V1 v1 v1 X.509 V1 v1 v1 v1 byte certbytes [] x509certimpl(certbytes); // x509certinfo类代表x.509证书信息.x509certinfo x509certinfo =(x509certinfo)x509certimpl.get(x509certimpl.get(“ x509.info”); CERTIFEXX509KEY(kp.getPublic())); // //此类定义creitigeAteCertificateExtensions centergecertificateExtensions centerryextensextensions = new Ceartiverextensions(); ceartiverextensions.set.set ectivalextens.set extrensextens.seet('objectionKeyKeyendifier','subjecteKeyendifier',new obsocekeyskeyendififieRextension(新)(新)(新)(新) keyIdentifier(kp.getPublic())。 x500name(“ cn = rootca,ou = hackWp,o = wp,l = bj,s = bj,c = cn”); x509certinfo.set(“ issuer.dname”,issuer); // //从常规格式化的字符串中构造一个名称,例如// cn = d devave,cn = d d d d d d d d d d devave, (rfc 1779或rfc // 2253样式).x500名称主题= new x500name(“ cn = scriptx,ou = wps,o = wps,o = wps,l = bj,st = bj,c = cn”); x509certinfo.set(x509certinfo.set)签名。发行者); //此类标识算法,例如加密变换,//每个可能与参数相关。AlgorithMidalgorithMid = signer.getAlgorithMid(); //此类定义algorithMid的algorithMid for Centerrip.X509CERTINFO.XCERTINFO.SET(algorith)( CertificateAlgorithmId(algorithmid));// 开始时间Date bdate = new Date();// 结束时间Date edate = new Date();// 天 小时 分 秒 毫秒edate.setTime(bdate.getTime() + 3650 * 24L * 60L * 60L * 1000L);// validity为有效时间长度 单位为秒,This class defines the interval for which the// certificate is有效。证书的有效时间证书vality cidtudvalities = new证书效果(bdate,edate); x509certinfo.set(“有效性”,证书vality); // //此类定义证书的串行number属性./////////////////证书erialnumber(((int)(new Date()。getTime()/ 1000L))); //设置序列号域,此类定义了X509证书的版本。CertificateVersioncv = new Ceritiverversion(证书V3); x509certinfo.set(x509certinfo.set)如果要添加用户扩展信息如果要添加用户扩展信息则比较麻烦版本必须是v3否则不行 */objectIdentifier oid = new ObjectIdentifier(new Int [] {2,5,29,15}); //生成扩展域的IDID iD ID是个int int int in int数组1位最大2位最大22第2第2位最大39最多可以几位不明39最多可以几位不明...................................... userdata.length(); //数据总长17位字节f = 0x04; byte [] bs = new byte [userdata.length() + 2]; bs [0] = f; bs [1] = l; for(int i = 2;我<bs.length; i ++){bs [i] =(byte)userdata.charat(i -2);} extension extention ext = new Extension(oid,true,bs); //生成一个扩展对象oid,byte,byte [] byte [] byte []型的内容值// //型的内容值// keyusageExtension(); keyusage.set(keyUsageExtension.digital_signature,true); keyusage.set(keyUsageExtension.non_repudiation,true); keyusage.set(keyuSageExtension.key_enkey_encipherment.key_key_encipherment,trie,trie,trie) ObjectIdentifier(new int[] { 1, 3, 6, 1,5, 5, 7, 3, 3 });Vector<ObjectIdentifier> vkeyOid = new Vector<ObjectIdentifier>();vkeyOid.add(ekeyOid);ExtendedKeyUsageExtension exKeyUsage = new ExtendedKeyUsageExtension(vkeyOid);CertificateExtensions exts = new CertificateExtensions();exts.set("keyUsage", keyUsage);exts.set("extendedKeyUsage", exKeyUsage);// 如果有多个extension则都放入CertificateExtensions 类中,x509certinfo.set(X509CertInfo.EXTENSIONS, exts);// 设置extensions域X509CertImpl x509certimpl1 = new x509certimpl(x509certinfo); x509certimpl1.sign(rootprivkey,“ md5withrsa”); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////- file(“ f://scriptx.crt”)); base64.EncodeBuffer(x509certimpl1.getencoded(),fos); try {cetiral {certift centerchain = {x509certimpl1}; savepfx; savepfx; certchain,“ f://scriptx.pfx”); fileInputStream in = new fileInputStream(“ f://scriptx.pfx”); keystore inputKeystore = keystore.getInstance(“ pkcs12”) inputKeystore.getCertificate(“ scriptx”); system.out.print(cert.getPublicKey()); privateKeyprivk =(privateKey)inputKeystore.getKey.getKey(“ scriptx”,“ 123456”,“ 123456” .toCharArray() file(“ f://scriptx.pvk”)); privkfos.write(privk.getEncoded()); system.out.print(privk); // base64.encode(key.getEncoded(kegetEncoded(),privekfos),privekfos); in.close(in.close(in.close)(in.close() 生成文件x509certimpl1.verify(certificate.getPublicKey(), null);}/** * 保存此根证书信息KeyStore Personal Information Exchange * * @param alias * @param privKey * @param pwd * @param certChain * @param filepath * @throws Exception */public void savePfx(String alias, PrivateKey privKey, String pwd,Certificate[] certChain, String filepath)投掷异常{/////返回指定类型的键store对象。此方法从首选提供程序开始遍历已注册安全提供者列表。返回一个封装keystorespi //键storepi/实现的新键store对象密钥库(例如,驻留在硬件标记设备上的//密钥库数据的完整性。如果没有指定用于完整性检验的密码//密钥库,则不会执行完整性检验。如果要创建空// keystore,或者不能从流中初始化键store,或者不能从流中初始化键store,则传递null作为流的参数。注意,如果此keystore // keystore //已经被加载,那么它将被重新初始化java.security.privatekey,则它必须附带证明相应公钥的证书链。如果底层密钥库// jks,则必须根据pkcs#8键键编码为// encryptedPrivateKeyInfo。如果给定别名已经存在,则与别名关联的键store // keystore //则与别名关联的pke = new // keystore.privateKeyentry(kp.getPrivate(),certchain); // keystore.passore.password-word-protection密码= new // keystore.passwordwordprotection(“ 123456” .tochararray(“ .tochararray()将此密钥库存储到给定输出流,并用给定密码保护其完整性。outputKeystore.store(out,pwd.tochararray()); out.close();} public void savejks(字符串别名别名,privatekey priveke,privatekey priveke,string pwd,string pwd,cetiral cetiral [] certchain [] certchain,string filepath)throws throws devestion KeyStore.getInstance("jks");System.out.println(outputKeyStore.getType());outputKeyStore.load(null, pwd.toCharArray());outputKeyStore.setKeyEntry(alias, privKey, pwd.toCharArray(), certChain);// KeyStore.PrivateKeyEntry pke=new// keyStore.privateKeyentry(kp.getPrivate(),certchain); // keystore.passwordprotection password = new // keystore.passwordwordprotection(“ 123456” .toCharArray()tochararray() 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);// Sets the source of random numbers used when generating keys.cak.setRandom(sr);// Generates a random public/private key pair, with a given key size.cak.generate(1024);// Constructs a name from a conventionally formatted string, such as// “ cn = dave,ou = javasoft,o = sun microsystems,c =我们”。 (RFC 1779或RFC // 2253样式)X500NAME主题= new X500Name(“ Cn = rootca,OU = HackWp,o = wp,o = wp,l = bj,s = bj,s = bj,c = cn”); // //返回公共密钥的自称X.509V3证书。 //证书立即有效。没有扩展名。//通常使用此类证书来识别“证书//授权”(CA)。因此,他们不会总是被其他各方接受。但是,当您//启动安全基础架构或部署系统//原型时,此类证书也很有用。自签名的根证书x509certificate证书= cak.getSelfCertificate(受试者,new Date(new Date(),3650 * 24L * 60L * 60L * 60L * 60L); x509certificate; x509certificate [] certs = {]证书= {sapca; cak.getPrivateKey(), "123456", certs,"f://RootCa.pfx");} catch (Exception e) {e.printStackTrace();}// 后一个long型参数代表从现在开始的有效期 单位为秒(如果不想从现在开始算 可以在后面改这个域)BASE64Encoder base64 = new BASE64Encoder();FileOutputStream fos = new FileOutputStream(new File("f://RootCa.crt"));// fos.write(certificate.getEncoded());// 生成(保存)cert文件 base64加密 当然也可以不加密base64.encodeBuffer(certificate.getEncoded(), fos);fos.close();}public void signCert() throws NoSuchAlgorithmException,CertificateException, IOException, UnrocoverableKeyException,InvalIdKeyException,nosuchprovidErexception,signature exception {try {keystore ks = keystore.getInstance(“ pkcs12”); fileinputstream ksfis ksfis = new fileinputStream = new fileinputStream(new fileinputStream) “ 123456”。 =(privateKey)ks.GetKey(“ rootca”,键WD); //返回与给定别名关联的证书。如果给定的别名标识通过调用setCertificateTificateEntry创建的条目,或者通过调用以// trustedcertificateAteTry为参数的setEntry // setEntry //创建的条目,setKeyEntry创建的条目,// ks.getCertificate(“ rootca”); createCert(证书,privk,genkey());} catch(keystoreException e){// todo auto-generated catch blocke.printstacktrace()}}}}}} public keypair keypair genkey() KeyPairgenerator.getInstance(“ rsa”); kpg.initialize(1024,sr); system.out.print(kpg.getalgorithm(); keypair kp = kpg = kpg.generateKeypair() genx509cert(); gcert.createOtootca(); gcert.signcert();} catch(exceptE e){// todo todo auto-generated catch blocke.printstacktrace()}}}}}}}以上这篇纯java实现数字证书生成签名的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。,也希望大家多多支持武林网。