Last active
July 25, 2022 05:52
-
-
Save danieljs777/df6d3259442396a2bba644f6623a6420 to your computer and use it in GitHub Desktop.
Encryting passwords with MD5 hash and salt in Java.
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
package PasswordEncryption; | |
/** | |
* | |
* @author daniel | |
*/ | |
import java.io.Console; | |
import java.io.IOException; | |
import java.security.*; | |
import java.io.ByteArrayOutputStream; | |
import javax.xml.bind.DatatypeConverter; | |
import java.util.*; | |
public class PasswordEncryption { | |
public static void main(String[] args) { | |
Console console = System.console(); | |
if (console == null) { | |
System.out.print("Console unavailable"); | |
return; | |
} | |
String password = console.readLine("Enter password:"); | |
try { | |
SecureRandom salt = new SecureRandom(); | |
int salt_len = 256; | |
byte salt_bytes[] = new byte[salt_len]; | |
salt.nextBytes(salt_bytes); | |
ByteArrayOutputStream data_to_hash = new ByteArrayOutputStream(); | |
data_to_hash.write(salt_bytes, 0, salt_len); | |
data_to_hash.write(password.getBytes()); | |
MessageDigest md = MessageDigest.getInstance("MD5"); | |
md.update(data_to_hash.toByteArray()); | |
byte[] digest = md.digest(); | |
String hash_pwd = DatatypeConverter.printHexBinary(digest).toUpperCase(); | |
String salt_str = DatatypeConverter.printHexBinary(salt_bytes).toUpperCase(); | |
console.printf("Storing into db hash:" + hash_pwd); | |
console.printf("\n"); | |
console.printf("Storing into db salt:" + salt_str); | |
console.printf("\n"); | |
} catch (NoSuchAlgorithmException e) { | |
System.out.print("MD5 not supported for some reason"); | |
return; | |
} catch (IOException e) { | |
System.out.print("Could not prepare data for hashing"); | |
return; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment