List of usage examples for org.bouncycastle.crypto Digest reset
public void reset();
From source file:com.DSC.crypto.ECDSA.java
License:Open Source License
/** * /*from www . j a v a 2 s . c o m*/ * @param data * @return */ private static byte[] hash(byte[] data) { Digest digest = new SHA256Digest(); byte[] hash = new byte[digest.getDigestSize()]; digest.update(data, 0, data.length); digest.doFinal(hash, 0); digest.reset(); return hash; }
From source file:com.github.horrorho.inflatabledonkey.chunk.engine.ChunkChecksums.java
License:Open Source License
public static byte[] hashType1(byte[] data) { Digest digest = new SHA256Digest(); byte[] hash = new byte[digest.getDigestSize()]; digest.reset(); digest.update(data, 0, data.length); digest.doFinal(hash, 0);/*w w w . j a v a 2s . co m*/ digest.update(hash, 0, hash.length); digest.doFinal(hash, 0); byte[] checksum = Arrays.copyOf(hash, 20); logger.debug("-- hashType1() - hash: 0x{}", Hex.toHexString(checksum)); return checksum; }
From source file:com.github.horrorho.inflatabledonkey.dataprotection.DPAESCBCBlockIVGenerator.java
License:Open Source License
static BlockCipher cipher(byte[] fileKey) { Digest digest = new SHA1Digest(); byte[] hash = new byte[digest.getDigestSize()]; digest.reset(); digest.update(fileKey, 0, fileKey.length); digest.doFinal(hash, 0);//from w w w . j a v a 2s. c om AESFastEngine cipher = new AESFastEngine(); int blockSize = cipher.getBlockSize(); KeyParameter keyParameter = new KeyParameter(Arrays.copyOfRange(hash, 0, blockSize)); cipher.init(true, keyParameter); return cipher; }
From source file:com.github.horrorho.inflatabledonkey.pcs.xfile.BlockDecrypters.java
License:Open Source License
static ParametersWithIV blockIVKey(Digest digest, int length, byte[] key) { byte[] hash = new byte[digest.getDigestSize()]; digest.reset(); digest.update(key, 0, key.length);//from w ww . java2 s. c o m digest.doFinal(hash, 0); KeyParameter keyParameter = new KeyParameter(Arrays.copyOfRange(hash, 0, length)); byte[] iv = new byte[length]; return new ParametersWithIV(keyParameter, iv); }
From source file:com.gpfcomics.android.cryptnos.SiteParameters.java
License:Open Source License
/** * Given the user's secret passphrase, combine it with all the other * site parameters saved within to produce the generated password and * return it to the theApp.//from ww w . j a v a2 s .co m * @param secret The user's secret passphrase, which is never stored. * @param handler If not null, this handler will be notified of the * progress of the generation process, for the purpose of updating a * progress dialog, for example. * @return A pseudo-random password generated from the site parameters. * @throws Exception Thrown when any error occurs. */ public String generatePassword(String secret, Handler handler) throws Exception { Message msg = null; Bundle b = null; ; // Asbestos underpants: try { // The character limit must be zero or greater, while the // iteration count must be one or greater: if (charLimit >= 0 && iterations > 0) { // Concatenate the site and passphrase values, then // convert the string to a byte array for hashing: byte[] result = site.concat(secret).getBytes(theApp.getTextEncoding()); // We will use one of two hashing engines. Internally, // Java supports MD5, SHA-1, and a trio of SHA-2 methods. // We'll assume that since these are built-in, they must // be optimized compared to external definitions. If // the selected hash is one of these, we'll use the // internal engine. MessageDigest internalHasher = null; Digest bcHasher = null; if (hash.compareTo("MD5") == 0 || hash.compareTo("SHA-1") == 0 || hash.compareTo("SHA-256") == 0 || hash.compareTo("SHA-384") == 0 || hash.compareTo("SHA-512") == 0) { internalHasher = MessageDigest.getInstance(hash); } // If it is any other engine, we'll fall back to the // Bouncy Castle implementations. We may add more later, // but for now we'll only use the same ones supported by // the .NET version of Cryptnos. There, we actually // re-implemented their code to fit with the .NET hashing // class structure; here, we'll using Bouncy Castle out // of the box, so it's trivial to implement them all. else if (hash.compareTo("RIPEMD-160") == 0) { bcHasher = new RIPEMD160Digest(); } else if (hash.compareTo("Tiger") == 0) { bcHasher = new TigerDigest(); } else if (hash.compareTo("Whirlpool") == 0) { bcHasher = new WhirlpoolDigest(); } // If we're using the internal hashing engine, we've // got things easy. The most complex part is feeding the // hash back into the engine for multiple iterations. if (internalHasher != null) { for (int i = 0; i < iterations; i++) { result = internalHasher.digest(result); if (handler != null) { msg = handler.obtainMessage(); b = new Bundle(); b.putInt("iteration", i); b.putString("password", null); msg.setData(b); handler.sendMessage(msg); } } } // If we're using the Bouncy Castle stuff, we'll need to // do a bit more work. Declare the result, feed it to // the engine, and get back the hash. Note that we redeclare // the result byte array after the update so each iteration // puts the result hash into the array. Also note that we // make sure to reset the engine after each iteration, which // apparently the built-in engines do automagically. else if (bcHasher != null) { for (int i = 0; i < iterations; i++) { bcHasher.update(result, 0, result.length); result = new byte[bcHasher.getDigestSize()]; bcHasher.doFinal(result, 0); bcHasher.reset(); if (handler != null) { msg = handler.obtainMessage(); b = new Bundle(); b.putInt("iteration", i); b.putString("password", null); msg.setData(b); handler.sendMessage(msg); } } } // By now, we *should* have the intermediate hash in hand. // We'll double check with a null check here, just in case. if (result != null) { // Get the raw hash as a Base64 string: String b64hash = base64String(result); // Now that we've got the hash string, we need to apply // our modifications. First, the character type // restriction. Based on the user's choice in the // drop-down, run the hash through some regular // expressions to chop out unwanted characters: Pattern p = null; switch (charTypes) { // Alphanumerics, change others to underscores case 1: p = Pattern.compile("\\W"); b64hash = p.matcher(b64hash).replaceAll("_"); break; // Alphanumerics only case 2: p = Pattern.compile("[^a-zA-Z0-9]"); b64hash = p.matcher(b64hash).replaceAll(""); break; // Alphabetic characters only case 3: p = Pattern.compile("[^a-zA-Z]"); b64hash = p.matcher(b64hash).replaceAll(""); break; // Numbers only case 4: p = Pattern.compile("\\D"); b64hash = p.matcher(b64hash).replaceAll(""); break; // By default, use all generated characters default: break; } // Next, apply the character limit. If it's any- // thing greater than zero, get only the first so // many characters: if (charLimit > 0 && b64hash.length() > charLimit) b64hash = b64hash.substring(0, charLimit); // Now we have our final value. Display it back // to the user and get ready to save it to the // database. if (handler != null) { msg = handler.obtainMessage(); b = new Bundle(); b.putInt("iteration", -100); b.putString("password", b64hash); msg.setData(b); handler.sendMessage(msg); } return b64hash; } // If for some reason something failed, the result could // be null. Warn the user as such: else { throw new Exception(theApp.getResources().getString(R.string.error_null_hash)); } } // If the iterations or character limit parsing didn't // come up roses, show error messages. Note that there's // also a generic "unknown" one here, just in case, but // it's probably irrelevant. else { if (iterations <= 0) throw new Exception(theApp.getResources().getString(R.string.error_bad_iterations)); else if (charLimit < 0) throw new Exception(theApp.getResources().getString(R.string.error_bad_charlimit)); else throw new Exception(theApp.getResources().getString(R.string.error_unknown)); } } // This should probably be more robust, but for now just throw back // out any exception we caught: catch (Exception e) { throw e; } }
From source file:com.healthmarketscience.jackcess.impl.BaseCryptCodecHandler.java
License:Apache License
/** * Hashes the given bytes1 and bytes2 using the given digest and returns the * hash fixed to the given length./*from w w w . j a v a 2 s. c o m*/ */ public static byte[] hash(Digest digest, byte[] bytes1, byte[] bytes2, int resultLen) { digest.reset(); digest.update(bytes1, 0, bytes1.length); if (bytes2 != null) { digest.update(bytes2, 0, bytes2.length); } // Get digest value byte[] digestBytes = new byte[digest.getDigestSize()]; digest.doFinal(digestBytes, 0); // adjust to desired length if (resultLen > 0) { digestBytes = fixToLength(digestBytes, resultLen); } return digestBytes; }
From source file:dorkbox.util.crypto.Crypto.java
License:Apache License
/** * Return the hash of the file or NULL if file is invalid * * @param logger/*from ww w .j av a 2s .c om*/ * may be null, if no log output is necessary */ public static byte[] hashFile(File file, Digest digest, long startPosition, long endPosition, Logger logger) { if (file.isFile() && file.canRead()) { InputStream inputStream = null; try { inputStream = new FileInputStream(file); long skip = inputStream.skip(startPosition); if (skip != startPosition) { throw new RuntimeException( "Unable to skip " + startPosition + " bytes. Only skippped " + skip + " instead"); } long size = file.length() - startPosition; long lengthFromEnd = size - endPosition; if (lengthFromEnd > 0 && lengthFromEnd < size) { size -= lengthFromEnd; } int bufferSize = 4096; byte[] buffer = new byte[bufferSize]; int readBytes; digest.reset(); while (size > 0) { //noinspection NumericCastThatLosesPrecision int maxToRead = (int) Math.min(bufferSize, size); readBytes = inputStream.read(buffer, 0, maxToRead); size -= readBytes; if (readBytes == 0) { //wtf. finally still gets called. return null; } digest.update(buffer, 0, readBytes); } } catch (Exception e) { if (logger != null) { logger.error("Error hashing file: {}", file.getAbsolutePath(), e); } else { e.printStackTrace(); } } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } byte[] digestBytes = new byte[digest.getDigestSize()]; digest.doFinal(digestBytes, 0); return digestBytes; } else { return null; } }
From source file:dorkbox.util.crypto.Crypto.java
License:Apache License
/** * Specifically, to return the hash of the ALL files/directories inside the jar, minus the action specified (LGPL) files. *///from www . ja v a2 s . com public static byte[] hashJarContentsExcludeAction(File jarDestFilename, Digest digest, int action) throws IOException { JarFile jarDestFile = new JarFile(jarDestFilename); try { Enumeration<JarEntry> jarElements = jarDestFile.entries(); boolean okToHash; boolean hasAction; byte[] buffer = new byte[2048]; int read; digest.reset(); while (jarElements.hasMoreElements()) { JarEntry jarEntry = jarElements.nextElement(); String name = jarEntry.getName(); okToHash = !jarEntry.isDirectory(); if (!okToHash) { continue; } // data with NO extra data will NOT BE HASHED // data that matches our action bitmask WILL NOT BE HASHED okToHash = false; hasAction = false; byte[] extraData = jarEntry.getExtra(); if (extraData == null || extraData.length == 0) { okToHash = false; } else if (extraData.length >= 4) { for (int i = 0; i < CUSTOM_HEADER.length; i++) { if (extraData[i] != CUSTOM_HEADER[i]) { throw new RuntimeException("Unexpected extra data in zip assigned. Aborting"); } } // this means we matched our header if (extraData[4] > 0) { hasAction = true; // we have an ACTION describing how it was compressed, etc int fileAction = LittleEndian.Int_ .from(new byte[] { extraData[5], extraData[6], extraData[7], extraData[8] }); if ((fileAction & action) != action) { okToHash = true; } } else { okToHash = true; } } else { throw new RuntimeException("Unexpected extra data in zip assigned. Aborting"); } // skips hashing lgpl files. (technically, whatever our action bitmask is...) // we want to hash everything BY DEFAULT. we ALSO want to hash the NAME, LOAD ACTION TYPE, and the contents if (okToHash) { // System.err.println("HASHING: " + name); // hash the file name byte[] bytes = name.getBytes(OS.US_ASCII); digest.update(bytes, 0, bytes.length); if (hasAction) { // hash the action - since we don't want to permit anyone to change this after we sign the file digest.update(extraData, 5, 4); } // hash the contents InputStream inputStream = jarDestFile.getInputStream(jarEntry); while ((read = inputStream.read(buffer)) > 0) { digest.update(buffer, 0, read); } inputStream.close(); } //else { // System.err.println("Skipping: " + name); //} } } catch (Exception e) { throw new RuntimeException("Unexpected extra data in zip assigned. Aborting"); } finally { jarDestFile.close(); } byte[] digestBytes = new byte[digest.getDigestSize()]; digest.doFinal(digestBytes, 0); return digestBytes; }
From source file:dorkbox.util.crypto.Crypto.java
License:Apache License
/** * Hash an input stream, based on the specified digest */// w ww .j a va2 s . c om public static byte[] hashStream(Digest digest, InputStream inputStream) throws IOException { byte[] buffer = new byte[2048]; int read; digest.reset(); while ((read = inputStream.read(buffer)) > 0) { digest.update(buffer, 0, read); } inputStream.close(); byte[] digestBytes = new byte[digest.getDigestSize()]; digest.doFinal(digestBytes, 0); return digestBytes; }
From source file:org.xipki.commons.security.FpIdCalculator.java
License:Open Source License
/** * Hash the data and returns the first 8 bytes of the hash value. * @return long represented of the first 8 bytes *//*from ww w. j a v a 2 s . co m*/ public static long hash(final byte[] data) { ParamUtil.requireNonNull("data", data); Digest md = null; for (int i = 0; i < 3; i++) { try { md = MDS.poll(10, TimeUnit.SECONDS); break; } catch (InterruptedException ex) { // CHECKSTYLE:SKIP } } if (md == null) { throw new RuntimeOperatorException("could not get idle MessageDigest"); } try { md.reset(); md.update(data, 0, data.length); byte[] bytes = new byte[md.getDigestSize()]; md.doFinal(bytes, 0); return bytesToLong(bytes); } finally { MDS.addLast(md); } }