Created
January 18, 2020 05:42
-
-
Save Jabriko/0f60ce755cc00282b8b843353ab51bc2 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
| /* | |
| * To change this license header, choose License Headers in Project Properties. | |
| * To change this template file, choose Tools | Templates | |
| * and open the template in the editor. | |
| */ | |
| package passwordfieldtomd5; | |
| import java.security.MessageDigest; | |
| import java.security.NoSuchAlgorithmException; | |
| import java.security.NoSuchProviderException; | |
| import java.security.SecureRandom; | |
| import java.util.ArrayList; | |
| public class PasswordFieldToMD5 { | |
| public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException { | |
| byte [] salt = getSalt(); | |
| char[] password ={ 'a', 'b', 'c', 'd', 'e' }; | |
| String passwordMD5WithSalt = digest (password, salt); | |
| System.out.println("Your plaintext password is : " + new String(password)); | |
| System.out.println("Your password MD5 with salt is : " + passwordMD5WithSalt); | |
| System.out.println("Nilai salt adalah : " +salt); | |
| System.out.println("Nilai char password adalah : " +password); | |
| } | |
| public static String digest (char [] in, byte[] salt) throws NoSuchAlgorithmException { | |
| MessageDigest messageDigest = MessageDigest.getInstance("MD5"); | |
| ArrayList<Byte> list = new ArrayList<>(); | |
| for (int i = 0; i<in.length; i++) { | |
| byte b = (byte) in[i]; | |
| list.add(b); | |
| } | |
| byte[] inputInByte = new byte[list.size()]; | |
| for (int i = 0; i<list.size(); i++) { | |
| inputInByte[i] = list.get(i); | |
| } | |
| messageDigest.update(salt); | |
| messageDigest.update(inputInByte); | |
| byte byteData[] = messageDigest.digest(); | |
| StringBuffer hexString = new StringBuffer(); | |
| for (int i = 0; i < byteData.length; i++) { | |
| String hex = Integer.toHexString(0xff & byteData[i]); | |
| if (hex.length() == 1) { | |
| hexString.append('0'); | |
| } | |
| hexString.append(hex); | |
| } | |
| return hexString.toString(); | |
| } | |
| public static byte[] getSalt() throws NoSuchAlgorithmException, NoSuchProviderException { | |
| //Always use a SecureRandom generator | |
| SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN"); | |
| //Create array for salt | |
| byte [] salt = new byte[16]; | |
| //Get a random salt | |
| secureRandom.nextBytes(salt); | |
| //return salt | |
| return salt; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment