Why is char[] preferred over String for passwords?

后端 未结 17 3686
清歌不尽
清歌不尽 2020-11-21 04:34

In Swing, the password field has a getPassword() (returns char[]) method instead of the usual getText() (returns String)

17条回答
  •  故里飘歌
    2020-11-21 04:56

    As Jon Skeet states, there is no way except by using reflection.

    However, if reflection is an option for you, you can do this.

    public static void main(String[] args) {
        System.out.println("please enter a password");
        // don't actually do this, this is an example only.
        Scanner in = new Scanner(System.in);
        String password = in.nextLine();
        usePassword(password);
    
        clearString(password);
    
        System.out.println("password: '" + password + "'");
    }
    
    private static void usePassword(String password) {
    
    }
    
    private static void clearString(String password) {
        try {
            Field value = String.class.getDeclaredField("value");
            value.setAccessible(true);
            char[] chars = (char[]) value.get(password);
            Arrays.fill(chars, '*');
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }
    

    when run

    please enter a password
    hello world
    password: '***********'
    

    Note: if the String's char[] has been copied as a part of a GC cycle, there is a chance the previous copy is somewhere in memory.

    This old copy wouldn't appear in a heap dump, but if you have direct access to the raw memory of the process you could see it. In general you should avoid anyone having such access.

提交回复
热议问题