Esempio n. 1
0
  /**
   * Calculate a password hash using a MessageDigest.
   *
   * @param hashAlgorithm - the MessageDigest algorithm name
   * @param hashEncoding - either base64 or hex to specify the type of encoding the MessageDigest as
   *     a string.
   * @param hashCharset - the charset used to create the byte[] passed to the MessageDigestfrom the
   *     password String. If null the platform default is used.
   * @param username - ignored in default version
   * @param password - the password string to be hashed
   * @param callback - the callback used to allow customization of the hash to occur. The preDigest
   *     method is called before the password is added and the postDigest method is called after the
   *     password has been added.
   * @return the hashed string if successful, null if there is a digest exception
   */
  public static String createPasswordHash(
      String hashAlgorithm,
      String hashEncoding,
      String hashCharset,
      String username,
      String password,
      DigestCallback callback) {
    byte[] passBytes;
    String passwordHash = null;

    // convert password to byte data
    try {
      if (hashCharset == null) passBytes = password.getBytes();
      else passBytes = password.getBytes(hashCharset);
    } catch (UnsupportedEncodingException uee) {
      PicketBoxLogger.LOGGER.errorFindingCharset(hashCharset, uee);
      passBytes = password.getBytes();
    }

    // calculate the hash and apply the encoding.
    try {
      MessageDigest md = MessageDigest.getInstance(hashAlgorithm);
      if (callback != null) callback.preDigest(md);
      md.update(passBytes);
      if (callback != null) callback.postDigest(md);
      byte[] hash = md.digest();
      if (hashEncoding.equalsIgnoreCase(BASE64_ENCODING)) {
        passwordHash = Util.encodeBase64(hash);
      } else if (hashEncoding.equalsIgnoreCase(BASE16_ENCODING)) {
        passwordHash = Util.encodeBase16(hash);
      } else if (hashEncoding.equalsIgnoreCase(RFC2617_ENCODING)) {
        passwordHash = Util.encodeRFC2617(hash);
      } else {
        PicketBoxLogger.LOGGER.unsupportedHashEncodingFormat(hashEncoding);
      }
    } catch (Exception e) {
      PicketBoxLogger.LOGGER.errorCalculatingPasswordHash(e);
    }
    return passwordHash;
  }