christian-schlichtherle / truelicense

An open source engine for license management on the Java Virtual Machine.
https://truelicense.namespace.global
Apache License 2.0
319 stars 66 forks source link

ObfuscatedString#toCharArray(): Unwarranted assumption that CharsetDecoder returns an array-based CharBuffer #19

Open Dani-Hub opened 3 years ago

Dani-Hub commented 3 years ago

The current implementation of ObfuscatedString#toCharArray() unconditionally returns from the obtained CharBuffer the result array by invoking its array() method. But there is no guarantee that CharsetDecoder.decode actually returns a result buffer that is backed by an array, though.

My recommendation would be to change the implementation so that it is guaranteed to work correctly regardless on assumptions about implementation details, something along the lines of the following:

final CharBuffer charBuffer = charset.newDecoder().decode(ByteBuffer.wrap(encoded, 0, length));
final char[] chars = new char[charBuffer.remaining()];
charBuffer.get(chars);
if (charBuffer.hasArray()) {
    Arrays.fill(charBuffer.array(), (char) 0);
}
return chars;

If agreement exists for this general idea, I would provide a corresponding pull request.