1 23 package org.openharmonise.rm.security.authentication; 24 25 import java.security.*; 26 import java.util.logging.*; 27 28 29 35 public class CryptPasswordHelper implements PasswordHelper { 36 37 private final String algorithm; 38 39 private static final String hexits = "0123456789abcdef"; 40 private static final Logger logger = Logger.getLogger(CryptPasswordHelper.class.getName()); 41 42 46 public CryptPasswordHelper(String algorithm) { 47 if (algorithm.equals("MD5") || algorithm.equals("SHA-1")) { 48 this.algorithm = algorithm; 49 logger.log(Level.FINE, "Set up cryptpassword handler to use algorithm " + algorithm); 50 } 51 else { 52 throw new IllegalArgumentException ("Unsupported algorithm - only MD5 or SHA-1 supported"); 53 } 54 } 55 56 59 public boolean compare(String presentedPassword, String storedPassword, String salt) { 60 61 String hashedPassword = null; 63 try { 64 MessageDigest md = MessageDigest.getInstance(algorithm); 65 md.update(presentedPassword.getBytes()); 66 md.update(salt.getBytes()); 67 hashedPassword = toHex(md.digest()); 68 } 69 catch (NoSuchAlgorithmException e) { 70 logger.log(Level.SEVERE, "no such algorithm exception", e); 71 } 72 73 if (hashedPassword.equals(storedPassword)) { 74 return true; 75 } 76 else { 77 return false; 78 } 79 } 80 81 86 public String getNewPassword(String newPassword, String salt) { 87 String hashedPassword = null; 88 try { 89 MessageDigest md = MessageDigest.getInstance(algorithm); 90 md.update(newPassword.getBytes()); 91 md.update(salt.getBytes()); 92 hashedPassword = toHex(md.digest()); 93 } 94 catch (NoSuchAlgorithmException e) { 95 logger.log(Level.SEVERE, "no such algorithm exception", e); 96 } 97 return hashedPassword; 98 } 99 100 101 102 107 private static String toHex(byte[] block) { 108 StringBuffer buf = new StringBuffer (); 109 for (int i = 0; i < block.length; ++i) { 110 buf.append(hexits.charAt((block[i] >>> 4) & 0xf)); 111 buf.append(hexits.charAt(block[i] & 0xf)); 112 } 113 return buf + ""; 114 } 115 116 121 private static byte[] fromHex(String s) { 122 s = s.toLowerCase(); 123 byte[] b = new byte[(s.length() + 1) / 2]; 124 int j = 0; 125 int h; 126 int nybble = -1; 127 for (int i = 0; i < s.length(); ++i) { 128 h = hexits.indexOf(s.charAt(i)); 129 if (h >= 0) { 130 if (nybble < 0) { 131 nybble = h; 132 } else { 133 b[j++] = (byte) ((nybble << 4) + h); 134 nybble = -1; 135 } 136 } 137 } 138 if (nybble >= 0) { 139 b[j++] = (byte) (nybble << 4); 140 } 141 if (j < b.length) { 142 byte[] b2 = new byte[j]; 143 System.arraycopy(b, 0, b2, 0, j); 144 b = b2; 145 } 146 return b; 147 } 148 149 } 150 | Popular Tags |