One, foreword

Recently, I am preparing for the level of network security protection. I have sorted out the security of the system, and have some thinking about this aspect. At the same time, I want to summarize the common password encryption methods and encryption algorithms I have used. This article will start with some basic issues of cryptography and introduce some encryption algorithms that I actually use.

Ii. Concepts related to cryptography

2.1 Four major functions and basic models of cryptography

Four main functions:

  • confidentiality
  • Authentication (Both sender and receiver can authenticate the other party. That is, third parties cannot impersonate)
  • Packet integrity (contents are not changed during transportation)
  • nonrepudiability

Basic model:

2.2 Classification of cryptography algorithms

  • Message programming: Base64
  • Message digest: MD class, SHA class, MAC(message verification code, added key support on MD class and SHA class)
  • Symmetric ciphers: DES, 3DES, AES(standard for symmetric ciphers (latest), increased key length)
  • Asymmetric password: RSA and DH key exchange
  • Signature: RSASignature(based on RSA), DSASignature(based on DSA)

2.3 Cryptography quintuple

  • clear
  • cipher
  • The encryption algorithm
  • Decryption algorithm
  • Keys (security depends on keys)

2.4 Common java-related cryptography classes

1. Message encoding

  • Base64Encoder (code)
  • BASE64Decoder (decoding)

2. MessageDigest -MessageDigest

3. Symmetric passwords

  • KeyGenerator
  • SecretKey
  • Cipher(encryption and decryption)

4. Asymmetric ciphers

  • KeyPairGenerator — public and private keys
  • KeyFactory
  • KeyPair(KeyPair)
  • PublicKey (the public)
  • PrivateKey (private key)
  • Cipher(encryption and decryption)

5. Digital signature

  • Signature

Three, practical application

With some of these categories in mind, let’s talk about three applications

3.1 Questions about password transmission security

According to the requirements of network security, cryptography technology should be used to ensure the confidentiality of important data during transmission, including but not limited to authentication data, important business data and important personal information.

Therefore, the front-end password needs to be encrypted. The encryption mode must be decrypted by the back-end to restore the original text, because the password complexity check is required after the password is transferred to the back-end. Because you can never trust the front end! Therefore, symmetric encryption or message coding is the only encryption method. This is not desirable for common message digitions because, for example, md5 encryption is irreversible, so the back end cannot restore and verify the password complexity.

For the sake of simplicity, this project adopts message encoding, carries on the front-end encryption through Base64, and completes the confidentiality of the password data in the transmission process after the back-end decryption.

The front part

NPM install ‘js-base64’ in vue project

Introduce global variables in main.js

import {Base64} from "js-base64";
Vue.prototype.$base64= Base64
Copy the code

The front-end is only responsible for encryption. The front-end encryption and decryption methods are as follows:

$data.form.password=this.$base64.encode(this.$data.form.password)  this.$data.form.password=this.$base64.decode(this.$data.form.password)Copy the code
The backend part

Back-end Base64 encryption can be done in a number of ways. There are two utility classes that can encrypt and decrypt strings.

import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; // Base decryption public static String base64DeCode(String s) {byte[] b = null; String result = null; if (s ! = null) { BASE64Decoder decoder = new BASE64Decoder(); try { b = decoder.decodeBuffer(s); result = new String(b); } catch (Exception e) { e.printStackTrace(); } } return result; } //base encryption public static String base64EnCode(String s) {byte[] b = s.get_bytes (); String result = null; if (s ! = null) { BASE64Encoder encoder = new BASE64Encoder(); try { result = encoder.encodeBuffer(b); } catch (Exception e) { e.printStackTrace(); } } return result; }Copy the code
. / / encrypted password loginVO setPassword (ValidateSafeUtil base64EnCode (loginDTO. GetPassword ())); / / decryption password loginDTO setPassword (ValidateSafeUtil base64DeCode (loginDTO. GetPassword ()));Copy the code

3.2 About common MD5 encryption usages

3.2.1 First write a tool class
import org.apache.commons.codec.digest.DigestUtils; import java.util.UUID; public class Md5UUIDSaltUtil { public static String uuid = UUID.randomUUID().toString().replace("-", ""); Public static String createMd5Code(String code) {return digestutils.md5hex (code); } public static Boolean checkPassword(String userCode, String dbCode) { if (dbCode.equals(createMd5Code(userCode))) { return true; } else { return false; } } public static String getUUID() { return uuid; } public static String getSalt() { String salt = uuid.substring(0, 5); return salt; }}Copy the code
3.2.2 Password + salt Encryption during user registration

Of course, the user needs to put the current encrypted salt value in the user field. When comparing, take out the salt value and password to encrypt again.

@override // add public void add(User User) {String id = uid.randomuuid ().toString().replace("-",""); user.setId(id); user.setCreateDate(new Date()); user.setLastUpdateDate(new Date()); String salt = md5uuidsaltutil.getsalt (); String password = Md5UUIDSaltUtil.createMd5Code(user.getPassword()+salt); user.setPassword(password); user.setSalt(salt); userDAO.insert(user); }Copy the code
3.2.3 Verifying User Passwords During Login
String salt = user.getsalt (); / / the user input password and salt into a cipher text String md5Code. = Md5UUIDSaltUtil createMd5Code (password + salt); If (user.getPassword().equals(md5Code)){message = "Login succeeded "; }else{message = "incorrect password "; }Copy the code

3.3 The application of primary national secret encryption

3.3.1 Common Encryption Mode

1, the use of symmetric encryption algorithm to save, such as 3DES, AES and other algorithms, using this way of encryption can be decrypted to restore the original password, of course, the premise is to obtain the key. However, if it is difficult to protect the key from being leaked, this method is not very good.

2. Use MD5 and other one-way HASH algorithms to protect the password. After using these algorithms, the original password cannot be restored through calculation, and the implementation is relatively simple, so this method is applied by pv.

3, special one-way HASH algorithm, due to the one-way HASH algorithm in protecting password is no longer safe, and some companies are one-way HASH algorithm based on the salt, multiple HASH extensions, such as the ways to increase the difficulty of crack, to some extent for added salt “fixed” HASH algorithm, need to protect the “salt” cannot leak, This is like symmetric encryption, once the “salt” leaks, from the “salt” to rebuild the rainbow table can be cracked.

3.3.2 State secret mode

The domestic cryptography algorithm (national cryptography algorithm) refers to the domestic commercial cryptography algorithm identified by the National Cryptography Administration. Currently, the public SM2, SM3 and SM4 algorithms are mainly used in the financial field, which are asymmetric algorithm, hash algorithm and symmetric algorithm respectively. In recent years, from the perspective of national security and long-term strategy, relevant national authorities and regulatory authorities have put forward the requirements to promote the application and implementation of national secret algorithm and strengthen the safety and control of the industry. Get rid of the dependence on foreign technology and product transition, the pressing needs of the construction industry network security environment, and in 2011, the state password administration issued the notice about to do a good job of public key cryptography algorithm upgrade, demanding “since March 1, 2011, under construction and plans to build a public key infrastructure electronic password authentication system should use SM2 algorithm and key management system, As of July 1, 2011, information systems that are operational and use public key cryptography should use SM2.”

SM2 algorithm: SM2 elliptic curve public key cryptography algorithm is a public key cryptography algorithm designed by China, including SM2-1 elliptic curve digital signature algorithm, SM2-2 elliptic curve key exchange protocol, and SM2-3 elliptic curve public key encryption algorithm, which are used to implement digital signature key negotiation and data encryption respectively. SM2 differs from RSA in that SM2 is based on the discrete logarithm problem of point groups on elliptic curves. Compared with RSA, the 256-bit SM2 password is stronger than the 2048-bit RSA password

3.3.3 Symmetric and Asymmetric Encryption

The two are different in encryption and decryption process, encryption and decryption speed, and transmission security. Details are as follows:

1. Encryption and decryption processes are different

Symmetric encryption and decryption use the same key. In the encryption process, the original text and the key can transmit ciphertext, while in the decryption process, the original text can be derived using ciphertext and the key. However, asymmetric encryption uses two keys, namely public key and private key. The public key encrypts the original text, and the private key decrypts the ciphertext to obtain the original text.

2. Different encryption and decryption speeds

This is experienced, encryption and decryption speed is relatively fast, suitable for the use of long data. Asymmetric encryption and decryption takes a long time, is relatively slow, and is only suitable for small amounts of data.

3. Different security of transmission

Symmetric encryption cannot ensure secure transmission of the key. The ciphertext may be intercepted by a third party during transmission. If the original password is also intercepted by a third party, the transmitted password information is discovered by the third party, resulting in low security.

In asymmetric encryption algorithms, the private key generates different random numbers based on different algorithms, and the private key is derived from the public key through certain encryption algorithms. However, the derivation process from the private key to the public key is one-way, that is, the public key cannot be derived from the private key backwards. So safety is higher.

3.3.4 SM2 Application

Based on the above analysis, I adopted SM2 national encryption algorithm, which is asymmetric encryption and has a high security level. There is no need to analyze the principle of SM2. After all, it is a state secret level, and the algorithm complexity does not need to be considered. SMUtil of Hutool can be easily integrated with SM2 algorithm. We encrypt or decrypt by custom key, and store the generated public key and private key base64 encoded and encrypted password into the user table. If the user logs in, we will find the public key and private key according to the user ID and restore the encrypted password after Base64 decryption for comparison. Of course, there are many kinds of encryption methods in the middle, which can carry out multi-layer encryption, and the security factor is higher and more complex.

1. Introduce jar packages

< the dependency > < groupId > org. Bouncycastle < / groupId > < artifactId > bcprov - jdk15to18 < / artifactId > < version > 1.66 < / version > </dependency> (If engin engine is missing errors, <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> The < version > 1.66 < / version > < / dependency >Copy the code

2. Customize key encryption

KeyPair pair = SecureUtil.generateKeyPair("SM2"); Byte [] privateKey = pair.getPrivate().getencoded (); //SM2 coded byte[] privateKey = pair.getPrivate().getencoded (); byte[] publicKey = pair.getPublic().getEncoded(); SM2 sm2 = SmUtil.sm2(privateKey, publicKey); subUser1.setPrivateKey(Base64.encode(privateKey)); subUser1.setPublicKey(Base64.encode(publicKey)); String encry=sm2.encryptBcd(subEditUserDTO.getPassword(),KeyType.PublicKey); subUser1.setPassword(encry);Copy the code

3. Obtain ciphertext decryption

byte[] privateKey=Base64.decode(subUser.getPrivateKey());
byte[] publicKey= Base64.decode(subUser.getPublicKey());
SM2 sm2=SmUtil.sm2(privateKey,publicKey);
String decryptStr=StrUtil.utf8Str(sm2.decryptFromBcd(subUser.getPassword(),KeyType.PrivateKey));
if(decryptStr.equals(loginDTO.getPassword())){
    sameUserNames.add(subUser);
}
Copy the code

Four, summary

This article introduces their own understanding of password encryption, password encryption there are many ways, they have not used one by one, therefore, there must be some omissions, but a lot of things, understand the content of other encryption will certainly be able to quickly master.