use of java.security.DigestInputStream in project jackrabbit-oak by apache.
the class FileBlobStore method writeBlob.
@Override
public String writeBlob(String tempFilePath) throws IOException {
File file = new File(tempFilePath);
InputStream in = new FileInputStream(file);
MessageDigest messageDigest;
try {
messageDigest = MessageDigest.getInstance(HASH_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
throw new IOException(e);
}
DigestInputStream din = new DigestInputStream(in, messageDigest);
long length = file.length();
try {
while (true) {
int len = din.read(buffer, 0, buffer.length);
if (len < 0) {
break;
}
}
} finally {
din.close();
}
ByteArrayOutputStream idStream = new ByteArrayOutputStream();
idStream.write(TYPE_HASH);
IOUtils.writeVarInt(idStream, 0);
IOUtils.writeVarLong(idStream, length);
byte[] digest = messageDigest.digest();
File f = getFile(digest, false);
if (f.exists()) {
file.delete();
} else {
File parent = f.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
file.renameTo(f);
}
IOUtils.writeVarInt(idStream, digest.length);
idStream.write(digest);
byte[] id = idStream.toByteArray();
String blobId = StringUtils.convertBytesToHex(id);
usesBlobId(blobId);
return blobId;
}
use of java.security.DigestInputStream in project sling by apache.
the class DistributionPackageImporterServlet method doPost.
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
DistributionPackageImporter distributionPackageImporter = request.getResource().adaptTo(DistributionPackageImporter.class);
String digestAlgorithm = null;
String digestMessage = null;
String digestHeader = request.getHeader(DIGEST_HEADER);
if (isNotEmpty(digestHeader)) {
log.debug("Found Digest header {}, extracting algorithm and message...", digestHeader);
Matcher matcher = digestHeaderRegex.matcher(digestHeader);
if (matcher.matches()) {
digestAlgorithm = matcher.group(1);
digestMessage = matcher.group(2);
} else {
log.debug("Digest header {} not supported, it doesn't match with expected pattern {}", new Object[] { digestHeader, digestHeaderRegex.pattern() });
}
}
final long start = System.currentTimeMillis();
response.setContentType("application/json");
InputStream stream;
if (isNotEmpty(digestAlgorithm) && isNotEmpty(digestMessage)) {
stream = openDigestInputStream(request.getInputStream(), digestAlgorithm);
} else {
stream = request.getInputStream();
}
ResourceResolver resourceResolver = request.getResourceResolver();
try {
if (request.getParameter("forceError") != null) {
throw new Exception("manually forced error");
}
DistributionPackageInfo distributionPackageInfo = distributionPackageImporter.importStream(resourceResolver, stream);
long end = System.currentTimeMillis();
if (isNotEmpty(digestAlgorithm) && isNotEmpty(digestMessage)) {
String receivedDigestMessage = readDigestMessage((DigestInputStream) stream);
if (!digestMessage.equalsIgnoreCase(receivedDigestMessage)) {
log.error("Error during distribution import: received distribution package is corrupted, expected [{}] but received [{}]", new Object[] { digestMessage, receivedDigestMessage });
Map<String, String> kv = new HashMap<String, String>();
kv.put("digestAlgorithm", digestAlgorithm);
kv.put("expected", digestMessage);
kv.put("received", receivedDigestMessage);
ServletJsonUtils.writeJson(response, SC_BAD_REQUEST, "Received distribution package is corrupted", kv);
return;
}
}
log.info("Package {} imported successfully in {}ms", distributionPackageInfo, end - start);
ServletJsonUtils.writeJson(response, SC_OK, "package imported successfully", null);
} catch (final Throwable e) {
ServletJsonUtils.writeJson(response, SC_INTERNAL_SERVER_ERROR, "an unexpected error has occurred during distribution import", null);
log.error("Error during distribution import", e);
} finally {
long end = System.currentTimeMillis();
log.debug("Processed package import request in {} ms", end - start);
}
}
use of java.security.DigestInputStream in project tomee by apache.
the class Files method hash.
public static String hash(final Set<URL> urls, final String algo) {
final Collection<File> files = new ArrayList<File>();
for (final URL u : urls) {
final File file = toFile(u);
if (!file.isDirectory()) {
files.add(file);
} else {
files.addAll(Files.collect(file, TrueFilter.INSTANCE));
}
}
MessageDigest digest = DIGESTS.get(algo);
if (digest == null) {
try {
digest = MessageDigest.getInstance(algo);
} catch (final NoSuchAlgorithmException e) {
throw new LoaderRuntimeException(e);
}
DIGESTS.put(algo, digest);
}
for (final File file : files) {
if (!file.exists()) {
continue;
}
DigestInputStream is = null;
try {
is = new DigestInputStream(new FileInputStream(file), digest);
// read the stream
IO.copy(is, new NoopOutputStream());
} catch (final IOException e) {
// no-op: shouldn't occur here
} finally {
IO.close(is);
}
}
final byte[] hash = digest.digest();
digest.reset();
final StringBuilder sb = new StringBuilder("");
for (final byte b : hash) {
// hex convertion
sb.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
use of java.security.DigestInputStream in project bnd by bndtools.
the class StoredRevisionCache method doDownload.
/*
* Download an URI into a temporary file while calculating SHA & MD5. The
* connection uses the normal protections
*/
Download doDownload(URI url) throws Exception {
InputStream connect = httpc.connect(url.toURL());
if (connect == null)
return null;
Download d = new Download();
d.tmp = IO.createTempFile(tmpdir, "tmp", ".tmp");
MessageDigest sha = MessageDigest.getInstance("SHA1");
MessageDigest md5 = MessageDigest.getInstance("MD5");
DigestInputStream shaIn = new DigestInputStream(connect, sha);
DigestInputStream md5In = new DigestInputStream(shaIn, md5);
IO.copy(md5In, d.tmp);
d.sha = sha.digest();
d.md5 = md5.digest();
return d;
}
use of java.security.DigestInputStream in project bndtools by bndtools.
the class ReposTemplateLoaderTest method testProcessTemplate.
public void testProcessTemplate() throws Exception {
List<Template> templates = loader.findTemplates("test1", new ProgressMonitorReporter(new NullProgressMonitor(), "")).getValue();
assertEquals(1, templates.size());
Template template = templates.get(0);
Map<String, List<Object>> parameters = new HashMap<>();
parameters.put("projectName", Collections.<Object>singletonList("org.example.foo"));
parameters.put("srcDir", Collections.<Object>singletonList("src/main/java"));
parameters.put("basePackageDir", Collections.<Object>singletonList("org/example/foo"));
ResourceMap outputs = template.generateOutputs(parameters);
assertEquals(5, outputs.size());
Entry<String, Resource> entry;
Iterator<Entry<String, Resource>> iter = outputs.entries().iterator();
entry = iter.next();
assertEquals("src/main/java/org/example/foo/Activator.java", entry.getKey());
assertEquals("package org.example.foo; public class Activator {}", IO.collect(entry.getValue().getContent()));
entry = iter.next();
assertEquals("pic.jpg", entry.getKey());
// Check the digest of the pic to ensure it didn't get damaged by the templating engine
DigestInputStream digestStream = new DigestInputStream(entry.getValue().getContent(), MessageDigest.getInstance("SHA-256"));
IO.drain(digestStream);
byte[] digest = digestStream.getMessageDigest().digest();
assertEquals("ea5d770bc2deddb1f9a20df3ad337bdc1490ba7b35fa41c33aa4e9a534e82ada", Hex.toHexString(digest).toLowerCase());
entry = iter.next();
assertEquals("src/main/java/", entry.getKey());
entry = iter.next();
assertEquals("src/main/java/org/example/foo/", entry.getKey());
entry = iter.next();
assertEquals("bnd.bnd", entry.getKey());
assertEquals("Bundle-SymbolicName: org.example.foo", IO.collect(entry.getValue().getContent()));
}
Aggregations