List of usage examples for java.security DigestInputStream DigestInputStream
public DigestInputStream(InputStream stream, MessageDigest digest)
From source file:nl.knaw.dans.easy.sword2examples.SimpleDeposit.java
public static URI depositPackage(File bagDir, IRI colIri, String uid, String pw) throws Exception { // 0. Zip the bagDir File zipFile = new File(bagDir.getAbsolutePath() + ".zip"); zipFile.delete();//w w w . ja v a2 s.co m Common.zipDirectory(bagDir, zipFile); // 1. Set up stream for calculating MD5 MessageDigest md = MessageDigest.getInstance("MD5"); try (FileInputStream fis = new FileInputStream(zipFile); DigestInputStream dis = new DigestInputStream(fis, md)) { // 2. Post entire bag to Col-IRI CloseableHttpClient http = Common.createHttpClient(colIri.toURI(), uid, pw); CloseableHttpResponse response = Common.sendChunk(dis, (int) zipFile.length(), "POST", colIri.toURI(), "bag.zip", "application/zip", http, false); // 3. Check the response. If transfer corrupt (MD5 doesn't check out), report and exit. String bodyText = Common.readEntityAsString(response.getEntity()); if (response.getStatusLine().getStatusCode() != 201) { System.err.println("FAILED. Status = " + response.getStatusLine()); System.err.println("Response body follows:"); System.err.println(bodyText); System.exit(2); } System.out.println("SUCCESS. Deposit receipt follows:"); System.out.println(bodyText); // 4. Get the statement URL. This is the URL from which to retrieve the current status of the deposit. System.out.println("Retrieving Statement IRI (Stat-IRI) from deposit receipt ..."); Entry receipt = Common.parse(bodyText); Link statLink = receipt.getLink("http://purl.org/net/sword/terms/statement"); IRI statIri = statLink.getHref(); System.out.println("Stat-IRI = " + statIri); // 5. Check statement every ten seconds (a bit too frantic, but okay for this test). If status changes: // report new status. If status is an error (INVALID, REJECTED, FAILED) or ARCHIVED: exit. return Common.trackDeposit(http, statIri.toURI()); } }
From source file:eu.peppol.document.PayloadDigestCalculator.java
public static MessageDigestResult calcDigest(String algorithm, StandardBusinessDocumentHeader sbdh, InputStream inputStream) { MessageDigest messageDigest;/*from w w w . j a va 2 s . c o m*/ try { messageDigest = MessageDigest.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException( "Unknown digest algorithm " + OxalisConstant.DEFAULT_DIGEST_ALGORITHM + " " + e.getMessage(), e); } InputStream inputStreamToCalculateDigestFrom = null; ManifestItem manifestItem = SbdhFastParser.searchForAsicManifestItem(sbdh); if (manifestItem != null) { // creates an FilterInputStream, which will extract the ASiC in binary format. inputStreamToCalculateDigestFrom = new Base64InputStream(new AsicFilterInputStream(inputStream)); } else inputStreamToCalculateDigestFrom = inputStream; DigestInputStream digestInputStream = new DigestInputStream( new BufferedInputStream(inputStreamToCalculateDigestFrom), messageDigest); try { IOUtils.copy(digestInputStream, new NullOutputStream()); } catch (IOException e) { throw new IllegalStateException("Unable to calculate digest for payload"); } return new MessageDigestResult(messageDigest.digest(), messageDigest.getAlgorithm()); }
From source file:rapture.plugin.install.PluginContentReader.java
public static byte[] readFromZip(ZipFile zip, ZipEntry entry, MessageDigest md) throws IOException { DigestInputStream is = new DigestInputStream(zip.getInputStream(entry), md); return readFromStream(is); }
From source file:com.lightboxtechnologies.ingest.Uploader.java
public int run(String[] args) throws IOException { if (args.length != 1) { System.err.println("Usage: Uploader <dest path>"); System.err.println("Writes data to HDFS path from stdin"); return 2; }// w w w . ja v a 2 s . com final String dst = args[0]; final Configuration conf = getConf(); final MessageDigest hasher = FsEntryUtils.getHashInstance("MD5"); final DigestInputStream hashedIn = new DigestInputStream(System.in, hasher); final FileSystem fs = FileSystem.get(conf); final Path path = new Path(dst); final FSDataOutputStream outFile = fs.create(path, true); IOUtils.copyLarge(hashedIn, outFile, new byte[1024 * 1024]); System.out.println(Hex.encodeHexString(hasher.digest())); return 0; }
From source file:org.unitils.dbmaintainer.script.ScriptContentHandle.java
/** * Opens a stream to the content of the script. * /*from ww w .j ava 2 s . c o m*/ * NOTE: do not forget to close the stream after usage. * * @return The content stream, not null */ public Reader openScriptContentReader() { scriptDigest = getScriptDigest(); scriptReader = new InputStreamReader(new DigestInputStream(getScriptInputStream(), scriptDigest)); return scriptReader; }
From source file:net.minecrell.serverlistplus.canary.SnakeYAML.java
@SneakyThrows public static void load(Plugin plugin) { try { // Check if it is already loaded Class.forName("org.yaml.snakeyaml.Yaml"); return;/* www . j a v a 2 s . c o m*/ } catch (ClassNotFoundException ignored) { } Path path = Paths.get("lib", SNAKE_YAML_JAR); if (Files.notExists(path)) { Files.createDirectories(path.getParent()); plugin.getLogman().info("Downloading SnakeYAML..."); URL url = new URL(SNAKE_YAML); MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); try (ReadableByteChannel source = Channels.newChannel(new DigestInputStream(url.openStream(), sha1)); FileChannel out = FileChannel.open(path, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) { out.transferFrom(source, 0, Long.MAX_VALUE); } if (!new String(Hex.encodeHex(sha1.digest())).equals(EXPECTED_HASH)) { Files.delete(path); throw new IllegalStateException( "Downloaded SnakeYAML, but checksum check failed. Please try again later."); } plugin.getLogman().info("Successfully downloaded!"); } loadJAR(path); }
From source file:com.github.ffremont.microservices.springboot.node.tasks.InstallJarTask.java
@Override public void run(MicroServiceTask task) throws TaskException { Path msVersionFolder = helper.targetDirOf(task.getMs()); Path checksumPath = Paths.get(msVersionFolder.toString(), InstallTask.CHECKSUM_FILE_NAME + ".txt"); Path jarTarget = helper.targetJarOf(task.getMs()); try {//from w w w. jav a2 s. c o m if (task.getJar() == null) { throw new InvalidInstallationException("Jar indisponible dans l'objet MicroServiceTask"); } Files.copy(task.getJar(), jarTarget); MessageDigest md = MessageDigest.getInstance("SHA-1"); try (DigestInputStream digestIs = new DigestInputStream(new FileInputStream(jarTarget.toFile()), md)) { byte[] buffer = new byte[10240]; // 10ko while (0 < digestIs.read(buffer)) { } digestIs.close(); } byte[] checksumTarget = md.digest(); if (!String.format("%032X", new BigInteger(1, checksumTarget)) .equals(task.getMs().getSha1().toUpperCase())) { throw new InvalidInstallationException( "Le checksum n'est pas valide suite la copie : " + this.nodeBase); } Files.write(checksumPath, task.getMs().getSha1().getBytes()); LOG.debug("Cration du fichier checksum.txt"); } catch (IOException | NoSuchAlgorithmException ex) { throw new InvalidInstallationException("Impossible d'installer le jar", ex); } }
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);/*from ww w . j a v a2 s . c o m*/ // 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:ch.cyberduck.core.b2.B2SingleUploadService.java
@Override protected InputStream decorate(final InputStream in, final MessageDigest digest) throws IOException { if (null == digest) { return super.decorate(in, null); } else {// w w w .j a va 2 s . com return new DigestInputStream(super.decorate(in, digest), digest); } }
From source file:me.lachlanap.summis.downloader.VerifierCallable.java
@Override public Void call() throws Exception { Path file = binaryRoot.resolve(info.getName()); MessageDigest md5 = MessageDigest.getInstance("MD5"); MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); byte[] buffer = new byte[1024]; try (final InputStream is = Files.newInputStream(file)) { DigestInputStream dis = new DigestInputStream(new DigestInputStream(is, md5), sha1); while (dis.read(buffer) != -1) { ;/*from w ww. j a v a2s.c o m*/ } } String md5Digest = new String(Hex.encodeHex(md5.digest())); String sha1Digest = new String(Hex.encodeHex(sha1.digest())); if (!md5Digest.equals(info.getMD5Digest()) || !sha1Digest.equals(info.getSHA1Digest())) throw new RuntimeException(info.getName() + " failed verification"); downloadListener.completedAVerify(); return null; }