Created
September 29, 2020 09:52
-
-
Save barend/1902e4dce2124c64b7f7fb09eeae938a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package example; | |
import com.google.common.base.Charsets; | |
import java.security.NoSuchAlgorithmException; | |
import java.security.SecureRandom; | |
import java.util.Optional; | |
/** | |
* Example password wrapper class that obfuscates the in-memory password so | |
* that it doesn't appear in crash dumps in cleartext. This does nothing | |
* to fend off a motivated attacker, but it will ensure that the password | |
* doesn't accidentally end up in a log file or something like that. Can be | |
* repurposed for sensitive data such as a credit card number. | |
*/ | |
public final class Password { | |
private static final SecureRandom RND = getRnd(); | |
private static final SecureRandom getRnd() { | |
try { | |
return SecureRandom.getInstanceStrong(); | |
} catch (NoSuchAlgorithmException e) { | |
throw new AssertionError(e); | |
} | |
} | |
private final byte[] value; | |
private final byte[] pad; | |
private Password(byte[] value, byte[] pad) { | |
this.value = value; | |
this.pad = pad; | |
} | |
public static Optional<Password> valueOf(String password) { | |
if (password == null) { | |
return java.util.Optional.empty(); | |
} | |
byte[] pwd = password.getBytes(Charsets.UTF_8); | |
byte[] pad = new byte[pwd.length]; | |
byte[] val = new byte[pwd.length]; | |
RND.nextBytes(pad); | |
for (int i = 0, max = pad.length; i < max; i++) { | |
val[i] = (byte) (pwd[i] ^ pad[i]); | |
} | |
return Optional.of(new Password(pad, val)); | |
} | |
public String getValue() { | |
byte[] val = new byte[this.pad.length]; | |
for (int i = 0, max = this.pad.length; i < max; i++) { | |
val[i] = (byte) (this.value[i] ^ this.pad[i]); | |
} | |
return new String(val, Charsets.UTF_8); | |
} | |
@Override | |
public String toString() { | |
return Password.class.getName(); // gets obfuscated along with everything else if you run an obfuscator | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment