Last active
February 15, 2020 23:15
-
-
Save kasundharmadasa/6d9a037fcccbb518b6bb1a99be2f072a to your computer and use it in GitHub Desktop.
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.binary.Hex; | |
import javax.crypto.SecretKey; | |
import javax.crypto.SecretKeyFactory; | |
import javax.crypto.spec.PBEKeySpec; | |
import java.io.UnsupportedEncodingException; | |
import java.security.NoSuchAlgorithmException; | |
import java.security.spec.InvalidKeySpecException; | |
/** | |
* This is the Main class. | |
*/ | |
public class Main { | |
public static void main(String[] args) throws UnsupportedEncodingException { | |
String password = "pass"; | |
String salt = "1234"; | |
int iterations = 10000; | |
int keyLength = 512; | |
char[] passwordChars = password.toCharArray(); | |
byte[] saltBytes = salt.getBytes(); | |
byte[] hashedBytes = hashPassword(passwordChars, saltBytes, iterations, keyLength); | |
String hashedString = Hex.encodeHexString(hashedBytes); | |
System.out.println(hashedString); | |
} | |
public static byte[] hashPassword( final char[] password, final byte[] salt, final int iterations, final int keyLength ) { | |
try { | |
SecretKeyFactory skf = SecretKeyFactory.getInstance( "PBKDF2WithHmacSHA512" ); | |
PBEKeySpec spec = new PBEKeySpec( password, salt, iterations, keyLength ); | |
SecretKey key = skf.generateSecret( spec ); | |
byte[] res = key.getEncoded( ); | |
return res; | |
} catch ( NoSuchAlgorithmException | InvalidKeySpecException e ) { | |
throw new RuntimeException( e ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment