包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實現數字證書生成簽名的簡單實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。 ,也希望大家多多支持武林網。