How to use Java programs to implement the public key, key, and digital certificate required for encryption

Source: Internet
Author: User
Tags decrypt printable characters asymmetric encryption java reference

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

1. Overview of digital Signature Algorithm

This section mainly refers to: 75007189

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

The role of digital signatures:

Verify data integrity, source of authentication data, anti-repudiation.

The specific principle of digital signature implementation:
1, the message according to the two parties agreed hash algorithm to calculate a fixed number of messages digest. Mathematically, as long as any one of the changes in the message, the recalculation of the digest value will be inconsistent with the original value. This guarantees the non-change of the message. (See Resources for the "Principles of Public Key Cryptography" section)
2, the paper Digest to the value of the sender's private key encryption, and then together with the original message and the digital certificate (including the public key) sent to the recipient of the message is called a digital signature.
3, the receiving party receives the digital signature, uses the same hash algorithm to calculate the digest value to the message, and then compares with the digest which decrypts with the sender's public key, if equal the message does come from the alleged sender.
4, at the same time through the certification Authority CA confirm the validity of the certificate can confirm the true identity sent.

Common digital signatures are: RSA, DSA, ECDSA

2. Overview of RSA algorithm

Principles of RSA Algorithm (i.)

Principles of RSA Algorithm (II.)

RSA is by far the most widely used asymmetric encryption algorithm. The asymmetric encryption algorithm is simply divided into public and private keys. Encryption and decryption using a different algorithm implementation, the advantage is not like the traditional symmetric encryption algorithm to the same algorithm as the same key distribution to the other side, thus reducing the key is acquired by the serious harm, the current is basically using asymmetric algorithms, and RSA is the most extensive. Theoretically, more than 1024 RSA is not cracked (or not disclosed).

Basic principle:

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

Basic steps:

To generate the public and private key steps:

  1. Randomly selects two unequal prime numbers p and q
  2. Calculates the product N of P and Q (the length of n is the key length.) 3233 is written in binary is 110010100001, a total of 12 bits, so this key is 12 bits. In practice, RSA keys are generally 1024-bit and 2048-bit for important occasions. )
  3. Calculates the Euler number of n? (n) = (p-1) (q-1) (Euler number is all prime numbers less than or equal to n
  4. Randomly selects an integer e, when the condition1<e<? (n) 1<e<? (n), and E and ? (n) ? (n) coprime.
  5. Calculates the modulo inverse element d (modulo inverse element) for E, which means that there is an integer that allowsexd/? (n) exd/?  The remainder of (n) is 1. ed-1 = kφ (n) )
  6. (n,e) is the public key, (N,D) is the private key.

Encryption process:

    • We need to encrypt the e-order of the data m and then use the result to the N to find the film, the result is C.

Decryption process:

    • The data that needs to be decrypted is D, and then the result is used to find the N film, and the result is M.

Limitations of the RSA algorithm:
First, the general RSA algorithm film long bit 1024 bits, that is, 128 bytes. The encrypted information must be less than this value. And sometimes you need some extra information. For example, Java implementation also requires 11 bytes of extra information, and hidden encrypted data cannot exceed 117 bytes.
The solution has two kinds of information segmentation encryption, the other is to select a "symmetric encryption algorithm" (such as DES), with the algorithm's key encryption information, and then use the RSA public key to encrypt the DES key.

3. Digital signature and digital certificate

RSA encryption algorithm, digital signature and digital certificate and its Java implementation

If RSA solves the problem of information encryption transmission , the digital signature solves the problem that the user verifies that the loopback data is from the server , and the digital certificate solves the problem that the user verifies that the server that is currently communicating is the server that the user expects.

When the server receives the user encrypted information, it needs to reply to the user, in order to make the user confirm that the information sent is from the server, digital signature is required.

Steps:

    1. The server uses the hash function to generate the digest first.
    2. The server then uses the digest and other authentication information to generate the digital signature using the private key encryption.
    3. The server sends the digital signature back to the user with the loopback data
    4. The user uses the public key to decrypt the digital signature to get a digest and to determine the loopback data from the server.
    5. The user uses the same hash function as the digest for the loopback data, and if the same, the loopback data has not been modified.
Digital certificates

More complex situation: because the public key is easy to obtain, if one user a changes the server public key of another user B to be the public key generated by user A, user A can impersonate the server domain user B to communicate.

How does User B verify that the server that is currently communicating is the correct server?
User B needs to go to CA (Certificate Center certificate Authority) to authenticate the public key.
The CA encrypts the server's public key and related authentication information with its own private key to generate a digital certificate (digitally Certificate)
So that the server to obtain a digital certificate, and then send the user back to the time attached to the digital certificate, the user received the digital certificate and then use the CA's public key decryption, you can get the server's public key, and then can prove that the digital signature is the server.

What is a digital signature?

BASE64 algorithm:

BASE64 is a way to represent a printable character that converts a binary number to a acsii code. Altogether need to represent 64 printable characters, uppercase and lowercase letters 52 plus 10 digits 0-9 Plus + and slash/altogether 64 characters, and an equal sign = as a suffix is also required.
BASE64 converts 3 characters to 4 characters. 3*8=4*6;
The data size will be about one-third larger after the conversion.

Why do I need to convert BASE64?

BASE64 conversions are primarily designed to avoid sensitive characters. For example, some% or enter and so on in the network protocol has a special meaning, in order to avoid parsing errors usually send data will be BASE64 conversion.
Second, some data do not look at the data that can be seen, sometimes need to copy and paste, using BASE64 encoding can be invisible to the data into the visible data, more easy to copy paste or other operations.
In addition, the conversion can avoid direct data exposure, which is an informal encryption algorithm.

RSA, digital signature and Base64 implementation main reference: Java encryption to decrypt the signature and verify the Java implementation of RSA key acquisition

First, in accordance with the Java object-oriented convention, everything has objects, which means that both the public and private keys need to be represented by a class (or interface). There are many types of public and private keys. Java provides an interface Rsaprivatekey and Rsapublickey. The public and private key interfaces that are used to refer to RSA types separately.
In general, there are two interfaces for the key, one for the public key or the private key such as Privatekey and PublicKey, and the other to explain what algorithm, such as RSA or DSA, etc. Similar to multiple inheritance.

Secondly, there are two kinds of ways to get the key, one is to generate itself, and the other is the string conversion from the network.

Generate the key yourself:
Generate your own key using Keypairgenerator this is a Java-generated key generation class, and the build step is divided into three steps:

    1. getInstance(算法名)the generated class of the characteristic algorithm is obtained through the way,
    2. Then initialize , with the initialization parameter, for RSA, it is usually a number of bits 1024, and then a random number generator such as new securerandom is specified.
    3. Finally generateKeyPair() , the KeyPair key pair is generated, and the public key and the private key are obtained by using the Get method for the key pair keypair.

      Get from the network:
      Typically, you get a string or byte[] format from the network, and note that the base encoding is usually used here, which is usually required for conversion.
      Such data have a fixed data format typical such as the ASN.1 format. X509encodedkeyspec is the public key ASN.1 format of RSA, PKCS8ENCODEDKEYSPEC is the ASN.1 format of the private key of RSA. In this way, the Privatekey and PublicKey formats can be obtained by converting the classes used for different keys in different formats.
      A Keyfactory class is also needed to get the converter.

Steps to convert:

    1. First KeyFactory.getInstance("RSA"); , by acquiring an RSA factory class.
    2. A class that specifies a specific format is obtained by X509ENCODEDKEYSPEC or Pkcs8encodedkeyspec's key data with the parameter constructor (byte[]).
    3. Finally through keyFactory.generatePublic(keySpec) and ( RSAPrivateCrtKey) keyFactory.generatePrivate(keySpec) to get, remember type conversion
Encryption and decryption of keys

The process is consistent for both the public and private keys, regardless of the type of key, whether it is encrypted or decrypted. 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); only two parameters, first set mode, encrypt to Encrypt_mode, decrypt to Decrypt_mode, second is public key or private key.
    3. Finally dofine , through the implementation process, the output is byte[];
The Java implementation of digital signature

The process of digitally signing and encrypting the decryption process in the second section above is similar, even more simplified, because the digital signature is only signed with the private key, the public key witness. And signature is the core class to accomplish this task:

Basic process:

    1. Get key, process as above:
    2. Signature.getInstance("SHA256withRSA");Use getinstance to get the signature class. and specify the algorithm for the signature. Common algorithms are specified in Java reference.
    3. Use the Signatur instance to initSign(PriKey) initialize the signature or initVerify(pubkey) to initialize the authentication.
    4. The input that uses the Signatur instance update(bytes) requires the data to be signed.
    5. Use the Signatur instance sign() or verify() implement the signature or authentication. Note that the former returns byte[] and the latter returns a Boolean.
Base64

Currently, there are three types of methods

    1. Apache Commons Codec
    2. Sun.misc
    3. Java8 after the Base64.decoder and encoder.

Here's the last one, the other versions of the app online are also many tutorials. It's all very simple indeed.

Basic steps:

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

How to use Java programs to implement the public key, key, and digital certificate required for encryption

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.