1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
| cat HashCrypt.java
package org.apache.ofbiz.base.crypto;
import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.util.Arrays;
import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang.RandomStringUtils; import org.apache.ofbiz.base.util.Debug; import org.apache.ofbiz.base.util.GeneralRuntimeException; import org.apache.ofbiz.base.util.StringUtil; import org.apache.ofbiz.base.util.UtilIO; import org.apache.ofbiz.base.util.UtilProperties; import org.apache.ofbiz.base.util.UtilValidate;
public class HashCrypt {
public static final String module = HashCrypt.class.getName(); public static final String CRYPT_CHAR_SET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./";
private static final String PBKDF2_SHA1 ="PBKDF2-SHA1"; private static final String PBKDF2_SHA256 ="PBKDF2-SHA256"; private static final String PBKDF2_SHA384 ="PBKDF2-SHA384"; private static final String PBKDF2_SHA512 ="PBKDF2-SHA512"; private static final int PBKDF2_ITERATIONS = UtilProperties.getPropertyAsInteger("security.properties", "password.encrypt.pbkdf2.iterations", 10000);
public static MessageDigest getMessageDigest(String type) { try { return MessageDigest.getInstance(type); } catch (NoSuchAlgorithmException e) { throw new GeneralRuntimeException("Could not load digestor(" + type + ")", e); } }
public static boolean comparePassword(String crypted, String defaultCrypt, String password) { if (crypted.startsWith("{PBKDF2")) { return doComparePbkdf2(crypted, password); } else if (crypted.startsWith("{")) { return doCompareTypePrefix(crypted, defaultCrypt, password.getBytes(UtilIO.getUtf8())); } else if (crypted.startsWith("$")) { return doComparePosix(crypted, defaultCrypt, password.getBytes(UtilIO.getUtf8())); } else { return doCompareBare(crypted, defaultCrypt, password.getBytes(UtilIO.getUtf8())); } }
private static boolean doCompareTypePrefix(String crypted, String defaultCrypt, byte[] bytes) { int typeEnd = crypted.indexOf("}"); String hashType = crypted.substring(1, typeEnd); String hashed = crypted.substring(typeEnd + 1); MessageDigest messagedigest = getMessageDigest(hashType); messagedigest.update(bytes); byte[] digestBytes = messagedigest.digest(); char[] digestChars = Hex.encodeHex(digestBytes); String checkCrypted = new String(digestChars); if (hashed.equals(checkCrypted)) { return true; } if (hashed.equals(oldFunnyHex(digestBytes))) { Debug.logWarning("Warning: detected oldFunnyHex password prefixed with a hashType; this is not valid, please update the value in the database with ({%s}%s)", module, hashType, checkCrypted); return true; } return false; }
private static boolean doComparePosix(String crypted, String defaultCrypt, byte[] bytes) { int typeEnd = crypted.indexOf("$", 1); int saltEnd = crypted.indexOf("$", typeEnd + 1); String hashType = crypted.substring(1, typeEnd); String salt = crypted.substring(typeEnd + 1, saltEnd); String hashed = crypted.substring(saltEnd + 1); return hashed.equals(getCryptedBytes(hashType, salt, bytes)); }
private static boolean doCompareBare(String crypted, String defaultCrypt, byte[] bytes) { String hashType = defaultCrypt; String hashed = crypted; MessageDigest messagedigest = getMessageDigest(hashType); messagedigest.update(bytes); return hashed.equals(oldFunnyHex(messagedigest.digest())); }
@Deprecated public static String cryptPassword(String hashType, String salt, String password) { if (hashType.startsWith("PBKDF2")) { return password != null ? pbkdf2HashCrypt(hashType, salt, password) : null; } return password != null ? cryptBytes(hashType, salt, password.getBytes(UtilIO.getUtf8())) : null; }
public static String cryptUTF8(String hashType, String salt, String value) { if (hashType.startsWith("PBKDF2")) { return value != null ? pbkdf2HashCrypt(hashType, salt, value) : null; } return value != null ? cryptBytes(hashType, salt, value.getBytes(UtilIO.getUtf8())) : null; }
public static String cryptValue(String hashType, String salt, String value) { if (hashType.startsWith("PBKDF2")) { return value != null ? pbkdf2HashCrypt(hashType, salt, value) : null; } return value != null ? cryptBytes(hashType, salt, value.getBytes(UtilIO.getUtf8())) : null; }
public static String cryptBytes(String hashType, String salt, byte[] bytes) { if (hashType == null) { hashType = "SHA"; } if (salt == null) { salt = RandomStringUtils.random(new SecureRandom().nextInt(15) + 1, CRYPT_CHAR_SET); } StringBuilder sb = new StringBuilder(); sb.append("$").append(hashType).append("$").append(salt).append("$"); sb.append(getCryptedBytes(hashType, salt, bytes)); return sb.toString(); }
private static String getCryptedBytes(String hashType, String salt, byte[] bytes) { try { MessageDigest messagedigest = MessageDigest.getInstance(hashType); messagedigest.update(salt.getBytes(UtilIO.getUtf8())); messagedigest.update(bytes); return Base64.encodeBase64URLSafeString(messagedigest.digest()).replace('+', '.'); } catch (NoSuchAlgorithmException e) { throw new GeneralRuntimeException("Error while comparing password", e); } }
public static String pbkdf2HashCrypt(String hashType, String salt, String value){ char[] chars = value.toCharArray(); if (UtilValidate.isEmpty(salt)) { salt = getSalt(); } try { PBEKeySpec spec = new PBEKeySpec(chars, salt.getBytes(UtilIO.getUtf8()), PBKDF2_ITERATIONS, 64 * 4); SecretKeyFactory skf = SecretKeyFactory.getInstance(hashType); byte[] hash = Base64.encodeBase64(skf.generateSecret(spec).getEncoded()); String pbkdf2Type = null; switch (hashType) { case "PBKDF2WithHmacSHA1": pbkdf2Type = PBKDF2_SHA1; break; case "PBKDF2WithHmacSHA256": pbkdf2Type = PBKDF2_SHA256; break; case "PBKDF2WithHmacSHA384": pbkdf2Type = PBKDF2_SHA384; break; case "PBKDF2WithHmacSHA512": pbkdf2Type = PBKDF2_SHA512; break; default: pbkdf2Type = PBKDF2_SHA1; } StringBuilder sb = new StringBuilder(); sb.append("{").append(pbkdf2Type).append("}"); sb.append(PBKDF2_ITERATIONS).append("$"); sb.append(org.apache.ofbiz.base.util.Base64.base64Encode(salt)).append("$"); sb.append(new String(hash)); return sb.toString(); } catch (InvalidKeySpecException e) { throw new GeneralRuntimeException("Error while creating SecretKey", e); } catch (NoSuchAlgorithmException e) { throw new GeneralRuntimeException("Error while computing SecretKeyFactory", e); } }
public static boolean doComparePbkdf2(String crypted, String password){ try { int typeEnd = crypted.indexOf("}"); String hashType = crypted.substring(1, typeEnd); String[] parts = crypted.split("\\$"); int iterations = Integer.parseInt(parts[0].substring(typeEnd+1)); byte[] salt = org.apache.ofbiz.base.util.Base64.base64Decode(parts[1]).getBytes(UtilIO.getUtf8()); byte[] hash = Base64.decodeBase64(parts[2].getBytes(UtilIO.getUtf8()));
PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, hash.length * 8); switch (hashType.substring(hashType.indexOf("-")+1)) { case "SHA256": hashType = "PBKDF2WithHmacSHA256"; break; case "SHA384": hashType = "PBKDF2WithHmacSHA384"; break; case "SHA512": hashType = "PBKDF2WithHmacSHA512"; break; default: hashType = "PBKDF2WithHmacSHA1"; } SecretKeyFactory skf = SecretKeyFactory.getInstance(hashType); byte[] testHash = skf.generateSecret(spec).getEncoded(); int diff = hash.length ^ testHash.length;
for (int i = 0; i < hash.length && i < testHash.length; i++) { diff |= hash[i] ^ testHash[i]; }
return diff == 0; } catch (NoSuchAlgorithmException e) { throw new GeneralRuntimeException("Error while computing SecretKeyFactory", e); } catch (InvalidKeySpecException e) { throw new GeneralRuntimeException("Error while creating SecretKey", e); } }
private static String getSalt() { try { SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); byte[] salt = new byte[16]; sr.nextBytes(salt); return Arrays.toString(salt); } catch (NoSuchAlgorithmException e) { throw new GeneralRuntimeException("Error while creating salt", e); } }
public static String digestHash(String hashType, String code, String str) { if (str == null) { return null; } byte[] codeBytes; try { if (code == null) { codeBytes = str.getBytes(UtilIO.getUtf8()); } else { codeBytes = str.getBytes(code); } } catch (UnsupportedEncodingException e) { throw new GeneralRuntimeException("Error while computing hash of type " + hashType, e); } return digestHash(hashType, codeBytes); }
public static String digestHash(String hashType, byte[] bytes) { try { MessageDigest messagedigest = MessageDigest.getInstance(hashType); messagedigest.update(bytes); byte[] digestBytes = messagedigest.digest(); char[] digestChars = Hex.encodeHex(digestBytes);
StringBuilder sb = new StringBuilder(); sb.append("{").append(hashType).append("}"); sb.append(digestChars, 0, digestChars.length); return sb.toString(); } catch (NoSuchAlgorithmException e) { throw new GeneralRuntimeException("Error while computing hash of type " + hashType, e); } }
public static String digestHash64(String hashType, byte[] bytes) { if (hashType == null) { hashType = "SHA"; } try { MessageDigest messagedigest = MessageDigest.getInstance(hashType); messagedigest.update(bytes); byte[] digestBytes = messagedigest.digest();
StringBuilder sb = new StringBuilder(); sb.append("{").append(hashType).append("}"); sb.append(Base64.encodeBase64URLSafeString(digestBytes).replace('+', '.')); return sb.toString(); } catch (NoSuchAlgorithmException e) { throw new GeneralRuntimeException("Error while computing hash of type " + hashType, e); } }
@Deprecated public static String getHashTypeFromPrefix(String hashString) { if (UtilValidate.isEmpty(hashString) || hashString.charAt(0) != '{') { return null; }
return hashString.substring(1, hashString.indexOf('}')); }
@Deprecated public static String removeHashTypePrefix(String hashString) { if (UtilValidate.isEmpty(hashString) || hashString.charAt(0) != '{') { return hashString; }
return hashString.substring(hashString.indexOf('}') + 1); }
@Deprecated public static String getDigestHashOldFunnyHexEncode(String str, String hashType) { return digestHashOldFunnyHex(hashType, str); }
public static String digestHashOldFunnyHex(String hashType, String str) { if (UtilValidate.isEmpty(hashType)) { hashType = "SHA"; } if (str == null) { return null; } try { MessageDigest messagedigest = MessageDigest.getInstance(hashType); byte[] strBytes = str.getBytes(UtilIO.getUtf8());
messagedigest.update(strBytes); return oldFunnyHex(messagedigest.digest()); } catch (Exception e) { Debug.logError(e, "Error while computing hash of type " + hashType, module); } return str; }
private static String oldFunnyHex(byte[] bytes) { int k = 0; char[] digestChars = new char[bytes.length * 2]; for (byte b : bytes) { int i1 = b;
if (i1 < 0) { i1 = 127 + i1 * -1; } StringUtil.encodeInt(i1, k, digestChars); k += 2; } return new String(digestChars); } }
|