Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
 /*
  This is free and unencumbered software released into the public domain.
 
  Anyone is free to copy, modify, publish, use, compile, sell, or
  distribute this software, either in source code form or as a compiled
  binary, for any purpose, commercial or non-commercial, and by any
  means.
 
  In jurisdictions that recognize copyright laws, the author or authors
 of this software dedicate any and all copyright interest in the
 software to the public domain. We make this dedication for the benefit
 of the public at large and to the detriment of our heirs and
 successors. We intend this dedication to be an overt act of
 relinquishment in perpetuity of all present and future rights to this
 software under copyright law.
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
 */
package base.text;
Utility functions related to string management.
public class Password {

Return a salted SHA-256 hashed version of a password, in the format salt:passwordhash.

Parameters:
password The unhashed version of a users password.
Returns:
The salted and hashed version of a users password.
Throws:
java.security.NoSuchAlgorithmException
java.io.UnsupportedEncodingException
See also:
verifyPassword(java.lang.String,java.lang.String)
		String salt = StringHelper.randomString(16);
		MessageDigest md = MessageDigest.getInstance("SHA-256");
		md.update((salt + password).getBytes("UTF-8"));
		return salt + ":" + Base64Encode.encode(md.digest());
	}

Verify a password matches its password hash. A colon in the password indicates the password hash has a salt. Null passwords or password hashes never match.

Parameters:
passwordHash The salted and hashed password.
password A password to compare to the salted and hashed password.
Returns:
True if the password matches the password hash.
Throws:
java.security.NoSuchAlgorithmException
java.io.UnsupportedEncodingException
See also:
encode(java.lang.String)
	public static boolean verifyPassword(String passwordHashString passwordthrows NoSuchAlgorithmExceptionUnsupportedEncodingException {
		if(passwordHash == null || password == null) {
			return false;
		}
		if(passwordHash.contains(":")) {
			String[] part = passwordHash.split(":");
			MessageDigest md = MessageDigest.getInstance("SHA-256");
			md.update((part[0] + password).getBytes("UTF-8"));
			return Base64Encode.encode(md.digest()).equals(part[1]);
else {
			return StringHelper.shaHash(password).equals(passwordHash);
		}
	}
New to GrepCode? Check out our FAQ X