“This is the 14th day of my participation in the First Challenge 2022. For details: First Challenge 2022
Generally, the system has high security requirements, and HTTPS is usually used for data transmission. In many cases, for generic javaweb sites, if security requirements are not very high, HTTPS will do the trick. In this case, the plain-text transfer of the password is obviously not appropriate, because if the request is intercepted in transit, the plain-text password can be used to log in to the site. For the security of data transmission, RSA encryption is used for encryption today.
Implementation ideas:
Public key method – Before sending a login request to the background, the front end requests the method to obtain the public key from the background, and then initiates the login request after encryption. – The front end code needs to import the jsencrypt.min.js file
Complete code implementation:
The back end first introduces the encrypted JAR package
<! -- Dependency jar to import -->
<! -- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk16 -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk16</artifactId>
<version>1.46</version>
</dependency>
Copy the code
Write RSA encryption tool class:
package com.railway.common.utils;
/** * Created by Administrator on 2022/2/8 0008. */
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPublicKey;
public class RSAUtil{
private static final KeyPair keyPair = initKey();
private static KeyPair initKey(a) {
try {
Provider provider =new BouncyCastleProvider();
Security.addProvider(provider);
SecureRandom random = new SecureRandom();
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", provider);
generator.initialize(1024,random);
return generator.generateKeyPair();
} catch(Exception e) {
throw newRuntimeException(e); }}private static byte[] decrypt(byte[] byteArray) {
try {
Provider provider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
Security.addProvider(provider);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", provider);
PrivateKey privateKey = keyPair.getPrivate();
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] plainText = cipher.doFinal(byteArray);
return plainText;
} catch(Exception e) {
throw newRuntimeException(e); }}public static String decryptBase64(String string) {
return new String(decrypt(Base64.decodeBase64(string.getBytes())));
}
public static String generateBase64PublicKey(a) {
PublicKey publicKey = (RSAPublicKey)keyPair.getPublic();
return newString(Base64.encodeBase64(publicKey.getEncoded())); }}Copy the code
Write front-end need to call the back-end generation public key method interface:
// The public key generation method for back-end login
@RequestMapping(value = "/getPublicKey", method = RequestMethod.GET)
public R RSAKey(a){
String publicKey = RSAUtil.generateBase64PublicKey();
return R.ok().put("publicKey",publicKey);
}
Copy the code
Before sending a login request to the background, the front-end requests the background to obtain the public key, encrypt the public key, and then initiate the login request.
You need to import the jsencrypt.min.js file or install NPM in advance
// Get the public key
export function encryption(username, password) {
return new Promise((resolve, reject) = > {
PublicKey().then((res) = > {
console.log(res);
let encrypt = new JSEncrypt(); // Create an encryption instance
let PublicKey = res.publicKey;
encrypt.setPublicKey(PublicKey);
username = encrypt.encrypt(username);
password = encrypt.encrypt(password);
resolve({
username: username,
password: password
})
})
})
}
Copy the code
Backend login receives and decrypts:
Back-end login interface implementation:
/** * login */
@RequestMapping(value = "/sys/login",method = {RequestMethod.GET,RequestMethod.POST})
public Map<String, Object> login(@RequestParam String username, @RequestParam String password)throws IOException {username=username.replaceAll(""."+");
password=password.replaceAll(""."+");
username = RSAUtil.decryptBase64(username.trim());
password = RSAUtil.decryptBase64(password.trim());
System.out.println(username+password);
SysUserEntity user = sysUserService.queryByUserName(username);
// The account does not exist or the password is incorrect
if(user == null| |! user.getPassword().equals(new Sha256Hash(password, user.getSalt()).toHex())) {
return R.error("Incorrect account number or password");
}
// The account is locked
if(user.getStatus() == 0) {return R.error("Account has been locked. Please contact your administrator.");
}
// Generate tokens and save them to the database
R r = sysUserTokenService.createToken(user.getUserId());
r.put("user",user);
return r;
}
Copy the code
Everyone likes, favorites, follows, comments check the home page for contact! Clocked articles updated 192/365 days