We said that information security is relative to system security, it is more focused on encryption, decryption, digital signature, verification, certificate, and more. The system security mainly focuses on whether the system itself has security vulnerabilities, such as common due to software design Impermatics caused by the sky-flying buffer overflow.
The part of the Java language is responsible for encryption. It is JAVA CRYPTO EXTENSTION. It uses open minds that allow users to write the specific implementation of the encryption algorithm. These things are called JCE Provider, JCE providers. Sun itself provides some provider. But I recommend using the bouncy castle's provider. The reason is that it is much more encryption algorithm, and even the new elliptic curve (ECC) algorithm has it. Go http://www.bouncycastle.org / You can find what you want. Bounce Castle, in addition to providing Provider itself, including a S / MIME and an Open PGP JAR package only provider itself, and then two packs are convenient for you to program. For example, After having the S / MIME package, you no longer need to write a large number of code for a very real application such as "Encrypted a string or a piece of article", as long as the S / MIME package is referenced A few categories can soon get it. And the existence of Open PGP makes you more convenient when writing and PGP / GPG interact with Java.
Preparations for procedures that need to be written in Java write information have been clear. Now you are already familiar with the Java language itself, you can write some programs in Java, and these downloaded JAR packs have been downloaded It can be officially started.
At all of all such programs (whether in the constructor of the class, it is good in the initialization function), you must first come first: security.addprovider (new bouncecastleprovider ()); Provider of BounceCaselte Add to the system so that the system is called when the system runs the relevant program is the encryption algorithm in this provider.
Then we can start CA. First, as a CA must have your own pair of public keys and private keys, we must build such a pair. You can use the keypairgenerator object, call the keypairgenerator.getInstance method to generate Key types to generate a suitable instance, such as commonly used RSA, DSA, etc., then call the object of the object to generate a KeyPair object. Then call the corresponding method in the KeyPair object to get the generated The public key and private key in the key pair.
With the public key and private key pair, the following is how to store them. Usually we have to coding these security objects, such as public keys, private keys, certificates, etc., the purpose of the encoding is to put Structure complex security objects become byte streams to store and read, such as DER coding. In addition, the DER encoded by the DER encoded will also be submitted again to make Base64 encoding, so that all bytes in the byte stream becomes all bytes. Printable bytes.
In Java languages, these security objects are basically a GeTENCODED () method. For example:
Byte [] Keybytes = privateKey.Getencoded ();
This saves a private key to the result of DER encoding to a BYTE array. Then you can save this Byte array to any media. If necessary, you can use the Base64 encoder codec class in BC Provider. Code, just like this:
Byte data [] = base64.encode (keybytes);
To read private keys from a file, it should be like this:
PKCS8ENCODEDKEYSPEC Spec = new pkcs8encodedKeyspec (keydata); keyfactory kfac = keyfactory.getInstance ("RSA"); privateKey = kfac.generateprivate (SPEC);
Here, it will be used to encode the RSA private key will automatically follow the PKCS8. Therefore, it is possible to generate a parameter of the constructor of the PKCS8EncodedKeyspec object when the read is read. Then create one The key factory object can generate a RSA private key in accordance with the requirements. It is clear that the keydata here should be the same as the keybytes above. In order to improve the security of the system, the private key will be used after the DER encoding will use a password. Encryption and then store it in the file system. When using the private key, if there is no correct password, it is not possible to restore the private key.
Save the certificate and save the private key Similar. There is also a getENCODED method in thecertificate object.
This time, you should tell these security objects very skilled in the file system and memory. This is important to implement CA. Below I will talk about the principal method in the certificate. : DN.
Above we talk about how to generate a key pair, and how to turn back and forth between file systems and memory such as public key, private key, certificate, etc., these are the basic skills of the CA, now we tell CA The basic principle and how to use the main name structure DN (DISTINGUISH NAME) to represent the body in each certificate.
A certificate is a certificate of confirmation of an authority to a subject. A certificate indicates that an authority confirmed that it is itself, not other kind of top replacement. The main body can be a person, or may not , For example, when a security service is required, the server needs to issue a certificate. The main body of this certificate is a server. The authority of the signing certificate is called CA, the authority itself is also a body. Authority passed A series of information containing a series of information containing the main body to be authenticated is digital signature to indicate that the agency is recognized to it. A TBS containing information about the main body to be authenticated is coupled to The byte extension generated by using its own private key is formed together, constitutes a standard X509 certificate.
One TBS contains the following main information:
Certificate version, usually 3 (x509v3)
The serial number of the certificate, the RFC3280 specifies that each CA must ensure that the serial number of each certificate it issues is unique, and the serial number can only use non-negative integers.
The main name of the issuer (CA), a DN object.
The validity period of the certificate is two time values, indicating when the certificate starts to take effect and starts to be invalid.
The main body of the subject to be certified is also a DN object.
The public key of the subject to be certified, any security application can start using the public key to securely communicate with the public key to confirm the validity of the certificate.
If the X509V3 certificate, that is, the version number is 3, there is a certificate extension information field, which can add some other information in the certificate.
Let's take a look at the main name structure of the main body: DN. This knot is a collection of a property. Each attribute has a property name and attribute value. Its role is to indicate "Who I", that is, Who is the public key to this certificate, this certificate is owned by the public key.
A string is usually used to represent a DN structure, which illustrates the types and values of each attribute in this structure:
C = CN; s =
Beijing
; L =
Beijing
; O = pku; ou = ICST; cn = Wolfenstein
Here C is the national and regional code, S and L are regional code, and s is equivalent to the level of provincial or state, L is equivalent to the city level, o is the name of the organization, OU is the secondary organization name, CN is the main body Common name. The type of attributes such as C, S, L, etc. is relatively fixed, such as C is usually used to represent national and regional code, and some other types of information can also be added in the DN structure. Generally, it is also expressed in "XXX = XXX".
Let's explain how to construct a body name object in the Java language.
The X509Name object is used in BC Provider to represent DN, and the step of constructing an X509NAME is generally as follows:
Construct two vector objects first, used to indicate attribute names and attribute values:
Vector oids = new vector (); Vector attributes = new vector ();
Then add one of the property names in the Vector name of the OIDS to indicate the attribute name:
Oids.addelement (x509name.c); ......
Oids.addelement (x509name.cn);
There are several constants in the X509Name object, such as X509Name.c. There are also X509name.sts, etc., can correspond to the examples mentioned above.
Then add the attribute value to the Attributes object:
Attributes.addeElement ("CN");
......
Attributes.addeElement ("Wolfenstein");
Finally, you can construct an X509Name object:
X509Name Subjectdn = New X509Name (OIDS, Attributes);
In this way, our body name structure has established it.
Below we can talk about the key part, that is how to use the Java program to complete the most important function of CA, sign a certificate.
To do CA, the first step is to prepare your own certificate and private key. How to read it from the file from the file. From the file system, the code reads the certificate is as follows:
CertificateFactory Certcf = CertificateFactory.GetInstance ("X.509"); x509certificate cace = Certcf.GenerateCertificate (CERTBIS);
Here CERBIS is an object of an InputStream. For example, a standard X509V3 format has a input stream formed by a certificate file.
The second step is to get the input from the user, then construct the main name structure DN, how to construct DN last time, how to get input from the user, this is not within the scope of this article.
The next step is to obtain the public key of the user, it corresponds to the certificate he needs. There are also many CA practices to generate a pair of key pairs for the user, then put the public key to the certificate to the user. This It should be seen that the actual needs should be selected.
Now everything is ready, you can sign a certificate, the following code illustrates this process:
/ / Construct a certificate generator object
X509V3CertificateGenerator Certgen = New X509V3CERTIFICATEGENERATORTOR ();
// Get a signator's main name (DN) // from the CA certificate, there is a little skill, we have to convert the // defined in the JCE to indicate the object X500Principal of the DN to transform the corresponding corresponding to the // bc provider The object X509Name // first reads the DN of CA from the CA's certificate to perform DER Code DerinputStream DNSTREAM = New DerinputStream (New ByTearrayInputStream (Cacert.getsubjectx500Principal (). GetENCODED ())); // Raise the word immediately after the encoding Read the DER encoding object DerconstructedSequence DNSEQUENCE = (DERCONSTRUCTEDSEQUENCE) DNSTREAM.READSEQUENCE DNSEQUENCE = (); // Create X509Name // object with the read DER encoding object, and set to "issuer DN" Certgen in the certificate generator .setissuerdn (New X509Name (DNSEQUENCE))); // Set "Receiver DN" Certgen.setSubjectDn (SubjectDN) in the Certificate Generator; // Sets some extension fields, including the public key of the issuer and // recipient identification certGen.addExtension (X509Extensions.SubjectKeyIdentifier, false, createSubjectKeyId (keyToCertify)); certGen.addExtension (X509Extensions.AuthorityKeyIdentifier, false, createAuthorityKeyId (caCert.getPublicKey ())); // set the validity of the certificate and a serial number certGen.setNotBefore ( StartDate); Certgen.setnotafter (Enddate); Certgen.setSerialNumber (SerialNumber); // Setting the signature algorithm In this example, the RSA // signed after MD5hash, and sets the public key Certgen.setsignatureAlgorithm ("MD5withRSA"); Certgen.SetPublicKey (KeyTocertify); // If everything is fine, you can generate a certificate. X509Certificate CERT = NULL; CERT = Certgen.Generatex509certificate (CaprivateKey);
Here is a function of the generated issuer's public key identifier used above:
Protected AuthorityKeyIdentifier CreateAuthorityKeyId (publickey pubkey) {authorseKeyidentifier authkeyid = NULL DITHKEYID = NULL;
try {ByteArrayInputStream bIn = new ByteArrayInputStream (pubKey.getEncoded ()); SubjectPublicKeyInfo info = new SubjectPublicKeyInfo ((DERConstructedSequence) new DERInputStream (bIn) .readObject ()); authKeyId = new AuthorityKeyIdentifier (info);} catch (IOException e) { System.err.println ("Error Generating SubjectKeyIdentifier:" E.TOString ()); System.exit (1);} Return AuthKeyId;}
The function of generating the main public key identifier is similar to the above, replacing the AuthorityKeyIdentifier to SubjectKeyIdentifier.
It should be noted here that the public key of the CA is also in a certificate. This certificate is characterized by the issuer DN and the recipient DN, that is, this certificate is the certificate you have issued by CA himself, that is "Self-signed Certificate", it is the public key of the CA itself, and the private key used to sign is the private key corresponding to the public key. Generally, each CA must have such a certificate unless the CA is not root. CA, that is, its authority is not proved by itself, but proves its superior CA. However, finally there is a root CA, which is trustworthy for users of various secure applications.
Here we have already finished using the most basic features of the CA with Java, how to read the user information from the PKCS # 10 format certificate request file, and then issue the public key directly.
I have already implemented a CA in front of Java. But they have a feature, that is, the user's information is available at the scene, can't do the application and check phase separation. Now we have to tell the PKCS # 10 certificate Request file. Its role is to separate the application and the issuance.
The main information in the PKCS # 10 certificate request structure contains the main name (DN) of the issuer (certificate applicant) and his public key. Therefore, after getting a PKCS # 10 certificate request, you can get it. To any and issue the certificate-related information, then sign your certificate with its own private key.
Use BC Provider to construct a certificate request format in Java to call its constructor, this function is as follows:
PKCS10CERTIFICATIONREQUEST (Java.lang.String SignatureAlgorithm, X509Name Subject, Java.security.publicKey Key, Asn1set Attributes, Java.security.priVateKey SigningKey)
Its parameters are self-signed algorithms, DN, certificate applicants' public key, and additional property set (which is the extension information to apply for the certificate), the private key for the application certificate, only the private key for the application certificate is only It is used to make a self-signature, do not appear in the certificate request, the purpose of the self-signature is to ensure that the public is true for the applicant.
Calling the object's getEncoded () method can make it DER encoding, then store it, the object is still another constructor: pkcs10certificationRequest (byte [] bytes) This constructor is to directly remove this from the stored DER encoding. Object is restored.
The code issued by the certificate request structure is as follows, where the CSR is a PKCS10CERTIFICATIONREQUEST structure that has been acquired:
PublicKey SubjectPublicKey = CSR.getPublicKey (); CertificationRequestInfo CSRInfo = CSR.getCertificationRequestInfo (); X509Name SubjectDN = CSRInfo.getSubject (); ASN1Set Attributes = CSRInfo.getAttributes (); Thus, the DN body applicant, the applicant's public key, Applicants want to get attributes filled in in the certificate extension information, and the rest is the same as the user, and other information is generally the applicant cannot be decided. In addition, there is no clear information in the other certificate request format. Give it out, that is, the validity period of the certificate, this should ask the user separately, or save it with other methods. Ezerg Programming