Example usage for org.apache.commons.codec.digest DigestUtils getSha1Digest

List of usage examples for org.apache.commons.codec.digest DigestUtils getSha1Digest

Introduction

In this page you can find the example usage for org.apache.commons.codec.digest DigestUtils getSha1Digest.

Prototype

public static MessageDigest getSha1Digest() 

Source Link

Usage

From source file:br.com.elotech.karina.service.impl.GeradorSenhaElotech.java

@SneakyThrows
private String internalGenerate(String concatLicense) {

    System.out.println(concatLicense);

    String keyForSha1 = DigestUtils.md5Hex(KEY_ELOTECH).toUpperCase();
    System.out.println(keyForSha1);

    String keyForIdea = new String(Hex.encode(DigestUtils.getSha1Digest().digest(keyForSha1.getBytes())))
            .toUpperCase();//from   ww w.j av a2s  .c  om

    System.out.println(keyForIdea);

    byte[] input = concatLicense.getBytes();
    byte[] out = new byte[input.length];

    KeyParameter keyParameter = new KeyParameter(keyForIdea.getBytes());

    BufferedBlockCipher cipher = new BufferedBlockCipher(new IDEAEngine());

    cipher.init(true, keyParameter);

    cipher.processBytes(input, 0, input.length, out, 0);

    String ideaSecret = Base64.getEncoder().encodeToString(out);

    System.out.println(ideaSecret);

    return null;

}

From source file:de.elomagic.carafile.server.bl.SeedBean.java

public MetaData seedFile(final InputStream inputStream, final String filename)
        throws IOException, GeneralSecurityException, JMSException {
    LOG.debug("Seeding file " + filename);
    MetaData md;/*from  www.j a va 2 s.co  m*/
    md = new MetaData();
    md.setFilename(filename);
    md.setCreationDate(new Date());
    md.setChunkSize(DEFAULT_PIECE_SIZE);
    md.setRegistryURI(UriBuilder.fromUri(registryURI).build());

    MessageDigest messageDigest = DigestUtils.getSha1Digest();
    long totalBytes = 0;

    try (DigestInputStream dis = new DigestInputStream(inputStream, messageDigest)) {
        byte[] buffer = new byte[md.getChunkSize()];
        int bytesRead;
        while ((bytesRead = readBlock(dis, buffer)) > 0) {
            totalBytes += bytesRead;
            String chunkId = Hex
                    .encodeHexString(DigestUtils.sha1(new ByteArrayInputStream(buffer, 0, bytesRead)));

            repositoryBean.writeChunk(chunkId, buffer, bytesRead);

            URI uri = UriBuilder.fromUri(ownURI).build();

            ChunkData chunkData = new ChunkData(chunkId, uri);
            md.addChunk(chunkData);
        }
    }

    md.setSize(totalBytes);
    md.setId(Hex.encodeHexString(messageDigest.digest()));

    LOG.debug("File id of seed file is " + md.getId() + "; Size=" + md.getSize() + "; Chunks="
            + md.getChunks().size());

    // Initiate to register at tracker
    LOG.debug("Queue up new file for registration.");
    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer messageProducer = session.createProducer(fileQueue);

    ObjectMessage message = session.createObjectMessage(md);

    messageProducer.send(message);

    connection.close();

    return md;
}

From source file:com.lightszentip.module.security.password.PasswordModuleImpl.java

private byte[] hashPwd(String password, AlgorithmType algorithm)
        throws NoSuchAlgorithmException, UnsupportedEncodingException {
    MessageDigest md = null;//from   www.j  a  v a  2s .  c om
    if (AlgorithmType.MD5.equals(algorithm)) {
        md = DigestUtils.getMd5Digest();
    } else if (AlgorithmType.SHA_512.equals(algorithm)) {
        md = DigestUtils.getSha512Digest();
    } else if (AlgorithmType.SHA_384.equals(algorithm)) {
        md = DigestUtils.getSha384Digest();
    } else if (AlgorithmType.SHA_256.equals(algorithm)) {
        md = DigestUtils.getSha256Digest();
    } else if (AlgorithmType.SHA_1.equals(algorithm)) {
        md = DigestUtils.getSha1Digest();
    }
    md.update(password.getBytes());
    return md.digest();
}

From source file:de.elomagic.carafile.client.CaraFileClient.java

/**
 * Uploads data via an {@link InputStream} (Single chunk upload).
 * <p/>/*from  w w  w.  j  a v a 2  s  .  com*/
 * Single chunk upload means that the complete file will be upload in one step.
 *
 * @param in The input stream. It's not recommended to use a buffered stream.
 * @param filename Name of the file
 * @param contentLength Length of the content in bytes
 * @return Returns the {@link MetaData} of the uploaded stream
 * @throws IOException Thrown when unable to call REST services
 * @see CaraFileClient#uploadFile(java.net.URI, java.nio.file.Path, java.lang.String)
 */
public MetaData uploadFile(final InputStream in, final String filename, final long contentLength)
        throws IOException {
    if (registryURI == null) {
        throw new IllegalArgumentException("Parameter 'registryURI' must not be null!");
    }

    if (in == null) {
        throw new IllegalArgumentException("Parameter 'in' must not be null!");
    }

    URI peerURI = peerSelector.getURI(downloadPeerSet(), -1);

    if (peerURI == null) {
        throw new IOException("No peer for upload available");
    }

    URI uri = CaraFileUtils.buildURI(peerURI, "peer", "seedFile", filename);

    MessageDigest messageDigest = DigestUtils.getSha1Digest();

    try (BufferedInputStream bis = new BufferedInputStream(in);
            DigestInputStream dis = new DigestInputStream(bis, messageDigest)) {
        HttpResponse response = executeRequest(
                Request.Post(uri).bodyStream(dis, ContentType.APPLICATION_OCTET_STREAM)).returnResponse();

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            throw new HttpResponseException(statusCode,
                    "Unable to upload file: " + response.getStatusLine().getReasonPhrase());
        }

        MetaData md = getMetaDataFromResponse(response);

        if (!Hex.encodeHexString(messageDigest.digest()).equals(md.getId())) {
            throw new IOException("Peer response invalid SHA1 of file");
        }

        return md;
    }
}

From source file:de.elomagic.carafile.client.CaraFileClientTest.java

@Test
public void testDownload2() throws Exception {
    Random random = new Random();
    random.nextBytes(data0);//w ww .j a  va  2  s  .  c  om
    random.nextBytes(data1);

    chunkId0 = Hex.encodeHexString(DigestUtils.sha1(data0));
    chunkId1 = Hex.encodeHexString(DigestUtils.sha1(data1));

    MessageDigest messageDigest = DigestUtils.getSha1Digest();
    messageDigest.update(data0);
    messageDigest.update(data1);

    id = Hex.encodeHexString(messageDigest.digest());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    client.setRegistryURI(getURI()).downloadFile(id, baos);

    Assert.assertArrayEquals(data0, Arrays.copyOf(baos.toByteArray(), DEFAULT_PIECE_SIZE));
    Assert.assertArrayEquals(data1,
            Arrays.copyOfRange(baos.toByteArray(), DEFAULT_PIECE_SIZE, DEFAULT_PIECE_SIZE + 128));
}

From source file:fr.letroll.ttorrentandroid.common.Torrent.java

public boolean isPieceValid(@Nonnegative int index, @Nonnull ByteBuffer data) {
    if (data.remaining() != getPieceLength(index))
        throw new IllegalArgumentException("Validating piece " + index + " expected " + getPieceLength(index)
                + ", not " + data.remaining());
    MessageDigest digest = DigestUtils.getSha1Digest();
    digest.update(data);//from   ww w . ja  v  a 2 s .  c om
    return Arrays.equals(digest.digest(), getPieceHash(index));
}

From source file:de.elomagic.carafile.client.CaraFileClient.java

/**
 * Downloads a file into a {@link OutputStream}.
 *
 * @param md {@link MetaData} of the file.
 * @param out The output stream. It's not recommended to use a buffered stream.
 * @throws IOException Thrown when unable to write file into the output stream or the SHA-1 validation failed.
 *///w w  w.  j  av a  2s. co  m
public void downloadFile(final MetaData md, final OutputStream out) throws IOException {
    if (md == null) {
        throw new IllegalArgumentException("Parameter 'md' must not be null!");
    }

    if (out == null) {
        throw new IllegalArgumentException("Parameter 'out' must not be null!");
    }

    Map<String, Path> downloadedChunks = new HashMap<>();
    Set<String> chunksToDownload = new HashSet<>();
    for (ChunkData chunkData : md.getChunks()) {
        chunksToDownload.add(chunkData.getId());
    }

    try {
        while (!chunksToDownload.isEmpty()) {
            PeerChunk pc = peerChunkSelector.getNext(md, chunksToDownload);
            if (pc == null || pc.getPeerURI() == null) {
                throw new IOException("No peer found or selected for download");
            }

            Path chunkFile = Files.createTempFile("fs_", ".tmp");
            try (OutputStream chunkOut = Files.newOutputStream(chunkFile, StandardOpenOption.APPEND)) {
                downloadShunk(pc, md, chunkOut);

                downloadedChunks.put(pc.getChunkId(), chunkFile);
                chunksToDownload.remove(pc.getChunkId());

                chunkOut.flush();
            } catch (Exception ex) {
                Files.deleteIfExists(chunkFile);
                throw ex;
            }
        }

        MessageDigest messageDigest = DigestUtils.getSha1Digest();

        // Write chunk on correct order to file.
        try (DigestOutputStream dos = new DigestOutputStream(out, messageDigest);
                BufferedOutputStream bos = new BufferedOutputStream(dos, md.getChunkSize())) {
            for (ChunkData chunk : md.getChunks()) {
                Path chunkPath = downloadedChunks.get(chunk.getId());
                Files.copy(chunkPath, bos);
            }
        }

        String sha1 = Hex.encodeHexString(messageDigest.digest());
        if (!sha1.equalsIgnoreCase(md.getId())) {
            throw new IOException(
                    "SHA1 validation of file failed. Expected " + md.getId() + " but was " + sha1);
        }
    } finally {
        for (Path path : downloadedChunks.values()) {
            try {
                Files.deleteIfExists(path);
            } catch (IOException ex) {
                LOG.error("Unable to delete chunk " + path.toString() + "; " + ex.getMessage(), ex);
            }
        }
    }
}

From source file:com.p2p.peercds.common.Torrent.java

/**
 * Helper method to create a {@link Torrent} object for a set of files.
 *
 * <p>/*  w ww  .  j  ava2 s. c  o m*/
 * Hash the given files to create the multi-file {@link Torrent} object
 * representing the Torrent meta-info about them, needed for announcing
 * and/or sharing these files. Since we created the torrent, we're
 * considering we'll be a full initial seeder for it.
 * </p>
 *
 * @param parent The parent directory or location of the torrent files,
 * also used as the torrent's name.
 * @param files The files to add into this torrent.
 * @param announce The announce URI that will be used for this torrent.
 * @param announceList The announce URIs organized as tiers that will 
 * be used for this torrent
 * @param createdBy The creator's name, or any string identifying the
 * torrent's creator.
 */
private static Torrent create(File parent, List<File> files, URI announce, List<List<URI>> announceList,
        String createdBy) throws InterruptedException, IOException {
    MessageDigest md = DigestUtils.getSha1Digest();
    if (files == null || files.isEmpty()) {
        logger.info("Creating single-file torrent for {}...", parent.getName());
    } else {
        logger.info("Creating {}-file torrent {}...", files.size(), parent.getName());
    }

    Map<String, BEValue> torrent = new HashMap<String, BEValue>();

    if (announce != null) {
        torrent.put("announce", new BEValue(announce.toString()));
    }
    if (announceList != null) {
        List<BEValue> tiers = new LinkedList<BEValue>();
        for (List<URI> trackers : announceList) {
            List<BEValue> tierInfo = new LinkedList<BEValue>();
            for (URI trackerURI : trackers) {
                tierInfo.add(new BEValue(trackerURI.toString()));
            }
            tiers.add(new BEValue(tierInfo));
        }
        torrent.put("announce-list", new BEValue(tiers));
    }

    torrent.put("creation date", new BEValue(new Date().getTime() / 1000));
    torrent.put("created by", new BEValue(createdBy));

    Map<String, BEValue> info = new HashMap<String, BEValue>();
    info.put("name", new BEValue(parent.getName()));
    info.put("piece length", new BEValue(PIECE_LENGTH));
    long size = 0;
    int numFiles = 0;
    if (files == null || files.isEmpty()) {
        info.put("length", new BEValue(parent.length()));
        size = parent.length();
        numFiles++;
        info.put("pieces", new BEValue(Torrent.hashFile(parent), BYTE_ENCODING));
    } else {
        List<BEValue> fileInfo = new LinkedList<BEValue>();
        List<File> updatedFilesList = new ArrayList<File>();
        updateFileInfo(files, parent, parent, fileInfo, updatedFilesList);
        logger.info("Number of files in this multi-file torrent: " + updatedFilesList.size());
        for (File file : updatedFilesList)
            size = size + file.length();
        logger.info("Number of bytes in this multi-file torrent: " + size);
        numFiles = updatedFilesList.size();
        info.put("files", new BEValue(fileInfo));
        BEValue piecesValue = new BEValue(Torrent.hashFiles(updatedFilesList), BYTE_ENCODING);
        info.put("pieces", piecesValue);
    }

    TreeMap<String, BEValue> sortInfoMap = new TreeMap<String, BEValue>();
    sortInfoMap.putAll(info);
    info = new HashMap<String, BEValue>();
    info.putAll(sortInfoMap);
    sortInfoMap = null;

    torrent.put("info", new BEValue(info));

    md.update(torrent.get("info").getMap().get("pieces").getBytes());
    byte[] digest = md.digest();
    byte[] transformedDigest = new byte[digest.length];
    int i = 0;
    for (byte bt : digest) {
        short s = (short) (bt & 0xFF);
        if (s >= 127) {
            s = (short) (s - 127);
            if (s < 32)
                s = (short) (s + 32);
        } else if (s < 32)
            s = (short) (s + 32);
        transformedDigest[i++] = (byte) s;
    }
    for (byte b : transformedDigest)
        logger.debug(new Byte(b).toString());
    logger.info("digest str " + new String(digest));
    logger.info("transformed digest str " + new String(transformedDigest));
    logger.info("Replacing special characters in the cloud key with regular characters");
    String cloudKeyForFile = new String(transformedDigest, "UTF-8");
    for (String nsChar : SPECIAL_TO_NSP_MAP.keySet()) {
        if (cloudKeyForFile.contains(nsChar))
            cloudKeyForFile = cloudKeyForFile.replaceAll(java.util.regex.Pattern.quote(nsChar),
                    SPECIAL_TO_NSP_MAP.get(nsChar));
    }

    logger.info("Sanitized cloud Key: " + cloudKeyForFile);
    CloudUploadProgressListener listener = new CloudUploadProgressListener(size, numFiles);
    boolean success = false;
    try {
        success = CloudHelper.uploadTorrent(BUCKET_NAME, cloudKeyForFile.trim(), parent, listener);
    } catch (S3FetchException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    if (!success)
        logger.info("File won't be uploaded to cloud as file is present in swarm and uploaded to cloud");
    else
        logger.info("New file has been introduced in the swarm and has been uploaded to the cloud");

    torrent.put(CLOUD_KEY, new BEValue(cloudKeyForFile));

    TreeMap<String, BEValue> sortTorrentMap = new TreeMap<String, BEValue>();
    sortTorrentMap.putAll(torrent);
    torrent = new HashMap<String, BEValue>();
    torrent.putAll(sortTorrentMap);
    sortTorrentMap = null;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BEncoder.bencode(new BEValue(torrent), baos);
    return new Torrent(baos.toByteArray(), true);
}

From source file:org.ancoron.hazelcast.rest.osgi.HazelcastServiceTest.java

@Test
public void lifecycleSimple() throws Exception {
    Config cfg = new Config("HazelcastServiceTest");

    // disable multicast...
    cfg.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);

    HazelcastInstance hz = Hazelcast.newHazelcastInstance(cfg);

    HazelcastMapServlet service = new HazelcastMapServlet();
    service.setHazelcast(hz);/* w  ww .  j av a  2  s .c  om*/

    // Step #1: create a bucket
    service.createBucket("A", 60, 0, 128);

    // Step #2: insert some data for a key
    MessageDigest md5 = DigestUtils.getMd5Digest();
    MessageDigest sha1 = DigestUtils.getSha1Digest();
    try (InputStream testData = new DigestInputStream(new DigestInputStream(stream("test.json"), sha1), md5)) {
        service.setValue("A", "1", "application/json", 171, testData);
    }

    // Step #3: fetch some data for a key
    byte[] value = service.getValue("A", "1");
    byte[] data = new byte[value.length - 1];
    System.arraycopy(value, 1, data, 0, data.length);

    Assert.assertThat(DigestUtils.md5Hex(data), CoreMatchers.is(Hex.encodeHexString(md5.digest())));
    Assert.assertThat(DigestUtils.sha1Hex(data), CoreMatchers.is(Hex.encodeHexString(sha1.digest())));

    // Step #4: delete the bucket
    service.deleteBucket("A");
}

From source file:org.graylog2.streams.StreamListFingerprint.java

private String buildFingerprint(List<Stream> streams) {
    final MessageDigest sha1Digest = DigestUtils.getSha1Digest();

    final StringBuilder sb = new StringBuilder();
    for (Stream stream : Ordering.from(getStreamComparator()).sortedCopy(streams)) {
        sb.append(stream.hashCode());/*from w w w  . java 2 s.co m*/

        for (StreamRule rule : Ordering.from(getStreamRuleComparator()).sortedCopy(stream.getStreamRules())) {
            sb.append(rule.hashCode());
        }
        for (Output output : Ordering.from(getOutputComparator()).sortedCopy(stream.getOutputs())) {
            sb.append(output.hashCode());
        }
    }
    return String.valueOf(Hex.encodeHex(sha1Digest.digest(sb.toString().getBytes(StandardCharsets.US_ASCII))));
}