Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Comprehensive disclosure of digital certificate applications (including certificate generation, encryption, decryption, signature, signature verification)

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

Introduction

A digital certificate is a file digitally signed by a certificate authority that contains information about the owner of the public key and the public key. For the actual network security standard, most of the B2B, B2C, P2P, O2O and other commercial websites contain important corporate data, personal data, information, credit websites, government agencies, financial institutions and other service websites use digital certificates to enhance the security of the network.

Digital certificates are generally issued by national authenticated authorities, that is, certificates issued by CA, such as CA company centers in various places in China, can also be issued by enterprise-level CA systems, such as Symantec, ResellerClub, Digital Times and so on. Developers can also use the tool to automatically generate certificates for development, but certificates that are not authenticated will be considered invalid certificates without security protection but can still function properly.

In this article, we will introduce the process of generating and using digital certificates and the ways of encrypting, decrypting, signing and verifying data.

I hope it will be helpful to your study and research. If there are any mistakes or omissions, please comment.

Catalogue

I. introduction of digital certificates

2. Introduction of encryption algorithm

Third, the way to generate digital certificates

Obtaining public and private keys

V. encryption and decryption of digital certificates

VI. Signature and verification of digital certificates

I. introduction of digital certificates

1.1 what is a digital certificate

A digital certificate is a string of digits that mark the identity information of each party in Internet communication. It provides a way to verify the identity of a communication entity on Internet. A digital certificate is not a digital × ×, but a seal or a signature stamped or added on the digital × × by an identity authentication body. It is issued by the authoritative organization CA, also known as the Certificate Authorization Certificate Authority Center, and people can use it to identify each other on the Internet.

The simplest certificate contains the key, the name, and the digital signature of the certificate authority. Another important feature of digital certificates is that they are only valid for a specific period of time. Digital certificate is a kind of authoritative electronic document, which can be issued by an authoritative and impartial third party, such as CA, such as the CA company center in various parts of China, or by an enterprise-level CA system.

Figure V.1.1

1.2 Classification of digital certificates

From the point of view of the object of use of digital signatures, the current types of digital certificates mainly include personal × × books, enterprises or institutions × × × books, payment gateway certificates, server certificates, secure e-mail certificates, and personal code signature certificates.

Personal × × book

The digital security certificate that conforms to the X.509 standard contains personal identity information and a personal public key to identify the personal identity of the certificate holder. The digital security certificate and the corresponding private key are stored in E-key for individuals to identify themselves in online activities such as contract signing, order, input audit, operation authority, payment information and so on.

Enterprises or institutions × × books

The digital security certificate that conforms to the X.509 standard contains the enterprise information and the enterprise's public key to identify the identity of the certificate holder. Digital security certificates and corresponding private keys stored in E-key or IC cards can be used for external activities of enterprises in e-commerce, such as contract signing, online securities transactions, transaction payment information and so on.

Payment gateway certificate

The payment gateway certificate is the digital certificate issued by the certificate issuing center for the payment gateway. It is the main tool for data encryption and decryption of the payment gateway for digital signature and information encryption. The payment gateway certificate is only used for the conversion between various security protocols on the service provided by the payment gateway Internet and the existing network data format of the bank. The payment gateway certificate can only be used in a valid state. The payment gateway certificate is not transferable by the applicant.

Server certificate

The digital security certificate that conforms to the X.509 standard contains server information and the server's public key is used to identify and verify the identity of the server in network communication. The digital security certificate and the corresponding private key are stored in E-key. The server software uses the certificate mechanism to ensure the authenticity, security and credibility of the identity of both parties when communicating with other servers or clients.

Enterprise or organization code signing certificate

The code signing certificate is a digital certificate issued by the CA center to the software provider, which contains the identity information, public key and CA signature of the software provider. Software providers use code signing certificates to sign the software and put it on Internet. When users download the software on Internet, they will be prompted to make sure that the source software of the software has not been modified or destroyed since it was signed and before download. Code signing certificates can sign programs and files such as 32-bit .exe, .cab, .ocx, .class, and so on.

Secure email certificate

Digital security certificates that comply with the X.509 standard are applied for through IE or Netscape. Certificates applied for by IE are stored in the WINDOWS registry and stored in the individual user directory requested by NETSCAPE. Used for secure email or to identify to a WEB server (https service) that requires customer authentication.

Personal Code signing Certificate

The personal code signature certificate is a digital certificate issued by the CA center to the software provider, which contains the personal identity information, public key and CA signature provided by the software. The software provider uses the code signing certificate to sign the software and put it on Internet. When users download the software on Internet, they will be prompted to make sure that the source software of the software has not been modified or destroyed since it was signed and before downloading. Code signing certificates can sign programs and files such as 32-bit .exe, .cab, .ocx, .class, and so on.

From the technical point of view of digital certificate, the certificates issued by CA Center can be divided into two types: SSL certificate and SET certificate. Generally speaking, SSL certificate secure socket layer serves bank-to-business or business-to-business e-commerce activities, while SET secure electronic transaction certificate serves card-holding consumption and online shopping. Although they are certificates for identification and digital signatures, they have completely different trust systems and meet different standards.

1.3 format of digital certificates

The main file types and protocols of certificates are: PEM, DER, PFX, JKS, KDB, CER, KEY, CSR, CRT, CRL, OCSP, SCEP and so on.

1.3.1 PEM format

Openssl uses PEM (Privacy Enhanced Mail) format to store all kinds of information, which is the default information storage method adopted by openssl. The PEM file in Openssl generally contains the following information:

Content type: indicates what information content is stored in this document in the form of "- BEGIN XXXX--", corresponding to the "- END XXXX--" at the end.

Header information: indicates that if the data is processed and stored, encrypted information is most commonly used in openssl, such as encryption algorithm and initialization vector iv.

Message body: data encoded for BASE64. Can include all private keys RSA and DSA, public key RSA and DSA, and (x509) certificates. It stores DER format data encoded in Base64 and is surrounded by ascii headers so it is suitable for text mode transmission between systems.

Use certificates stored in PEM format

-BEGIN CERTIFICATE-MIIF6TCCBNGgAwIBAgIQSSOR8EYFvAGtG16qv0lZ4DANBgkqhkiG9w0BAQsFADBCMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEbMBkGA1UEAxMSUmFwaWRTU0wgU0hBMjU2IENBMB4XDTE3MDQyNDAwMDAwMFoXDTE5MDQyNDIzNTk1OVowITEfMB0GA1UEAwwWc2VjdXJpdHkucHVqaW53YW5nLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANrPWriCfyigreL9cVAyEPesYScRd176xhH0.-END CERTIFICATE-

Use the private key stored in PEM format

-BEGIN RSA PRIVATE KEY-MIIF6TCCBNGgAwIBAgIQSSOR8EYFvAGtG16qv0lZ4DANBgkqhkiG9w0BAQsFADBCMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEbMBkGA1UEAxMSUmFwaWRTU0wgU0hBMjU2IENBMB4XDTE3MDQyNDAwMDAwMFoXDTE5MDQyNDIzNTk1OVowITEfMB0GA1UEAwwWc2VjdXJpdHkucHVqaW53YW5nLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANrPWriCfyigreL9cVAyEPesYScRd176xhH0.-END RSA PRIVATE KEY-

Use the certificate request file stored in PEM format

-BEGIN CERTIFICATE REQUEST-MIIF6TCCBNGgAwIBAgIQSSOR8EYFvAGtG16qv0lZ4DANBgkqhkiG9w0BAQsFADBCMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEbMBkGA1UEAxMSUmFwaWRTU0wgU0hBMjU2IENBMB4XDTE3MDQyNDAwMDAwMFoXDTE5MDQyNDIzNTk1OVowITEfMB0GA1UEAwwWc2VjdXJpdHkucHVqaW53YW5nLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANrPWriCfyigreL9cVAyEPesYScRd176xhH0.-END&~bsp;KETIFICATE REQUEST-

1.3.2 DER format

The Identification Encoding Rule (DER) can contain all private keys, public keys, and certificates. It is the default format for most browsers and is stored in ASN1 DER format. It is a headless PEM and a DER surrounded by text headers.

PFX or P12-Public key encryption Standard # 12 (PKCS#12) can contain all private keys, public keys, and certificates. It is stored in binary format, also known as PFX files. You can usually merge and convert the "KEY file + CRT file" format used by Apache/OpenSSL into a standard PFX file. You can import the PFX file format into Microsoft IIS 5, 6, Microsoft ISA, Microsoft Exchange Server and other software. You need to enter the encrypted password of the PFX file during the conversion.

1.3.3 JKS format

Usually, the "KEY file + CRT file" format used by Apache/OpenSSL can be converted into standard Java Key Store (JKS) files. JKS file format is widely used in Java-based WEB servers, application servers, middleware. You can import JKS files into TOMCAT, WEBLOGIC and other software.

1.3.4 KDB format

You can usually convert the KEY File + CRT File format used by Apache/OpenSSL to a standard IBM KDB file. KDB file format is widely used in IBM WEB server, application server and middleware. You can import KDB files into IBM HTTP Server, IBM Websphere and other software.

1.3.5 Certificate request file Certificate Signing Request in CSR format)

Before the X509 digital certificate is generated, the certificate application file is generally submitted by the user, and then the certificate is signed by CA. The general process is as follows (the format standard for X509 certificate request is pkcs#10 and rfc2314):

Users generate their own public and private key pairs

Construct your own certificate application document, which conforms to PKCS#10 standard. The file mainly includes user information, public key and some optional attribute information, and signs the content with its own private key.

The user submits the certificate request document to CA

CA verifies the signature, extracts user information, adds other information (such as issuer, etc.), and issues digital certificates with the private key of CA.

Description: a digital certificate (such as x.509) is an information carrier that binds the identity of a user (or other entity) to a public key. A legitimate digital certificate must not only conform to the X509 format specification, but also have the signature of CA. Users not only have their own digital certificates, but also must have corresponding private keys. The main contents of X509v3 digital certificate are: certificate version, certificate serial number, signature algorithm, issuer information, validity time, holder information, public key information, issuer ID, holder ID and extension.

1.3.6 online Certificate status Protocol Online Certificate StatusProtocol,rfc2560 in OCSP format)

Used to indicate the status of the certificate in real time. The OCSP client determines the status of a certificate by querying the OCSP service, which can provide users with information about the validity of one or more digital certificates. It establishes a real-time response mechanism so that users can confirm the validity of each certificate in real time to solve the security problems caused by CRL. OCSP can be implemented through the HTTP protocol. Rfc2560 defines the message format for the OCSP client and server.

1.3.7 Certificate revocation list in CRL format Certification Revocation List)

Is a signature data structure that contains a list of revoked certificates. CRL is the published form of certificate revocation status, and CRL is like a blacklist of credit cards, used to announce that some digital certificates are no longer valid. CRL is an offline certificate status information. It is updated in a certain cycle. CRL can be divided into full CRL and incremental CRL. All the revoked certificate information is contained in the complete CRL, and the incremental CRL is indicated by a series of CRL to indicate the revoked certificate information. Each issued CRL is an incremental extension of the previously issued CRL. The basic CRL information includes: serial number of revoked certificate, time of revocation, reason for revocation, signer and CRL signature and so on. CRL-based verification is a kind of lax certificate authentication. CRL can prove that a certificate revoked in CRL is invalid. However, it cannot give the status of a certificate that is not in the CRL. If you carry out strict authentication, you need to use online authentication, that is, OCSP authentication. Typically, a set of electronic documents signed by CA includes the certificate serial number CRL, which uniquely identifies the revoked certificate, which is used to list digital certificates that have expired or revoked. It is updated every once in a while, so it must be downloaded regularly to get the latest information.

1.3.8 SCEP simple Certificate enrollment Protocol

File-based certificate enrollment requires copying and pasting text files from your local computer to the Certificate Publishing Center and copying and pasting from the Certificate Publishing Center to your local computer. SCEP can handle this process automatically, but CRLs still needs to manually copy and paste between the local computer and the CA distribution center.

1.3.9 PKCS7 encrypted message Syntax (pkcs7)

Is the format standard for storing all kinds of messages. These messages include: data, signed data, digital envelopes, signed digital envelopes, digest data, and encrypted data.

1.3.10 PKCS12 (personal digital certificate standard Public Key Cryptography Standards # 12)

Certificates in binary format that contain both public and private keys usually use pfx as the suffix of the certificate file. Used to store user certificate, crl, user private key and private key in certificate chain pkcs12

1.3.11 CER generally refers to certificates in DER format

CER certificates are generally DER binary coded certificates with no private key with *. Cer as the suffix of the certificate file. Certificates can be outputted in BASE64-encoded certificates in Base64-encoded certificates with no private key in BASE64-encoded certificate files with * .cer as the suffix of the certificate file.

1.3.12 CRT certificate file can be in PEM format

1.3.13 KEY generally refers to a private key file in PEM format

Go back to the directory

2. Introduction of encryption algorithm

When generating data certificates, users can choose different encryption methods to encrypt data. common encryption algorithms can be divided into three types of symmetric encryption algorithms, asymmetric encryption algorithms and Hash algorithms.

2.1 symmetric encryption

In symmetric encryption algorithms, the keys used for encryption and decryption are the same. In other words, both encryption and decryption use the same key. Therefore, in order to ensure the security of the symmetric encryption algorithm, if the key is to be kept secret, it can only let the users know that it cannot be made public. In symmetric encryption algorithms, both encryption and decryption use the same key without distinguishing between public and private keys.

The advantage of symmetric encryption algorithm lies in the high speed of encryption and decryption and the difficulty to crack when using long keys. Suppose that two users need to use symmetric encryption to encrypt and exchange data, then users need at least two keys and exchange use. if there are n users in the enterprise, the generation and distribution of n × (nmai 1) keys in the whole enterprise will become a nightmare for the enterprise information department. The security of the symmetric encryption algorithm depends on the preservation of the encryption key, but it is impossible to require everyone in the enterprise to keep the key secret, and they usually leak the key intentionally or unintentionally-- if the key used by a user is obtained by the user, the user can read all the documents encrypted by the user key if the whole enterprise shares an encryption key. Then the confidentiality of the entire enterprise document is out of the question.

Common symmetric encryption algorithms DES, 3DES, DESX, Blowfish, IDEA, RC4, RC5, RC6 and AES.

DES is a packet data encryption technology that first divides the data into small data blocks of fixed length and then encrypts the data at a faster speed. 3DES is a DES-based encryption algorithm that uses three different keys to encrypt the same packet data block three times to make the ciphertext stronger.

Compared with DES and 3DES algorithm, AES algorithm has higher speed and resource efficiency and higher security level, which is called the next generation encryption standard.

2.2 asymmetric encryption

In asymmetric encryption algorithms, the keys used for encryption and decryption are different, also known as public and private key encryption, that is, the keys used for encryption are different from those used for decryption.

Suppose that when two users want to encrypt the exchange data and exchange the public key, one party encrypts the other with the other's public key and the other party can decrypt with its own private key. If there are n users in the enterprise, the enterprise needs to generate n pairs of keys and distribute n public keys. Because the public key can be made public, as long as users take good care of their private keys, the distribution of encryption keys will become very simple. At the same time, because the private key of each user is the only other user can verify whether the source of the information is true through the public key of the sender, it can also ensure that the sender can not deny that the message has been sent. The disadvantage of asymmetric encryption is that the speed of encryption and decryption is much slower than symmetric encryption and even 1000 times slower than asymmetric encryption in some extreme cases.

Common asymmetric encryption algorithms RSA, ECC for mobile devices, Diffie-Hellman, El Gamal, DSA digital signature.

The security and other performances of RSA and DSA are similar, while ECC has many advantages, including processing speed, bandwidth requirements, storage space and so on.

2.3 Hash algorithm

The special feature of Hash algorithm is that it is an one-way algorithm that users can generate a unique hash value of a specific length for the target information through the Hash algorithm, but can not get the target information back through this hash value. Therefore, Hash algorithm is often used in irreducible password storage, information integrity check and so on.

Common Hash algorithms MD2, MD4, MD5, HAVAL, SHA, SHA-1, HMAC, HMAC-MD5, HMAC-SHA1.

These algorithms only generate a series of irreversible ciphertext, which is often used to verify whether the data has been modified in the process of data transmission, because the same generation algorithm will only generate unique ciphertext for the same plaintext. If the ciphertext generated by the same algorithm is different, it proves that the transmission data has been modified. Usually, using MD5 and SHA1 algorithms before data legend requires both sender and receiver to know the key generation algorithm before data transmission, while HMAC needs to generate a key sender to process the data with this key to generate ciphertext, and then use this key to process the received data to determine whether the generated ciphertext is the same.

The performance of the encryption algorithm can usually be measured according to the complexity of the algorithm itself, the longer the key length, the more secure the key, the speed of encryption and decryption and so on. The above algorithms are still used in the current encryption system products, except that the length of DES key is not enough and the slow speed of MD2 has been gradually eliminated.

Go back to the directory

Third, the way to generate digital certificates

Digital certificates can be generated in many ways, such as online tools, script codes, KEYTOOL tools, OPEN SSL tools, etc. The following is to take the commonly used RSA asymmetric encryption as an example to introduce several commonly used digital certificate generation methods.

3.1 using KEYTOOL tools to generate digital certificates

KEYTOOL is a key and certificate management tool that manages the generation and installation of security keys and certificates in the JAVA environment. It is also an effective security key and certificate management tool that enables users to manage their own public / private key pairs and related certificates. It manages a keystore that stores private keys and validates their associated X.509 certificate chains (equivalent to multiple X.509 standard certificates in a database). Enables users to use digital signatures to manage their own private / public key pairs, manage related certificates for self-identification, manage data integrity and winter detection services enable users to cache their public keys during communication.

3.1.1 introduction to KEYTOOL command

KEYTOOL is a common command in keytool switches:

Keytool-genkey-alias casserver-keypass cas123-keyalg RSA-keystore casserver.keystore-validity 365keytool-validity 365keytool-export-storepass cas123-file casserver.cer-keystore casserver.keystorekeytool-import-trustcacerts-alias casserver-storepass cas123-file casserver.cer-keystore cacerts

-genkey creates a default file ".KeyStore" in the user's home directory and generates a mykey alias mykey that contains the user's public key, private key, and certificate

In the absence of a build location, keystore will have a user system default directory, such as for window xp, a C:/Documents and Settings/UserName/ file named ".KeyStore" will be generated on the system.

-alias generates aliases-keystore specifies the name of the KeyStore (all kinds of information generated will not be in the .KeyStore file)-keyalg specifies the algorithm of the key (for example, if RSA DSA does not specify default DSA)

-validity specifies the validity period of the created certificate.-keysize specifies the key length.

-storepass specifies the password of the KeyStore (the password required to obtain keystore information)

-keypass specifies the password of the alias entry (password of the private key)

-dname specifies the certificate owner information

For example, "CN= first and last name, OU= organizational unit name, O = organization name, L = city or region name, ST= state or province name, C = two-letter country code of the unit"

-list displays certificate information in the KeyStore

For example, keytool-list-v-keystore specifies the keystore-storepass password-v to display the certificate details in the KeyStore.

-export exports the certificate specified by the alias to a file

For example, keytool-export-alias needs to export aliases-keystore specifies keystore-file specifies the exported certificate location and certificate name-storepass password

The-file parameter specifies the file name to export to the file

-delete deletes an entry in the KeyStore

For example, keytool-delete-alias specifies the type to be deleted-keystore specifies the keystore-storepass password

-printcert to view the exported certificate information

For example, keytool-printcert-file leslie.crt

-keypasswd modifies the password of the specified entry in the KeyStore

For example, keytool-keypasswd-alias alias to be modified-keypass old password-new new password-storepass keystore password-keystore sage

-storepasswd modifies keystore password

For example, keytool-storepasswd-keystore c:/leslie.keystore (keystore to change password)-storepass 123456 (original password)-new 888888 (new password)

-import imports a signed digital certificate into the KeyStore

Keytool-import-alias specifies the alias of the import entry-keystore specifies the certificate to be imported by keystore-file

3.1.2 the process of generating * .keystore files

First of all, execute the following command to input the KeyStore password, name unit organization, city, province, country and other information to generate the corresponding leslie.keystore file. Note that *. Keystore file is equivalent to a repository behind the public key, private key, certificate, etc., all depend on its generation and must be kept carefully.

Keytool-genkey-alias everygold-keypass 123456-keyalg RSA-keystore leslie.keystore-validity

Prompt-alias specifies alias as everygold-keyalg specifies RSA algorithm-keypass specifies private key password as 123456

-keystore specifies that the key file name is leslie.keystore-validity and the validity period is 365 days.

3.1.3 generate digital certificates

The digital certificate leslie.cer can be generated by executing the following command according to the generated leslie.keystore file above

Keytool-export-alias everygold-storepass 123456-file leslie.cer-keystore leslie.keystore

Prompt-alias specifies alias as everygold-storepass specifies private key as 123456

-file specifies the file name of the export certificate as leslie.cer-keystore specifies the file name of the previously generated key file

Note-alias and-storepass must be the same alias and password specified when generating the leslie.keystore key file, or the certificate export fails.

Generate a certificate

If you need to obtain a BASE64 or DER certificate, you can use the export function to select a file format by pressing "copy to File" on the picture.

By opening the exported BASE64 certificate in text format, you can see

-BEGIN CERTIFICATE-MIICRjCCAa+gAwIBAgIEIvzKsDANBgkqhkiG9w0BAQsFADBWMQswCQYDVQQGEwJDTjELMAkGA1UECBMCR0QxCzAJBgNVBAcTAkdaMQ4wDAYDVQQKEwVwdWppbjEMMAoGA1UECxMDU3VuMQ8wDQYDVQQDEwZMZXNsaWUwHhcNMTcwODI5MDMwMjE4WhcNMTgwODI5MDMwMjE4WjBWMQswCQYDVQQGEwJDTjELMAkGA1UECBMCR0QxCzAJBgNVBAcTAkdaMQ4wDAYDVQQKEwVwdWppbjEMMAoGA1UECxMDU3VuMQ8wDQYDVQQDEwZMZXNsaWUwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAKFVrCaKFi2GtJjyuWSPrJah.-END CERTIFICATE-

Or you can view the exported certificate using the following statement

Keytool-list-rfc-keystore d:/leslie.keystore-storepass 123456

The display result is consistent with the above method.

3.2 script code generation certificate

If you are not familiar with KEYTOOL tools, you can also generate digital certificates directly through JAVA code. The principle is basically the same as that generated by KEYTOOL.

Public class CerTest {public static void main (String [] args) {CerTest test=new CerTest (); / generate keystore file test.getKeyStore (); / generate * .cer certificate file test.export ();} public void execCommand (String [] arstringCommand) {for (int I = 0; I)

< arstringCommand.length; i++) { System.out.print(arstringCommand[i] + " "); } try {  :&nb髉;"nbsp; Runtime.getRuntime().exec(arstringCommand); } catch (Exception e) { System.out.println(e.getMessage()); } } public void execCommand(String arstringCommand) { try { Runtime.getRuntime().exec(arstringCommand); } catch (Exception e) { System.out.println(e.getMessage()); } } /** * 生成 *.keystore */ public void getKeyStore() { String[] arstringCommand = new String[] { "cmd ", "/k", "start", // cmd Shell命令 "keytool", "-genkey", // -genkey表示生成密钥 "-validity", // -validity指定证书有效期(单位天)这里是365天 "365", "-keysize",// 指定密钥长度 "1024", "-alias", // -alias指定别名这里是everygold "everygold", "-keyalg", // -keyalg 指定密钥的算法 (如 RSA DSA如果不指定默认采用DSA) "RSA", "-keystore", // -keystore指定存储位置这里是d:/leslie.keystore "d:/leslie.keystore", "-dname",// CN=(名字与姓氏), OU=(组织单位名称), O=(组织名称), L=(城市或区域名称), // ST=(州或省份名称), C=(单位的两字母国家代码)" "CN=(leslie), OU=(everygold), O=(pujinwang), L=(Guangzhou), ST=(Guangdong), C=(CN)&qumt;,&ob{p; "-storepass", // 指定密钥库的密码(获取keystore信息所需的密码) "123456", "-keypass",// 指定别名条目的密码(私钥的密码) "123456", "-v"// -v 显示密钥库中的证书详细信息 }; execCommand(arstringCommand); } /** * 导出证书文件 */ public void export() { String[] arstringCommand = new String[] { "cmd ", "/k", &.bsp;nbrp; "start", // cmd Shell命令 "keytool", "-export", // - export指定为导出操作 "-keystore", // -keystore指定keystore文件这里是d:/leslie.keystore "d:/leslie.keystore", "-alias", // -alias指定别名这里是ss "everygold", "-file",//-file指向导出路径 "d:/leslie.cer", "-storepass",// 指定密钥库的密码 "123456" }; execCommand(arstringCommand); } } 运行成功后可获取与3.1节相同的 leslie.keystore 文件与 leslie.cer 数字证书。 若需要获取 BASE64 或 DER 证书也可使用与 3.1.3 节所述方式获取 在此不再重复介绍。 3.3 利用在线工具获取数字证书 如果觉得使用KEYTOOL或代码生成数字证书过于繁琐可以直接使勇在蟔生飞工具生成免费数字证书。一般在线生成的证书有效期为 3 个月到 1年到期后需要续费或证书无效。以下是几个常用的在线证书生成工具由于用法比较简单在此不作详细介绍。 Amazon Web Services (AWS) 是 Amazon.com 旗下的一个网络云服务站点 addresshttps://aws.amazon.com/cn/?nc2=h_lg ChinaSSL是亚狐科技旗下专为客户提供数字证书、网络安全服务的站点 addresshttps://csr.chinassl.net/index.html MySSL 则是亚洲诚信TRUSTASIA旗下专为用户提供网络安全云服务平台 addresshttps://myssl.com/csr_create.html 回到目录 四、获取公钥和私钥 在第二节已经介绍过在加密算法中有对称加密非对称加密Hash算法等几类。在对称加密算法中加密使用的密钥和解密使用的密钥是相同的使用起来比较简单。而公钥与私钥一般用于非对称的加密方式是安全性最高使用最为频密的加密方式下面几节将为大家介绍一下非对称加密的使用方式。 公钥Public Key与私钥Private Key是通过一种算法得到的一个密钥对即一个公钥和一个私钥公钥是密芸对衷箣开的部分私钥则是非公开的部分。公钥通常用于加密会话密钥、验证数字签名加密数据可以用相应的私钥进行数据解密。通过这种算法得到的密钥对能保证在世界范围内是唯一的。使用这个密钥对的时候如果用其中一个密钥加密一段数据必须用另一个密钥解密。比如用公钥加密数据就必须用私钥解密如果用私钥签名则必须用公钥验签否则数据将不会成功生成。 由于使用 KEYTOOL 等工具无法直接导出公钥和私钥所以必须通过代码进行导出。而公钥和私钥都是二进制数据所以一般 用Base64 方式进行保存。下面以上述有证书为例子导出对应的公钥与私钥。 public abstract class Coder { /** * BASE64解密 * * @param key * @return * @throws Exception */ public static byte[] decryptBASE64(String key) throws Exception { return (new BASE64Decoder()).decodeBuffer(key); } /** {&nbsP;&obsp;* BASE64加密 * * @param key * @return * @throws Exception */ public static String encryptBASE64(byte[] key) throws Exception { return (new BASE64Encoder()).encodeBuffer(key).replace("\r", "").replace("\n", ""); }}public class KeyStoreTool{ /** * Java密钥库(Java Key StoreJKS)KEY_STORE */ public static final String KEY_STORE = "JKS"; public static final String X509 = "X.509"; /** * 获得KeyStore * * @version 2016-3-16 * @param keyStorePath * @param password * @return * @throws Exception */ public static KeyStore getKeyStore(String keyStorePatx,&nb{p{String password) throws Exception { FileInputStream is = new FileInputStream(keyStorePath); KeyStore ks = KeyStore.getInstance(KEY_STORE); ks.load(is, password.toCharArray()); is.close(); return ks; } /** * 由KeyStore获得私钥 * @param keyStorePath * @param alias * @param storePass * @return * @throws Exception */ public static PrivateKey getPrivateKey(String keyStorePath, String alias, String storePass, String keyPass) throws Exception { KeyStore ks = getKeyStore(keyStorePath, storePass); PrivateKey key = (PrivateKey) ks.getKey(alias, keyPass.toCharArray()); return key; } /** * 由Certificate获得公钥 * @param keyStorePath * KeyStore路径 * @param alias * 别名 * @param storePass * KeyStore访问密码 * @return * @throws Exception */ public static PublicKey getPublicKey(String keyStorePath, String alias, String storePass) throws Exception { KeyStore ks = getKeyStore(keyStorePath, storePass); PublicKey key = ks.getCertificate(alias).getPublicKey(); return key; } /** * 从KeyStore中获取公钥并经BASE64编码 * @param keyStorePath * @param alias * @param storePass * @return * @throws Exception */ public static String getStrPublicKey(String keyStorePath, String alias,String storePass) throws Exception{ &ncsp;bwp; PublicKey key = getPublicKey(keyStorePath, alias, storePass); String strKey = Coder.encryptBASE64(key.getEncoded()); return strKey; } /* * 获取经BASE64编码后的私钥 * @param keyStorePath * @param alias * @param storePass * @param keyPass * @return * @throws Exception */ public static String getStrPrivateKey(String keyStorePath, String alias,String storePass, String keyPass) throws Exception{ PrivateKey key = getPrivateKey(keyStorePath, alias, storePass, keyPass); String strKey = Coder.encryptBASE64(key.getEncoded()); return strKey; } public static void main(String args[]){ // 公钥 String strPublicKey = ""; // 私钥 String strPrivateKey = ""; try { strPublicKey = KeyStoreCoder.getStrPublicKey("d://leslie.keystore", "everygold", "123456"); System.out.println("公钥 = 【" + strPublicKey + "】"); strPrivateKey = KeyStoreCoder.getStrPrivateKey("d://leslie.keystore", "everygold", "123456", "123456"); System.out.println("\n私钥 = 【" + strPrivateKey + "】"); } catch (Exception e1) { &nbwp;&n`s`; e1.printStackTrace(); } } } 输出藉果>

/ `>

In order to save conveniently, we usually store the public key and private key in Base64 bit.

PublicKey.key public key file

-BEGIN PUBLIC KEY-MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDbUPe3WGFA0QPGCrPrXCUR7K7MaZQY1btYZrAFjpT/k00zkj/AfcUeEZk6Tf+9mgvZ3KRVvSFaA9kYiVCJOjGfnW2Hfk6u7iOwSs/kwpC5uUzdoWlc5ZX7iC9SACXJgDg/T5HBRpXpsEkxhzWLUKy1FQDCKduLuEFdzaO4XsSX7QIDAQAB-END PUBLIC KEY-

PrivateKey.key, her key words.

-BEGIN PRIVATE KEY-MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBANtQ97dYYUDRA8YKs+tcJRHsrsxplBjVu1hmsAWOlP+TTTOSP8B9xR4RmTpN/72aC9ncpFW9IVoD2RiJUIk6MZ+dbYd+Tq7uI7BKz+TCkLm5TN2haVzllfuIL1IAJcmAOD9PkcFGlemwSTGHNYtQrLUVAMIp24u4QV3No7hexJftAgMBAAECgYEAkcm/8Yv5kimfFY3VzhXBuqmYBOAGB4BEel5AkmEWoNIdVrPYVzAD0ZonPn/NCg+V4yvtveTsf7bhIJNfCum5Q8NLV0YNn5+C1JMZoI9BrRXQjCH30Oy78QfHH9ATigDZ7cr/ke/0hJqO4hks++XlM6OyMIuoHy1WUTy5Hm3qbWECQQDvZFDixgwYwiyC9fzEj8NmWyINZx+Ny2DhnZKtKN6ro7aplGfBPU9NZ/vLQk7AZPS+24hhu7CYlOUhhhoQjWr1AkEA6ogaMAQfPslyrl1WR2KkPEOVbSSy4IJ5ZIBeJCDisgEtLb9EZ4JzXIfN6usyiJNtwf5k04zEkWBz1f5rmtTOGQJBAMSodkI1TA6yxPo4thOLvovBZfH4u1UytD3jwnD52CLMdOxOfAWlJhaCy7iomiU3Sk/X7OvM0kAmYSzvC055vlkCQQDOR0sRNG7u4Gv3pKyAOOhPAPpqdr7F7LwsgyNKD4qUGajM9c+KYxhoKCIbHybhLRp6Z+/yiXtSik0XyKCIG+fxAkEAsdlzYkpcG6T38wC0px+Mhq06AIhEF3sy3wLbM3d4ABlNMj3HqlHMPtvCV1L3dpc/8y89dAPu9OiHf8nyar9eVQ==-END PRIVATE& n`sp; KDY%

Now * .keystore, * .cer certificate, Base64 certificate, public key file public.key private key file private.key have been successfully generated. The following chapters will introduce how to use data encryption, data decryption, digital signature and digital signature verification. But before I do that, I'd like to explain their concepts and application scenarios.

I remember that in the second section, I introduced the difference between symmetric encryption and asymmetric encryption because the keys of symmetric encryption and decryption are consistent. Both sides of encryption and decryption have the same key, which is easy to cause the disclosure of the key. Therefore, in general, enterprises will use different keys under different business processes to prevent data from being compromised. However, in large enterprises, if we use symmetric encryption, enterprises will produce a large number of keys that are difficult to manage and the security is difficult to guarantee and undesirable, so asymmetric encryption is produced.

In the case of asymmetric encryption, when the enterprise needs to obtain client data, it can disclose the public key to the client to encrypt the data, even if the encrypted data is taken without a private key, the data content will not be cracked to ensure the security of the data. At this time, as long as the enterprise ensures the confidentiality of the private key, a public key can be made public to multiple clients for data transmission encryption.

On the other hand, the application scenario of digital signature is the opposite. Digital signature is a service provided by enterprises to confirm the accuracy of data sources for clients. It is generally used in the release of data owned by government agencies, administrative departments, financial industry and information industry. The data is signed by the enterprise through the private key, as long as the client has the corresponding public key, the data can be verified. As long as the signature verification is successful, it can prove that the data is the enterprise to which the digital certificate belongs to to ensure the reliability of the data source. Generally speaking, it should be the most extensive in such scenarios as the release of enterprise data by national policies, the disclosure of economic data, and so on.

Go back to the directory

V. encryption and decryption of digital certificates

After the above introduction, we should know the use scenarios of data encryption, data decryption, digital signature and digital signature verification.

Next, we will introduce the methods of data encryption and decryption.

Public abstract class Coder {/ * BASE64 decryption * * @ param key * @ return * @ throws Exception * / public static byte [] decryptBASE64 (String key) throws Exception {return (new BASE64Decoder ()) .decodeBuffer (key) } / * BASE64 encryption * * @ param key * @ return * @ throws Exception * / public static String encryptBASE64 (byte [] key) throws Exception {return (new BASE64Encoder ()) .encodeBuffer (key) .replace ("\ r", ") .replace ("\ n ",") }} public class MyCoder extends Coder {/ * use public key to encrypt data * @ param publicKey * @ param srcData * @ throws Exception * / public static String encryptByPublicKey (String publicKey, String srcData) throws Exception {/ / decrypt byte [] Competition = Coder.decryptBASE64 (publicKey); X509EncodedKeySpec spec = new X509EncodedKeySpec (competition); KeyFactorq&nbst;Kf = KeyFactory.getInstance ("RSA") / / obtain public key PublicKey pubKey = kf.generatePublic (spec); / / A pair of data encryption Cipher cipher = Cipher.getInstance ("RSA"); cipher.init (Cipher.ENCRYPT_MODE, pubKey); byte [] doFinal = cipher.doFinal (srcData.getBytes ()); return encryptBASE64 (doFinal) } / * * use private key to decrypt data * @ param privateKey * @ param data * @ return * @ throws Exception * / public static String descryptByPrivateKey (String privateKey, String data) throws Exception {/ / BASE64 transcoding decryption private key byte [] Competition = Coder.decryptBASE64 (privateKey); / / BASE64 transcode decryption ciphertext byte [] text = decryptBASE64 (data) PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec (competition); KeyFactory kf = KeyFactory.getInstance ("RSA"); / / obtain private key PrivateKey prvKey = kf.generatePrivate (spec); / / A pair of data encryption Cipher cipher = Cipher.getInstance ("RSA"); cipher.init (Cipher.DECRYPT_MODE, prvKey); byte [] doFinal = cipher.doFinal (text) Return new String (doFinal);} public static void main () {/ / Public key String strPublicKey = ""; / / Private key 6nbsp3room.bsp; String strPrivateKey = ""; try {strPublicKey = KeyStoreTool.getStrPublicKey ("d://leslie.keystore", "everygold", "123456") StrPrivateKey = KeyStoreTool.getStrPrivateKey ("d://leslie.keystore", "everygold", "123456", "123456");} catch (Exception E1) {e1.printStackTrace ();} / / original String originalText = "original text = even though I am poor, I have to travel even though I am poor"; & nbsp:&nb tourism; "nbsp; System.out.println (originalText)" Try {/ / RSA algorithm public key encryption random number String secretText = MyCoder.encryptByPublicKey (strPublicKey, originalText); System.out.println ("\ nencrypted by RSA public key =" + secretText); System.out.println ("\ nlength after encrypted by RSA public key =" + secretText.length ()); String text = MyCoder.descryptByPrivateKey (strPrivateKey, secretText) System.out.println ("\ n decrypted by RSA private key = [" + text + "]"); System.out.println ("\ nlength after decrypted by RSA private key = [" + text.length () + "]");} catch (Exception e) {e.printStackTrace ();}

Test result

Of course, if the public key and private key have been saved in the public.key and private.key files, they can be read directly from the file without going through *. Get the keystore file.

Go back to the directory

VI. Signature and verification of digital certificates

As mentioned above, signatures and signatures are mainly used for policy organs, financial institutions, authoritative information websites, foreign bulletins.

In general, signature and signature verification are often used with encryption and decryption at the same time. The enterprise will generate two pairs of keys to sign the official registered name of the enterprise and the other pair to encrypt detailed data. After checking the signature, the customer can prove the authenticity of the source of information and then decrypt the detailed information.

The signature and verification codes are as follows

Public class MySign {/ * * @ param keyStorePath KeyStore storage path * @ param alias KeyStore alias * @ param password KeyStore password * / private static String keyStorePath,alias,password; private static Certificate getCertificate () throws Exception {KeyStore keyStore = KeyStoreTool.getKeyStore (keyStorePath, password); nbsp+C store tificate certificate = keyStore.getCertificate (alias); return certificate } public static void setKeyStorePath (String path) {MySign.keyStorePath=path;} public static void setAlias (String alias) {MySign.alias=alias;} public static void setPass7ord (strhng password) {MySign.password=password } / * * generate data signature * @ param data Source data * / public static byte [] sign (byte [] data) throws Exception {/ / obtain certificate X509Certificate x509Certificate = (X509Certificate) getCertificate (); / / obtain KeyStore KeyStore keyStore = KeyStoreTool.getKeyStore (keyStorePath, password) / / get private key PrivateKey privateKey = (PrivateKey) keyStore.getKey (alias, password.toCharArray ()); / / build signature Signature signature = Signature.getInstance (x509Certificate.getSigAlgName ()); signature.initSign (privateKey); signature.update (data); return signature.sign () } / * * generate data signature and encode * @ param data source data in BASE64 * / public static String signToBase64 (String data) throws Exception {byte [] byteData=data.getBytes (); return Base64.encode (sign (byteData)) } / * * verify the binary data * @ param data encrypted data * @ param sign data signature [BASE64] * / public static boolean verifySign (byte [] data, String sign) throws Exception {/ / obtain the certificate X509Certificate x509Certificate = (X509Certificate) getCertificate (); / / obtain the public key PublicKey publicKey = x509Certificate.getPublicKey () / / build signature Signature signature = Signature.getInstance (x509Certificate.getSigAlgName ()); signature.initVerify (publicKey); signature.update (data); return signature.verify (Base64.decode (sign)) } / * * check the signature of String data * @ param data string * @ param sign data signature [BASE64] * / public static boolean verifySginString (String data, String sign) throws Exception {byte [] byteData = data.getBytes (); return verifySign (byteData, sign) } public static void main (String [] args) throws Exception {MySign.setKeyStorePath ("d://leslie.keystore"); MySign.setPassword ("123456"); MySign.setAlias ("everygold"); String sign= "Sky Club of hikers"; String base64=MySign.signToBase64 (sign); System.out.println ("signature" + sign+ "\ n\ nsignature data\ n" + base64) Boolean isRight=MySign.verifySginString (sign,base64); System.out.println ("\ nVerification result" + isRight);}}

Output result

Go back to the directory

Summary of this chapter

This paper briefly introduces the generation and use process of digital certificate *. Cer certificate export public key public.key private key private.key export and other functions, but for the function of digital certificate, this paper introduces only the tip of the iceberg. Generally, the use of digital certificates is more common in government projects, large-scale financial projects and B2B/B2C/P2P commercial websites. Especially in the mobile phone APP popular today, the use of digital certificates is becoming more and more popular. I hope this article will be helpful to your understanding of data certificates.

Application and Management of Service tools

Detailed explanation of Apache2.2+Tomcat7.0 Integration configuration

An introduction to Windows Server 2008 R2 load balancing

The comprehensive disclosure of digital certificate applications includes certificate generation, encryption, decryption, signature and signature verification.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report