Java secure communication, digital certificate and digital certificate application practice (transfer)
ABNERCHAI (Chai Zheng) June 2004
Summary:
In this article, I show you how to use the detailed language and a large number of pictures and complete program source code, how to implement the message summary in Java, the message verification code reaches secure communication, and generates digital certificates, and the program with Java tools A detailed code of all examples is given to the digital certificate signature, and the process of signing the access rights of the applet after the signature.
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 digital certificate libraries using Java tools
How to use the program to verify the signature of the digital certificate
How to use the digital certificate to the Applet signature breakthrough access to access.
Keywords:
Message summary, message verification code, fingerprint, encryption, security, java, digital signature, applet, digital certificate
First, basic knowledge
During computer security communication, often use message summary and message verification code to ensure that the transmitted data 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 message summary of a string
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, etc.
Md.Update (Str.getBytes ("UTF-8")); // Incoming the original string
BYTE [] RE = md.digest (); // calculate message summary to put into the BYTE array
// Convert message summary below to strings
String result = "";
For (int i = 0; i Result = integer.tohexstring ((0x000000FF & Re [I]) | 0xffffff00) .substring (6); } System.out.println (Result); } } When we sometimes need to encrypt a file, the above method is no longer applicable. Also: The following program calculates a summary of the message from the input (out) stream. 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); // Constructive input stream // DigestOutputStream Dout = New DigestOutputStream (Fout, MD); // Use the input (out) stream to control when you start and turn off the calculation summary / / Can also be not controlled, the whole process is calculated // Initiality is starting from the beginning, if we can turn it off at the beginning, then start from a part, as follows: //din.on(false); INT B; While ((b = din.read ())! = - 1) { / / Do some of the processing of files // if (b == '$') DIN.ON (TRUE); // When you encounter symbols in the file, you start calculation. } Byte [] re = md.digest (); // Get message summary // Convert message summary below to strings String result = ""; For (int i = 0; i Result = integer.tohexstring ((0x000000FF & Re [I]) | 0xffffff00) .substring (6); } System.out.println (Result); } } When A and B communicates, a When data is transmitted to B, it also passes the message summary of the data to B, and the message can be used to verify that the message of the A transmission is correct after receiving the message summary. The problem will occur at this time, that is, if the data is modified during the transfer, the message summary is also modified. B If you can't confirm that the data is correct. Message verification code can solve this problem. The premise of using the message verification code is that the A and B have a common key so that A can be encrypted after encryption of the message summary to prevent the message summary. Since the common key is used, it is called "verification code". For example, the following program can utilize a common key to calculate the verification code of the message summary 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 Byte [] kb = {11, 105, -119, 50, 4, -105, 16, 38, -14, -111, 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 objects Mac m = mac.getInstance ("hmacmd5"); M.init (k); M.UPDATE (Str.GetBytes ("UTF-8")); Byte [] RE = m.dofinal (); // Generate a message code // Convert the message code to a string below String result = ""; For (int i = 0; i Result = integer.tohexstring ((0x000000FF & Re [I]) | 0xffffff00). Substring (6); System.out.println (Result); } } The above two techniques can ensure that the data has not changed, but the recipient is not determined whether the data is indeed a person. Although the message code can determine that the data is sent by a person having the same key, this requires that the two sides have a shared key. If there is a set of users sharing, we cannot determine the source of data. Digital signatures can solve this problem. Digital signatures utilize asymmetric encryption techniques, senders use the message summary (signature) generated by the private key encrypted data, the recipient uses the sender's public key decryption message summary to verify that the signature is someone. Since the private key is only encrypted, if the recipient decrypts a message summary with a public key, it is necessary to determine that this message summary is inevitably sent by the corresponding private key holder. The premise of using digital signatures is that the public key used to receive the data when verify the signature (by the sender's private key encryption message summary) is indeed a person (because there may be a public key). Digital certificates can solve this problem. The digital certificate contains two partial data: a part is information corresponding to the subject (unit or individual), and the other is the public key corresponding to this body. That is, the digital certificate holds a correspondence between the body and its public key. Similarly, digital certificates may also be assume that how to determine the authenticity of the contents of the digital certificate? Therefore, the effective digital certificate must be signed by the authority CA, that is, the authentic CA verification of the authenticity of the contents of the digital certificate, and then use its own private key signature on the digital certificate (equivalent to confirmation of the certificate. Thus, after the user receives such a digital certificate, the signature of the certificate is verified with the corresponding authority CA (because the public key of the authority CA is installed in the operating system). According to the principles of asymmetric encryption, if the certificate is not the authority CA signature, it will not be able to verify that the certificate is unreliable. If verified, it is possible to prove that information (sender's public key and information) of this certificate is correct. So you can trust the certificate, you can confirm that the data is indeed sent by the public key contained in the certificate. 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 digital certificates in Java I. Introduction KeyTool.exe in Java can be used to create a digital certificate, and all digital certificates are in the form of a certificate library with a one-piece (using the alias). One certificate in the certificate library contains the private key of the certificate, public Information for the key and the corresponding digital 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. This information includes CN = XX, OU = XX, O = XX, L = XX, ST = XX, C = XX, they mean: CN (Common Name Name and Last Name) OU (Organization Unit Organization Name) O (Organization organizational name) L (Locality city or area name) ST (State State or Provincial Name) C (Country Name) You can use an interactive tool tips to enter the above information, or you can use parameters. -dname "CN = XX, OU = XX, O = XX, L = XX, ST = XX, C = XX" is created. Second, the example A certificate is created in an interactive, specifying a certificate library as ABNERCALIB, creating a certificate called Abnerca, which specifies the generated by 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 -alias abnerca -keyalg rsa -keysize 1024 -keystore abnercalib -validity 3650 As shown below: In the last step in the above picture, we entered the CN, representing China's abbreviation, or directly enter the word "China". Third, the operation method of the certificate ? Certificate display Such as: KeyTool -List-Keystore AbnerCalib All certificates of the ABNERCALIB certificate library will be displayed: as shown below: Another example: keytool -list -alias abnerca-readystore abnercalib Information will be displayed in the ABNERCALIB certificate library that is not named ABNERCA. As shown below: Another example: keytool -list -v -alias abnerca -keystore abnercalib The details of the certificate (-V parameter) will be displayed as shown below: ? Export the certificate to the certificate file Such as: keytool -export -alias abnerca -file abnerca.cer-readystore abnercalib Will export the aliasing of the certificate library ABNERCALIB to AbnerCA's certificate to the abnerca.cer certificate file, It contains the information of the certificate body and the public key of the certificate, does not include private keys, which can be disclosed, as shown below: The certificate file exported above is a binary code file, which cannot be properly displayed with a text editor, so it is not using the publication certificate, and the -RFC parameter can be used in a printable editor encoded output. Such as: KeyTool -Export -Alias Abnerca -file abnerca.cer-readystore abnercalib -storepass 100200 -RFC This command specifies the access password for the certificate library in the command line, specifying to view the encoded mode. 3. View the certificate of the certificate via certificate file By 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 the certificate entry KeyTool's command line parameters - Delete can delete entries in the keystore, such as Keytool -Delete -Alias Abnerca-Keystore AbnerCalib This command deletes this certificate in the ABNERCALIB library. ? Certificate of certificate entry Such as: KeyTool -KeyPasswd -Alaias Abnerca-KeyStore AbnerCalib The entries in the ABNERCALIB certificate library can be modified in an interaction. KeyTool -KeyPasswd -Alaias Abnerca -Keypass 123456 -New 200100 -StorePass 1002 00-keystore AbnerCalib This line of command modifies the password of the certificate other than ABNERCA in the non-interactive manner to the new password 123456, the 200100 in the row refers to the original code of the certificate, and 1002 00 is the password of the applying library. Third, the issuance of the digital certificate (signature) We have created a digital certificate above, but these digital certificates have not confirmed 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 digital certificate of a CA: 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 Missionca -Keyalg RSA -Keysize 1024 -keystore abnercalib -keypass 200100 -storepass 100200 -Validity 3650 Above, we created an alias: missionca in the digital certificate library of ABNERCALIB, the validity period of 3,650 days, the algorithm is RSA and the key length is 1024, the private key password for this certificate is: 200100, certificate library Access password 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 to myself, I can do this: Create a certificate in the digital certificate library: Keytool -Genkey-DName "CN = Chai Zheng, OU = Myssen System Software Co., Ltd., O = Myssen System Software Co., Ltd., L = Chengdu, ST = Sichuan, C = China" -Alaias Abnerca -Keyalg RSA-Keysize 1024 -KeyStore AbnerCalib -KeyPass 200100 -StorePass 100200 -Validity 3650 This creates a digital certificate called 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 with 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: The program is issued by the issuer according to the certificate information of the issuer (CA) (ie the CA's private key). * The certificate is signed, the process is to use the CA certificate and the visa book to refacture to form a new certificate p> * @Author Abnerchai * @version 1.0 * / Public class signcert { Public static void main (string [] args) throws exception { Char [] storepass = "100200" .tochararray (); // Store the CA certificate and the password of the certificate library of the visa book 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 the name of the CA certificate and the certificate library subject to the visa 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 of the new library Char [] newlibpass = "100200" .tochararray (); // Set the access password for the new library String cerfilename = "abnerca.cer"; // Venus certificate file name String aliasName = "abnerca"; // Alias alias in the certificate library Char [] namepass = "200100" .tochararray (); // The private key password of the visa book on the certificate library INT n = 3; // The validity period of the visa book, in the year, start calculation at the current time INT SN = 200406001; // The serial number can be defined by himself. The meaning defined here is issued in June 2004. It is the number of months issued by this year's CA, requiring unique String AFTERALIASNAME = "abnerca_signed"; // The newly generated named certificate after the signature is the alias in the library Char [] afternewpass = "200100" .tochararray (); // The newly generated password of the newly generated certificate in the library password // Loading a certificate library FileInputStream in = new fileinputstream (name); KeyStore Ks = KeyStore.GetInstance ("jks"); // jks is the type of certificate library Ks.Load (in, storepass); / / Read the certificate from the issuer (CA) from the certificate library Java.security.cert.certificate cl = ks.getCertificate (alias); // read a CA certificate, where l is the letter L is not a data word 1 PrivateKey PrivateKey = (privatekey) Ks.getKey (alias, cakeypass); / / read the private key of the CA certificate according to the alias and certificate password In.Close (); / / Extract the information from the issuer (CA) of the issuer (CA) read from the certificate library Byte [] eNCodl = cl.getencoded (); // Extract the certificate of the certificate, here is the letter L is not a data word 1 X509CERTIMPL CIMPL = New X509CERTIMPL (ENCODL); // This is the letter L is not a data word 1, and an object of X509certimpl type is created according to the coding of the certificate. // obtain an object of the X509certinfo type according to the object above, which encapsulates the entire contents of the certificate. X509CERTINFO CINFO_FIRST = (X509CERTINFO) CIMPL.GET (X509CERTIMPL.NAME "." X509certimpl.info); / / Then get the X500name type of issuer information X500Name Issuer = (X500Name) Cinfo_first.get (x509certinfo.subject "." CERTIFICATESSUERNAME.DN_NAME); / / Get the certificate to be issued, that is, get the certificate of the issuer // You can get it from the keystore, or you can get it from the exported certificate file, here is given here ////// // Method 1, get started from the exported CER file /// / * CertificateFactory Cf = CertificateFactory.GetInstance ("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 a certificate that needs to be signed In2.Close (); BYTE [] ENCOD2 = C2.Getencoded (); X509CERTIMPL CIMP2 = New X509CERTIMPL (ENCOD2); // Get the details of the visa book, then generate a new certificate according to this certificate X509CERTINFO CINFO_SECOND = (X509CERTINFO) CIMP2.GET (X509CERTIMPL.NAME "." X509certimpl.info); * / /// // end method /// /// // mode 2, read the signed certificate from the certificate library START /// Java.security.cert.certificate c3 = ks.getCertificate (aliasName); // read the visa book from the certificate library, then generate a new certificate BYTE [] ENCOD3 = C3.Getencoded (); X509CERTIMPL CIMP3 = New X509CERTIMPL (Encod3); X509CERTINFO CINFO_SECOND = (X509certinfo) Cimp3.Get (x509certimpl.name "." X509certimpl.info); /// // end // / / Set the validity period of the new certificate so that it is valid for the current N years, the new certificate // Deadline cannot exceed the effective 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 Certificate, 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 of the new certificate Cinfo_second.set (x509certinfo.issuer "." CERTIFICATESSUERNAME.DN_NAME, Issuer; // The new issuer is read from the CA certificate. / / Set the algorithm for the new certificate, specify the algorithm used by the CA sign, MD5withRSA Algorithmid algorithm = New algorithmid (algorithmid.md5withrsaencryption_oid); CINFO_SECOND.SET (CertificateAlgorithmid.name "." CertificateAlgorithmid.Algorithm, Algorithm); // Create a new signature certificate X509CERTIMPL NEWCERT = New X509CERTIMPL (CINFO_SECOND); // Signature, use the private key of the CA certificate to sign, the algorithm for signature is MD5withRSA Newcert.sign (PrivateKey, "MD5withRSA"); // This has obtained a certificate after the CA signature // Deposit a new certificate into the certificate library // Store newly generated certificates into a new certificate library, or deposit the original certificate library. // Deposit a new certificate library, the new certificate library not only contains all the entries in the original certificate library, // and newly adds an entry produced. Note, at this time, the certificate after the newly generated signature is only / / Includes public key and subject information and signature information, excluding private key information. It will be given here. /// / / Method 1: Deposit into a new keystore /// / * Ks.setcertificateEntry (AfteraliasName, Newcert); FileOutputStream out = new fileoutputstream (newlib); // Deposit into the new library SignedLib and set the library access password of the new library Ks.Store (OUT, NewLibpass); Out.close (); * / /// // end method /// / / Can also be used in another way, deposit into the original certificate library // Deposit into the original library, that is, an additional certificate is added to the original certificate library, this certificate is the certificate after the original certificate is signed. // This new certificate contains private key and private key password /// // mode 2, 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}; // Deposit the original library, the second parameter is the private key of the original certificate, the third parameter is the private key password for the new certificate, the third parameter is a new certificate Ks.SetKeyEntry (AfteraliasName, PRK, AFTERNEWPASS, CCHAIN); // replaces the original password without signature certificate with new key FileOutputStream out2 = new fileoutputstream (name); Ks.Store (OUT2, STOREPASS); // Deposit into the original library, the second parameter is the access password of the library /// // end /// } } If you run the above program, you can use the MissionCA certificate to issue an ABNERCA certificate. After running, add a digital certificate that is an aligned abnerca_signed in ABNERCALIB, and we export it to a CER file (before the export method see). 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 of the above picture shows "Can't verify the certificate" 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, use the digital certificate to the Applet signature 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 in the c: /winnt/system.ini file. Content and display). 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: First, generate a digital certificate for this project signing applet, unknown as: mission_water Generate a digital certificate for this project signature as follows: Keytool -Genkey-DName "CN = Messen Software - Water Company Project, OU = Mesen System Software Co., Ltd. O = Mesen System Software Co., Ltd., L = Chengdu, ST = Sichuan, C = China" -alias mission_water -Keyalg RSA-Keysize 1024 -KeyStore AbnerCalib -KeyPass 200100 -StorePass 100200 -Validity 3650 Second, use our CA (Missinca) to issue this digital certificate 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 AfteraliasName = "mission_water_signed"; Then run, the program generates a digital certificate named: mission_water_signed in the ABNERCALIB certificate library, which is issued by our CA (Missionca). Below, we use the following instructions to export this certificate: KeyTool -Export -Alias mission_water_signed -file mission_water_signed.cer-readystore abnercalib -RFC A mission_water_signed.cer file will be generated. Third, sign our applet with the issued digital certificate We now make a simple applet, its code 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 boolean isstandalone = false; The content of the private string content = "file 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 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 (); // ourselves defined } Catch (Exception E) { E.PrintStackTrace (); } } Private void jbinit () throws exception { This.Setsize (New Dimension (400, 300)); } / ** * Custom initialization method, read into the content of a file in the system and save it, then add one * Visualized output box * / Private vid 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); } / * * 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 STATIC { Try { } Catch (Exception E) { } } } Ok, this applet is written, let's compile this applet to JAR files. 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 /*.* So generate 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 execution: Jarsigner -keystore abnercalib myapplet.jar mission_water_signed ENTER Passphrase for KeyStore: 100200 ENTER key password for mission_water_signed: 200100 That is, using mission_water_signed this digital certificate issued by our CA sign. Fourth, run our applet Let's write an HTML file to run the applet after this signature, as follows: hEAD>
Applet will display if your browser supports Java
hEAD>
Applet will display if your browser supports Java