/** * Encode a password. * * @param password Password to encode. * * @return Encoded password. * * @throws UnsupportedEncodingException If password is not UTF-8 encoded. */ public static String encodePassword(String password) throws UnsupportedEncodingException { return "{base64}" + new String(Base64.encode(password.getBytes("UTF-8"))); } }
/** * @return the password, decoded format * @throws UnsupportedEncodingException Shouldn't be thrown since * constructor already checks for it. */ public String decodePassword() throws UnsupportedEncodingException { if (password.startsWith("{base64}")) { return new String(Base64.decode(password.substring("{base64}".length()).toCharArray()), "UTF-8"); } else { return password; } }
/** * Performs an algorithm specified by the user hashing on the supplied * password and return a char array containing the encrypted password as a * printable string. The hash is computed on the low 8 bits of each * character. * @param pwd The password to hash * @param algo The type of Message Digest Algorithms * @return a string representation of the hash password * @throws NoSuchAlgorithmException if the algorithm can not be found */ public static String hashPassword(char[] pwd, String algo) throws NoSuchAlgorithmException { if (!isAValidAlgorithm(algo)) { throw new NoSuchAlgorithmException("Your algorithm isn't valid or not yet supported."); } MessageDigest md = MessageDigest.getInstance(algo); md.reset(); byte[] pwdb = new byte[pwd.length]; byte[] crypt = null; for (int b = 0; b < pwd.length; b++) { pwdb[b] = (byte) pwd[b]; } crypt = md.digest(pwdb); smudge(pwdb); return new String(Base64.encode(crypt)); }
/** * Saves the authentication information. * @param username user name * @param password password, may be encoded in the following formats: * - None, don't prefix at all * - Encoded using base64, prefix with {base64} * @throws UnsupportedEncodingException If password is not base64 encoded UTF-8 */ public AuthenticationInformation(String username, String password) throws UnsupportedEncodingException { if (password.startsWith("{base64}")) { try { new String(Base64.decode(password.substring("{base64}".length()).toCharArray()), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new UnsupportedEncodingException("The given password is not a UTF-8 string encoded in base64"); } } else { logger.log(BasicLevel.WARN, "The password for the user " + username + " is in clear text!"); } this.password = password; this.username = username; }