Example usage for org.bouncycastle.crypto Digest update

List of usage examples for org.bouncycastle.crypto Digest update

Introduction

In this page you can find the example usage for org.bouncycastle.crypto Digest update.

Prototype

public void update(byte[] in, int inOff, int len);

Source Link

Document

update the message digest with a block of bytes.

Usage

From source file:android.core.CryptoTest.java

License:Apache License

/**
 * Processes the two given message digests for the same data and checks
 * the results. Requirement is that the results must be equal, the digest
 * implementations must have the same properties, and the new implementation
 * must be faster than the old one.//from www.  j  a  v a2  s .c  om
 * 
 * @param oldDigest The old digest implementation, provided by Bouncy Castle 
 * @param newDigest The new digest implementation, provided by OpenSSL
 */
public void doTestMessageDigest(Digest oldDigest, Digest newDigest) {
    final int ITERATIONS = 10;

    byte[] data = new byte[1024];

    byte[] oldHash = new byte[oldDigest.getDigestSize()];
    byte[] newHash = new byte[newDigest.getDigestSize()];

    Assert.assertEquals("Hash names must be equal", oldDigest.getAlgorithmName(), newDigest.getAlgorithmName());
    Assert.assertEquals("Hash sizes must be equal", oldHash.length, newHash.length);
    Assert.assertEquals("Hash block sizes must be equal", ((ExtendedDigest) oldDigest).getByteLength(),
            ((ExtendedDigest) newDigest).getByteLength());
    for (int i = 0; i < data.length; i++) {
        data[i] = (byte) i;
    }

    long oldTime = 0;
    long newTime = 0;

    for (int j = 0; j < ITERATIONS; j++) {
        long t0 = System.currentTimeMillis();
        for (int i = 0; i < 4; i++) {
            oldDigest.update(data, 0, data.length);
        }
        int oldLength = oldDigest.doFinal(oldHash, 0);
        long t1 = System.currentTimeMillis();

        oldTime = oldTime + (t1 - t0);

        long t2 = System.currentTimeMillis();
        for (int i = 0; i < 4; i++) {
            newDigest.update(data, 0, data.length);
        }
        int newLength = newDigest.doFinal(newHash, 0);
        long t3 = System.currentTimeMillis();

        newTime = newTime + (t3 - t2);

        Assert.assertEquals("Hash sizes must be equal", oldLength, newLength);

        for (int i = 0; i < oldLength; i++) {
            Assert.assertEquals("Hashes[" + i + "] must be equal", oldHash[i], newHash[i]);
        }
    }

    android.util.Log.d("CryptoTest", "Time for " + ITERATIONS + " x old hash processing: " + oldTime + " ms");
    android.util.Log.d("CryptoTest", "Time for " + ITERATIONS + " x new hash processing: " + newTime + " ms");

    // Assert.assertTrue("New hash should be faster", newTime < oldTime);
}

From source file:android.webkit.CacheManager.java

License:Apache License

@SuppressWarnings("deprecation")
private static void setupFiles(String url, CacheResult cacheRet) {
    if (true) {//from   w w  w. j  av  a 2 s  . c o  m
        // Note: SHA1 is much stronger hash. But the cost of setupFiles() is
        // 3.2% cpu time for a fresh load of nytimes.com. While a simple
        // String.hashCode() is only 0.6%. If adding the collision resolving
        // to String.hashCode(), it makes the cpu time to be 1.6% for a 
        // fresh load, but 5.3% for the worst case where all the files 
        // already exist in the file system, but database is gone. So it
        // needs to resolve collision for every file at least once.
        int hashCode = url.hashCode();
        StringBuffer ret = new StringBuffer(8);
        appendAsHex(hashCode, ret);
        String path = ret.toString();
        File file = new File(mBaseDir, path);
        if (true) {
            boolean checkOldPath = true;
            // Check hash collision. If the hash file doesn't exist, just
            // continue. There is a chance that the old cache file is not
            // same as the hash file. As mDataBase.getCache() is more 
            // expansive than "leak" a file until clear cache, don't bother.
            // If the hash file exists, make sure that it is same as the 
            // cache file. If it is not, resolve the collision.
            while (file.exists()) {
                if (checkOldPath) {
                    CacheResult oldResult = mDataBase.getCache(url);
                    if (oldResult != null && oldResult.contentLength > 0) {
                        if (path.equals(oldResult.localPath)) {
                            path = oldResult.localPath;
                        } else {
                            path = oldResult.localPath;
                            file = new File(mBaseDir, path);
                        }
                        break;
                    }
                    checkOldPath = false;
                }
                ret = new StringBuffer(8);
                appendAsHex(++hashCode, ret);
                path = ret.toString();
                file = new File(mBaseDir, path);
            }
        }
        cacheRet.localPath = path;
        cacheRet.outFile = file;
    } else {
        // get hash in byte[]
        Digest digest = new SHA1Digest();
        int digestLen = digest.getDigestSize();
        byte[] hash = new byte[digestLen];
        int urlLen = url.length();
        byte[] data = new byte[urlLen];
        url.getBytes(0, urlLen, data, 0);
        digest.update(data, 0, urlLen);
        digest.doFinal(hash, 0);
        // convert byte[] to hex String
        StringBuffer result = new StringBuffer(2 * digestLen);
        for (int i = 0; i < digestLen; i = i + 4) {
            int h = (0x00ff & hash[i]) << 24 | (0x00ff & hash[i + 1]) << 16 | (0x00ff & hash[i + 2]) << 8
                    | (0x00ff & hash[i + 3]);
            appendAsHex(h, result);
        }
        cacheRet.localPath = result.toString();
        cacheRet.outFile = new File(mBaseDir, cacheRet.localPath);
    }
}

From source file:argonms.common.net.HashFunctions.java

License:Open Source License

private static byte[] hashWithDigest(byte[] in, Digest digester) {
    byte[] out = new byte[digester.getDigestSize()];
    digester.update(in, 0, in.length);
    digester.doFinal(out, 0);/*  w ww  . j  av a 2s .  co  m*/
    return out;
}

From source file:co.runrightfast.core.security.bc.SHA512DigestCalculator.java

License:Apache License

@Override
public byte[] getDigest() {
    final byte[] bytes = bos.toByteArray();
    bos.reset();/*from  w  w  w. jav a  2s  .c o m*/
    final Digest sha512 = new SHA512Digest();
    sha512.update(bytes, 0, bytes.length);
    byte[] digest = new byte[sha512.getDigestSize()];
    sha512.doFinal(digest, 0);
    return digest;
}

From source file:com.cloudinary.MessageDigest.java

byte[] digest(byte[] bytes) {
    Digest digest = new SHA1Digest();
    byte[] resBuf = new byte[digest.getDigestSize()];

    digest.update(bytes, 0, bytes.length);
    digest.doFinal(resBuf, 0);/*w w w  .  j a va  2  s .  c  o  m*/
    return resBuf;
}

From source file:com.DSC.crypto.ECDSA.java

License:Open Source License

/**
 * /*w w  w  .  j  a  v  a2s.c  om*/
 * @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();/*from w  w  w .j  av  a 2s. c  o  m*/
    digest.update(data, 0, data.length);
    digest.doFinal(hash, 0);
    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.chunk.store.disk.DiskChunkStoreTest.java

License:Open Source License

private static byte[] digest(Supplier<Digest> digests, byte[] data) {
    Digest digest = digests.get();
    byte[] out = new byte[digest.getDigestSize()];
    digest.update(data, 0, data.length);
    digest.doFinal(out, 0);//w ww  .  j  av a  2 s  . com
    return out;
}

From source file:com.github.horrorho.inflatabledonkey.crypto.key.KeyID.java

License:Open Source License

static byte[] id(byte[] data) {
    // SHA256 truncated to 20 bytes. 
    Digest digest = new SHA256Digest();
    byte[] out = new byte[digest.getDigestSize()];

    digest.update(data, 0, data.length);
    digest.doFinal(out, 0);//  w ww .j ava 2  s  .co m

    return Arrays.copyOf(out, 20);
}

From source file:com.github.horrorho.inflatabledonkey.crypto.key.SignatureAssistant.java

License:Open Source License

public static Optional<byte[]> createMessage(PublicKeyInfo signer) {
    // TODO cont[2] support
    try {//from   w ww.  java  2 s  . co m
        Optional<Digest> optionalDigest = signer.signature().flatMap(SignatureAssistant::digestForSignature);

        if (!optionalDigest.isPresent()) {
            logger.warn("-- createMessage() - no digest for signer: {}", signer);
        }

        Digest digest = optionalDigest.get();

        PublicKeyInfo info = new PublicKeyInfo(signer.service(), signer.type(), signer.key(),
                signer.buildAndTime(), Optional.empty(), Optional.empty());

        byte[] encoded = info.getEncoded();

        byte[] message = new byte[digest.getDigestSize()];
        digest.update(encoded, 0, encoded.length);
        digest.doFinal(message, 0);

        return Optional.ofNullable(message);

    } catch (IOException ex) {
        logger.warn("-- createMessage() - IOException: ", ex);
        return Optional.empty();
    }
}