Переглянути джерело

增加了密码以 SHA-256算法加密后存入数据库的功能

Snow 2 тижнів тому
батько
коміт
9c141789bf

+ 2 - 2
src/main/java/org/snowchen/GreatSonServer/Main.java

@@ -1,6 +1,6 @@
 package org.snowchen.GreatSonServer;
 
-import org.snowchen.GreatSonServer.programinit.UserInit;
+import org.snowchen.GreatSonServer.programinit.UserRegister;
 
 import java.util.Arrays;
 
@@ -8,7 +8,7 @@ public class Main {
     public static void main(String[] args) {
 
         System.out.printf("Hello and welcome!");
-        UserInit userInit = new UserInit();
+        UserRegister userInit = new UserRegister();
         String[] userData = userInit.getUserData(); // 外部获取UserData数组
         System.out.println("UserData: " + Arrays.toString(userData));
     }

+ 27 - 2
src/main/java/org/snowchen/GreatSonServer/programinit/UserInit.java → src/main/java/org/snowchen/GreatSonServer/programinit/UserRegister.java

@@ -1,11 +1,13 @@
 package org.snowchen.GreatSonServer.programinit;
 
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
 import java.sql.*;
 import java.util.Arrays;
 import java.util.Scanner;
 import java.util.UUID;
 
-public class UserInit {
+public class UserRegister {
     private Scanner scan = new Scanner(System.in);
     private String user_name;
     private String user_password;
@@ -14,7 +16,7 @@ public class UserInit {
     private int user_permission_level;
     private String[] UserData; // 将UserData数组定义为私有
 
-    public UserInit() {
+    public UserRegister() {
         UserData = new String[5];
         // 用户信息初始化
         System.out.println("请输入用户名:");
@@ -30,6 +32,12 @@ public class UserInit {
             System.out.println("密码需为8位以上大小写字母和数字组合,请重新输入:");
             this.user_password = scan.nextLine();
         }
+        // 使用SHA-256加密密码
+        try {
+            this.user_password = hashPassword(this.user_password);
+        } catch (NoSuchAlgorithmException e) {
+            System.err.println("加密错误: " + e.getMessage());
+        }
         UserData[1] = this.user_password;
         this.uuid = UUID.randomUUID().toString(); // 使用标准的 UUID 生成方法
         UserData[2] = this.uuid;
@@ -90,6 +98,23 @@ public class UserInit {
         return password.matches(PWD_REGEX);
     }
 
+    /**
+     * 使用SHA-256算法加密密码
+     *
+     * @param password 待加密的密码字符串
+     * @return 加密后的密码字符串
+     * @throws NoSuchAlgorithmException 如果指定的算法不存在
+     */
+    public static String hashPassword(String password) throws NoSuchAlgorithmException {
+        MessageDigest md = MessageDigest.getInstance("SHA-256");
+        byte[] hashedPassword = md.digest(password.getBytes());
+        StringBuilder sb = new StringBuilder();
+        for (byte b : hashedPassword) {
+            sb.append(String.format("%02x", b));
+        }
+        return sb.toString();
+    }
 }
 
 
+