List of usage examples for java.security MessageDigest reset
public void reset()
From source file:com.cloud.test.stress.StressTestDirectAttach.java
public static String createMD5Password(String password) { MessageDigest md5; try {/*from w w w . j a v a 2s. c o m*/ md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new CloudRuntimeException("Error", e); } md5.reset(); BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes())); // make sure our MD5 hash value is 32 digits long... StringBuffer sb = new StringBuffer(); String pwStr = pwInt.toString(16); int padding = 32 - pwStr.length(); for (int i = 0; i < padding; i++) { sb.append('0'); } sb.append(pwStr); return sb.toString(); }
From source file:egovframework.rte.fdl.string.EgovStringUtil.java
/** * Encode a string using algorithm specified in * web.xml and return the resulting encrypted * password. If exception, the plain credentials * string is returned/*w ww.jav a 2s . c o m*/ * @param password * Password or other credentials to use in * authenticating this username * @param algorithm * Algorithm used to do the digest * @return encypted password based on the * algorithm. */ public static String encodePassword(String password, String algorithm) { byte[] unencodedPassword = password.getBytes(); MessageDigest md = null; try { // first create an instance, given the // provider md = MessageDigest.getInstance(algorithm); } catch (Exception e) { log.error("Exception: " + e); return password; } md.reset(); // call the update method one or more times // (useful when you don't know the size of your // data, eg. stream) md.update(unencodedPassword); // now calculate the hash byte[] encodedPassword = md.digest(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < encodedPassword.length; i++) { if (((int) encodedPassword[i] & 0xff) < 0x10) { buf.append("0"); } buf.append(Long.toString((int) encodedPassword[i] & 0xff, 16)); } return buf.toString(); }
From source file:de.tiqsolutions.hdfs.HadoopFileSystemProvider.java
private String getURIKey(URI uri) { String s = String.format("%s://%s@%s:%d", getScheme(), uri.getUserInfo() == null ? "" : uri.getUserInfo(), uri.getHost(), uri.getPort()); try {// w w w . j a va 2 s . c om MessageDigest cript = MessageDigest.getInstance("SHA-1"); cript.reset(); cript.update(s.getBytes("utf8")); return new HexBinaryAdapter().marshal(cript.digest()); } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { } return null; }
From source file:us.camin.api.Server.java
private String genToken() { Random r = new Random(); int salt = r.nextInt(); MessageDigest crypt; try {/*from ww w. j a va2 s . c o m*/ crypt = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { log.warning("Could not find SHA-1 algorithm"); return ""; } crypt.reset(); String token = m_name + salt + m_secret; crypt.update(token.getBytes()); token = m_name + "$" + salt + "$" + Hex.encodeHexString(crypt.digest()); log.info("Generated token " + token + " from " + m_name + salt + m_secret); return token; }
From source file:ru.develgame.jflickrorganizer.MainForm.java
private void jMenuItemSetPasswordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemSetPasswordActionPerformed PasswordForm passwordForm = new PasswordForm(this, true); passwordForm.setVisible(true);/*from w w w .j a v a2 s . c o m*/ if (passwordForm.getAnswer()) { String hashedPass = ""; try { MessageDigest m = MessageDigest.getInstance("SHA-1"); m.reset(); m.update(passwordForm.getPassword().getBytes()); hashedPass = new String(m.digest()); } catch (NoSuchAlgorithmException ex) { // TODO return; } authorizer.getUser().setPass(hashedPass); userRepository.save(authorizer.getUser()); } passwordForm.dispose(); }
From source file:com.base.service.WeixinService.java
@Transactional public Map<String, String> getSignMap(String url) { WeixinApptoken apptoken = this.getToken(); String jsapi_ticket = apptoken.getJsapiTicket(); long timestamp = new Date().getTime(); if (StringUtils.isBlank(jsapi_ticket) || (timestamp - apptoken.getJsapiTime().getTime()) > 7200 * 1000L) { String accessToken = apptoken.getAccessToken(); String requesturl = get_jsapi_ticket_url.replaceAll("ACCESS_TOKEN", accessToken); String result = null;//from w ww .jav a 2 s . com try { // result = HTTPSRequest.httpsRequest(requesturl, "GET", null); result = HttpUtil.sendGet(requesturl, null); } catch (Exception e) { } JSONObject json = JSONObject.parseObject(result); if (json.containsKey("ticket")) { jsapi_ticket = json.getString("ticket"); apptoken.setJsapiTicket(jsapi_ticket); apptoken.setJsapiTime(new Date()); // TODO ?weixinApptokenService.saveOrUpdate()</p>?dao this.weixinDao.merge(apptoken); } } Map<String, String> ret = new HashMap<String, String>(); String nonce_str = create_nonce_str(); String string1; String signature = ""; // ?????? string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "×tamp=" + timestamp + "&url=" + url; try { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(string1.getBytes("UTF-8")); signature = byteToHex(crypt.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } ret.put("url", url); ret.put("jsapi_ticket", jsapi_ticket); ret.put("nonceStr", nonce_str); ret.put("timestamp", timestamp + ""); ret.put("signature", signature); ret.put("appId", apptoken.getAppId()); return ret; // return sign(this.getJsapi(), url); }
From source file:com.vkassin.mtrade.Common.java
public static String getMd5(String txt) { StringBuffer result = new StringBuffer(); try {/*from w w w . j a v a2s . c o m*/ MessageDigest m = MessageDigest.getInstance("MD5"); m.reset(); // m.update(txt.getBytes(Charset.forName("UTF-8"))); m.update(txt.getBytes()); byte[] digest = m.digest(); for (int i = 0; i < digest.length; i++) result.append(String.format("%02x", digest[i])); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); Log.e(TAG, "Error in getMd5!!", e); } return result.toString(); }
From source file:org.collectionspace.chain.csp.webui.userdetails.UserDetailsReset.java
private String createHash(String csid) throws UIException { try {//from www . j a v a 2s .c o m byte[] buffer = csid.getBytes(); byte[] result = null; StringBuffer buf = null; MessageDigest md5 = MessageDigest.getInstance("MD5"); result = new byte[md5.getDigestLength()]; md5.reset(); md5.update(buffer); result = md5.digest(tokensalt.getBytes()); //create hex string from the 16-byte hash buf = new StringBuffer(result.length * 2); for (int i = 0; i < result.length; i++) { int intVal = result[i] & 0xff; if (intVal < 0x10) { buf.append("0"); } buf.append(Integer.toHexString(intVal).toUpperCase()); } return buf.toString().substring(0, 5); } catch (NoSuchAlgorithmException e) { throw new UIException("There were problems with the algorithum"); } }
From source file:org.ejbca.ui.cmpclient.CmpClientMessageHelper.java
private PKIMessage protectPKIMessageWithHMAC(PKIMessage msg, boolean badObjectId, String password, int iterations) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException { // Create the PasswordBased protection of the message PKIHeaderBuilder head = getHeaderBuilder(msg.getHeader()); // SHA1//from ww w . j a v a 2s . c o m AlgorithmIdentifier owfAlg = new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.3.14.3.2.26")); // 567 iterations int iterationCount = iterations; ASN1Integer iteration = new ASN1Integer(iterationCount); // HMAC/SHA1 AlgorithmIdentifier macAlg = new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.2.840.113549.2.7")); byte[] salt = "foo123".getBytes(); DEROctetString derSalt = new DEROctetString(salt); // Create the new protected return message String objectId = "1.2.840.113533.7.66.13"; if (badObjectId) { objectId += ".7"; } PBMParameter pp = new PBMParameter(derSalt, owfAlg, iteration, macAlg); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(new ASN1ObjectIdentifier(objectId), pp); head.setProtectionAlg(pAlg); PKIHeader header = head.build(); // Calculate the protection bits byte[] raSecret = password.getBytes(); byte[] basekey = new byte[raSecret.length + salt.length]; System.arraycopy(raSecret, 0, basekey, 0, raSecret.length); for (int i = 0; i < salt.length; i++) { basekey[raSecret.length + i] = salt[i]; } // Construct the base key according to rfc4210, section 5.1.3.1 MessageDigest dig = MessageDigest.getInstance(owfAlg.getAlgorithm().getId(), "BC"); for (int i = 0; i < iterationCount; i++) { basekey = dig.digest(basekey); dig.reset(); } // For HMAC/SHA1 there is another oid, that is not known in BC, but the // result is the same so... String macOid = macAlg.getAlgorithm().getId(); PKIBody body = msg.getBody(); byte[] protectedBytes = getProtectedBytes(header, body); Mac mac = Mac.getInstance(macOid, "BC"); SecretKey key = new SecretKeySpec(basekey, macOid); mac.init(key); mac.reset(); mac.update(protectedBytes, 0, protectedBytes.length); byte[] out = mac.doFinal(); DERBitString bs = new DERBitString(out); return new PKIMessage(header, body, bs); }
From source file:edu.odu.cs.cs350.yellow1.jar.ExecuteJar.java
/** * /*from ww w . ja v a2 s. c o m*/ * {@inheritDoc} * <br>Run all tests in the test suit on the mutant * capturing the output created and if the execution of the mutant with a test exits successfully compare the standard output generated by<br> * the mutant if different stop running tests and return {@link ExecutionResults} * <br> Treats exiting the jvm with error as was not killed continue to run more tests * @return {@link ExecutionResults} */ @Override public ExecutionResults call() throws Exception { //create new Executor for monitoring mutation running executor = new DefaultExecutor(); //get a MessageDigest Instance for use in comparing outputs MessageDigest mDigest = MessageDigest.getInstance("MD5"); //get file object for gold file File f = new File(pathToGold); //get the hash value for the gold file goldHash = mDigest.digest(FileUtils.readFileToByteArray(f)); //reset the MessageDigest mDigest.reset(); int testCount = 0; //Create a new ExecuteWatchdog with timeout at 10 seconds wDog = new ExecuteWatchdog(10000); executor.setWatchdog(wDog); //loop through the tests till empty while (!tests.isEmpty()) { //get the next test File test = tests.poll();//poll removes the test from the queue //prepair captured output files String testName = test.getName(); testName = testName.toUpperCase(Locale.getDefault()).substring(0, testName.indexOf(".")); String outName = jarName + "_" + testName + "_out.txt"; String errOutName = jarName + "_" + testName + "_err.txt"; //create file objects to be written to File standardOut = new File(pathToOutputDir + File.separator + outName); File standardErr = new File(pathToOutputDir + File.separator + errOutName); //file streams create the files for me try { log = new FileOutputStream(standardOut); err = new FileOutputStream(standardErr); } catch (FileNotFoundException e1) { logger.error("log or err file not found for jar " + jarName, e1.getMessage()); } //create new stream handler for each execution streamHandler = new PumpStreamHandler(/* standard out */log, /* error out */err); executor.setStreamHandler(streamHandler); //construct the executable command CommandLine args = new CommandLine(pathToJVM); args.addArgument("-jar"); args.addArgument(jar.getAbsolutePath()); args.addArgument(test.getAbsolutePath()); //new process destroyer per execution ShutDownSpawnedJVMProcess killJVM = new ShutDownSpawnedJVMProcess("java -jar " + jarName, 10000); killJVM.setWaitOnShutdown(true); executor.setProcessDestroyer(killJVM); success = false; try { streamHandler.start(); int result = executor.execute(args); logger.info(jarName + " Sucess with val=[" + result + "] for test[" + testName + "]"); success = true; } catch (ExecuteException ee) { logger.error(jarName + " Execute exception " + ee.getMessage() + " with val=[" + ee.getExitValue() + "] for test[" + testName + "]"); } catch (IOException e) { logger.error(jarName + " IOExecption " + e.getMessage()); } finally { //PumpStreamHandler does not guarantee the closing of stream 100% so to release the locks held by the filestreams //on the created output files so close manually //if the streamhandler was able to close then this will through exception which we ignore try { streamHandler.stop(); //log.flush(); log.close(); //err.flush(); err.close(); } catch (IOException e) { logger.error(e.getMessage()); //ignore nothing I can do } } //if the spawned process exited with success value //check the hash of the output file and delete the empty error file //if the hash is different the mutant was killed otherwise test more //if the spawned process exited with an error value delete empty standard out file and test more if (success) { ++numOfSucesses; standardErr.delete(); outFiles.add(standardOut); if (!Arrays.equals(goldHash, mDigest.digest(FileUtils.readFileToByteArray(standardOut)))) { testMore = false; logger.debug("Different hashes for jar [" + jarName + "] for test [" + testName + "]"); } else { logger.debug("Same hashes for jar [" + jarName + "] for test [" + testName + "]"); } mDigest.reset(); } else { ++numOfFailurs; standardOut.delete(); errFiles.add(standardErr); this.didNotExecute.add(test); } ++testCount; //the mutant was killed so stop testing if (!testMore) { testMore = false; killed = true; testNumKilledME = testCount; break; } } jar.delete(); return new ExecutionResults(numOfSucesses, numOfFailurs, testNumKilledME, jarName, killed, killedMutant, outFiles, errFiles); }