Use asymmetric encryption (RSA) to achieve front-end encryption and back-end decryption

Data encryption methods are:

One-way encryption, symmetric encryption, asymmetric encryption, encryption salt, hash function, digital signature.

1. One-way encryption

One-way encryption generates ciphertext by summarizing the data, and the ciphertext is irreversible. It can only be encrypted, but not decrypted. It is often used to extract the fingerprint information of the data to verify the integrity of the data. But it will cause an avalanche effect (the avalanche effect is an unstable equilibrium state and is also a characteristic of encryption algorithms, which indicates that a small change in the text or key will cause a large change in the ciphertext, just like before the avalanche, the mountain looks like Very calm, but as long as there is a little problem, it will cause a big crash. It can be used in many occasions. For Hash codes, the avalanche effect means that changes in a small number of message bits will cause many bits of the information summary to change.)

Algorithms represent: Base64, MD5, SHA .

2. Symmetric encryption

The encryption and decryption of symmetric encryption use the same key; the speed of encryption and decryption is relatively fast and the efficiency is relatively high; but the key transmission process is not safe, easy to crack, and key management is also troublesome.

Algorithms represent: DES, 3DES, AES, IDEA, RC4, RC5 .

Symmetric encryption can be divided into two categories: sequence ciphers and block ciphers

2.1. Sequence cipher
Conceptually, the operation process of a stream cipher is consistent with the encryption process we imagined. Input 1-byte plaintext into the encryption algorithm, and get 1-byte ciphertext output. The opposite process is performed at the opposite end. The whole process continues to repeat until all data processing is complete. Because of the simplicity of this line of thinking, a serial cipher must never use the same key a second time. This is because in actual use, the attacker knows or can predict the plaintext in a specific area (please consider the scenario of encrypted HTTP requests; many requests have the same request method, protocol version, and request header name). When the ciphertext is observed, a portion of the key sequence can be resolved. If the same key is used, subsequent partial ciphertexts can be decrypted. To address this issue, serial ciphers are used with one-time keys derived from long-term keys.

2.2, block cipher

Block ciphers encrypt a whole block of data at a time, and modern block ciphers tend to use 128-bit (16-byte) blocks. A block cipher is a transformation function: it takes an input and produces a seemingly random output. As long as the same key is used, there is a unique output for every possible combination of inputs.

We can understand it as a more advanced symmetric encryption algorithm. This encryption algorithm is also very common, such as AES encryption, with 128-bit, 192-bit, and 256-bit encryption strengths. AES encryption is very common in today's system docking.

3. Asymmetric encryption

Compared with symmetric encryption, there is no need to have the same set of keys, and asymmetric encryption is a "key exchange protocol for information disclosure". Asymmetric encryption requires two sets of keys, a public key and a private key. The public key and the private key are paired, that is to say, data is encrypted using the public key, and only the corresponding private key can be decrypted. The two keys are mathematically related, and the ciphertext encrypted with a certain user key can only be decrypted with the user's encryption key. If one of them is known, the other cannot be calculated. Therefore, if one of a pair of keys is disclosed, the properties of the other key will not be compromised. Here, the public key is referred to as the public key, and the private key is referred to as the private key.

Algorithm stands for: RSA, DSA .

4. Encrypted salt

Encrypted salt is also a concept that is often heard. Salt is a random string used to concatenate with our encrypted string for encryption. Salting is primarily used to provide security for encrypted strings. If there is an encrypted string after adding salt, the hacker uses the encrypted string through certain means, and the plaintext he gets is not the string before we encrypt it, but the string combined with the string before encryption and the salt. Said to increase the security of the string.

5. Hash function

Hash functions are also an integral part of cryptography. A hash function is an algorithm that converts an input of any length into a fixed-length output. When it comes to hash functions, you will definitely think of MD5 encryption, which is the most common hash function. Features of the hash function:

Anti-imageness (unidirectionality) Given a hash, it is computationally impossible to find or construct the message that generated it. That is, it cannot be restored. MD5 is a single-item encryption. Therefore, it is often used for password encryption to realize the function that even the administrator cannot know the user's password.
Second preimage resistance (weak collision resistance) Given a message and its hash, it is computationally impossible to find a different message with the same hash.
Strong collision resistance Computationally no two messages with the same hash can be found.

6. Digital signature

When verifying the integrity of the message through the hash function, it is only possible when the hash of the information and the data are transmitted separately, otherwise the middleman can modify the hash while modifying the data, thereby avoiding detection. Digital signature is mainly to verify the authenticity of data. WeChat generates a signature through symmetric encryption, and Alipay generates a signature through asymmetric encryption. The effect is not much different. Just enough to prove your identity.

Here we will focus on RSA, which is the first algorithm that uses signatures as encryption. It is used for bank online payment and e-commerce transactions.
RSA is the acronym for three mathematicians Rivest, Shamir, and Adleman. Its mathematical principle is an algorithm designed for the reason that the factorization of large integers is extremely difficult.

Advantages of RSA algorithm

No need for key transfer, which improves security
Digital signature authentication is possible

Disadvantages of RSA Algorithm

The efficiency of encryption and decryption is not high, and it is generally only suitable for processing small amounts of data (such as: keys)
and is vulnerable to small index attacks

Non-encryption algorithm implementation flow chart:
insert image description here
As you can see here, asymmetric encryption uses two keys (public key-private key) to encrypt and decrypt data. The public key is used for encryption and the private key is used for decryption.

Let's make a simple login function to test the example

Front end: jsencrypt.js is used here

code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试</title>
</head>
<body>
<div>打开控制台查看</div>
</body>
<!--jquery cdn-->
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<!--引入jsencrypt.js  cdn-->
<script src="https://cdn.bootcss.com/jsencrypt/3.0.0-beta.1/jsencrypt.js"></script>
<script type="text/javascript">
    var publicKey = '公钥串';
    console.log(encrypt(publicKey, 'HelloWord'))

    // RSA前端加密
    function encrypt(key, oldPwd) {
      
      
      let encrypt = new JSEncrypt();
      encrypt.setPublicKey(key);
      let encrypted = encrypt.encrypt(oldPwd);
      return encrypted;
    }
</script>
</html>

Get the form value and request the interface:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form id="doLogin">
    <!--用户名-->
    <input type="text"  name="username" required="" autofocus="">
    <!--密码-->
    <input type="password" name="password" required="">
    <button type="button" id="bt">登录</button>
    <a th:href="@{/AddPage}">注册</a>
</form>
</body>
<!--jquery cdn-->
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<!--引入jsencrypt.js  cdn-->
<script src="https://cdn.bootcss.com/jsencrypt/3.0.0-beta.1/jsencrypt.js"></script>
<script type="text/javascript">
    var publicKey = '公钥串';
    
    // RSA前端加密
    function encrypt(key, oldPwd) {
      
      
      let encrypt = new JSEncrypt();
      encrypt.setPublicKey(key);
      let encrypted = encrypt.encrypt(oldPwd);
      return encrypted;
    }

    $("#bt").click(function () {
      
      
      let data = $("#doLogin").serializeArray();
      console.log(data)
      
      var obj = {
      
      }
      data.forEach((item) => {
      
      
        obj[item.name] = item.value
      })
      console.log(obj)

      $.ajax({
      
      
        url: '/app/v1/checkSign',
        type: 'get',
        data: getSign(obj),
        dataType: 'json',
        success: function (res) {
      
      
          console.log(res)
        }
      })
    })

    function getSign(params) {
      
      
      var signParam = "";
      var bandParam = publicKey;
      params["signTime"] = (new Date().getTime() / 1000).toFixed(0);
      var sign = '';
      var newData = Object.keys(params).sort();
      for (var i = 0; i < newData.length; i++) {
      
      
        if (
          Object.prototype.toString.call(params[newData[i]]) !==
          "[object Array]" &&
          Object.prototype.toString.call(params[newData[i]]) !== "[object Object]"
        ) {
      
      
          if (newData[i] !== "sign") {
      
      
            sign += newData[i] + params[newData[i]];
          }
        }
      }
      signParam = encrypt(publicKey, sign);
      params["sign"] = signParam;
      return params;
    }
</script>
</html>

You can also put a hidden field on the page to store the public key:

<!--也可以页面放置一个隐藏域标签,用于存放公钥-->
<input type="hidden" th:value="${session.publicKey}" id="publicKey">

Guess you like

Origin blog.csdn.net/joe0235/article/details/129242269