Getting a char array from the user without using a String

前端 未结 3 1043
深忆病人
深忆病人 2021-01-11 13:02

I want to acquire a password string from the user on Android.

I do not want this string to be stored in a Java String at any point in the process from when the user

相关标签:
3条回答
  • 2021-01-11 13:21

    I don't see the EditText.java (API 17) using the String internally. It is merely 2 pages long code. Of course, TextView.java from which EditText has inherited has 9k lines in the file. You still won't see TextView.java using the String internally but with its own implementation of CharWrapper for CharSequence. (TextView.java line #8535 API 17). Here you have the method call getChars. As you will notice that buf is copied over from mChars which is char[] and not String.

        private char[] mChars;
        public void getChars(int start, int end, char[] buf, int off) {
            if (start < 0 || end < 0 || start > mLength || end > mLength) {
                throw new IndexOutOfBoundsException(start + ", " + end);
            }
    
            System.arraycopy(mChars, start + mStart, buf, off, end - start);
        }
    

    Now all you have to do is call getChar and pass along the char[] to be filled in.

                int pl = mPasswordEt.length();
                char[] password = new char[pl];
                mPasswordEt.getText().getChars(0, pl, password, 0);
    

    You have the desired char[] password without using String. After you have finish working with it you can clear it from memory as follow.

    Arrays.fill(password, ' ');
    
    0 讨论(0)
  • 2021-01-11 13:24

    Editable implements CharSequence, which, according to the docs, is a "readable sequence of char values".

    0 讨论(0)
  • 2021-01-11 13:42

    There are two possible situations your application may encounter:

    1. All applications are properly sand-boxed in their environment. In this case you should not worry about your passwords, because other processes cannot access your process memory, no matter if there are Strings or byte[] arrays in there.

    2. There's a rogue application with superuser access. In this case you should not worry about Strings either, because there are too many places to intercept your passwords, so Strings should be close to the bottom of the list of things to worry about.

    0 讨论(0)
提交回复
热议问题