package jcp; 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; 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; public static String createHash(String password) throws NoSuchAlgorithmException, InvalidKeySpecException { return createHash(password.toCharArray()); } 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); } public static boolean validatePassword(String password, String goodHash) throws NoSuchAlgorithmException, InvalidKeySpecException { return validatePassword(password.toCharArray(), goodHash); } 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); } 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; } 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(); } 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; } 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("(1)¼­¹ö¿¡¼­ º¹±¸µÈ ºñ¹Ð ÅäÅ«(SecToken) = HMAC(PubToken,K) = "+bytesToHex(secretToken1)); System.out.println("(2)Ŭ¶óÀ̾ðÆ®°¡ º¸³»¿Â ÀÏȸ¿ë ÀÎÁõ°ª = "+bytesToHex(autoLoginToken)); MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(secretToken1); md.update(time.getBytes()); byte[] autoLoginToken1 = md.digest(); System.out.println("(3)¼­¹ö¿¡¼­ °è»êµÈ ÀÏȸ¿ë ÀÎÁõ°ª = H(SecToken,T) = "+bytesToHex(autoLoginToken1)); if(slowEquals(autoLoginToken, autoLoginToken1)) return true; else return false; } 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) = "+bytesToHex(publicToken)); mac.update(publicToken); byte[] secretToken = mac.doFinal(); System.out.println("ºñ¹ÐÅäÅ«(SecToken) = HMAC(PubToken,K) = "+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("Ŭ¶óÀ̾ðÆ®°¡ ¼­¹ö¿¡°Ô Àü¼ÛÇÏ´Â Á¤º¸: 1)ÇöÀç½Ã°£, 2)°ø°³ÅäÅ«, 3)ÀÏȸ¿ëÀÎÁõ°ª"); System.out.println("(1)ÇöÀç½Ã°£(T): " + datetime1); System.out.println("(2)°ø°³ÅäÅ«(PubToken): "+bytesToHex(publicToken)); byte[] autoLoginToken = generateAutoLoginToken(secretToken, datetime1); System.out.println("(3)ÀÏȸ¿ë ÀÎÁõ°ª = H(SecToken,T) = "+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); } } }