Created
February 14, 2012 13:09
-
-
Save froop/1826669 to your computer and use it in GitHub Desktop.
[Java] パスワードをSHA-256でハッシュ化
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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