List of usage examples for java.security MessageDigest reset
public void reset()
From source file:wptools.lib.Misc.java
/** * Bypass the normal SSL certificate authentication. If the passed * fingerprint is null, bypasses all authentication (dangerous). * Else trust anything whose chain contains a cert with the specified * fingerprint.//from w ww. j a va2 s . co m * @param fing Fingerprint */ public static void bypassSslAuth(final byte[] fing) { // Determine fingerprint type from its length final String type; if (fing == null) { type = null; } else { switch (fing.length) { case MD5_LEN: type = "MD5"; break; case SHA1_LEN: type = "SHA-1"; break; case SHA256_LEN: type = "SHA-256"; break; default: throw new IllegalArgumentException("Invalid hash."); } } // Create a trust manager TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException { matchFing(certs); } public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException { matchFing(certs); } private void matchFing(X509Certificate[] certs) throws CertificateException { if (fing == null) return; MessageDigest md = null; try { md = MessageDigest.getInstance(type); } catch (NoSuchAlgorithmException e) { throw new CertificateException(e); } for (X509Certificate cert : certs) { md.reset(); if (Arrays.equals(md.digest(cert.getEncoded()), fing)) return; } throw new CertificateException("No matching fingerprint found."); } } }; // Install the trust manager SSLContext sc = null; try { sc = SSLContext.getInstance("SSL"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } // Create empty HostnameVerifier HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String arg0, SSLSession arg1) { return true; } }; try { sc.init(null, trustAllCerts, new java.security.SecureRandom()); } catch (KeyManagementException e) { throw new RuntimeException(e); } HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(hv); }
From source file:org.spirit.util.BotListUniqueId.java
public static final String getUniqueId() { String digest = ""; try {/*from ww w. ja va2 s . c o m*/ MessageDigest md = MessageDigest.getInstance("MD5"); String timeVal = "" + (System.currentTimeMillis() + 1); String localHost = ""; ; try { localHost = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { // If an error, we can use other values. log.error("Error trying to get localhost" + e.getMessage()); } String randVal = "" + new Random().nextInt(); String val = timeVal + localHost + randVal; md.reset(); md.update(val.getBytes()); // Generate the digest. digest = toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { log.error("Error trying to generate unique Id" + e.getMessage()); } // End of the Try - Catch return digest; }
From source file:com.mnt.base.web.DigestAuthenticator.java
static public String md5(String sb, char[] passwd) { byte[] unencodedPassword = sb.toString().getBytes(); MessageDigest md = null; try {/* w ww. ja v a 2 s . c om*/ md = MessageDigest.getInstance("MD5"); } catch (Exception e) { return sb.toString(); } md.reset(); md.update(unencodedPassword); for (int i = 0; i < passwd.length; i++) { md.update((byte) passwd[i]); } byte[] digest = md.digest(); //StringBuffer buf = new StringBuffer(); /*char j; for (int i = 0; i < encodedPassword.length; i++) { j = (char)((encodedPassword[i] >> 4) & 0xf); if(j <= 9) { buf.append((char)(j + '0')); } else { buf.append((char)(j + 'a' - 10)); } j = (char)((encodedPassword[i]) & 0xf); if(j <= 9) { buf.append((char)(j + '0')); } else { buf.append((char)(j + 'a' - 10)); } }*/ StringBuffer res = new StringBuffer(digest.length * 2); for (int i = 0; i < digest.length; i++) { int hashchar = ((digest[i] >>> 4) & 0xf); res.append(charArray[hashchar]); hashchar = (digest[i] & 0xf); res.append(charArray[hashchar]); } return res.toString(); }
From source file:com.mnt.base.web.DigestAuthenticator.java
static public String md5(String... ss) { StringBuilder sb = new StringBuilder(); if (ss != null) { for (String si : ss) { sb.append(si);/*from ww w.j av a 2 s .c o m*/ } } byte[] unencodedPassword = sb.toString().getBytes(); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (Exception e) { return sb.toString(); } md.reset(); md.update(unencodedPassword); byte[] digest = md.digest(); //StringBuffer buf = new StringBuffer(); /*char j; for (int i = 0; i < encodedPassword.length; i++) { j = (char)((encodedPassword[i] >> 4) & 0xf); if(j <= 9) { buf.append((char)(j + '0')); } else { buf.append((char)(j + 'a' - 10)); } j = (char)((encodedPassword[i]) & 0xf); if(j <= 9) { buf.append((char)(j + '0')); } else { buf.append((char)(j + 'a' - 10)); } }*/ StringBuffer res = new StringBuffer(digest.length * 2); for (int i = 0; i < digest.length; i++) { int hashchar = ((digest[i] >>> 4) & 0xf); res.append(charArray[hashchar]); hashchar = (digest[i] & 0xf); res.append(charArray[hashchar]); } return res.toString(); }
From source file:fshp.FSHP.java
/** * Returns the hash of <tt>passwd</tt> * * @param passwd Byte representation of clear text password. * @param salt Byte representation of salt to be used in hashing. * @param saltlen Length of the salt. Should be 0 if a salt is already * provided. If salt is null, saltlen bytes of salt will be * auto generated./*from w w w.j a va2s . c om*/ * @param rounds Number of hashing rounds. * @param variant FSHP variant indicating the behaviour and/or * <ul> * <li><tt>0: SHA-1</tt> <em>(not recommended)</em></li> * <li><tt>1: SHA-256</tt></li> * <li><tt>2: SHA-384</tt></li> * <li><tt>3: SHA-512</tt></li> * </ul> * * @return FSHP hash of <tt>passwd</tt> */ public static String crypt(byte[] passwd, byte[] salt, int saltlen, int rounds, int variant) throws Exception { // Ensure we have sane values for salt length and rounds. if (saltlen < 0) saltlen = 0; if (rounds < 1) rounds = 1; if (salt == null) { salt = new byte[saltlen]; new SecureRandom().nextBytes(salt); } else saltlen = salt.length; HashMap<Integer, String> algoMap = new HashMap<Integer, String>(); algoMap.put(0, "SHA-1"); algoMap.put(1, "SHA-256"); algoMap.put(2, "SHA-384"); algoMap.put(3, "SHA-512"); MessageDigest md; try { if (!algoMap.containsKey(variant)) throw new NoSuchAlgorithmException(); md = MessageDigest.getInstance(algoMap.get(variant)); } catch (NoSuchAlgorithmException e) { throw new Exception("Unsupported FSHP variant " + variant); } md.update(salt); md.update(passwd); byte[] digest = md.digest(); for (int i = 1; i < rounds; i++) { md.reset(); md.update(digest); digest = md.digest(); } String meta = "{FSHP" + variant + "|" + saltlen + "|" + rounds + "}"; byte[] saltdigest = new byte[salt.length + digest.length]; System.arraycopy(salt, 0, saltdigest, 0, salt.length); System.arraycopy(digest, 0, saltdigest, salt.length, digest.length); byte[] b64saltdigest = Base64.encodeBase64(saltdigest); return meta + new String(b64saltdigest, "US-ASCII"); }
From source file:org.craftercms.cstudio.alfresco.dm.util.DmUtils.java
public static String getMd5ForFile(InputStream input) { //PushbackInputStream helper = null; String result = null;//from ww w . j a v a 2 s . c o m MessageDigest md = null; try { //helper = new PushbackInputStream(input); //InputStreamReader reader = new InputStreamReader(input); md = MessageDigest.getInstance("MD5"); md.reset(); byte[] bytes = new byte[1024]; int numBytes; //input.mark(input.available()); input.mark(Integer.MAX_VALUE); while ((numBytes = input.read(bytes)) != -1) { md.update(bytes, 0, numBytes); } byte[] digest = md.digest(); result = new String(Hex.encodeHex(digest)); input.reset(); } catch (NoSuchAlgorithmException e) { logger.error("Error while creating MD5 digest", e); } catch (IOException e) { logger.error("Error while reading input stream", e); } finally { } return result; }
From source file:org.zilverline.util.FileUtils.java
/** * Get the MD5 hash (unique identifier based on contents) of a file. * //from ww w. ja v a 2 s . c om * <p> * N.B. This is an expensive operation, since the entire file is read. * </p> * * @param sourceFile the File the MD5 hash is created from, can take null or not a normalFile * * @return MD5 hash of file as a String, null if it can't create a hash. */ public static String getMD5Hash(final File sourceFile) { log.debug("Getting MD5 hash for " + sourceFile); final char[] HEX = "0123456789abcdef".toCharArray(); if (sourceFile == null || !sourceFile.isFile()) { log.error("Error creating MD5 Hash for " + sourceFile); return null; } BufferedInputStream bis = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); // IMessageDigest md = HashFactory.getInstance("MD5"); if (md == null) { log.error("Error creating MessageDigest for " + sourceFile); return null; } bis = new BufferedInputStream(new FileInputStream(sourceFile)); md.reset(); int len = 0; byte[] buffer = new byte[8192]; while ((len = bis.read(buffer)) > -1) { md.update(buffer, 0, len); } byte[] bytes = md.digest(); if (bytes == null) { log.error("MessageDigest has no bytes for " + sourceFile); return null; } // base64? encode the digest StringBuffer sb = new StringBuffer(bytes.length * 2); int b; for (int i = 0; i < bytes.length; i++) { b = bytes[i] & 0xFF; sb.append(HEX[b >>> 4]); sb.append(HEX[b & 0x0F]); } log.debug("MD5 hash for " + sourceFile + " is " + sb); return sb.toString(); } catch (Exception e) { log.error("Can't determine MD5 hash for " + sourceFile, e); return null; } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { log.warn("Can't close stream for " + sourceFile, e); } } } }
From source file:com.google.sampling.experiential.model.Event.java
public static String getAnonymousId(String who) { MessageDigest messageDigest = null; try {//from w w w . j av a 2 s. c om messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { //Log.info("Could not get MD5 algorithm"); return null; } messageDigest.reset(); messageDigest.update(who.getBytes(Charset.forName("UTF8"))); byte[] resultByte = messageDigest.digest(); return new String(Hex.encodeHex(resultByte)); }
From source file:org.openme_ck.openme_ck.java
public static JSONObject convert_str_to_sha1(JSONObject i) { /*/*from w w w.j ava2 s . c o m*/ Convert string to sha1 Input: { string - string } Output: { return - return code >0 if not authentificated string_sha1 - password in SHA1 (digest) string_sha1_hex - password in SHA1 (digest in hex) string_sha1_base64 - BASE64 (SHA1 digest) - compatible with htpasswd format } */ byte[] sha1 = null; String sha1_hex = ""; String sha1_base64 = ""; // Prepare return object JSONObject r = new JSONObject(); String x = (String) i.get("string"); if (x == null || x == "") { r.put("return", new Long(1)); r.put("error", "'string' is not set in openme/convert_str_to_sha1"); return r; } try { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(x.getBytes("UTF-8")); sha1 = crypt.digest(); sha1_hex = byteToHexString(sha1); sha1_base64 = new String(Base64.encodeBase64(sha1)); } catch (NoSuchAlgorithmException e) { r.put("return", new Long(0)); r.put("error", "can't crypt password (" + e.getMessage() + ") ..."); return r; } catch (UnsupportedEncodingException e) { r.put("return", new Long(0)); r.put("error", "can't crypt password (" + e.getMessage() + ") ..."); return r; } r.put("return", new Long(0)); r.put("string_sha1", sha1.toString()); r.put("string_sha1_hex", sha1_hex); r.put("string_sha1_base64", sha1_base64); return r; }
From source file:org.openme.openme.java
public static JSONObject convert_str_to_sha1(JSONObject i) { /*/*from ww w . j a v a2s . c o m*/ Convert string to sha1 Input: { cm_string - string } Output: { cm_return - return code >0 if not authentificated cm_string_sha1 - password in SHA1 (digest) cm_string_sha1_hex - password in SHA1 (digest in hex) cm_string_sha1_base64 - BASE64 (SHA1 digest) - compatible with htpasswd format } */ byte[] sha1 = null; String sha1_hex = ""; String sha1_base64 = ""; // Prepare return object JSONObject r = new JSONObject(); String x = (String) i.get("cm_string"); if (x == null || x == "") { r.put("cm_return", new Long(1)); r.put("cm_error", "'cm_string' is not set in openme/convert_str_to_sha1"); return r; } try { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(x.getBytes("UTF-8")); sha1 = crypt.digest(); sha1_hex = byteToHexString(sha1); sha1_base64 = new String(Base64.encodeBase64(sha1)); } catch (NoSuchAlgorithmException e) { r.put("cm_return", new Long(0)); r.put("cm_error", "can't crypt password (" + e.getMessage() + ") ..."); return r; } catch (UnsupportedEncodingException e) { r.put("cm_return", new Long(0)); r.put("cm_error", "can't crypt password (" + e.getMessage() + ") ..."); return r; } r.put("cm_return", new Long(0)); r.put("cm_string_sha1", sha1.toString()); r.put("cm_string_sha1_hex", sha1_hex); r.put("cm_string_sha1_base64", sha1_base64); return r; }