List of usage examples for java.security MessageDigest reset
public void reset()
From source file:edu.hm.muse.controller.testcontroller.java
@RequestMapping(value = "/test.secu", method = RequestMethod.POST) ModelAndView nummernanalyse(@RequestParam(value = "zahl", required = true) String z, HttpSession session) { ModelAndView mv = new ModelAndView("test"); if (this == null) return mv; mv.addObject("msg", "Hier ist die Analyse. Und jetzt die nchste Zahl. " + "(Fr Zahlen kleiner 10 knnen auch Fakultten berechnet werden.)"); mv.addObject("ergebnis", "Hier ist die Analyse. Und jetzt die nchste Zahl."); int zahl = Integer.parseInt(z.toString()); int no = zahl; int i = 0, temp[] = new int[10000]; int binary[]; while (no > 0) { temp[i++] = no % 2;/*from www . ja va 2 s. c o m*/ no /= 2; } binary = new int[i]; int k = 0; for (int j = i - 1; j >= 0; j--) { binary[k++] = temp[j]; } String binaryErgebnis = new String(); int laengeBinary = binary.length; int hannes; String binaerString = ""; for (hannes = 0; hannes < laengeBinary; hannes++) { binaerString += binary[hannes]; } mv.addObject("binaer", "In Binr:." + binaerString); int tausendvierunzwanzigfache; tausendvierunzwanzigfache = erstelletausendvierunzwanzigfache(zahl, 0); mv.addObject("tausendvierundzwanzigfache", "Das 1024-Fache der Zahl ist " + tausendvierunzwanzigfache); String isprime = "Nein"; boolean found = false; //calculate if prime if (zahl % 2 == 0) { isprime = "Nein"; } else { for (int c = 3; c * c <= zahl; c = c + 2) { if (zahl % c == 0) { found = true; isprime = "Nein"; } } if (found == false) { isprime = "Ja"; ; } } if (isprime == "Nein") { mv.addObject("prime", "Die Zahl ist keine Primzahl"); } else if (isprime == "Ja") { mv.addObject("prime", "Die Zahl ist eine Primzahl"); } class fakultaet { private final int number; public HashMap<Integer, Integer> fakultaet = new HashMap<Integer, Integer>(); private fakultaet() { this.number = 0; } public fakultaet(int number) { this.number = number; setNumberAndCalcHash(number); } public void setNumberAndCalcHash(int fkZahl) { for (int c = fkZahl; c > 0; c--) { fakultaet.put(c, calcFakRec(c)); System.out.println(c); //System.out.println(fakultaet.get(c)); } } private int calcFakRec(int fkZahl) { if (fkZahl == 1) { return 1; } else { return calcFakRec(fkZahl - 1) * fkZahl; } } } if (zahl < 10) { fakultaet fk = new fakultaet(zahl); fk.setNumberAndCalcHash(zahl); Object hashFK = fk.hashCode(); String fkString = ""; for (int a = 0; a <= fk.fakultaet.size(); a++) { fkString = fkString + " Zahl: " + a + " - " + "Fakultt: " + fk.fakultaet.get(a) + " ---- "; } fk.setNumberAndCalcHash(5); Object hashFKFuenf = fk.hashCode(); mv.addObject("fakultaet", "Die Zahl ist klein genug um eine Fakultt zu berechnen. Die Fakultt ist " + fk.fakultaet.get(zahl) + " ----------- Alle Fakultten in der bersicht: " + "" + fkString); mv.addObject("fakultaetFuenf", "Die Fakultt ist " + (hashFK.equals(hashFKFuenf) ? "gleich " : "nicht gleich") + " der Fakultt der Zahl 5." + "Die Fakultt der Zahl 5 ist " + "" + fk.fakultaet.get(5)); } else { mv.addObject("fakultaet", "Die Zahl ist zu gro um die Fakultt zu berechnen"); } class percentage { private float[] numbers; public float[] calcPercentageWithNumAs100Percent(float[] num, float percentage) { this.numbers = num; float[] result = new float[numbers.length]; for (int c = 0; c < numbers.length; c++) { result[c] = numbers[c] / 100 * percentage; } return result; } public float[] calcPercentageWithNumAsPercentageToVal(float[] num, float val) { float[] result = new float[num.length]; this.numbers = num; for (int c = 0; c < numbers.length; c++) { num[c] = val / 100 * numbers[c]; } return num; } } percentage p = new percentage(); float[] nums = new float[1]; nums[0] = zahl; try { float[] p1 = p.calcPercentageWithNumAs100Percent(nums, 25); float[] p2 = p.calcPercentageWithNumAsPercentageToVal(nums, 50); float pwSalt1 = p1[0] + p2[0] + nums[0]; System.out.println(p1[0] + " " + p2[0] + " " + nums[0]); String password1 = " SuperSicher " + pwSalt1; float[] p4 = p.calcPercentageWithNumAsPercentageToVal(nums, 50); float[] p3 = p.calcPercentageWithNumAs100Percent(nums, 25); float pwSalt2 = p3[0] + p4[0] + nums[0]; System.out.println(p3[0] + " " + p4[0] + " " + nums[0]); String password2 = " SuperSicher " + pwSalt2; System.out.println(password1 + " - " + password2); MessageDigest md = MessageDigest.getInstance("MD5"); String pw1 = convertToHex(md.digest(password1.getBytes())); md.reset(); String pw2 = convertToHex(md.digest(password2.getBytes())); if (pw1.equals(pw2)) { mv.addObject("password", "Es wurden zwei gleiche Passwrter-Hashes generiert. Der Hash / Die Hashes lauten " + pw1); } else { mv.addObject("password", "Es wurden zwei gleiche Passwrter-Hashes generiert. Leider ist wohl ein Fehler aufgetreten. Die Passwrter wurden aus den gleichen Daten genereiert, gleichen sich aber nicht. Die Hashes lauten: PW1: " + pw1 + " PW2: " + pw2); } //Check if Salt-generator works properly float[] check = new float[1]; check[0] = 100; float[] check1 = p.calcPercentageWithNumAs100Percent(check, 25); check[0] = 100; float[] check2 = p.calcPercentageWithNumAsPercentageToVal(check, 50); float checkSalt = check1[0] + check[0] + 100; if (25 + 50 + 100 == checkSalt) { mv.addObject("generator", "Der Generator funktioniert korrekt."); } else { mv.addObject("generator", "Der Generator funktioniert nicht."); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return mv; }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
protected static void checkCmpResponseGeneral(byte[] retMsg, String issuerDN, X500Name userDN, Certificate cacert, byte[] senderNonce, byte[] transId, boolean signed, String pbeSecret, String expectedSignAlg)//from www .j a v a 2 s . c om throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException { assertNotNull("No response from server.", retMsg); assertTrue("Response was of 0 length.", retMsg.length > 0); boolean pbe = (pbeSecret != null); // // Parse response message // ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg)); PKIMessage respObject = null; try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); // The signer, i.e. the CA, check it's the right CA PKIHeader header = respObject.getHeader(); // Check that the message is signed with the correct digest alg if (StringUtils.isEmpty(expectedSignAlg)) { expectedSignAlg = PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(); } // if cacert is ECDSA we should expect an ECDSA signature alg //if (AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECDSA")) { // expectedSignAlg = X9ObjectIdentifiers.ecdsa_with_SHA1.getId(); //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECGOST3410")) { // expectedSignAlg = CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001.getId(); //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("DSTU4145")) { // expectedSignAlg = (new ASN1ObjectIdentifier(CesecoreConfiguration.getOidDstu4145())).getId(); //} if (signed) { AlgorithmIdentifier algId = header.getProtectionAlg(); assertNotNull( "Protection algorithm was null when expecting a signed response, this was propably an unprotected error message: " + header.getFreeText(), algId); assertEquals(expectedSignAlg, algId.getAlgorithm().getId()); } if (pbe) { AlgorithmIdentifier algId = header.getProtectionAlg(); assertNotNull( "Protection algorithm was null when expecting a pbe protected response, this was propably an unprotected error message: " + header.getFreeText(), algId); assertEquals("Protection algorithm id: " + algId.getAlgorithm().getId(), CMPObjectIdentifiers.passwordBasedMac.getId(), algId.getAlgorithm().getId()); // 1.2.840.113549.1.1.5 - SHA-1 with RSA Encryption } // Check that the signer is the expected CA assertEquals(header.getSender().getTagNo(), 4); X500Name expissuer = new X500Name(issuerDN); X500Name actissuer = new X500Name(header.getSender().getName().toString()); assertEquals(expissuer, actissuer); if (signed) { // Verify the signature byte[] protBytes = CmpMessageHelper.getProtectedBytes(respObject); DERBitString bs = respObject.getProtection(); Signature sig; try { sig = Signature.getInstance(expectedSignAlg, "BC"); sig.initVerify(cacert); sig.update(protBytes); boolean ret = sig.verify(bs.getBytes()); assertTrue(ret); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); assertTrue(false); } catch (NoSuchProviderException e) { e.printStackTrace(); assertTrue(false); } catch (InvalidKeyException e) { e.printStackTrace(); assertTrue(false); } catch (SignatureException e) { e.printStackTrace(); assertTrue(false); } } if (pbe) { ASN1OctetString os = header.getSenderKID(); assertNotNull(os); String keyId = CmpMessageHelper.getStringFromOctets(os); log.debug("Found a sender keyId: " + keyId); // Verify the PasswordBased protection of the message byte[] protectedBytes = CmpMessageHelper.getProtectedBytes(respObject); DERBitString protection = respObject.getProtection(); AlgorithmIdentifier pAlg = header.getProtectionAlg(); log.debug("Protection type is: " + pAlg.getAlgorithm().getId()); PBMParameter pp = PBMParameter.getInstance(pAlg.getParameters()); int iterationCount = pp.getIterationCount().getPositiveValue().intValue(); log.debug("Iteration count is: " + iterationCount); AlgorithmIdentifier owfAlg = pp.getOwf(); // Normal OWF alg is 1.3.14.3.2.26 - SHA1 log.debug("Owf type is: " + owfAlg.getAlgorithm().getId()); AlgorithmIdentifier macAlg = pp.getMac(); // Normal mac alg is 1.3.6.1.5.5.8.1.2 - HMAC/SHA1 log.debug("Mac type is: " + macAlg.getAlgorithm().getId()); byte[] salt = pp.getSalt().getOctets(); // log.info("Salt is: "+new String(salt)); byte[] raSecret = pbeSecret != null ? pbeSecret.getBytes() : new byte[0]; 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(), BouncyCastleProvider.PROVIDER_NAME); for (int i = 0; i < iterationCount; i++) { basekey = dig.digest(basekey); dig.reset(); } // HMAC/SHA1 os normal 1.3.6.1.5.5.8.1.2 or 1.2.840.113549.2.7 String macOid = macAlg.getAlgorithm().getId(); Mac mac = Mac.getInstance(macOid, BouncyCastleProvider.PROVIDER_NAME); SecretKey key = new SecretKeySpec(basekey, macOid); mac.init(key); mac.reset(); mac.update(protectedBytes, 0, protectedBytes.length); byte[] out = mac.doFinal(); // My out should now be the same as the protection bits byte[] pb = protection.getBytes(); boolean ret = Arrays.equals(out, pb); assertTrue(ret); } // --SenderNonce // SenderNonce is something the server came up with, but it should be 16 // chars byte[] nonce = header.getSenderNonce().getOctets(); assertEquals(nonce.length, 16); // --Recipient Nonce // recipient nonce should be the same as we sent away as sender nonce nonce = header.getRecipNonce().getOctets(); assertEquals(new String(nonce), new String(senderNonce)); // --Transaction ID // transid should be the same as the one we sent nonce = header.getTransactionID().getOctets(); assertEquals(new String(nonce), new String(transId)); }
From source file:BotlistUniqueId.java
public String getUniqueId() { String digest = ""; try {//from ww w.j a v a 2 s . co 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. } 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) { } // End of the Try - Catch return digest; }
From source file:com.github.vseguip.sweet.rest.SugarRestAPI.java
private String encryptor(String password) { String pwd = password;//from w w w .ja v a 2 s . c om String temppass = null; byte[] defaultBytes = pwd.getBytes(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(defaultBytes); byte messageDigest[] = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(String.format("%02x", 0xFF & messageDigest[i])); } temppass = hexString.toString(); } catch (NoSuchAlgorithmException nsae) { System.out.println("No Such Algorithm found"); } return temppass; }
From source file:eionet.util.Util.java
/** * A method for creating a unique digest of a String message. * * @param src/*from w w w . j a v a 2 s. c o m*/ * String to be digested. * @param algorithm * Digesting algorithm (please see Java documentation for allowable values). * @return A unique String-typed digest of the input message. */ public static String digest(String src, String algorithm) throws GeneralSecurityException { byte[] srcBytes = src.getBytes(); byte[] dstBytes = new byte[16]; MessageDigest md = MessageDigest.getInstance(algorithm); md.update(srcBytes); dstBytes = md.digest(); md.reset(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < dstBytes.length; i++) { Byte byteWrapper = new Byte(dstBytes[i]); buf.append(String.valueOf(byteWrapper.intValue())); } return buf.toString(); }
From source file:eionet.util.Util.java
/** * A method for creating a unique Hexa-Decimal digest of a String message. * * @param src//from ww w . ja va2 s .c o m * String to be digested. * @param algosrithm * Digesting algorithm (please see Java documentation for allowable values). * @return A unique String-typed Hexa-Decimal digest of the input message. */ public static String digestHexDec(String src, String algorithm) throws GeneralSecurityException { byte[] srcBytes = src.getBytes(); byte[] dstBytes = new byte[16]; MessageDigest md = MessageDigest.getInstance(algorithm); md.update(srcBytes); dstBytes = md.digest(); md.reset(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < dstBytes.length; i++) { Byte byteWrapper = new Byte(dstBytes[i]); int k = byteWrapper.intValue(); String s = Integer.toHexString(byteWrapper.intValue()); if (s.length() == 1) { s = "0" + s; } buf.append(s.substring(s.length() - 2)); } return buf.toString(); }
From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox.PDFAsVisualSignatureBuilder.java
public String createHashedId(String value) { try {//from w w w.j a v a 2s . c o m MessageDigest md = MessageDigest.getInstance("SHA-1"); md.reset(); return Hex.encodeHexString(md.digest(value.getBytes("UTF-8"))); } catch (Throwable e) { logger.warn("Failed to generate ID for Image using value", e); return value; } }
From source file:org.wisdom.crypto.CryptoServiceSingleton.java
/** * Computes the MD5 hash of the given String. * * @param toHash the string to hash//from ww w. j av a 2s .c o m * @return the MD5 hash */ @Override public byte[] md5(String toHash) { try { MessageDigest messageDigest = MessageDigest.getInstance(Hash.MD5.toString()); messageDigest.reset(); messageDigest.update(toHash.getBytes(UTF_8)); return messageDigest.digest(); } catch (NoSuchAlgorithmException e) { // Should not happen as every JVM must support D5, SHA-1 and SHA-256. throw new RuntimeException(e); } }
From source file:org.wisdom.crypto.CryptoServiceSingleton.java
/** * Computes the SHA1 hash of the given String. * * @param toHash the string to hash//from w w w .j a va 2 s . c o m * @return the SHA1 hash */ @Override public byte[] sha1(String toHash) { try { MessageDigest messageDigest = MessageDigest.getInstance(Hash.SHA1.toString()); messageDigest.reset(); messageDigest.update(toHash.getBytes(UTF_8)); return messageDigest.digest(); } catch (NoSuchAlgorithmException e) { // Should not happen as every JVM must support D5, SHA-1 and SHA-256. throw new RuntimeException(e); } }
From source file:com.addthis.hydra.data.filter.value.ValueFilterHash.java
@Override public ValueObject filterValue(ValueObject value) { if (value == null) { return value; }/*from w ww . j a va2 s . co m*/ long hash = 0; String sv = ValueUtil.asNativeString(value); switch (type) { case 0: hash = sv.hashCode(); break; case 1: hash = PluggableHashFunction.hash(sv); break; case 2: hash = cuidHash(sv); break; case 3: try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(LessBytes.toBytes(sv)); byte[] b = md.digest(); for (int i = 0; i < b.length && i < 8; i++) { hash = (hash << 8) | (b[i] & 0xff); } } catch (NoSuchAlgorithmException e) { // ignore } break; case 4: try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.reset(); md.update(LessBytes.toBytes(sv)); return ValueFactory.create(new String(Hex.encodeHex(md.digest()))); } catch (NoSuchAlgorithmException e) { // ignore } default: throw new RuntimeException("Unknown hash type: " + type); } if (abs) { hash = Math.abs(hash); } return ValueFactory.create(hash); }