/** * 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"))); } }
/** * 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)); }