Example usage for java.util.zip CRC32 update

List of usage examples for java.util.zip CRC32 update

Introduction

In this page you can find the example usage for java.util.zip CRC32 update.

Prototype

@Override
public void update(ByteBuffer buffer) 

Source Link

Document

Updates the CRC-32 checksum with the bytes from the specified buffer.

Usage

From source file:com.seer.datacruncher.utils.CryptoUtil.java

private boolean checkKeyVerify() {
    CRC32 crc = new CRC32();
    crc.update(cryWorm(Reserved.ENCRYPTIONKEY, Reserved.CHECK, 0).getBytes());
    return Long.toString((crc.getValue())).equals(Reserved.CHECK);
}

From source file:org.ambiance.codec.YEncDecoder.java

/**
 * Decode a single file/*from   w w  w .  j  a va  2  s.c  o m*/
 */
public void decode(File input) throws DecoderException {
    try {
        YEncFile yencFile = new YEncFile(input);

        // Get the output file
        StringBuffer outputName = new StringBuffer(outputDirName);
        outputName.append(File.separator);
        outputName.append(yencFile.getHeader().getName());
        RandomAccessFile output = new RandomAccessFile(outputName.toString(), "rw");

        // Place the pointer to the begining of data to decode
        long pos = yencFile.getDataBegin();
        yencFile.getInput().seek(pos);

        // Bufferise the file
        // TODO - A Amliorer
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while (pos < yencFile.getDataEnd()) {
            baos.write(yencFile.getInput().read());
            pos++;
        }

        byte[] buff = decoder.decode(baos.toByteArray());

        // Write and close output
        output.write(buff);
        output.close();

        // Warn if CRC32 check is not OK
        CRC32 crc32 = new CRC32();
        crc32.update(buff);
        if (!yencFile.getTrailer().getCrc32().equals(Long.toHexString(crc32.getValue()).toUpperCase()))
            throw new DecoderException("Error in CRC32 check.");

    } catch (YEncException ye) {
        throw new DecoderException("Input file is not a YEnc file or contains error : " + ye.getMessage());
    } catch (FileNotFoundException fnfe) {
        throw new DecoderException("Enable to create output file : " + fnfe.getMessage());
    } catch (IOException ioe) {
        throw new DecoderException("Enable to read input file : " + ioe.getMessage());
    }
}

From source file:org.digidoc4j.impl.bdoc.asic.AsicContainerCreator.java

private ZipEntry getAsicMimeTypeZipEntry(byte[] mimeTypeBytes) {
    ZipEntry entryMimetype = new ZipEntry(ZIP_ENTRY_MIMETYPE);
    entryMimetype.setMethod(ZipEntry.STORED);
    entryMimetype.setSize(mimeTypeBytes.length);
    entryMimetype.setCompressedSize(mimeTypeBytes.length);
    CRC32 crc = new CRC32();
    crc.update(mimeTypeBytes);
    entryMimetype.setCrc(crc.getValue());
    return entryMimetype;
}

From source file:org.nuxeo.template.odt.OOoArchiveModifier.java

protected void writeOOoEntry(ZipOutputStream zipOutputStream, String entryName, File fileEntry, int zipMethod)
        throws IOException {

    if (fileEntry.isDirectory()) {
        entryName = entryName + "/";
        ZipEntry zentry = new ZipEntry(entryName);
        zipOutputStream.putNextEntry(zentry);
        zipOutputStream.closeEntry();//from w  ww.j av  a 2 s  . c om
        for (File child : fileEntry.listFiles()) {
            writeOOoEntry(zipOutputStream, entryName + child.getName(), child, zipMethod);
        }
        return;
    }

    ZipEntry zipEntry = new ZipEntry(entryName);
    try (InputStream entryInputStream = new FileInputStream(fileEntry)) {
        zipEntry.setMethod(zipMethod);
        if (zipMethod == ZipEntry.STORED) {
            byte[] inputBytes = IOUtils.toByteArray(entryInputStream);
            CRC32 crc = new CRC32();
            crc.update(inputBytes);
            zipEntry.setCrc(crc.getValue());
            zipEntry.setSize(inputBytes.length);
            zipEntry.setCompressedSize(inputBytes.length);
            zipOutputStream.putNextEntry(zipEntry);
            IOUtils.write(inputBytes, zipOutputStream);
        } else {
            zipOutputStream.putNextEntry(zipEntry);
            IOUtils.copy(entryInputStream, zipOutputStream);
        }
    }
    zipOutputStream.closeEntry();
}

From source file:com.bitbreeds.webrtc.stun.StunMessage.java

public void validate(String pass, byte[] data) {
    StunAttribute fingerprint = this.attributeSet.remove(StunAttributeTypeEnum.FINGERPRINT);
    String finger = new String(fingerprint.getData());
    byte[] fingerprintData = Arrays.copyOfRange(data, 0, data.length - fingerprint.getLength() - 4);
    final CRC32 crc = new CRC32();
    crc.update(fingerprintData);
    String comp = new String(SignalUtil.xor(SignalUtil.fourBytesFromInt((int) crc.getValue()),
            new byte[] { 0x53, 0x54, 0x55, 0x4e }));

    if (!comp.equals(finger)) {
        throw new StunError("Fingerprint bad, computed=" + comp + " sent=" + finger);
    }//ww  w. j  a  v  a 2 s. com

    StunAttribute integrity = attributeSet.remove(StunAttributeTypeEnum.MESSAGE_INTEGRITY);

    byte[] integrityData = Arrays.copyOfRange(data, 0,
            data.length - fingerprint.getLength() - integrity.getLength() - 8);
    byte[] lgt = SignalUtil.twoBytesFromInt(fingerprintData.length - 20);
    integrityData[2] = lgt[0];
    integrityData[3] = lgt[1];

    byte[] mac = SignalUtil.hmacSha1(integrityData, pass.getBytes());

    if (!Arrays.equals(mac, integrity.getData())) {
        throw new StunError("Integrity bad, computed=" + Hex.encodeHexString(mac) + " sent="
                + Hex.encodeHexString(integrity.getData()));
    }
}

From source file:com.indeed.lsmtree.recordlog.BasicRecordFile.java

private Option<E> readAndCheck(long address, MutableLong nextElementStart) throws IOException {
    if (address + 4 > memory.length()) {
        throw new ConsistencyException("not enough bytes in file");
    }/*from   w w w  .  jav a  2s.  co  m*/
    final int length = memory.getInt(address);
    if (length < 0) {
        return Option.none();
    }
    if (address + 8 > memory.length()) {
        throw new ConsistencyException("not enough bytes in file");
    }
    if (address + 8 + length > memory.length()) {
        throw new ConsistencyException("not enough bytes in file");
    }
    final int checksum = memory.getInt(address + 4);
    MemoryDataInput in = new MemoryDataInput(memory);
    in.seek(address + 8);
    CRC32 crc32 = new CRC32();
    crc32.update(CRC_SEED);
    byte[] bytes = new byte[length];
    in.readFully(bytes);
    crc32.update(bytes);
    if ((int) crc32.getValue() != checksum) {
        throw new ConsistencyException("checksum for record does not match: expected " + checksum + " actual "
                + (int) crc32.getValue());
    }
    E ret = serializer.read(ByteStreams.newDataInput(bytes));
    if (nextElementStart != null)
        nextElementStart.setValue(address + 8 + length);
    return Option.some(ret);
}

From source file:org.kepler.objectmanager.cache.DataCacheManager.java

/**
 * Return a temporary local LSID based on a string.
 * @param magicstring// w  w  w  . j a v  a  2 s.c o m
 *     * @throws Exception
 */
private KeplerLSID getDataLSID(String magicstring) throws Exception {
    CRC32 c = new CRC32();
    c.update(magicstring.getBytes());
    String hexValue = Long.toHexString(c.getValue());
    KeplerLSID lsid = new KeplerLSID("localdata", hexValue, 0L, 0L);
    return lsid;
}

From source file:com.bitbreeds.webrtc.stun.StunMessage.java

/**
 * @return array of bytes representing message
 *//*from   ww  w .  j a va2s .co m*/
public byte[] toBytes() {
    final List<byte[]> bt = new ArrayList<>();

    attributeSet.values().stream().forEach(i -> bt.add(i.toBytes()));

    StunHeader hd1 = withIntegrity ? header.updateMessageLength(header.getMessageLength() + 24) : header;
    if (withIntegrity) {
        byte[] macData = SignalUtil.joinBytesArrays(hd1.toBytes(), SignalUtil.joinBytesArrays(bt));

        byte[] mac = SignalUtil.hmacSha1(macData, password.getBytes());

        StunAttribute integrity = new StunAttribute(StunAttributeTypeEnum.MESSAGE_INTEGRITY, mac);
        bt.add(integrity.toBytes());
    }

    StunHeader hd2 = withFingerprint ? hd1.updateMessageLength(hd1.getMessageLength() + 8) : hd1;
    if (withFingerprint) {
        //Generate fingerprint
        final CRC32 crc = new CRC32();
        crc.update(hd2.toBytes());
        bt.forEach(crc::update);
        byte[] xorCRC32 = SignalUtil.xor(SignalUtil.fourBytesFromInt((int) crc.getValue()),
                new byte[] { 0x53, 0x54, 0x55, 0x4e });

        StunAttribute finger = new StunAttribute(StunAttributeTypeEnum.FINGERPRINT, xorCRC32);
        bt.add(finger.toBytes());
    }

    return SignalUtil.joinBytesArrays(hd2.toBytes(), SignalUtil.joinBytesArrays(bt));
}

From source file:Main.java

public void doZip(String filename, String zipfilename) throws Exception {
    byte[] buf = new byte[1024];
    FileInputStream fis = new FileInputStream(filename);
    fis.read(buf, 0, buf.length);/*from ww  w . j av a  2 s . c o  m*/

    CRC32 crc = new CRC32();
    ZipOutputStream s = new ZipOutputStream((OutputStream) new FileOutputStream(zipfilename));
    s.setLevel(6);

    ZipEntry entry = new ZipEntry(filename);
    entry.setSize((long) buf.length);
    crc.reset();
    crc.update(buf);
    entry.setCrc(crc.getValue());
    s.putNextEntry(entry);
    s.write(buf, 0, buf.length);
    s.finish();
    s.close();
}

From source file:org.trancecode.xproc.step.HashStepProcessor.java

@Override
protected void execute(final StepInput input, final StepOutput output) {
    final XdmNode sourceDocument = input.readNode(XProcPorts.SOURCE);
    final String value = input.getOptionValue(XProcOptions.VALUE);
    assert value != null;
    LOG.trace("value = {}", value);
    final String algorithm = input.getOptionValue(XProcOptions.ALGORITHM);
    assert algorithm != null;
    LOG.trace("algorithm = {}", algorithm);
    final String match = input.getOptionValue(XProcOptions.MATCH);
    assert match != null;
    LOG.trace("match = {}", match);
    final String version = input.getOptionValue(XProcOptions.VERSION);
    LOG.trace("version = {}", version);

    final String hashValue;
    if (StringUtils.equalsIgnoreCase("crc", algorithm)) {
        if ("32".equals(version) || version == null) {
            final CRC32 crc32 = new CRC32();
            crc32.update(value.getBytes());
            hashValue = Long.toHexString(crc32.getValue());
        } else {/*  w  ww.  j  a v  a 2  s.  co  m*/
            throw XProcExceptions.xc0036(input.getLocation());
        }
    } else if (StringUtils.equalsIgnoreCase("md", algorithm)) {
        if (version == null || "5".equals(version)) {
            hashValue = DigestUtils.md5Hex(value);
        } else {
            throw XProcExceptions.xc0036(input.getLocation());
        }
    } else if (StringUtils.equalsIgnoreCase("sha", algorithm)) {
        if (version == null || "1".equals(version)) {
            hashValue = DigestUtils.shaHex(value);
        } else if ("256".equals(version)) {
            hashValue = DigestUtils.sha256Hex(value);
        } else if ("384".equals(version)) {
            hashValue = DigestUtils.sha384Hex(value);
        } else if ("512".equals(version)) {
            hashValue = DigestUtils.sha512Hex(value);
        } else {
            throw XProcExceptions.xc0036(input.getLocation());
        }
    } else {
        throw XProcExceptions.xc0036(input.getLocation());
    }

    final SaxonProcessorDelegate hashDelegate = new AbstractSaxonProcessorDelegate() {
        @Override
        public boolean startDocument(final XdmNode node, final SaxonBuilder builder) {
            return true;
        }

        @Override
        public void endDocument(final XdmNode node, final SaxonBuilder builder) {
        }

        @Override
        public EnumSet<NextSteps> startElement(final XdmNode element, final SaxonBuilder builder) {
            builder.text(hashValue);
            return EnumSet.noneOf(NextSteps.class);
        }

        @Override
        public void endElement(final XdmNode node, final SaxonBuilder builder) {
            builder.endElement();
        }

        @Override
        public void attribute(final XdmNode node, final SaxonBuilder builder) {
            builder.attribute(node.getNodeName(), hashValue);
        }

        @Override
        public void comment(final XdmNode node, final SaxonBuilder builder) {
            builder.comment(hashValue);
        }

        @Override
        public void processingInstruction(final XdmNode node, final SaxonBuilder builder) {
            builder.processingInstruction(node.getNodeName().getLocalName(), hashValue);
        }

        @Override
        public void text(final XdmNode node, final SaxonBuilder builder) {
            builder.text(hashValue);
        }
    };

    final SaxonProcessor hashProcessor = new SaxonProcessor(input.getPipelineContext().getProcessor(),
            SaxonProcessorDelegates.forXsltMatchPattern(input.getPipelineContext().getProcessor(), match,
                    input.getStep().getNode(), hashDelegate, new CopyingSaxonProcessorDelegate()));

    final XdmNode result = hashProcessor.apply(sourceDocument);
    output.writeNodes(XProcPorts.RESULT, result);
}