+ /** Hash and clear the password */
+ private byte[] hash(char[] password) {
+ byte[] hashedPassword = ("{SHA}" + Base64
+ .encodeBase64String(DigestUtils.sha1(toBytes(password))))
+ .getBytes();
+ Arrays.fill(password, '\u0000');
+ return hashedPassword;
+ }
+
+ private byte[] toBytes(char[] chars) {
+ CharBuffer charBuffer = CharBuffer.wrap(chars);
+ ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
+ byte[] bytes = Arrays.copyOfRange(byteBuffer.array(),
+ byteBuffer.position(), byteBuffer.limit());
+ Arrays.fill(charBuffer.array(), '\u0000'); // clear sensitive data
+ Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data
+ return bytes;
+ }
+
+ private char[] toChars(Object obj) {
+ if (obj instanceof char[])
+ return (char[]) obj;
+ if (!(obj instanceof byte[]))
+ throw new IllegalArgumentException(obj.getClass()
+ + " is not a byte array");
+ ByteBuffer fromBuffer = ByteBuffer.wrap((byte[]) obj);
+ CharBuffer toBuffer = Charset.forName("UTF-8").decode(fromBuffer);
+ char[] res = Arrays.copyOfRange(toBuffer.array(), toBuffer.position(),
+ toBuffer.limit());
+ Arrays.fill(fromBuffer.array(), (byte) 0); // clear sensitive data
+ Arrays.fill((byte[]) obj, (byte) 0); // clear sensitive data
+ Arrays.fill(toBuffer.array(), '\u0000'); // clear sensitive data
+ return res;
+ }
+