Digital certificate of Java security

Source: Internet
Author: User
Tags object object asymmetric encryption

   said earlier that message digest is used to verify data integrity, and symmetric and asymmetric encryption is used to guarantee data confidentiality. Data signatures are used for the anti-repudiation of data, so the ultimate weapon that sets these security measures--digital certificates--appears. Digital certificate has the necessary information of encryption/decryption, including signature algorithm, can be used for network data encryption/decryption interaction, identify network user (computer) identity. The data certificate provides a convenient way to publish the public key, which becomes the carrier of the encryption algorithm and the public key.

   Digital certificates have several file encoding formats, mainly including CER encoding, DER Encoding, and so on:
A.cer (Canonical Encoding Rules, canonical encoding format), is a digital certificate encoding format, it is BER (Basic Encoding rules, Basic coding format) A variant, more stringent than the BER rules. The
B.der (distinguished Encoding Rule, the excellent encoding format), also a variant of BER, is not the same as a CER: DER uses the fixed-length mode, while the CER uses the variable-length mode.
C.PKCS (Public-key Cryptography Standards, Public key cryptography standard), a set of standards developed by RSA Labs and other security system developers to facilitate the development of public key cryptography.
   where CER, der Format certificates are compliant with the X509 International standard for Public Key Infrastructure (PKI), collectively referred to as X509 format certificates. PKCS has released a total of 15 standards, common standards include pkcs#7, PKCS#10 and pkcs#12. Pkcs#7 is the password message syntax standard, the file name suffix is generally:. p7b,. p7c,. spc;pkcs10# is the standard for certificate request syntax, so the certificate request file takes this format, and the file name suffix is generally:. P10,. csr;pkcs#12 for personal Information exchange grammar standards, Therefore, the personal information certificate in this format, the file name suffix is generally:. P12,. pfx. It is worth mentioning that although PKCS#12 is a certificate format, in Java, the individual is more like a keystore format, because the pkcs#12 format file can store both the certificate and the private key, and generally speaking, the certificate does not contain the private key information.

First, the digital certificate contains exactly what information, we take 12306 digital certificate as an example:


As can be seen from the above, a digital certificate contains a lot of information, mainly, the version number, serial number, Signature algorithm, signature hash algorithm, issuer, validity period, user, public key, fingerprint algorithm, fingerprint and some of the extended attribute information of the digital certificate.

Second, how to obtain the certificate
If your company is going to launch a shopping site, then it will certainly use the HTTPS protocol and will certainly use the digital certificate, then where does the digital certificate come from? Is it your own generation? Of course not, the correct approach is that the company generates a certificate request file, and then submits the certificate request file to the certificate authority, and then the certificate authority uses its root certificate to generate a trusted certificate for you based on the information in the certificate request file, that is, to issue a certificate. Of course, it is necessary for the certification authority to issue certificates to your company. But sometimes you can create your own certificate, but this time the certificate is your own, just someone else's information of your own root certificate, the certificate can also be used as usual.

Third, whether the certificate is legal (trusted)
When it comes to the question of whether a certificate is trusted, you need to know one rule: a certificate issued by a trusted certificate is also trusted. Then the first chicken or egg problem comes, the first trusted certificate is from where, in order to solve this problem leads to the root certificate, the root certificate is issued to its own certificate, as long as the root certificate is trusted, so that the certificate issued by the root certificate can be trusted, so certificate issuance is actually a tree structure, The root certificate can issue a first-level certificate, and a level certificate can also issue a secondary certificate to other users if allowed. Take windows, ie as an example (ie shared the certificate in Windows System), after Windows is installed, the system has trusted the root certificate of some authoritative certificate authority, of course, you can also import the root certificate you made.

Iv. What is certificate issuance
Certificate issuance is a professional term, in fact, is to use the certificate issuer's private key to sign the certificate consumer's certificate, and set the issuer of the consumer certificate, the certificate generally needs to be issued by an authoritative certificate authority, the original is to sign the certificate using the private key, the private key is only issued by the authority.

Here's a look at how the various operations on certificates are done in Java:

Package Com.xtayfjpk.security.certificate;import Java.io.bytearrayoutputstream;import Java.io.FileInputStream; Import Java.io.fileoutputstream;import Java.io.objectinputstream;import Java.io.objectoutputstream;import Java.math.biginteger;import Java.security.key;import Java.security.keyfactory;import Java.security.KeyPair;import Java.security.keypairgenerator;import Java.security.privatekey;import Java.security.provider;import Java.security.publickey;import Java.security.security;import Java.security.signature;import Java.security.cert.certificatefactory;import Java.security.cert.x509certificate;import Java.security.spec.rsapublickeyspec;import Java.util.date;import Java.util.hashmap;import Java.util.Map;import Javax.security.auth.x500.x500principal;import Org.bouncycastle.asn1.derbmpstring;import Org.bouncycastle.asn1.pkcs.pkcsobjectidentifiers;import Org.bouncycastle.asn1.x500.x500name;import Org.bouncycastle.asn1.x509.algorithmidentifier;import org.bouncycastle.asn1.x509.Certificate;Import Org.bouncycastle.asn1.x509.subjectpublickeyinfo;import Org.bouncycastle.cert.x509certificateholder;import Org.bouncycastle.cert.x509v3certificatebuilder;import Org.bouncycastle.crypto.params.AsymmetricKeyParameter; Import Org.bouncycastle.crypto.params.rsakeyparameters;import org.bouncycastle.crypto.util.PrivateKeyFactory; Import Org.bouncycastle.crypto.util.publickeyfactory;import Org.bouncycastle.crypto.util.subjectpublickeyinfofactory;import Org.bouncycastle.jce.interfaces.pkcs12bagattributecarrier;import Org.bouncycastle.jce.provider.bouncycastleprovider;import Org.bouncycastle.operator.contentsigner;import Org.bouncycastle.operator.defaultdigestalgorithmidentifierfinder;import Org.bouncycastle.operator.defaultsignaturealgorithmidentifierfinder;import Org.bouncycastle.operator.bc.bcrsacontentsignerbuilder;import org.bouncycastle.pkcs.PKCS10CertificationRequest; Import Org.bouncycastle.pkcs.pkcs10certificationrequestbuilder;import Org.bouncycastle.x509.X509V3CertificateGenerator; Import org.junit.before;import org.junit.test;/** * Issuer certificate issuer * Subject Certificate User * * Dn:distinguish name * format: cn= name, ou= organization form Bit name, o= organization name, L= City or region name, st= state/province name, c= country Double Letter * */@SuppressWarnings ("deprecation") public class Certifacategeneratetest  {private static final string key_pair_alg = "RSA";p rivate static final String sig_alg = "Sha1withrsa";p rivate static final String Dn_zhangsan = "CN=ZHANGSAN,OU=DEVELOPMENT,O=HUAWEI,L=SHENZHEN,ST=GUANGDONG,C=CN";p rivate static final String Dn_ca = "CN=KINGYEA,OU=KINGYEA,O=KINGYEA,L=GUANGZOU,ST=GUANGDONG,C=CN";p rivate static map<string, String> Algorithmmap = new hashmap<> (); static {/** * algorithm name and Algorithm identifier mapping */algorithmmap.put ("1.2.840.113549.1.1.5", sig_alg); Algorithmmap.put ("1.2.840.113549.1.1.1", Key_pair_alg);} @Beforepublic void before () {//register BC Provider, because some of the operations on the certificate used to bouncycastle this third-party library on the way to register, actually do not register also line Provider Provider = new Bouncycastleprovider (); Security.addprovider (provider);} /** * Generate root certificate public key and private key pair */@Testpublic void Testgenrootkeypair () throws Exception {Keypairgenerator keypairgenerator = keypairgenerator.getinstance (key_pair_alg); keyPairGenerator.initialize (2048); KeyPair KeyPair = Keypairgenerator.generatekeypair () writeobject ("H:/certtest/kingyea.public", Keypair.getpublic () ); WriteObject ("H:/certtest/kingyea.private", Keypair.getprivate ());} /** * Generate user Certificate public key and private key pair * @throws Exception */@Testpublic void Testzhangsankeypair () throws Exception {Keypairgenerator KeyPair Generator = Keypairgenerator.getinstance (KEY_PAIR_ALG); keypairgenerator.initialize (2048); KeyPair KeyPair = Keypairgenerator.generatekeypair (); WriteObject ("H:/certtest/zhangsan.public", Keypair.getpublic ( ); WriteObject ("H:/certtest/zhangsan.private", Keypair.getprivate ());} /** * Generate root certificate (deprecated by BC, but can be used) */@Testpublic void Testgenrootcert () throws Exception {X509v3certificategenerator Certgen = new X 509v3certificategenerator ();//Set certificate issuer Certgen.setissuerdn (new X500principal (Dn_ca));//Set certificate validity period Certgen.setnotafter (New Date (System.currenttimemillis () + * *); CERTgen.setnotbefore (New Date ());//Set Certificate public key Certgen.setpublickey (Getrootpublickey ());//Set certificate serial number Certgen.setserialnumber (biginteger.ten);//Set the signature Algorithm certgen.setsignaturealgorithm (SIG_ALG);//Set up certificate consumer Certgen.setsubjectdn (new X500principal (Dn_ca)); /Use the private key to generate the certificate, primarily for signature operations X509Certificate certificate = certgen.generate (Getrootprivatekey ()); Pkcs12bagattributecarrier bagattr = (pkcs12bagattributecarrier) certificate;bagattr.setbagattribute (PKCSObjectI Dentifiers.pkcs_9_at_friendlyname, New Derbmpstring ("Kingyea coperation Certificate"); WriteFile ("h:/certtest/c A.cer ", certificate.getencoded ());} /** * Another way to generate a root certificate * @throws Exception */@Testpublic void Testgenrootcertwithbuilder () throws Exception {final Algorithmid Entifier sigalgid = new Defaultsignaturealgorithmidentifierfinder (). Find (Sig_alg); final Algorithmidentifier DigAlgId = new Defaultdigestalgorithmidentifierfinder (). Find (Sigalgid); PublicKey PublicKey = Getrootpublickey (); Privatekey Privatekey = Getrootprivatekey (); X500name issueR = new X500name (DN_CA); BigInteger serial = Biginteger.ten;date Notbefore = new Date ();D ate notafter = new Date (System.currenttimemillis () + 100 * 24 * 60 * 60 * 1000); X500name subject = new X500name (DN_CA); Algorithmidentifier Algid = algorithmidentifier.getinstance (PKCSObjectIdentifiers.rsaEncryption.toString ()); System.out.println (Algid.getalgorithm ()); Asymmetrickeyparameter publickeyparameter = Publickeyfactory.createkey (publickey.getencoded ()); Subjectpublickeyinfo publickeyinfo = Subjectpublickeyinfofactory.createsubjectpublickeyinfo (PublicKeyParameter); /Not in this way, the generated certificate is incomplete//subjectpublickeyinfo publickeyinfo = new Subjectpublickeyinfo (Algid, publickey.getencoded ()); X509v3certificatebuilder X509v3certificatebuilder = new X509v3certificatebuilder (issuer, serial, Notbefore, NotAfter, Subject, Publickeyinfo); Bcrsacontentsignerbuilder Contentsignerbuilder = new Bcrsacontentsignerbuilder (Sigalgid, digAlgId); Asymmetrickeyparameter privatekeyparameter = Privatekeyfactory.createkey (privatekey.geTencoded ()); Contentsigner Contentsigner = Contentsignerbuilder.build (Privatekeyparameter); X509certificateholder Certificateholder = X509v3certificatebuilder.build (Contentsigner); Certificate Certificate = Certificateholder.toasn1structure (); WriteFile ("H:/certtest/ca.cer", Certificate.getencoded ());} /** * Generate User certificate */@Testpublic void Testgenzhangsancert () throws Exception {X509v3certificategenerator Certgen = new X509v3cer Tificategenerator (); Certgen.setissuerdn (new X500principal (Dn_ca)); Certgen.setnotafter (New Date ( System.currenttimemillis () + () () (), Certgen.setnotbefore (New Date ()), Certgen.setpublickey ( Getzhangsanpublickey ()); Certgen.setserialnumber (Biginteger.ten); Certgen.setsignaturealgorithm (SIG_ALG); Certgen.setsubjectdn (New X500principal (Dn_zhangsan)); X509Certificate certificate = certgen.generate (Getrootprivatekey ()); WriteFile ("H:/certtest/zhangsan.cer", Certificate.getencoded ());} /** * Verify root certificate signature */@Testpublic void Testverifyrootcert () throws Exception {CertificatefaCtory certificatefactory = certificatefactory.getinstance ("the"); FileInputStream instream = new FileInputStream ("H:/certtest/ca.cer"); X509Certificate certificate = (x509certificate) certificatefactory.generatecertificate (instream); SYSTEM.OUT.PRINTLN (certificate); Signature Signature = signature.getinstance (Certificate.getsigalgname ()); signature.initverify (certificate); Signature.update (Certificate.gettbscertificate ()); Boolean legal = Signature.verify (Certificate.getsignature ()); SYSTEM.OUT.PRINTLN (legal); /** * Verify User certificate signature */@Testpublic void Testverifyzhangsancert () throws Exception {certificatefactory certificatefactory = Cert Ificatefactory.getinstance ("the"); FileInputStream instream = new FileInputStream ("H:/certtest/zhangsan.cer"); X509Certificate certificate = (x509certificate) certificatefactory.generatecertificate (instream); System.out.println (Certificate.getpublickey (). GetClass ()); Signature Signature = signature.getinstance (Certificate.getsigalgname ()); Signature.initverify (GETROOTPUBlickey ()); Signature.update (Certificate.gettbscertificate ()); Boolean legal = Signature.verify ( Certificate.getsignature ()); SYSTEM.OUT.PRINTLN (legal); /** * Generate certificate Request file */@Testpublic void TESTGENCSR () throws Exception {x500name subject = new X500name (Dn_zhangsan); Asymmetrickeyparameter keyparameter = Privatekeyfactory.createkey (Getzhangsanprivatekey (). getEncoded ()); Subjectpublickeyinfo publickeyinfo = Subjectpublickeyinfofactory.createsubjectpublickeyinfo (KeyParameter); Pkcs10certificationrequestbuilder Certificationrequestbuilder = new Pkcs10certificationrequestbuilder (subject, Publickeyinfo); final Algorithmidentifier sigalgid = new Defaultsignaturealgorithmidentifierfinder (). Find (SIG_ALG); Final Algorithmidentifier digalgid = new Defaultdigestalgorithmidentifierfinder (). Find (Sigalgid); Bcrsacontentsignerbuilder Contentsignerbuilder = new Bcrsacontentsignerbuilder (Sigalgid, digAlgId); Pkcs10certificationrequest certificationrequest = Certificationrequestbuilder.build (contentSignerBuilder.build(Keyparameter)); System.out.println (certificationrequest); WriteFile ("H:/CERTTEST/ZHANGSAN.CSR", certificationrequest.getencoded ( ));} /** * Generate a user certificate based on a certificate request file, essentially using the root certificate private key for its signature */@Testpublic void TESTZHANGSANCERTWITHCSR () throws Exception {byte[] encoded = Rea Dfile ("H:/CERTTEST/ZHANGSAN.CSR"); Pkcs10certificationrequest certificationrequest = new Pkcs10certificationrequest (encoded); Rsakeyparameters parameter = (rsakeyparameters) Publickeyfactory.createkey ( Certificationrequest.getsubjectpublickeyinfo ()); Rsapublickeyspec KeySpec = new Rsapublickeyspec (Parameter.getmodulus (), parameter.getexponent ()); String algorithm = Algorithmmap.get (Certificationrequest.getsubjectpublickeyinfo (). Getalgorithm (). GetAlgorithm (). ToString ()); PublicKey PublicKey = keyfactory.getinstance (algorithm). Generatepublic (KeySpec); System.out.println (Certificationrequest.getsubject ()); X509v3certificategenerator Certgen = new X509v3certificategenerator (); Certgen.setissuerdn (new X500Principal (DN_CA)) ; Certgen.setnotafter (New Date (System.currenttimemillis () + (+) * * * * * + *); Certgen.setnotbefore (new Date ()); Certgen.setpublickey (PublicKey) ; Certgen.setserialnumber (Biginteger.ten); Certgen.setsignaturealgorithm (Algorithmmap.get ( Certificationrequest.getsignaturealgorithm (). Getalgorithm (). toString ()); Certgen.setsubjectdn (New X500principal (Certificationrequest.getsubject (). toString ())); X509Certificate certificate = certgen.generate (Getrootprivatekey ()); WriteFile ("H:/certtest/zhangsan.cer", Certificate.getencoded ());} Public Privatekey Getrootprivatekey () throws Exception {return PrivateKey.class.cast (ReadKey ("h:/certtest/ Kingyea.private "));} Public PublicKey Getrootpublickey () throws Exception {return PublicKey.class.cast (ReadKey ("h:/certtest/ Kingyea.public "));} Public Privatekey Getzhangsanprivatekey () throws Exception {return PrivateKey.class.cast (ReadKey ("h:/certtest/ Zhangsan.private "));} Public PublicKey Getzhangsanpublickey () throws Exception {return PublicKey.class.cast (ReadKey ("h:/certtest/ Zhangsan.publiC "));} Public byte[] ReadFile (String path) throws Exception {FileInputStream cntinput = new FileInputStream (path); Bytearrayoutputstream BAOs = new Bytearrayoutputstream (), int b = -1;while ((B=cntinput.read ())!=-1) {baos.write (b);} Cntinput.close (); byte[] contents = Baos.tobytearray (); Baos.close (); return contents;} public void WriteFile (String path, byte[] content) throws Exception {FileOutputStream fos = new FileOutputStream (path); Fos . write (content); Fos.close ();} public void WriteObject (String path, Object object) throws Exception {ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream (path)); Oos.writeobject (object); Oos.close ();} Public Object ReadObject (String path) throws Exception {ObjectInputStream ois = new ObjectInputStream (New FileInputStream (path)); O Bject obj = Ois.readobject (); Ois.close (); return obj;} Public Key ReadKey (String path) throws Exception {ObjectInputStream ois = new ObjectInputStream (new FileInputStream (PATH) ); Key key = Key.class.cast (Ois.readobject ()); ois.cLose (); return key;}} 

After the root certificate is generated, double-click Open, Windows prompts: The CA root certificate is not trusted. To enable trust, install the certificate to the trusted Root Certification Authorities store. After you install the root certificate that you generated to a trusted root certification authority, you will find that the user certificate it issued is also trusted.

Digital certificate of Java security

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.