【Java】編程練習:一個極其容易被破解的登錄驗證(滑動滑塊進行拼圖)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.Math;
class Global {
    public static String iconPath = System.getProperty("user.dir") + "\\demo.png", blockPath = System.getProperty("user.dir") + "\\slider.png";
    public static ImageIcon icon = new ImageIcon(iconPath), block = new ImageIcon(blockPath);
    public static JLabel pic = new JLabel(icon), slider = new JLabel(block);
    public static Point targetCoordinate = new Point();
    public static JTextField textUsername = new JTextField(48);
    public static JPasswordField textPassword = new JPasswordField(48);
    public static String username = "root", password = "a aaa abcdefgh";
}
public class Authentication {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Login Authentication");
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setBounds(screen.width / 2 - 320, screen.height / 2 - 240, 640, 480); frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true);
        JPanel panel = new JPanel();
        frame.setContentPane(panel); panel.setLayout(new FlowLayout());
        JLabel labelUsername = new JLabel("Username:"), labelPassword = new JLabel("Password:"), labelDrag = new JLabel("Drag the separated small block to the appropriate position of the original picture to finish the authentication.");
        panel.add(labelUsername); panel.add(Global.textUsername); panel.add(labelPassword); panel.add(Global.textPassword);
        panel.add(labelDrag); panel.add(Global.slider); panel.add(Global.pic);
        panel.validate();
        Global.targetCoordinate = Global.pic.getLocation(); Global.targetCoordinate.x += 224; Global.targetCoordinate.y += 112;
        Global.slider.addMouseMotionListener(new MouseDetecter());
        frame.validate();
    }
}
class MouseDetecter implements MouseMotionListener {
    Point p = new Point(); boolean sliderMovable = true;
    public void mouseDragged(MouseEvent e) {
        if (sliderMovable) { p = e.getPoint(); Global.slider.setLocation(p.x, p.y); }
        if (Math.abs(p.x - Global.targetCoordinate.x) <= 16 && Math.abs(p.y - Global.targetCoordinate.y) <= 16) {
            sliderMovable = false; Global.slider.setLocation(Global.targetCoordinate);
            if (Global.textUsername.getText().equals(Global.username) && String.valueOf(Global.textPassword.getPassword()).equals(Global.password)) {
                JOptionPane.showMessageDialog(null, "登錄成功。");
            } else {
                JOptionPane.showMessageDialog(null, "用戶名或密碼錯誤。", "登錄失敗", JOptionPane.WARNING_MESSAGE);
            }
        }
    }
    public void mouseMoved(MouseEvent e) {}
}

在這裏插入圖片描述在這裏插入圖片描述在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章