首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

圖片驗證碼原理與實作完整指南

     編輯:Java 相關知識

什麼是圖片驗證碼?

圖片驗證碼(CAPTCHA)是網站常見的安全機制,主要用於 區分真人用戶與自動化腳本,提升系統安全性。其核心邏輯是:伺服器生成包含隨機字符的圖片,用戶需正確輸入圖片上的文字才能通過驗證,從而防止暴力破解、機器人註冊、垃圾留言等惡意行為。

核心技術原理

實作圖片驗證碼主要用到 Java 圖形處理相關的兩個關鍵類:

  • BufferedImage:在記憶體中建立圖片物件
  • ImageIO:將圖片輸出為指定格式(如 JPG)
// 建立 60x20 像素的 RGB 圖片
BufferedImage im = new BufferedImage(60, 20, BufferedImage.TYPE_INT_RGB);

// 將圖片以 JPG 格式輸出到回應流,瀏覽器即可直接顯示
ImageIO.write(im, "JPG", response.getOutputStream());

完整實作步驟

1. 建立畫布並輸出圖片

BufferedImage im = new BufferedImage(60, 20, BufferedImage.TYPE_INT_RGB);
ImageIO.write(im, "JPG", response.getOutputStream());

2. 取得繪圖物件

Graphics g = im.getGraphics();

3. 填充背景顏色(隨機顏色增加識別難度)

Random rm = new Random();
Color c = new Color(rm.nextInt(255), rm.nextInt(255), rm.nextInt(255));
g.setColor(c);
g.fillRect(0, 0, 60, 20);

4. 繪製固定字符(可選)

g.setColor(new Color(rm.nextInt(255), rm.nextInt(255), rm.nextInt(255)));
g.setFont(new Font("華文隸書", Font.BOLD | Font.ITALIC, 28));
g.drawString("8", 1, 18);

5. 生成 4 位隨機數字

for (int i = 0; i < 4; i++) {
    g.setColor(new Color(rm.nextInt(255), rm.nextInt(255), rm.nextInt(255)));
    g.setFont(new Font("Gungsuh", Font.BOLD | Font.ITALIC, 22));
    g.drawString("" + rm.nextInt(10), (i * 15) + 2, 18);
}

6. 生成隨機中文字符(進階)

String str = "胸有激雷而面如平湖者可拜上將軍";
for (int i = 0; i < 4; i++) {
    g.setColor(new Color(rm.nextInt(255), rm.nextInt(255), rm.nextInt(255)));
    g.setFont(new Font("Gungsuh", Font.BOLD | Font.ITALIC, 15));
    g.drawString("" + str.charAt(rm.nextInt(str.length())), (i * 15) + 2, 18);
}

7. 前端頁面引用驗證碼

在 JSP/HTML 中直接用 <img> 標籤指向生成驗證碼的 Servlet:

<img alt="驗證碼" src="/ImageServlet">

8. 將驗證碼存入 Session 供後續比對

// 假設 sbf 是 StringBuilder,已拼湊好 4 位驗證碼
request.getSession().setAttribute("piccode", sbf.toString());

9. 登入時驗證邏輯

// 先驗證用戶是否存在
boolean b_exist = login.validate(username, passwd);

if (b_exist) {
    // 從 Session 取出正確驗證碼
    String pic = "" + request.getSession().getAttribute("piccode");
    
    // 比對用戶輸入
    if (!pic.equals("") && pic.equals(code)) {
        // 驗證通過,存入用戶資訊並導向首頁
        request.getSession().setAttribute("username", username);
        response.sendRedirect("index.jsp");
    }
}

完整代碼範例

將上述邏輯封裝在一個 Servlet 中,配置好 web.xml 映射路徑即可使用。建議加入干擾線、噪點等進階功能以提高安全性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved