Maintenance and generation of digital certificates in Java

Source: Internet
Author: User
Tags aliases cas dname

Keytool.exe in Java can be used to create digital certificates, where all digital certificates are stored in a certificate library in a single piece (in the form of aliases), and a certificate in the certificate store contains information about the private key of the certificate, the public key, and the corresponding digital certificate. A certificate in the certificate store can export a digital certificate file, and the digital certificate file includes only the principal information and the corresponding public key.
Each certificate store is a file that has an access password that, when it is first created, automatically generates a certificate library and requires that you specify a password to access the certificate store.
When you create a certificate, you need to fill in some information about the certificate and the private key password for the certificate. This information includes cn=xx,ou=xx,o=xx,l=xx,st=xx,c=xx, which means:
CN (Common name and last name)
OU (Organization Unit organizational unit name)
O (Organization organization name)
L (locality city or region name)
ST (state or province name)
C (Country country name)
You can use interactive to let the ToolTip enter the above information, or you can use the parameters:-dname "Cn=xx,ou=xx,o=xx,l=xx,st=xx,c=xx" to automatically create.
  1. Example
As shown in the following sentence, create a certificate interactively, specify the certificate library as Abnercalib, create a certificate with an alias of Abnerca, which specifies to be generated with the RSA algorithm,
With a specified key length of 1024, the certificate is valid for 3,650 days: Keytool-genkey-alias abnerca-keyalg rsa-keysize 1024-keystore d:/abnercalib-validity 3650

The KeyStore password can be set by itself. As shown in the following:

  

In the last step, we entered the CN, representing the abbreviation of China, can also be directly input "China" two words.

To export a certificate to a certificate file
such as: Keytool-export-alias abnerca-file d:/abnerca.cer-keystore d:/abnercalib
The certificate that is alias Abnerca in certificate store Abnercalib is exported to the Abnerca.cer certificate file.
It contains the information of the certificate principal and the public key of the certificate, excluding the private key, which can be exposed as shown in:

  

  2. View certificate information through a certificate file
by command: Keytool-printcert-file d:/abnerca.cer can view information about the certificate file.
You can also double-click the resulting certificate file in Windows to view it directly.

Issuance of digital certificates (signature)
We created the digital certificate above, but these digital certificates have not been verified by the authoritative CA (that is, signed). In general, we need to send these certificates to the authoritative CA and request their signature to confirm that the digital certificate has been trusted by the customer.
Below we will imitate ourselves as an authoritative digital certification authority CA, which will use its own private key to issue other certificates. This is the issuing process: we ourselves are CAs, we ourselves have a self-signed digital certificate stored in the digital certificate library. In the digital certificate library, this is our CA digital certificate, which contains the private key, the public key, and the principal information of our CA. The following instruction can create a self-signed digital certificate for a CA:
Keytool–genkey–dname "cn= System Software Co., Ltd., ou= System Software Co., Ltd., o= Mei Sen System Software Co., Ltd., l= Chengdu, st= Sichuan Province, c= China" –alias missionca–keyalg rsa– KeySize 1024–keystore abnercalib–keypass 200100–storepass 100200–validity 3650
Above, we created an alias in Abnercalib this digital certificate library: Missionca, valid for 3,650 days, the algorithm is RSA and the key length is 1024 digital certificate, this certificate's private key password is: 200100, the certificate library access password is: 100200. This certificate, named Missionca, represents our own authoritative CA, which is the authoritative CA for Mason Systems software. In the future we will use this certificate to sign other digital certificates.
Now I want to apply for a digital certificate for myself, I can do this: first create a certificate in the digital Certificate library:
Keytool–genkey–dname "cn= Chai, ou= Mei Sen System Software Co., Ltd., o= Mei Sen System Software Co., Ltd., l= Chengdu, st= Sichuan Province, c= China" –alias abnerca–keyalg rsa–keysize 1024– KeyStore abnercalib–keypass 200100–storepass 100200–validity 3650
This creates a digital certificate with an alias of Abnerca, which we can export as a CER file (see preceding).
Next, we can sign my digital certificate with the self-visa of the CA that was generated in the previous step.
The procedure for CA-Signed digital certificates requires the following procedures, which are self-explanatory:

Package com.security;
Import java.io.*;
Import java.security.*;
Import java.security.cert.*;
Import java.util.*;
Import java.math.*;
Import sun.security.x509.*;
/**
* <p> Description: The program is based on the certificate information of the issuer (CA) (that is, the private key of the CA) to the issuer
* The certificate is signed, the process is to use the CA's certificate and the visa book to refactor the formation of a new certificate </p>
* @author Abnerchai
* @version 1.0
*/

public class Signcert {
public static void Main (string[] args) throws exception{
char[] Storepass = "100200". ToCharArray ();
The access password for the certificate store that holds the CA certificate and the visa book
char[] Cakeypass = "200100". ToCharArray (); Access password for//CA digital certificate entry
String alias = "Missionca";
The CA certificate is an alias in the certificate store, and this CA's certificate is used to sign other certificates
String name = "Abnercalib";//The name of the certificate store that holds the CA certificate and the visa book
String newlib = "Signedlib";
The name of the new library, if you need to put the signed certificate into the new library, this is the name of the new vault
char[] Newlibpass = "100200". ToCharArray ();//set access password for new library
String cerfilename = "abnerca.cer";//certificate file name of the visa book
String aliasname = "Abnerca";//the alias name of the visa book in the certificate store
char[] Namepass = "200100". ToCharArray ();
The entry of the visa book in the certificate store's private key password
int n = 3; The validity period of the visa book, in years, starting at the current time
int sn = 200406001;
The serial number can be defined by itself, and the meaning defined here is issued in June 2004, which is the number of CAs issued in the year 001, which requires a unique
String afteraliasname = "abnerca_signed";
Aliases of newly generated signed certificates in the library after signing
char[] Afternewpass = "200100". ToCharArray ();
The password for the private key of the entry for the newly generated signed certificate in the library after the signature
Load Certificate Library
FileInputStream in = new FileInputStream (name);
KeyStore KS = keystore.getinstance ("JKS");//jks is the type of library
Ks.load (In,storepass);
To read the certificate of the issuer (CA) from the certificate library
Java.security.cert.Certificate cl = ks.getcertificate (alias);
read out a CA certificate, where L is the letter L is not a data word 1
Privatekey Privatekey = (privatekey) ks.getkey (Alias,cakeypass);
read out the private key of the CA certificate based on alias and certificate password
In.close ();
Extract the issuer's information from the certificate of the issuer (CA) read out in the certificate library
byte[] Encodl = cl.getencoded ();//Extract the certificate of the code, here is the letter L is not the data word 1
X509certimpl Cimpl = new X509certimpl (ENCODL);
Here is the letter L is not the data word 1, create an object of type X509certimpl according to the certificate's encoding
Gets an object of type X509certinfo based on the object above, which encapsulates the entire contents of the certificate.
X509certinfo Cinfo_first =
(x509certinfo) Cimpl.get (x509certimpl.name+ ".") +x509certimpl.info);
Then obtain the issuer information for the X500name type
X500name issuer = (x500name)
Cinfo_first.get (x509certinfo.subject+ ".") +certificateissuername.dn_name);
Obtain the certificate to be issued, i.e. obtain the certificate of the issuer
Can be obtained from the KeyStore or from the exported certificate file, here are two ways to////////////////////////////////////////////////////////////////////////

Method One, takes start from the exported CER file

///////////////////////////////////////////////////////////////////////////////

/*

Certificatefactory CF = Certificatefactory.getinstance ("n");
The most used digital certificate standard

FileInputStream in2 = new FileInputStream (cerfilename);//Visa Document

Java.security.cert.Certificate C2 = cf.generatecertificate (in2);
Generate certificates that need to be signed
In2.close ();
byte[] encod2 = c2.getencoded ();
X509certimpl cimp2 = new X509certimpl (ENCOD2);

Obtain the details of the visa and then generate a new certificate based on this certificate

X509certinfo Cinfo_second =
(x509certinfo) Cimp2.get (x509certimpl.name+ ".") +x509certimpl.info);
*/

///////////////////////////////////////////////////////////////////////////////

End mode One

///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////

Mode two, read the signed certificate from the certificate store start

///////////////////////////////////////////////////////////////////////////////

Java.security.cert.Certificate C3 = Ks.getcertificate (aliasname);
Read the visa book from the certificate store and generate a new certificate
byte[] encod3 = c3.getencoded ();
X509certimpl Cimp3 = new X509certimpl (ENCOD3);
X509certinfo Cinfo_second =
(x509certinfo) Cimp3.get (x509certimpl.name+ ".") +x509certimpl.info); ///////////////////////////////////////////////////////////////////////////

End Mode II

Sets the validity period of the new certificate, which is valid for the current backward N-year, the new certificate's

The due date cannot exceed the valid date of the CA certificate

Date begindate = new Date ();
Calendar cal = Calendar.getinstance ();
Cal.settime (begindate);
Cal.add (Cal. YEAR,N);
Date endDate = Cal.gettime ();
certificatevalidity CV = new certificatevalidity (begindate,enddate);
Cinfo_second.set (X509CERTINFO.VALIDITY,CV);
Set the serial number of the new certificate

Certificateserialnumber CSN = new Certificateserialnumber (SN);
Cinfo_second.set (X509CERTINFO.SERIAL_NUMBER,CSN);
Set up a new certificate issuer
Cinfo_second.set (x509certinfo.issuer+ ".") +certificateissuername.dn_name,issuer);
The new issuer is read in the CA's certificate

Sets the algorithm for the new certificate, specifying the algorithm used by the CA to sign the certificate is MD5WITHRSA

Algorithmid algorithm = new Algorithmid (algorithmid.md5withrsaencryption_oid);
Cinfo_second.set (certificatealgorithmid.name+ ".") +
CERTIFICATEALGORITHMID.ALGORITHM,ALGORITHM);

Create a new signed certificate

X509certimpl Newcert = new X509certimpl (Cinfo_second);

Signature, signed with the private key of the CA certificate, the algorithm used by the signature is Md5withrsa

Newcert.sign (Privatekey, "Md5withrsa");//This will result in a CA-signed certificate

Put the new certificate in the certificate library
The newly generated certificate can be stored in a new certificate library or stored in the original certificate library.
In the new library, not only does it contain all the entries in the original certificate store,
And added a new entry for this generation. Note that at this point, the newly generated signed certificate is only
Includes public key and principal information and signature information, not including private key information. Here are two ways of doing it.
///////////////////////////////////////////////////////////////////////////

Method One: Deposit to Xinmi Key vault

///////////////////////////////////////////////////////////////////////////

/*

Ks.setcertificateentry (Afteraliasname,newcert);
FileOutputStream out = new FileOutputStream (newlib);
Deposit The new library Signedlib and set the library access password for the new library
Ks.store (Out,newlibpass);
Out.close ();
*/

///////////////////////////////////////////////////////////////////////////

End mode One

///////////////////////////////////////////////////////////////////////////

can also be used in another way, in the original certificate library

In the original library, add a certificate to the original certificate, which is the certificate signed by the original certificate

This new certificate contains the private and private key passwords

///////////////////////////////////////////////////////////////////////////

Mode two, deposit the original KeyStore

///////////////////////////////////////////////////////////////////////////

First read the private key of the visa book in the original library

Privatekey PRK = (privatekey) ks.getkey (Aliasname,namepass);
Java.security.cert.certificate[] Cchain = {Newcert};
Into the original library, the second parameter is the private key of the original certificate, the third parameter is the private key password of the new certificate, the third parameter is the new certificate

Ks.setkeyentry (Afteraliasname,prk,afternewpass,cchain); Replace the password of the original unsigned certificate with a new key

FileOutputStream out2 = new FileOutputStream (name);
Ks.store (Out2,storepass);//deposit in the original library, the second parameter is the access password for the library

///////////////////////////////////////////////////////////////////////////

End Mode II

///////////////////////////////////////////////////////////////////////////

}

}


Run the above program, you can use the Missionca certificate to sign the ABNERCA certificate, run after the abnercalib to add an alias abnerca_signed digital certificate, we export it as a CER file (before the export method see).

At this point, we have durable CA's certificate signed with our digital certificate. In Windows, double-click the exported abnerca_signend.cer file that appears as shown:


The Certificate information column shows "Cannot verify this certificate" because the issuer of our digital certificate Missionca certificate is not installed on the system. We can export a self-signed digital certificate with an alias of Missionca in the certificate library to a CER file and then install it on the system. Double-click to see this certificate again, as shown in:

    

To this, we have obtained a personal digital certificate issued by our own CA signature. and install our own CA certificate into the system as the root certificate of the System trust. As a result, a digital certificate issued by our CA certificate signature will be trusted by the system in the future.

Iv. signing applets with digital certificates

Now suppose our company does a project for XX company, this project needs applets, and these applets need privileges to implement some special functions (such as reading and displaying the contents of the C:/winnt/system.ini file in the client user's system). Then we can issue a digital certificate and sign the digital certificate, then sign our applet with this digital certificate after signing, so that the customer trusts. The process is as follows:

1. Generate a digital certificate for this project signing applet, alias: Mission_water

Generate a digital certificate for the signing of this project as follows:

Keytool–genkey–dname "cn= Software-water company project, ou= System Software Co., Ltd., o= Mason System Software Co., Ltd., l= Chengdu, st= Sichuan Province, c= China" –alias mission_water–keyalg rsa– KeySize 1024–keystore abnercalib–keypass 200100–storepass 100200–validity 3650

2. Use our CA (Missinca) to issue this digital certificate

Then, run the program that we given in the previous section, note: Before you run this program, modify the following parameters:

String cerfilename = "Mission_water.cer";

String aliasname = "Mission_water";

String afteraliasname = "mission_water_signed";


Then run, the program will generate an alias in the Abnercalib certificate store: mission_water_signed digital certificate, this certificate was issued by our CA (Missionca).

Below, we export this certificate with the following instructions:

Keytool-export-alias mission_water_signed-file Mission_water_signed.cer-keystore ABNERCALIB-RFC


A mission_water_signed.cer file is generated.

3. Sign our applet with the digital certificate issued

Now let's do a simple applet with the following code:

Package com.applet;

Import java.awt.*;

Import java.awt.event.*;

Import java.applet.*;

Import javax.swing.*;

Import java.io.*;

public class Showfileapplet extends JApplet {

Private Boolean isstandalone = false;

Private String content = "The contents of the file are:"; Customizing the Prompt Information

Private String FileName = "C://winnt//system.ini";//read out the contents of this file

Private TextArea ta = new TextArea (10,80);//Custom Output box

public string GetParameter (string key, String def) {

Return Isstandalone? System.getproperty (Key, Def):

(GetParameter (key)! = null? GetParameter (Key): Def);

}

Public Showfileapplet () {

}

public void init () {

try {

Jbinit ();

Myinit ();//self-defined method

}

catch (Exception e) {

E.printstacktrace ();

}

}

private void Jbinit () throws Exception {

This.setsize (New Dimension (400,300));

}

/**

* Customize the initialization method, read the contents of a file in the system and save it, then add a

* Visual Output box

*/

private void Myinit () {

String s;

BufferedReader in;

try {

in = new BufferedReader (new FileReader (FileName));

while ((s = in.readline ()) = null) {

Content +=s + "/n";

}

}catch (IOException ex) {

Ex.printstacktrace ();

}

SYSTEM.OUT.PRINTLN (content);

Ta.settext (content);

Getcontentpane (). Add (TA);

}

/*

* Overloaded method, output content

**/

public void Paint (Graphics g) {

Ta.settext (content);

}

Public String Getappletinfo () {

Return "Applet information";

}

Public string[][] GetParameterInfo () {

return null;

}

Static initializer for setting look & feel

static {

try {

}

catch (Exception e) {

}

}

}


Well, this applet is written, so let's get this applet compiled and packaged into a jar file.

Compiling this applet file will generate a Com/applet directory structure under the current directory (the current directory is the classes directory), and in the applet directory there is a showfileapplet.class that goes to the current directory and executes:

Jar CVF Myapplet.jar Com/applet/*.*


A Myapplet.jar file is generated under the current directory.

Then in the current directory (the current directory is the classes directory) to create a new applet directory, dedicated to the applet's jar file, the previously generated digital certificate Library Abnercalib This file is also copied to the applet directory, Also move the Myapplet.jar file that you just generated to the applet directory. Then go to the directory to execute:

Jarsigner-keystore abnercalib Myapplet.jar mission_water_signed

Enter Passphrase for keystore:100200

Enter Key password for mission_water_signed:200100


We signed this applet with mission_water_signed, a digital certificate issued by our CA.

4. Run our applets

Let's write an HTML file to run this signed applet with the following content:

!--showfileapplet.html--> 

 

 

&NBSP;

htmltestpage  

 

Applet will be displayed if your browser supports Java
 


Archive = "./applet/myapplet.jar" &NBSP;

Code = "Com.applet.ShowFileApplet.class"  

Name = "Testapplet" &NBSP;

width = " ",

height = "+" &NBSP;

hspace = "0" &NBSP;

Vspace = "0"  

align = "middle"  



 

 


This HTML file can run applets, but if the browser does not support Java, that is, the JRE is not installed, it will not prompt the user to download the installation. We can use the Java Htmlconverter tool to convert this HTML file, the converted file can be in a JAVA2-enabled browser (whether the browser is set to use the JAVA2 run applet, it will run the applet in the JAVA2 environment, If the browser does not support JAVA2, the required files will be downloaded automatically.

Run Htmlconverter in DOS mode, pop up the picture frame as shown, select the HTML file just as shown in the figure, as shown in:



Click "Convert" to generate an HTML file in the current directory and back up the original HTML file.

The contents of the resulting HTML file are as follows:

!--showfileapplet.html-->



<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 ">

<title> Htmltestpage </title>


<body>

The applet will be displayed if your browser supports Java <br>

<object

ClassID = "CLSID:CAFEEFAC-0014-0001-0001-ABCDEFFEDCBA"

codebase = "http://java.sun.com/products/plugin/autodl/jinstall-1_4_1_01-windows-i586.cab#Version=1,4,1,1"

WIDTH = "HEIGHT" = "testapplet" NAME = "ALIGN" = "middle" vspace = "0" hspace = "0" >

<param NAME = CODE VALUE = "Com.applet.ShowFileApplet.class" >

<param NAME = ARCHIVE VALUE = "./applet/myapplet.jar" >

<param name = Name VALUE = "Testapplet" >

<param NAME = "type" VALUE = "application/x-java-applet;jpi-version=1.4.1_01" >

<param NAME = "scriptable" VALUE = "false" >

<COMMENT>

<embed

Type = "Application/x-java-applet;jpi-version=1.4.1_01"

CODE = "Com.applet.ShowFileApplet.class"

ARCHIVE = "./applet/myapplet.jar"

NAME = "Testapplet"

WIDTH = "400"

HEIGHT = "300"

ALIGN = "Middle"

Vspace = "0"

hspace = "0"

scriptable = False

pluginspage = "Http://java.sun.com/products/plugin/index.html#download" >

<NOEMBED>

</NOEMBED>

</EMBED>

</COMMENT>

</OBJECT>

</body>

Maintenance and generation of digital certificates in Java

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.