Skip to content

Instantly share code, notes, and snippets.

@froop
Created February 14, 2012 13:09
Show Gist options
  • Save froop/1826669 to your computer and use it in GitHub Desktop.
Save froop/1826669 to your computer and use it in GitHub Desktop.
[Java] パスワードをSHA-256でハッシュ化
import org.apache.commons.codec.digest.DigestUtils;
public static String hash(String password, String salt) {
return DigestUtils.sha256Hex(password + salt);
}
public static String hashAndStretch(String password, String salt, int count) {
String hashed = password;
for (int i = 0; i < count; i++) {
hashed = hash(hashed, salt);
}
return hashed;
}
private static final String hash1 = hash("password1", "[email protected]");
@Test
public void testHashEqual() {
String hashed = hash("password1", "[email protected]");
assertTrue(hashed, hashed.matches("[0-9a-f]{64}"));
assertTrue(hashed.equals(hash1));
assertEquals("f3b89377204b8c312722982de07d5178086c2ba070e43a061b105d73982a1b5b", hashed);
}
@Test
public void testHashChangePassword() {
String hashed = hash("password2", "[email protected]");
assertTrue(hashed, hashed.matches("[0-9a-f]{64}"));
assertFalse(hashed.equals(hash1));
}
@Test
public void testHashChangeSalt() {
String hashed = hash("password1", "[email protected]");
assertTrue(hashed, hashed.matches("[0-9a-f]{64}"));
assertFalse(hashed.equals(hash1));
}
@Test
public void testHashAndStretch1() {
String hashed = hashAndStretch("password1", "[email protected]", 1);
assertTrue(hashed, hashed.matches("[0-9a-f]{64}"));
assertTrue(hashed.equals(hash1));
}
@Test
public void testHashAndStretch1000() {
String hashed = hashAndStretch("password1", "[email protected]", 1000);
assertTrue(hashed, hashed.matches("[0-9a-f]{64}"));
assertFalse(hashed.equals(hash1));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment