Created
September 19, 2014 19:09
-
-
Save komiya-atsushi/6ffac79533c3bfad8bba to your computer and use it in GitHub Desktop.
Java 8 でのパスワードハッシュのデモプログラム。
This file contains 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 javax.crypto.SecretKeyFactory; | |
import javax.crypto.spec.PBEKeySpec; | |
import java.security.NoSuchAlgorithmException; | |
import java.security.SecureRandom; | |
import java.security.spec.InvalidKeySpecException; | |
import java.util.Base64; | |
/** | |
* パスワードハッシュのデモ。 | |
*/ | |
public class Java8PasswordHashDemo { | |
static final int NUM_SALT_BYTES = 32; | |
static final int NUM_ITERATIONS = 20_000; | |
static final int NUM_KEY_BYTES = 512; | |
public static void main(String[] args) throws NoSuchAlgorithmException { | |
String password = "password123"; | |
byte[] salt = newSalt(NUM_SALT_BYTES); | |
byte[] hashedPassword = hash(password, salt, NUM_ITERATIONS, NUM_KEY_BYTES); | |
System.out.println("salt : " + Base64.getEncoder().encodeToString(salt)); | |
System.out.println("salt : " + Base64.getEncoder().encodeToString(hashedPassword)); | |
} | |
static byte[] newSalt(int length) { | |
try { | |
byte[] result = new byte[length]; | |
SecureRandom.getInstance( | |
// "NativePRNGNonBlocking" | |
// "NativePRNGBlocking" | |
"SHA1PRNG" | |
).nextBytes(result); | |
return result; | |
} catch (NoSuchAlgorithmException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
static byte[] hash(String password, byte[] salt, int numIterations, int numHashLength) { | |
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, numIterations, numHashLength); | |
SecretKeyFactory factory; | |
try { | |
factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512"); | |
} catch (NoSuchAlgorithmException e) { | |
throw new RuntimeException(e); | |
} | |
try { | |
return factory.generateSecret(keySpec) | |
.getEncoded(); | |
} catch (InvalidKeySpecException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment