import java.security.SecureRandom; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import javax.crypto.KeyGenerator; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Formatter; import java.util.Scanner; /* * PBKDF2 salted password hashing. * Author: havoc AT defuse.ca * www: http://crackstation.net/hashing-security.htm */ public class TokenLogin { public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1"; // The following constants may be changed without breaking existing hashes. public static final int SALT_BYTES = 20; public static final int HASH_BYTES = 20; public static final int PBKDF2_ITERATIONS = 1000; public static final int ITERATION_INDEX = 0; public static final int SALT_INDEX = 1; public static final int PBKDF2_INDEX = 2; /** * Returns a salted PBKDF2 hash of the password. * * @param password the password to hash * @return a salted PBKDF2 hash of the password */ public static String createHash(String password) throws NoSuchAlgorithmException, InvalidKeySpecException { return createHash(password.toCharArray()); } /** * Returns a salted PBKDF2 hash of the password. * * @param password the password to hash * @return a salted PBKDF2 hash of the password */ public static String createHash(char[] password) throws NoSuchAlgorithmException, InvalidKeySpecException { // Generate a random salt SecureRandom random = new SecureRandom(); byte[] salt = new byte[SALT_BYTES]; random.nextBytes(salt); // Hash the password byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTES); // format iterations:salt:hash return PBKDF2_ITERATIONS + ":" + toHex(salt) + ":" + toHex(hash); } /** * Validates a password using a hash. * * @param password the password to check * @param goodHash the hash of the valid password * @return true if the password is correct, false if not */ public static boolean validatePassword(String password, String goodHash) throws NoSuchAlgorithmException, InvalidKeySpecException { return validatePassword(password.toCharArray(), goodHash); } /** * Validates a password using a hash. * * @param password the password to check * @param goodHash the hash of the valid password * @return true if the password is correct, false if not */ public static boolean validatePassword(char[] password, String goodHash) throws NoSuchAlgorithmException, InvalidKeySpecException { // Decode the hash into its parameters String[] params = goodHash.split(":"); int iterations = Integer.parseInt(params[ITERATION_INDEX]); byte[] salt = fromHex(params[SALT_INDEX]); byte[] hash = fromHex(params[PBKDF2_INDEX]); // Compute the hash of the provided password, using the same salt, // iteration count, and hash length byte[] testHash = pbkdf2(password, salt, iterations, hash.length); // Compare the hashes in constant time. The password is correct if // both hashes match. return slowEquals(hash, testHash); } /** * Compares two byte arrays in length-constant time. This comparison method * is used so that password hashes cannot be extracted from an on-line * system using a timing attack and then attacked off-line. * * @param a the first byte array * @param b the second byte array * @return true if both byte arrays are the same, false if not */ private static boolean slowEquals(byte[] a, byte[] b) { int diff = a.length ^ b.length; for(int i = 0; i < a.length && i < b.length; i++) diff |= a[i] ^ b[i]; return diff == 0; } /** * Computes the PBKDF2 hash of a password. * * @param password the password to hash. * @param salt the salt * @param iterations the iteration count (slowness factor) * @param bytes the length of the hash to compute in bytes * @return the PBDKF2 hash of the password */ private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes) throws NoSuchAlgorithmException, InvalidKeySpecException { PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8); SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM); return skf.generateSecret(spec).getEncoded(); } /** * Converts a string of hexadecimal characters into a byte array. * * @param hex the hex string * @return the hex string decoded into a byte array */ private static byte[] fromHex(String hex) { byte[] binary = new byte[hex.length() / 2]; for(int i = 0; i < binary.length; i++) { binary[i] = (byte)Integer.parseInt(hex.substring(2*i, 2*i+2), 16); } return binary; } /** * Converts a byte array into a hexadecimal string. * * @param array the byte array to convert * @return a length*2 character string encoding the byte array */ private static String toHex(byte[] array) { BigInteger bi = new BigInteger(1, array); String hex = bi.toString(16); int paddingLength = (array.length * 2) - hex.length(); if(paddingLength > 0) return String.format("%0" + paddingLength + "d", 0) + hex; else return hex; } public static String bytesToHex(byte[] bytes) { StringBuilder sb = new StringBuilder(bytes.length * 2); @SuppressWarnings("resource") Formatter formatter = new Formatter(sb); for (byte b : bytes) { formatter.format("%02x", b); } return sb.toString(); } public static byte[] generateAutoLoginToken(byte[] secretToken, String time) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(secretToken); md.update(time.getBytes()); byte[] autoLoginToken = md.digest(); return autoLoginToken; } public static boolean verifyAutoLoginToken(Mac mac, byte[] publicToken, String time, byte[] autoLoginToken) throws NoSuchAlgorithmException { mac.update(publicToken); byte[] secretToken1 = mac.doFinal(); System.out.println("비밀토큰: SecToken=HMAC(PubToken,K)"); System.out.println("서버에서 복구된 비밀 토큰: "+bytesToHex(secretToken1)); MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(secretToken1); md.update(time.getBytes()); byte[] autoLoginToken1 = md.digest(); System.out.println("자동로그인토큰: AutoLoginToken=H(SecToken,T)"); System.out.println("서버에서 계산된 자동로그인 토큰: "+bytesToHex(autoLoginToken1)); if(slowEquals(autoLoginToken, autoLoginToken1)) return true; else return false; } /** * Tests the basic functionality of the PasswordHash class * * @param args ignored */ public static void main(String[] args) { Scanner a = new Scanner(System.in); try { KeyGenerator kg = KeyGenerator.getInstance("AES"); SecretKey key = kg.generateKey(); SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(),"HmacSHA1"); byte[] serverKey = key.getEncoded(); System.out.println("안전한 자동 로그인 시스템 시뮬레이션"); System.out.println(); System.out.println("서버의 비밀키 (K) : "+bytesToHex(serverKey)); System.out.println(); // Test password validation System.out.println("시뮬레이션 순서 "); System.out.println(); System.out.println("1. 사용자 등록 (서버에 아이디, 패스워드 등록)"); System.out.println("2. 사용자 로그인 (아이디, 패스워드로 서버에 로그인)"); System.out.println("3. 서버가 사용자에게 토큰 발급 "); System.out.println("4. 토큰을 이용한 자동 로그인 "); System.out.println("5. 서버의 자동 로그인 검증 "); System.out.println(); System.out.println("1. 사용자 등록 "); System.out.print("등록할 아이디를 입력하세요>> "); String id= a.next(); System.out.print("등록할 패스워드를 입력하세요>> "); String password = a.next(); String hash = createHash(password); System.out.println("사용자가 입력한 아이디(ID): "+id); System.out.println("사용자가 입력한 패스워드(Pass): "+password); System.out.println("서버에 저장된 패스워드 해쉬(PassHash): "+hash); if(validatePassword(password, hash)) { System.out.println("패스워드 유효성 검증: valid"); //System.out.println("Valid Password!"); } else { System.out.println("Error - Invalid Password!"); } System.out.println(); System.out.println("2. 사용자 로그인 "); System.out.print("로그인하려면 패스워드를 입력하세요>> "); String password1 = a.next(); System.out.println("사용자가 입력한 패스워드(Pass): "+password1); if(validatePassword(password1, hash)) { System.out.println("--->로그인 완료"); } else System.out.println("Error - Invalid Password!"); System.out.println(); System.out.println("3. 서버가 로그인된 사용자에게 토큰 발급 "); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(keySpec); mac.update(id.getBytes()); byte[] publicToken = mac.doFinal(); System.out.println("공개토큰: PubToken=HMAC(ID,기기명,유효기간,K)"); System.out.println("공개토큰: "+bytesToHex(publicToken)); mac.update(publicToken); byte[] secretToken = mac.doFinal(); System.out.println("비밀토큰: SecToken=HMAC(PubToken,K)"); System.out.println("비밀토큰: "+bytesToHex(secretToken)); System.out.println(); while(true) { System.out.print("자동로그인을 할까요?>> (y/n) "); String yn= a.next(); System.out.println(); if(yn.equalsIgnoreCase("y")) { System.out.println("4. 토큰을 이용한 자동 로그인 "); long curr1 = System.currentTimeMillis(); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy:MM:dd-hh:mm:ss"); String datetime1 = sdf1.format(new Date(curr1)); System.out.println("현재시간(T): " + datetime1); byte[] autoLoginToken = generateAutoLoginToken(secretToken, datetime1); System.out.println("서버에게 전송되는 공개토큰: "+bytesToHex(publicToken)); System.out.println("자동로그인토큰: AutoLoginToken=H(SecToken,T)"); System.out.println("서버에게 전송되는 자동로그인 토큰: "+bytesToHex(autoLoginToken)); System.out.println(); System.out.println("5. 서버의 자동 로그인 검증 "); if(verifyAutoLoginToken(mac, publicToken, datetime1, autoLoginToken)) System.out.println("---> 자동로그인 허가"); else System.out.println("자동로그인 거부 - 다시 로그인 하세요."); long curr2 = System.currentTimeMillis(); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy:MM:dd-hh:mm:ss"); String datetime2 = sdf2.format(new Date(curr2)); System.out.println("현재시간: " + datetime2); long dt = curr2 - curr1; System.out.println("시간차이: " + dt +" msec"); System.out.println(); } else break; } } catch(Exception ex) { System.out.println("ERROR: " + ex); } } }