mirror of
https://github.com/pgpainless/pgpainless.git
synced 2024-11-26 22:32:07 +01:00
Improve Passphrase implementation
This commit is contained in:
parent
a8255ec3f2
commit
c1e217f7b7
1 changed files with 54 additions and 8 deletions
|
@ -19,28 +19,74 @@ import java.util.Arrays;
|
||||||
|
|
||||||
public class Passphrase {
|
public class Passphrase {
|
||||||
|
|
||||||
private final char[] chars;
|
private final Object lock = new Object();
|
||||||
|
|
||||||
|
private final char[] chars;
|
||||||
|
private boolean valid = true;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Passphrase for keys etc.
|
||||||
|
*
|
||||||
|
* @param chars may be null for empty passwords.
|
||||||
|
*/
|
||||||
public Passphrase(char[] chars) {
|
public Passphrase(char[] chars) {
|
||||||
if (chars == null) {
|
|
||||||
throw new NullPointerException("chars MUST NOT be null.");
|
|
||||||
}
|
|
||||||
this.chars = chars;
|
this.chars = chars;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Overwrite the char array with spaces and mark the {@link Passphrase} as invalidated.
|
||||||
|
*/
|
||||||
public void clear() {
|
public void clear() {
|
||||||
Arrays.fill(chars, ' ');
|
synchronized (lock) {
|
||||||
|
if (chars != null) {
|
||||||
|
Arrays.fill(chars, ' ');
|
||||||
|
}
|
||||||
|
valid = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Call {@link #clear()} to make sure the memory is overwritten.
|
||||||
|
*
|
||||||
|
* @throws Throwable bad things might happen in {@link Object#finalize()}.
|
||||||
|
*/
|
||||||
@Override
|
@Override
|
||||||
protected void finalize() throws Throwable {
|
protected void finalize() throws Throwable {
|
||||||
clear();
|
clear();
|
||||||
super.finalize();
|
super.finalize();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return a copy of the underlying char array.
|
||||||
|
*
|
||||||
|
* @return passphrase chars.
|
||||||
|
*
|
||||||
|
* @throws IllegalStateException in case the password has been cleared at this point.
|
||||||
|
*/
|
||||||
public char[] getChars() {
|
public char[] getChars() {
|
||||||
char[] copy = new char[chars.length];
|
synchronized (lock) {
|
||||||
System.arraycopy(chars, 0, copy, 0, chars.length);
|
if (!valid) {
|
||||||
return copy;
|
throw new IllegalStateException("Passphrase has been cleared.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (chars == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
char[] copy = new char[chars.length];
|
||||||
|
System.arraycopy(chars, 0, copy, 0, chars.length);
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return true if the passphrase has not yet been cleared.
|
||||||
|
*
|
||||||
|
* @return valid
|
||||||
|
*/
|
||||||
|
public boolean isValid() {
|
||||||
|
synchronized (lock) {
|
||||||
|
return valid;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue