Advertisement
Nakumas

PBKDF2Encoder

Jul 2nd, 2019
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.27 KB | None | 0 0
  1. package pbkdf2encoder;
  2.  
  3. import java.math.BigInteger;
  4. import java.security.GeneralSecurityException;
  5. import java.util.Scanner;
  6.  
  7. //importy dla pbkdf2
  8. import javax.crypto.spec.PBEKeySpec;
  9. import javax.crypto.SecretKeyFactory;
  10. import java.util.Base64;
  11.  
  12. public class PBKDF2Encoder
  13. {
  14.     public static void main(String[] args) throws GeneralSecurityException
  15.     {
  16.         Encode();
  17.     }
  18.    
  19.     public static String toHex(byte[] hash)
  20.     {
  21.         BigInteger bi = new BigInteger(1, hash);
  22.         String hex = bi.toString(16);
  23.         return hex;
  24.     }
  25.    
  26.     public static byte[] PBKDF2(String paswd, byte[] salt, int pLength, int i)
  27.             throws GeneralSecurityException
  28.     {
  29.         PBEKeySpec keySpec = new PBEKeySpec(paswd.toCharArray(), salt, i, pLength * 4);
  30.         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
  31.         byte[] hash = keyFactory.generateSecret(keySpec).getEncoded();
  32.        
  33.         return hash;
  34.     }
  35.    
  36.     public static void Encode() throws GeneralSecurityException
  37.     {
  38.         String paswd, acc ,id;
  39.         int pLength, ver;
  40.         Scanner scanner = new Scanner(System.in);
  41.        
  42.         System.out.print("Hasło: ");
  43.         paswd = scanner.nextLine();
  44.         System.out.print("Konto: ");
  45.         acc = scanner.nextLine();
  46.         System.out.print("Identyfikator: ");
  47.         id = scanner.nextLine();
  48.         System.out.print("Długość: ");
  49.         pLength = scanner.nextInt();
  50.         System.out.print("Numer wersji: ");
  51.         ver = scanner.nextInt();
  52.        
  53. //        SecureRandom rnd = new SecureRandom();
  54. //        byte[] salt = new byte[24];
  55. //        rnd.nextBytes(salt);
  56.        
  57.         byte[] salt = (acc+id+ver).getBytes();
  58.  
  59.         byte[] hash = PBKDF2(paswd, salt, pLength, 1000);
  60.         String hex = toHex(hash);
  61.        
  62.         String b64 = Base64.getEncoder().withoutPadding().encodeToString(hex.getBytes());
  63.         char[] encd = new char[pLength];
  64.         char[] b64c = b64.toCharArray();
  65.        
  66.         for(int i=0; i<pLength;i++)
  67.             encd[i] = (char)(((int)b64c[i])+3);
  68.         System.out.print("Zakodowane hasło: ");
  69.         for(char e : encd)
  70.             System.out.print(e);
  71.         System.out.println();
  72.     }        
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement