You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java或Python开发行为生物识别工具,捕获键盘按键的按压时长与间隔时间?

Hey there! Great idea building a behavioral biometrics tool focused on typing patterns—this is such an interesting use case. The good news is both pynput and jnativehook are perfectly capable of capturing the metrics you need (key hold time and inter-key press interval) without logging actual keystroke content. Let me walk you through actionable implementations for both tools:

Using pynput (Python)

pynput is super straightforward for Python projects, and you don't need to track the actual key characters—just timestamps of press/release events.

Core Approach

  • Track the timestamp when a key is pressed (on_press event)
  • Track the timestamp when the same key is released (on_release event)
  • Calculate hold time as release_timestamp - press_timestamp
  • Calculate inter-key interval as current_press_timestamp - last_press_timestamp (skip this for the first key pressed)

Minimal Code Example

from pynput.keyboard import Listener
import time

# Store timestamps and last press time
key_press_times = {}
last_press_time = None

def on_press(key):
    global last_press_time
    current_time = time.time()
    
    # Calculate inter-key interval if this isn't the first key
    if last_press_time is not None:
        inter_key_interval = current_time - last_press_time
        print(f"Inter-key interval: {inter_key_interval:.4f}s")
    
    # Record the press time for this key
    key_press_times[key] = current_time
    last_press_time = current_time

def on_release(key):
    if key in key_press_times:
        press_time = key_press_times.pop(key)
        hold_time = time.time() - press_time
        print(f"Key hold time: {hold_time:.4f}s")

# Start the listener
with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

Notes

  • This code prints the metrics instead of logging keys—you can easily modify it to store these values in a CSV, database, or memory for later analysis.
  • Avoid storing the key object's string representation if you want to keep keystroke content private.

Using jnativehook (Java)

If you're working in a Java environment, jnativehook provides global keyboard event listening across operating systems.

Core Approach

  • Use GlobalScreen.addNativeKeyListener() to register a listener
  • Capture keyPressed and keyReleased events, recording their Event.getWhen() timestamps
  • Compute hold time and inter-key interval the same way as with pynput

Minimal Code Example

import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

import java.util.HashMap;
import java.util.Map;

public class TypingPatternListener implements NativeKeyListener {
    private Map<Integer, Long> keyPressTimes = new HashMap<>();
    private Long lastPressTime = null;

    @Override
    public void nativeKeyPressed(NativeKeyEvent e) {
        long currentTime = e.getWhen();
        
        // Calculate inter-key interval
        if (lastPressTime != null) {
            double interKeyInterval = (currentTime - lastPressTime) / 1000.0;
            System.out.printf("Inter-key interval: %.4fs%n", interKeyInterval);
        }
        
        keyPressTimes.put(e.getKeyCode(), currentTime);
        lastPressTime = currentTime;
    }

    @Override
    public void nativeKeyReleased(NativeKeyEvent e) {
        Integer keyCode = e.getKeyCode();
        if (keyPressTimes.containsKey(keyCode)) {
            long pressTime = keyPressTimes.remove(keyCode);
            double holdTime = (e.getWhen() - pressTime) / 1000.0;
            System.out.printf("Key hold time: %.4fs%n", holdTime);
        }
    }

    @Override
    public void nativeKeyTyped(NativeKeyEvent e) {
        // We don't need this event since we're ignoring actual character input
    }

    public static void main(String[] args) {
        try {
            GlobalScreen.registerNativeHook();
        } catch (NativeHookException ex) {
            System.err.println("Failed to register native hook: " + ex.getMessage());
            System.exit(1);
        }

        GlobalScreen.addNativeKeyListener(new TypingPatternListener());
    }
}

Notes

  • Make sure to include the jnativehook dependency in your project (via Maven/Gradle or direct JAR).
  • The getWhen() method returns timestamps in milliseconds, so we divide by 1000 to get seconds.

Additional Tips for Your Project

  • Data Storage: Save metrics with a user identifier (e.g., session ID) to build a dataset for training. Use formats like CSV or SQLite for simplicity.
  • Preprocessing: Filter out outliers (e.g., hold times longer than 5 seconds, which might indicate a key was accidentally held) to improve model accuracy.
  • Model Training: Once you have enough data, use machine learning algorithms like SVM, Random Forest, or even neural networks to classify users based on their typing patterns.
  • Privacy: Since you're not capturing actual keystrokes, you're avoiding keylogger concerns—make sure to highlight this in your tool's documentation if it's intended for public use.

内容的提问来源于stack exchange,提问作者Fork

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 07:17:48