1-1.サンプルコード
※コピペでそのまま使用可能
public static String getSafetyPassword(String password, String salt) {
char subCharArry = password.toCharArray();
byte hashedSalt = getHashedSalt(salt);
PBEKeySpec keySpec = new PBEKeySpec(subCharArry, hashedSalt, 1000, 256);
SecretKeyFactory skf;
String hashSub = null;
try {
skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
SecretKey secretkey;
try {
secretkey = skf.generateSecret(keySpec);
} catch (InvalidKeySpecException e) {
throw new RuntimeException(e);
}
byte passByteAry = secretkey.getEncoded();
StringBuilder sb = new StringBuilder();
for (byte b : passByteAry) {
sb.append(String.format("%02x", b & 0xff));
}
hashSub = sb.toString();
return hashSub;
}
private static byte getHashedSalt(String salt) {
MessageDigest messageDigest;
try {
messageDigest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
messageDigest.update(salt.getBytes());
return messageDigest.digest();
}
以上