How to use java program to realize the public key, key and digital certificate required for encryption

The main purpose of this article is to realize the digital signature problem of pdf, just as a summary of my knowledge.

1. Overview of Digital Signature Algorithms

This part mainly refers to: https://blog.csdn.net/lovelichao12/article/details/75007189

Digital signature: The private key is used for signing and the public key is used for verification.

The role of digital signature:

   Verify data integrity, authenticate data origin, resist repudiation.

The specific principles of digital signature implementation: 
   1. Calculate the message according to the HASH algorithm agreed by both parties to obtain a message digest with a fixed number of digits. It is mathematically guaranteed that as long as any bit in the message is changed, the recalculated message digest value will not match the original value. This ensures the immutability of the message. (For details, please refer to the "Principle of Public Key Cryptography" in the reference materials.)
   2. Encrypt the message digest value with the sender's private key, and then send it to the receiver together with the original message and the digital certificate (including the public key). The resulting message is called a digital signature.
   3. After the receiver receives the digital signature, it uses the same HASH algorithm to calculate the digest value of the message, and then compares it with the digest value of the message decrypted with the sender's public key. If they are equal, the message is true. from the alleged sender.
   4. At the same time, the real identity of the sending can be confirmed by confirming the validity of the certificate through the certificate authority CA.

Commonly used digital signatures are: RSA, DSA, ECDSA

 

2, RSA algorithm overview

RSA algorithm principle (1)

RSA algorithm principle (2)

RSA is by far the most widely used asymmetric encryption algorithm. Asymmetric encryption algorithm is simply divided into public key and private key. Encryption and decryption are implemented with different algorithms. The advantage of this is that there is no need to distribute the key of the same algorithm to the other party as in the traditional symmetric encryption algorithm, thereby reducing the serious harm caused by the key being obtained. Asymmetric algorithms, and RSA is the most widespread. RSA above 1024 bits is theoretically unbreakable (or unpublished).

Fundamental:

The asymmetric algorithm divides the password into a public key and a private key. The public key is sent to the user (there can be multiple), and the user encrypts the data that he wants to send with the public key, and then sends it to the server. The server decrypts the encrypted data with the private key. The data.

The basic steps:

Steps to generate public and private keys:

  1. Randomly choose two unequal prime numbers p and q
  2. Calculate the product n of p and q (the length of n is the key length. 3233 written in binary is 110010100001, a total of 12 bits, so the key is 12 bits. In practical applications, the RSA key is generally 1024 bits, and in important occasions is 2048 bits.)
  3. Calculate the Euler number of n ϕ(n)=(p-1)(q-1) (Eulerian number is all prime numbers less than or equal to n
  4. Randomly choose an integer e with the condition that 1 < e < ϕ ( n ) 1<e<ϕ(n), and e is relatively prime to ϕ ( n ) ϕ(n).
  5. Calculate the modulo inverse element d of e for (modulo inverse element, which means that there is an integer such that the remainder of e × d / ϕ ( n ) e×d/ϕ(n) is 1.   ed - 1 = kϕ(n)   )
  6. (n, e) is the public key and (n, d) is the private key.

Encryption process:

  • Find the e-th power of the encrypted data m, and then use the result to find the membrane of n, and the result is c.

Decryption process:

  • The data c to be decrypted is raised to the power of d, and then the result is used to obtain the membrane of n, and the result is m.

Restriction of RSA algorithm: 
First, the general RSA algorithm has a membrane length of 1024 bits, which is 128 bytes. Encrypted messages must be smaller than this value. And sometimes some additional information is required. For example, the implementation of java requires 11 bytes of additional information, and the hidden encrypted data cannot exceed 117 bytes. 
There are two solutions: one is to encrypt the information in segments, and the other is to choose a "symmetric encryption algorithm" (such as DES), encrypt the information with the key of this algorithm, and then encrypt the DES with the RSA public key. key.

 

3. Digital signatures and digital certificates

RSA encryption algorithm, digital signature and digital certificate and their java implementation

If RSA solves the problem of encrypted transmission of information, then digital signature solves the problem of users verifying whether the returned data comes from the server , and digital certificates solves the problem of users verifying whether the server currently communicating is the server the user expects.

After the server receives the encrypted information from the user, it needs to reply to the user. In order to make the user confirm that the information sent is from the server, a digital signature needs to be used.

step:

  1. The server first uses a hash function to generate a digest.
  2. The server then uses the digest and other authentication information to generate a digital signature using private key encryption.
  3. The server attaches the digital signature to the echo data and sends it back to the user
  4. The user decrypts the digital signature with the public key to get the digest and confirms that the returned data comes from the server.
  5. The user uses the same hash function for the echo data and compares it with the digest. If the same, the echo data has not been modified.

digital certificate

More complicated situation: Since the public key is easy to obtain, if a user a modifies the server public key of another user b into a public key generated by user a himself, user a can pretend to be the server domain user b to communicate. .

How can user b verify that the server currently communicating with is the correct server? 
User b needs to go to the CA (certificate authority) to authenticate the public key. 
The CA encrypts the server's public key and related verification information with its own private key, and generates a digital certificate (Digital Certificate), 
so that the server obtains the digital certificate, and then attaches the digital certificate to the user's reply, and the user receives the digital certificate. Then use the public key of the CA to decrypt, you can get the public key of the server, and then you can prove whether the digital signature is the server's.

What is a digital signature?

BASE64 algorithm:

BASE64 is a representation of printable characters that converts binary numbers into ACSii codes. A total of 64 printable characters need to be represented, 52 uppercase and lowercase letters plus 10 numbers 0-9 plus a + sign and a slash / a total of 64 characters, and an equal sign = is required as a suffix. 
BASE64 swaps 3 characters for 4 characters. 3*8=4*6; 
the data size will become about one third larger after conversion

Why do I need to convert to BASE64?

BASE64 conversion is mainly to avoid sensitive characters. For example, some % or carriage returns have special meanings in network protocols. In order to avoid parsing errors, BASE64 conversion is usually performed when sending data. 
Secondly, some data are invisible to visible data, and sometimes need to be copied and pasted. Using BASE64 encoding can convert invisible data into visible data, making it easier to copy and paste or other operations. 
In addition, conversion can also avoid direct exposure of data, which is an informal encryption algorithm.

Implementation of RSA, digital signature and base64

Main reference: Java uses RSA encryption, decryption, signature and verification

java implementation of RSA

Get the key

First of all, according to the Java object-oriented convention, everything has an object, that is to say, both public and private keys need to be represented by classes (or interfaces). There are many types of public and private keys. java provides an interface RSAPrivateKey and RSAPublicKey. Used to refer to the public and private key interfaces of the RSA type, respectively. 
Generally speaking, the key has two interfaces, one interface indicates whether the public key or private key such as PrivateKey and PublicKey, the other interface indicates what algorithm such as RSA or DSA and so on. Similar to multiple inheritance.

Secondly, there are two ways to obtain the key, one is to generate it yourself, and the other is to convert the string obtained from the network.

Generate the key 
yourself: Generate the key yourself using KeyPairGenerator, which is a key generation class that comes with java. The generation steps are divided into three steps:

  1. getInstance(算法名)The generated class of the characteristic algorithm is obtained by means of
  2. Then use the initializeinitialization parameters, usually specifying a number of digits 1024 for RSA, and then specifying a random number generator such as new SecureRandom.
  3. Finally generateKeyPair(), generate the KeyPair key pair, and then use the get method on the key pair KeyPair to obtain the public key and private key.

    Obtained from the network: 
    Generally speaking, what is obtained from the network is in string or byte[] format. Note that base encoding is usually used here, and conversion is usually required when using it. 
    Such data has a fixed data format typically such as ASN.1 format. X509EncodedKeySpec is the RSA public key ASN.1 format, and PKCS8EncodedKeySpec is the RSA private key ASN.1 format. In this way, the formats of PrivateKey and PublicKey can be obtained by converting different key formats using the corresponding classes. 
    Here also need to use a KeyFactory class to get the converter.

Conversion steps:

  1. First by KeyFactory.getInstance("RSA");getting an RSA factory class.
  2. Obtain a class that specifies a specific format through the parameterized constructor of X509EncodedKeySpec or PKCS8EncodedKeySpec (the parameter is the key data of byte[]).
  3. Finally, it is obtained by keyFactory.generatePublic(keySpec)and ( RSAPrivateCrtKey) keyFactory.generatePrivate(keySpec), remember the type conversion

Encryption and decryption of keys

The process is the same for both public and private keys, regardless of which type of key is used for encryption or decryption. And Cipher is the core class to accomplish this task.

Basic process:

  1. First by  Cipher.getInstance("RSA")getting a Cipher.
  2. Initialization: cipher.init(Cipher.ENCRYPT_MODE, privatekey);There are only two parameters, the first is to set the mode, the encryption is ENCRYPT_MODE, the decryption is DECRYPT_MODE, and the second is the public or private key.
  3. Finally, through the dofineimplementation process, the output is byte[];

java implementation of digital signature

The process of digital signature is similar to the process of encryption and decryption in the second subsection above, even more simplified, because digital signature only uses private key to sign, public key witness. And signature is the core class to accomplish this task:

Basic process:

  1. To get the key, the process is as above:
  2. Signature.getInstance("SHA256withRSA");Use getInstance to get the Signature class. And specify the algorithm of the signature. Commonly used algorithms are specified in the java reference.
  3. Use the signatur instance initSign(PriKey)for signature initialization, or initVerify(pubkey)for authentication initialization.
  4. Using the input of a signatur instance update(bytes)requires data to be signed.
  5. sign()Either verify()implement signing or authentication using an instance of signatur. Note that the former returns byte[] and the latter returns boolean.

base64

Currently, there are three types of methods

  1. Apache Commons Codec
  2. sun.misc
  3. The BASE64.Decoder and Encoder that come with java8.

The last one is introduced here, and there are many tutorials on the Internet for other versions of the application. It's actually quite simple.

The basic steps:

    1. First you have to generate an encoder and decoder pass, Encoder encoder = Base64.getEncoder();andDecoder decoder = Base64.getDecoder();
    2. by encoder.encodeToString(bytes);encoding by ecoder.decode(string)decoding

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324450625&siteId=291194637