Example usage for java.util.zip CRC32 CRC32

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

Introduction

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

Prototype

public CRC32() 

Source Link

Document

Creates a new CRC32 object.

Usage

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);/*  ww  w. ja v  a  2 s .c o  m*/
    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);
    }

    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:org.smartfrog.services.www.bulkio.client.SunJavaBulkIOClient.java

@Override
public long doDownload(long ioSize) throws IOException, InterruptedException {
    validateURL();//from w  ww.j a  v  a 2  s  .  c om
    URL target = createFullURL(ioSize, format);
    getLog().info("Downloading " + ioSize + " bytes from " + target);
    CRC32 checksum = new CRC32();
    HttpURLConnection connection = openConnection(target);
    connection.setRequestMethod(HttpAttributes.METHOD_GET);
    connection.setDoOutput(false);
    connection.connect();
    checkStatusCode(target, connection, HttpURLConnection.HTTP_OK);
    String contentLengthHeader = connection.getHeaderField(HttpHeaders.CONTENT_LENGTH);
    long contentLength = Long.parseLong(contentLengthHeader);
    if (contentLength != ioSize) {
        throw new IOException("Wrong content length returned from " + target + " - expected " + ioSize
                + " but got " + contentLength);
    }
    String formatHeader = connection.getHeaderField(HttpHeaders.CONTENT_TYPE);
    if (!format.equals(formatHeader)) {
        throw new IOException("Wrong content type returned from " + target + " - expected " + format
                + " but got " + formatHeader);
    }
    InputStream stream = connection.getInputStream();
    long bytes = 0;
    try {
        for (bytes = 0; bytes < ioSize; bytes++) {
            int octet = stream.read();
            checksum.update(octet);
            if (interrupted) {
                throw new InterruptedException(
                        "Interrupted after reading" + bytes + " bytes" + " from " + target);
            }
        }
    } finally {
        closeQuietly(stream);
    }
    long actualChecksum = checksum.getValue();
    getLog().info("Download finished after " + bytes + " bytes, checksum=" + actualChecksum);
    if (bytes != ioSize) {
        throw new IOException("Wrong content length downloaded from " + target + " - requested " + ioSize
                + " but got " + bytes);
    }
    if (expectedChecksumFromGet >= 0 && expectedChecksumFromGet != actualChecksum) {
        throw new IOException("Wrong checksum from download of " + ioSize + " bytes " + " from " + target
                + " expected " + expectedChecksumFromGet + " but got " + actualChecksum);
    }
    return bytes;
}

From source file:it.jnrpe.net.JNRPEProtocolPacket.java

/**
 * Validates the packet CRC./*from www .j a  v a 2  s . c om*/
 * 
 * @throws BadCRCException
 *             If the CRC can't be validated 
 */
public void validate() throws BadCRCException {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(bout);

    try {
        dout.writeShort(packetVersion);
        dout.writeShort(packetTypeCode);
        dout.writeInt(0); // NO CRC
        dout.writeShort(resultCode);
        dout.write(byteBufferAry);
        dout.write(dummyBytesAry);

        dout.close();

        byte[] vBytes = bout.toByteArray();

        CRC32 crcAlg = new CRC32();
        crcAlg.update(vBytes);

        if (!(((int) crcAlg.getValue()) == crcValue)) {
            throw new BadCRCException("Bad CRC");
        }
    } catch (IOException e) {
        // Never happens...
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:org.mariotaku.twidere.util.TwitterContentUtils.java

public static boolean isOfficialKey(final Context context, final String consumerKey,
        final String consumerSecret) {
    if (context == null || consumerKey == null || consumerSecret == null)
        return false;
    final String[] keySecrets = context.getResources()
            .getStringArray(R.array.values_official_consumer_secret_crc32);
    final CRC32 crc32 = new CRC32();
    final byte[] consumerSecretBytes = consumerSecret.getBytes(Charset.forName("UTF-8"));
    crc32.update(consumerSecretBytes, 0, consumerSecretBytes.length);
    final long value = crc32.getValue();
    crc32.reset();//from  www. jav  a  2  s.c  om
    for (final String keySecret : keySecrets) {
        if (Long.parseLong(keySecret, 16) == value)
            return true;
    }
    return false;
}

From source file:com.hortonworks.registries.storage.tool.shell.ShellMigrationResolver.java

/**
 * Calculates the checksum of these bytes.
 *
 * @param bytes The bytes to calculate the checksum for.
 * @return The crc-32 checksum of the bytes.
 *///from w  ww.  ja  v a 2 s .co m
private static int calculateChecksum(byte[] bytes) {
    final CRC32 crc32 = new CRC32();
    crc32.update(bytes);
    return (int) crc32.getValue();
}

From source file:it.reexon.lib.files.FileUtils.java

/**
 * Utility method for copying file /*from w  ww.j  a v a2s .  c o  m*/
 *  
 * @param srcFile - source file 
 * @param destFile - destination file 
 * @author A. Weinberger
 * 
 * @throws IOException              If the first byte cannot be read for any reason other than the end of the file, if the input stream has been closed, or if some other I/O error occurs.
 * @throws IllegalArgumentException If file are null
 * @throws FileNotFoundException    If srcFile doens't exist
 */
public static void copyFile(File srcFile, File destFile) throws IOException {
    if (srcFile == null || destFile == null)
        throw new IllegalArgumentException("Files cannot be null");
    if (!srcFile.exists())
        throw new FileNotFoundException("Start file must be exists");

    try (final InputStream in = new FileInputStream(srcFile);
            final OutputStream out = new FileOutputStream(destFile);) {
        long millis = System.currentTimeMillis();
        CRC32 checksum;
        if (VERIFY) {
            checksum = new CRC32();
            checksum.reset();
        }
        final byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = in.read(buffer);
        while (bytesRead >= 0) {
            if (VERIFY) {
                checksum.update(buffer, 0, bytesRead);
            }
            out.write(buffer, 0, bytesRead);
            bytesRead = in.read(buffer);
        }
        if (CLOCK) {
            millis = System.currentTimeMillis() - millis;
            if (LOGS)
                System.out.println("Copy file '" + srcFile.getPath() + "' on " + millis / 1000L + " second(s)");
        }
    } catch (IOException e) {
        throw e;
    }
}

From source file:org.apache.isis.objectstore.nosql.db.file.FileServerDb.java

private String checkData(final String data) {
    final String objectData = data.substring(8);

    final CRC32 inputChecksum = new CRC32();
    inputChecksum.update(objectData.getBytes());
    final long actualChecksum = inputChecksum.getValue();

    final String encodedChecksum = data.substring(0, 8);
    final long expectedChecksum = Long.valueOf(encodedChecksum, 16);

    if (actualChecksum != expectedChecksum) {
        throw new NoSqlStoreException("Data integrity error; checksums different");
    }/*  w w w.  j  a  v  a  2  s . com*/

    return objectData;
}

From source file:org.apache.hadoop.dfs.TestDFSUpgradeFromImage.java

private void verifyDir(DFSClient client, String dir) throws IOException {

    DFSFileInfo[] fileArr = client.listPaths(dir);
    TreeMap<String, Boolean> fileMap = new TreeMap<String, Boolean>();

    for (DFSFileInfo file : fileArr) {
        String path = file.getPath().toString();
        fileMap.put(path, Boolean.valueOf(file.isDir()));
    }/*www.  ja  v  a 2  s.c  o  m*/

    for (Iterator<String> it = fileMap.keySet().iterator(); it.hasNext();) {
        String path = it.next();
        boolean isDir = fileMap.get(path);

        overallChecksum.update(path.getBytes());

        if (isDir) {
            verifyDir(client, path);
        } else {
            // this is not a directory. Checksum the file data.
            CRC32 fileCRC = new CRC32();
            FSInputStream in = client.open(path);
            byte[] buf = new byte[4096];
            int nRead = 0;
            while ((nRead = in.read(buf, 0, buf.length)) > 0) {
                fileCRC.update(buf, 0, nRead);
            }

            verifyChecksum(path, fileCRC.getValue());
        }
    }
}

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  ww w . ja  va 2s  .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:nl.nn.adapterframework.compression.ZipWriter.java

public void writeEntryWithCompletedHeader(String filename, Object contents, boolean close, String charset)
        throws CompressionException, IOException {
    if (StringUtils.isEmpty(filename)) {
        throw new CompressionException("filename cannot be empty");
    }/* www .  j  a  va 2 s. c o m*/

    byte[] contentBytes = null;
    BufferedInputStream bis = null;
    long size = 0;
    if (contents != null) {
        if (contents instanceof byte[]) {
            contentBytes = (byte[]) contents;
        } else if (contents instanceof InputStream) {
            contentBytes = Misc.streamToBytes((InputStream) contents);
        } else {
            contentBytes = contents.toString().getBytes(charset);
        }
        bis = new BufferedInputStream(new ByteArrayInputStream(contentBytes));
        size = bis.available();
    } else {
        log.warn("contents of zip entry [" + filename + "] is null");
    }

    int bytesRead;
    byte[] buffer = new byte[1024];
    CRC32 crc = new CRC32();
    crc.reset();
    if (bis != null) {
        while ((bytesRead = bis.read(buffer)) != -1) {
            crc.update(buffer, 0, bytesRead);
        }
        bis.close();
    }
    if (contents != null) {
        bis = new BufferedInputStream(new ByteArrayInputStream(contentBytes));
    }
    ZipEntry entry = new ZipEntry(filename);
    entry.setMethod(ZipEntry.STORED);
    entry.setCompressedSize(size);
    entry.setSize(size);
    entry.setCrc(crc.getValue());
    getZipoutput().putNextEntry(entry);
    if (bis != null) {
        while ((bytesRead = bis.read(buffer)) != -1) {
            getZipoutput().write(buffer, 0, bytesRead);
        }
        bis.close();
    }
    getZipoutput().closeEntry();
}