Java Security Communication, Digital Certificate and Digital Certificate Application Practice ABNERCHAI (Chai Zheng) June 2004 Summary: In this article, I show you how to implement in Java with a detailed language and a lot of pictures and complete program source code. Message summary, message verification code reaches secure communication, and generates a digital certificate with Java, and uses the program to sign a digital certificate, and the process of signing the access rights of Applet with the signed mathematical certificate, gives all examples. Detailed code. Through this article, you can learn the following knowledge: • How to communicate during the program • What is how to generate a message summary • What is how to generate a message verification code • How to generate and maintain a digital certificate library using Java tools • How to use programs to numbers Certificate Verification Signature • How to Use Digital Certificate to Apply Access to Applet Keywords: Message Summary, Message Verification Code, Fingerprint, Encryption, Security, Java, Digital Signature, Applet, Digital Certificate First, Basic Knowledge Computer Security Communication , Often use the message summary and message verification code to ensure that the data transmitted has not been modified by a third party. The message summary is the result of calculating the raw data in accordance with a certain algorithm, which mainly detects whether the original data is modified. The message summary is different from the encryption, and the encryption is transformed to the original data. It can get raw data from the transformed data, and the message summary is part of the information from the original data, which is much less than the original data, so the message summary can be seen It is the fingerprint of raw data. Example: The following program calculates a string message summary package com.MessageDigest; import java.security. *; Public class digestpass {public static void main (String [] args) throws exception {string str = "Hello, i Sent To YOU 80 Yuan. "; MessageDigest MD = MessageDigest.getInstance (" MD5 "); // Commonly used MD5, SHA algorithm and other md.Update (Str.GetBytes)); // Incoming original word String Byte [] RE = md.digest (); // Calculation message summary is placed in a BYTE array / / Summary Summary Summary String Result = ""; for (int i = 0; I package com.messagedigest; import java.io. *; import java.security *;. public class DigestInput {public static void main (String [] args) throws Exception {String fileName = "test.txt"; MessageDigest md = MessageDigest. getInstance ( "MD5"); FileInputStream fin = new FileInputStream (fileName); DigestInputStream din = new DigestInputStream (fin, md); // configured input stream // DigestOutputStream dout = new DigestOutputStream (fout, md); // using an input ( Out) The stream can control when you start and turn off calculation summary // can also not control, calculate the whole process // initially start calculation from the beginning, as we can close, then start from a part, as follows: //din.on (face); int b; while ((b = din.read ())! = - 1) {// Do some to process // if (b == '$') DIN. On (TRUE); // When you encounter symbols in a file, you will start calculation} byte [] re = md.digest (); // Get message summary // Summary Summary Summary String Result = " "; for (int i = 0; i For example, the following program can utilize a common key to calculate the verification code for the message summure Package Com.mac; import java.io. *; import java.security. *; Import javax.crypto. *; Import javax.crypto. Spec. *; public class mymac {public static void main (String [] args) throws exception {// This is a message summary string string str = "teststring"; / / common key coding, this can be calculated by other algorithms Come out byte [] KB = {11, 105, -119, 50, 4, -105, 16, 38, -14, -11, 21, -95, 70, -15, 76, -74, 67, -88, 59 , -71, 55, -125, 104, 42}; // Get a common key SECRETKEYSPEC K = New SecretKeyspec (KB, "HMACSHA1"); // Get MAC object Mac m = mac.getInstance ("hmacmd5"); m .init (k); M.Update (Str.getbytes); Byte [] RE = m.dofinal (); // Generate message code // Switch the message code to a string String Result = ""; INT i = 0; I So, when both parties communicate, a message summary is encrypted with their own private key (ie, then send their digital certificate and data and signature messages to B, B) Digital Certificate, If the digital certificate is reliable, it is trusted by the authority CA verification, it can use A to decrypt the message summary (this process confirms the sending data at the same time to decrypt the message summary) ), Then verify that the data is correct without mistakenness by decryption. With this principle, we can break through the permissions of Java's Applet applet in the browser, because the default Applet permission control does not allow it to access everything of the operating system level. So we can use our digital certificate to sign the Applet, and then the client receives the applet, the system automatically views the digital certificate signed by the applet and provides the end user to determine whether the digital certificate is recognized. If the user confesses, The applet has access to the system's permissions. Second, the generation and maintenance method of the digital certificate in Java, the preface, the keytool.exe in Java can be used to create a digital certificate, all digital certificates are deposited in the form of a certificate library in the form of one (using the alias). One certificate in the certificate library contains the private key, public key, and corresponding digital certificate of the certificate. One certificate in the certificate library can export the digital certificate file, and the digital certificate file includes only the main information and the corresponding public key. Each certificate library is a file composition. It has access your password. When you created first time, it automatically generates a certificate library and requires the specified password to access the certificate library. When you create a certificate, you need to fill out some information of the certificate and the private key password corresponding to the certificate. These information include CN = XX, OU = XX, O = XX, L = XX, ST = XX, C = XX, what they mean: CN (Common Name Name and last name) OU (Organization Unit Organized Unit Name) o Organization Organized Name) L (Locality City or Region Name) ST (State State or provincial name) C (Country country name) can use interactive to make tool tips to enter the above information, or parameter -DName "CN = XX, OU = XX, O = XX, L = XX, ST = XX, C = XX "is created. Second, the example is a certificate to create a certificate using an interactive, specifying a certificate library to ABNERCALIB, creating a certificate called Abnerca, specifies the generated by the RSA algorithm, and the specified key length is 1024, the certificate is valid for 3,650 days: C : /J2SDK1.4.1_01/MyKeyStore> KeyTool -Genkey -Arias abnerca -keyalg rsa -keysize 1024 -keystore abnercalib -validity 3650 As shown below: The last step in the figure, we entered CN, represent China's abbreviation, also You can enter the "China" two words directly. Third, the certificate of the certificate • The certificate of the certificate is: keytool -list -keystore abnercalib will display all the certificates of the ABNERCALIB certificate library: as shown in: KeyTool -List -Alias Abnerca -keystore abnercalib will display the ABNERCALIB certificate library Information about the certificate called Abnerca. As shown in the figure below: Another example: keytool -list -v -alias abnerca -keystore abnerCalib will display the details of the certificate (-V parameter) as shown below: • Export the certificate to the certificate file such as: KeyTool -Export -Alias Abnerca -file abnerca.cer -keystore abnercalib will export an aliasing of the certificate library ABNERCALIB to the ABNERCA certificate to the abnerca.cer certificate file, which contains the information of the certificate body and the public key of the certificate, does not include the private key, can be disclosed, as follows Diagram shows: The certificate file exported above is a binary code file, which cannot be properly displayed with a text editor. Therefore, it is not possible to use the -RFC parameter to encode the output of a printable editor. Such as: keytool -export -alias abnerca -file abnerca.cer -keystore abnercalib -storepass 100200 -rfc This command specifies the access password for the certificate library in the command line, and specifies to view the encoded manner. 3. View the certificate of the certificate via the certificate file through the command: keytool -printcert -file abnerca.cer can view the information of the certificate file. You can also view the certificate files you generated in Windows. • Delete KeyTool command line parameters - DELETE can delete entries in the keystore, such as: KeyTool -Delete -alias abnerca-readystore abnercalib This command deletes this ABNERCALIB library. • Modifications to the certificate entry, such as: keytool -keypasswd -alias abnerca -keystore abnercalib can modify the entry of the AbnerCA in the abnerCAlib certificate library in an interaction. KeyTool -Keypass WD -ALIAS ABNERCA -KEYPASS 123456 -NEW 200100 -STOREPASS 1002 00 - KeyStore ABNERCALIB This line of command is in a non-interactive manner to modify the password of the certificate that is not the certificate of ABNERCA in the new password 123456, the 200100 in the line refers to the The original code of the certificate, 1002 00 is the password of the apparent library. Third, the issuance of the digital certificate (signature) We create a digital certificate above, but these digital certificates have not had a confirmation of the authority CA (ie signature). In general, we need to send these certificates to authoritative CA and apply for its signature to confirm that the digital certificate is trusted. Below we will imitate yourself is an authoritative Digital Certification Authority CA, which will use your own private key to issue other certificates. This issuance process is like this: we are CA, we have a self-friendly digital certificate in the digital certificate library. In the digital certificate library, our CA digital certificate, which contains the private key, public key, and the main information of our CA. The following instructions can create a CA's self-signed digital certificate: keytool -genkey -dname "CN = Myssen System Software Co., Ltd., OU = Myssen System Software Co., Ltd., O = Mesen System Software Co., Ltd., L = Chengdu, ST = Sichuan, c = China "-alias mission 1024 -keystore abnercalib -keypass 200100 -storepass 100200 -Validity 3650, we created an alias: missionca in the ABNERCALIB digital certificate library, valid 3650 days, the algorithm is a digital certificate for RSA and the key length is 1024. The private key password for this certificate is: 200100, the access password of the certificate library is: 100200. This alias for Missionca represents our own authority CA: Myssen System Software Co., Ltd. This authority CA. We will use this certificate to sign other digital certificates. Now I have to apply for a digital certificate, I can do this: First create a certificate in the digital certificate library: keytool -genkey -dname "CN = Chai Zheng, OU = Myssen System Software Co., Ltd., o = Mesen system software limited Company, L = Chengdu, ST = Sichuan, C = China "-alias abnerca -keyalg rsa -keysize 1024 -keystore abnercalib -keypass 200100 -storepass 100200 -Validity 3650 This created a digital certificate with ABNERCA, we can Export it as a CER file (see before). Next, we can sign my digital certificate with the self-signed certificate of the previously generated CA. The process of the CA signature digital certificate needs to be performed by the following procedure, this program is 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. *; / ** * Description: This program is paired according to the certificate information of the issuer (CA) (ie the CA's private key) Signing by the certificate of the issuer *, the process is to use the CA certificate and the visa book to refactor to form a new certificate p> * @Author abnerchai * @version 1.0 * / public class signter {public static void main (String [] args) throws exception {char [] storepass = "100200" .tochararray (); // Store CA certificate and visa password CHAR [] CAKEYPASS = "200100" .tochararray (); // CA digital certificate entry Access password string alias = "missionca"; // CA certificate alias in the certificate library, this CA certificate is used to sign other certificates String name = "abnercalib"; // Store CA certificate and The name of the certificate library by the visa book String newlib = "signedlib"; / / The name of the new certificate library, if you need to put the signature certificate into the new library, this is the name char [] newlibpass = "100200". TOCHARARRAY (); // Set the access password for the new library string cerfilename = "abnerca.cer"; // Certificate file name String aliasName = "abnerca"; // V. Alias alias char [] NamePass = "200100" .tochararray (); // The entry of the visa book in the private key password INT n = 3; // Validity period of the visa book, in the year, start calculating int SN = 200406001; // The serial number can be defined by himself. The meaning defined here is issued in June 2004. It is this year. The number of the degree CA is issued with 001 calculation, requiring unique string anarchiasName = "abnerca_signed"; // The newly generated named certificate in the library is a name char []AfternewPass = "200100" .tochararray () ; // Sign, newly generated certificate of certificates in the library // load certificate library fileInputstream in = new fileinputstream (name); keystore ks = keystore.getInstance ("jks"); / / Jks is the type of certificate library Ks.Load (in, storepass); // reads a certificate java.security.cert.certificate cl = ks.GetCertificate (alias); // read from the certificate library Out of a CA certificate, where l is the letter L is not a data word 1 privateKey privatekey = (Privatekey); // read out the private key in. Close () of the CA certificate based on the alias and certificate password; // Extract from the issuer (CA) of the certificate library The information of the issuer Byte [] encodl = cl.getencoded (); // Extract the code encoding, here is the letter L is not the data word 1 x509certimpl cimpl = new x509certimpl (eNCodl); // This is the letter L is not a data word 1, Creating an object // based on the object of the certificate // According to the object above, the object is obtained, which encapsulates all the contents of the certificate. X509CertInfo cinfo_first = (X509CertInfo) cimpl.get (X509CertImpl.NAME X509CertImpl.INFO "."); "." // then obtained X500Name issuer type information X500Name issuer = (X500Name) cinfo_first.get (X509CertInfo.SUBJECT CertificateIssuerName .Dn_name); // Get the certificate to be issued, that is, obtain the certificate // can be obtained from the keystore, or can be obtained from the exported certificate file, two ways /// Method 1. Using the start /// / * ceertificate.getInstance ("X.509") from the exported CER file ("X.509"); // X.509 is the most digital certificate standard fileInputstream in2 = new fileInputStream (CERFILENAME); // Visa file java.security.cert.certificate C2 = cf.generatecertificate (in2); // Generate certificate in2.close (); byte [] encod2 = c2.getencoded () ; X509CertImpl cimp2 = new X509CertImpl (encod2); // get the details signed certificate, and then generate a new certificate X509CertInfo cinfo_second = (X509CertInfo) cimp2.get (X509CertImpl.NAME X509CertImpl.INFO ".") according to this certificate; * / // / / END method 2, second, read from the certificate library START /// java.security.cert.certificate C3 = ks.getCertificate (aliasname); // Read the visa book from the certificate library, then generate new certificate BYTE [] encod3 = c3.getencoded (); x509certimpl cimp3 = new x509certimpl (eNCod3); x509certinfo cinfo_second = (X509certinfo) cimp3.get (x509certimpl.name "." X509certimpl.info); // // End mode 2 // // Set the validity period of the new certificate, make it valid for the current N-year, new Certificate // Dead date can not exceed the effective date of the CA certificate = 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 the issuer CINFO_SECOND.SET (x509certinfo.issuer "of the new certificate." CERTIFICATESSUERNAME.DN_NAME, ISSUER); / / The new issuer is the algorithm for the // set new certificate in the CA certificate, specifying CA cinfo_second.set ( "." CertificateAlgorithmId.NAME CertificateAlgorithmId.ALGORITHM, algorithm);; // create a new certificate after signature X509CertImpl newcert = signature algorithm used by the certificate md5WithRSA AlgorithmId algorithm = new AlgorithmId (AlgorithmId.md5WithRSAEncryption_oid) is NEW X509CERTIMPL (CINFO_SECOND); // Signature, use the private key of the CA certificate to sign, the algorithm for the signature is MD5withrsa newcert.sign (PrivateKey, "MD5withRSA"); // This has obtained the certificate after the CA signature ///// Deposit a new certificate into the certificate library // put the newly generated certificate into a new certificate library, or deposit the original certificate library, // store the new certificate library, the new certificate library not only contains the original certificate library All entries, / / and newly adding an entry produced. Note that at this time, the certificate after the newly generated signature is only // including the public key and the main information and the signature information, and does not include private key information. It will be given here. // / / mode 1: Deposit of new keystore /// / * ks.setcertificateEntry (FileoutPutStream out = new fileoutputstream (newlib); // store the new library SignedLib, and set up a new library Library access password ks.Store (out, newlibpass); out.close (); * / / / / / END mode 1 / / / / / can also use another way, deposit in the original certificate library / / In the original library, an additional certificate is added in the original certificate library, which is the original certificate after signature // this new certificate contains private key and private key password // / / mode 2, deposit into the original keystore /// / Prior to read the private key privateKey PRK = (privatekey) of the visa book in the original library; java.security.cert.certificate [] cchain = {newcert}; // Enter the original library, the second parameter is the private key for the original certificate, the third parameter is the private key password of the new certificate, the third parameter is a new certificate Ks.setKeyentry (AfteraliasName, PRK, AFTERNEWPASS, CCHAIN); // Instead of replacing the original password fileOutputStream out2 = new fileoutputstream out2 = new fileoutputstream out2 = new fileoutputstream (name); // Store the original library, the second parameter is the access password for the library // // end mode 2 ///}} Run the above program to use the MissionCA certificate to issue an ABNERCA certificate, add a digital certificate that is not named abnerca_signed in ABNERCALIB, and we export it as a CER file (export The method is seen). At this point, we have been signed with our digital certificate with the CA certificate. In Windows, double-click the exported abnerca_signend.cer file, as shown below: The certificate information column shows "Can't verify the certificate" above, because our digital certificate issuer MissionCA certificate is not installed In the system. We can export the self-signed digital certificates of the certificate library to the CER file and then install it into the system. Check again and double-click this certificate, as shown below: At this point, we have obtained a personal digital certificate issued by our own CA signature. And install our own CA certificate into the system to become a system trust. So, as long as it is a digital certificate issued by our CA certificate signature, it will be trusted by the system. Fourth, using the digital certificate to Applet Sign Now, our company is a project to XX, this project needs to be used in this project, and these applets need privileges to implement some special features (such as reading the client user system C: / The content in the WinNT / System.ini file is displayed). Then we can give a digital certificate and sign this digital certificate, then sign our applet with this digital certificate after signature to enable customer trust. The specific process is as follows: 1. Generate a digital certificate for this item signing applet, an alignment is set: Mission_water generates a digital certificate for this project signature as follows: keytool -genkey -dname "CN = Mesen software - water company project, OU = Myssen System Software Co., Ltd., O = Mesen System Software Co., Ltd., L = Chengdu, ST = Sichuan, C = China "-alias mission_water -keyalg rsa -keysize 1024-kestore abnercalib -KeyPass 200100 -StorePass 100200 -Validity 3650 II, use our CA (Missinca) to issue this digital certificate and then run our program given in the previous section III, note: Before running this program, modify the following parameters: string cerfilename = "mission_water.cer" String aliasname = "mission_water"; string instageriasName = "mission_water_signed"; then running, the program generates a digital certificate named: mission_water_signed in the ABNERCALIB certificate library, which is 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 generates a mission_water_signed.cer file. Third, use the issued digital certificate to sign our applet We now make a simple applet, its code is as follows: 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 bolean isstandalone = false; private string content = "file content is:"; // Custom prompt information Private string filename = "c: //winnt//system.ini"; // read the contents of this file Private textarea Ta = New Textarea (10, 80); // Custom Outbox Public String getParameter (String Key , String def) {RETURN ISSTANDALONE? System.getProperty (Key, Def): (GetParameter (key)! = Null? GetParameter (key): DEF);} public showfileapplet ()} public void init () {} public void init () { (); Myinit (); // ourselves defined method} Catch (Exception E) {E.PrintStackTrace ();}} private void jbinit () THROWS Exception {this.setsize (NEW DIMENSION (400, 300));} / * * * Customized initialization method, read into the content of a file in the system and save it, add a * visualized output box * / private void myinit () {string s; bufferedreader in; try {in = new bufferedReader (New FileReader); while ((s = in.readline ())! = null) {Content = S "/ N";}} catch (ooException ex) {ex.printStackTrace ();} system.out.println (content); ta.settext (content); getContentPane (). Add (ta) } / * * Overload 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 (Exception E) {}}} is ok, this applet is written, let's compile this applet to Jar file. Compile this applet file, you will generate a COM / Applet directory structure in the current directory (current directory), there is a showfileapplet.class in the applet directory, enter the current directory, execute: jar cvf myapplet.jar COM / Applet /*. This creates a MyApplet.jar file in the current directory. Then, in the current directory (current directory as a class directory), create a new applet directory, which is specifically stored, and put the previously generated digital certificate library ABNERCALIB below the applet directory, while generating myapplet. The JAR file is also moved below the applet directory. Then enter the directory execute: jarsigner -keystore abnerCALib myapplet.jar Mission_Water_Signed Enter Passphrase for keystore: 100200 Enter key password for Mission_Water_Signed: 200100 Mission_Water_Signed ready to use this digital certificate issued by our CA to the applet signed. Fourth, run our applet, let's write an HTML file to run the applet after this signature, the content is as follows: The content of the generated HTML file is as follows: