# Explain the commonly used encryption algorithms in 5 minutes

Why encrypt?

Of course it's for secrecy.

The earliest applications of cryptography were accompanied by conspiracies and wars.

The ancient Chinese "Yin Talisman" and "Yin Book" are the representatives.

In modern times, the most famous story of World War II is the Enigma cipher machine of Nazi Germany.

And Turing and his code-breaking machine.

It can be said that in modern warfare, information security is extremely important

If your deployment and orders are known to the opponent

The instructions you received were forged by the opponent

How can I fight this?

At present, the application of encrypted data and passwords,

From the military, to the commercial world, and to the scientific community

to everyone's ordinary life

Without data encryption, everyone's information is transparent

Think of the dreaded phone scams, do you still feel your information is safe?

There is a saying that says:

In the era of big data, there are no secrets

# Encryption

There are three most common forms of computer encryption:

Symmetrical, Asymmetrical, Abstract

Symmetric means:

```i have a key K，Can put the original text A encrypted into A1，can also put A1 reduced to A

f(A, K) =A1
f(A1, K) =A```
copy

Symmetric encryption is the most widely used,

Simple operation, fast speed,

Various occasions

But the disadvantage is obvious, the secret key K is too critical

If you need to let the ciphertext be accessed by other trusted people

must send him the key

But the problem is,

As long as you get the secret key, you can crack everything, including illegal users

Asymmetric security is slightly higher

There are 2 secret keys, usually a pair of public key and private key

Usually encrypted with the public key and decrypted with the private key

In this case, the problem of sending secret keys for symmetric encryption is solved

Now the public key is public, and the private key is only mine

Never send, no leaks

Digest encryption generally uses the hash algorithm.

Only encrypt but not decrypt,

It is suitable to only verify whether it is right or not, not what it is.

To give a simple example:

For students of No. 2 Middle School, the student ID format is L220130103 format

For students of No.3 Middle School, the student ID format is PLE821 format

Now I want to verify which school this person is from,

In fact, there is no need to pay attention to the specific content,

Just judge the length

Of course, the real algorithm is not so simple

Let's talk about it in detail

Easy for everyone to understand

we build a project

Unified use of the hutool toolkit

```    <dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.5</version>
</dependency>```
copy

# Symmetric encryption

The easiest is the des method

He uses a simple secret key to realize encryption and decryption

We can write a junit test, or write a main

```class Test1 {
@Test
void test() {
String text0 = "This is the original text";
String key = "xiaomian";

DES des = new DES(key.getBytes());
String text1=des.encryptBase64(text0);
System.out.println(text1);
}
}```
copy

The running result is +iJWs7q8+dyiRBouA8lDBA==

We use the secret key "xiaomian",

Encrypt "this is the original text" into an incomprehensible string

Then start decrypting

```class Test1 {
@Test
void test() {
String key = "xiaomian";
DES des = new DES(key.getBytes());

String text2=des.decryptStr("+iJWs7q8+dyiRBouA8lDBA==");
System.out.println(text2);
}
}```
copy

The result of the operation is this is the original text

Still the same key,

In the opposite way, the original text was deciphered

Operation is very simple.

des is the simplest symmetric encryption and decryption method

Similar to the aes algorithm

You can use the hutool toolkit,

almost the same operation

# asymmetric encryption

Main Reasons to Use Asymmetric

Is it safe, safe, safe

Asymmetric is not comparable to symmetric in terms of performance

Therefore, it is recommended to use short data occasions asymmetrically

Long data is implemented using symmetry.

The most commonly used is the RSA algorithm

First, a pair of secret keys must be generated, which cannot be created manually.

we can use tools

```class Test2 {
@Test
void test() {
KeyPair pair = SecureUtil.generateKeyPair("RSA");
String privateKey = Base64.encode(pair.getPrivate().getEncoded());
System.out.println("privateKey: " + privateKey);
String publicKey = Base64.encode(pair.getPublic().getEncoded());
System.out.println("publicKey: " + publicKey);
}
}```
copy

The output is:

```privateKey: MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALBgrUOQySQB72VrGyijYZcaNM26t49oaKlNddu4SLpEdJzpUnVjXtIi9Nj/DkFBXgSB9FYdrv7MpQWzTmLw0do6pcfo2cekmBGPnFRdChtEf8Npq0pAV2LlNahwkB8fxZcbQYaaWBuBkx7aHT09JGsEpi9P3y7ae4vwYmFlWgEHAgMBAAECgYBVBnXgEWb1Zb1rLaPNBl3gQrDb0Dv29QUnQIElZ4QfzypMDipDDqFCObnA9cuAZ6uUDrWj4fFfQXX39oU+KwtuESddT9rJw1hPSy2i5ityEyYO5OZQRJaTVWPWzpph+bqFLkngaOvlr3OBG7YtywUL0P8toz2pOQKpoQOkffetuQJBAP26GKiOcs/sKhrzuM/t0S2ERXXDcu07jWxJ8gioQBuQaM7AA14tbiRzaZm3Xt+cGPjHJUGEJpDvGLQ9MavEZDMCQQCx9S+JevTGpxHMX/R3uUawlTsks1keyd0rqBtqQQx7V9Bm8htrlVU3QbhacFd/FJodWX7mGOAO6nLVGK/5qXvdAkB13zSBadvwuDg/WSZsgoEA8kgKk4gaqeXjft7QIsnVhFsMYauu3tAiYvOWE9ghbbU0LeAi9a+s+UayxRMERzJ9AkA5Y7fL32I2+kQMI9nEDnUUl1u2bzxLaJAx9wm4T3gGAwDLYkKjhEoyArjAOcCN1AgLdQQuklEXnlYgENEXc6flAkEAwDbTBfOtuP/6S5nU0gX9D5fYlF/fz4YTfBjHC2dZ/wrmWlJA0f7QFf5DysQB9AXJX6ZWL/3LkMtHPafqBMKpJw==

copy

Look, ghosts can't understand

but it works

Next, start using the key pair for encryption and decryption

```class Test2 {
static String privateKey;
static String publicKey;

@BeforeAll
static void createKey() {
KeyPair pair = SecureUtil.generateKeyPair("RSA");
privateKey = Base64.encode(pair.getPrivate().getEncoded());
System.out.println("privateKey: " + privateKey);
publicKey = Base64.encode(pair.getPublic().getEncoded());
System.out.println("publicKey: " + publicKey);
}

@Test
void test() {
String text = "This is the original text";
RSA rsa = new RSA(AsymmetricAlgorithm.RSA_ECB_PKCS1.getValue(), privateKey, publicKey);

String text1 = rsa.encryptBase64(text, KeyType.PublicKey);
System.out.println("public key encryption: " + text1);
String text2 = rsa.decryptStr(text1, KeyType.PrivateKey);
System.out.println("private key decryption: " + text2);
}
}```
copy

The output is:

```public key encryption: KSifTf6tS6LGlBT9LJC33VXzkXtaQEIGJcpf1BU2ptzRXTtBzvjx83EffCqntD7/M7ZciTr4MIBFBPFCxLs9NVEeC4K9/B8fQE/3hdsMzWBTnKQzQR2vd1i5mOgFaHYwTLwrq9Dbkv1YGluCb004YtLEqdjSO/Oljs7x2YVtvGc=
private key decryption: This is the original text```
copy

can also be used in reverse

```	@Test
void test() {
String text = "This is the original text";
RSA rsa = new RSA(AsymmetricAlgorithm.RSA_ECB_PKCS1.getValue(), privateKey, publicKey);

String text1 = rsa.encryptBase64(text, KeyType.PrivateKey);
System.out.println("private key encryption: " + text1);
String text2 = rsa.decryptStr(text1, KeyType.PublicKey);
System.out.println("public key decryption: " + text2);
}```
copy
```private key encryption: Ty5YGXHUajKHtlmQ7yGYJtc39Rjb3IvSIm7WWg4+Ge6u8MDeJ3TLYZokgBbAMZRcZBZ8bIWiou12+KxoW8moRwke4PlWVipgwhC2l6qo7WtTMiwnGh+0+B8wnY3OySFK4ZeOMQFgYuiTL2uZqofLXyNzwID7GKCfWI6EL29wtbE=
public key decryption: This is the original text```
copy

Symmetrical algorithms are characterized by

Use whatever first, then use another solution

In general, meaningful information is transmitted encrypted

It is recommended to use public key encryption and private key decryption

This method ensures that the message can only be received by the object you specify

Another approach in reverse,

Private key encryption, public key decryption

For digital signature occasions

Prove that this signature was made by someone

Because only he has his own private key

# digest encryption

Digest encryption is one-way

The main purpose is to generate signatures

Commonly used algorithms include md5, sha, etc.

```class Test3 {
@Test
void test() {
String text = "This is the original text";
String text1 = DigestUtil.md5Hex(text);
System.out.println(text1);
}
}```
copy

The output is:

`531ffeed49bb13a6cf93049cc1e5ee53`
copy

For example, system passwords are generally encrypted with digests.

Let's say my password is 123456,

If anyone can see the database tables,

Also don't know my actual password is 123456

When logging in, the password entered by the user will be md5 again,

If the result is still equal to e10adc3949ba59abbe56e057f20f883e,

It means that you have entered the correct password.

Digest encryption is characterized by

The number of output results is fixed

For example, the md5 listed above will always be a fixed length after encryption

His characteristics are mainly:

```The input is different, the encryption result is different

The same input, the encryption result must be the same```
copy

Now md5 is generally used less, mainly because of length and complexity

Generally use sha256 or sha512

He can do simplified verification

For example, I have a document with a size of 100M

How to verify that his content has been altered

It is impossible for us to take two 100M files and compare them byte by byte

At this time, as long as the summary operation is performed on the two,

Get a short string and compare them

The characteristics of this kind of verification are: I know you are right and wrong, but I don't know what is wrong

# Summarize

Among the three methods, the general principle of use is

1. fast, symmetrical
2. High security/less data, using asymmetric
3. Used to verify right and wrong, retain the signature, use the summary

You can try it, by the way, Amway hutool,

very good kit

Later, we will introduce the National Secret Algorithm in a special article

Tags: Algorithm security

Posted by pontiac007 on Thu, 23 Mar 2023 12:17:08 +0530