Files
NeitzelFXDesigner/designer-maven-plugin/src/main/java/de/neitzel/fxdesigner/maven/DependencyProof.java
T

59 lines
2.0 KiB
Java

package de.neitzel.fxdesigner.maven;
import java.nio.file.*;
import java.util.*;
import org.apache.maven.project.MavenProject;
final class DependencyProof {
static String signature(Path path) throws Exception {
var a = Files.readAttributes(path, java.nio.file.attribute.BasicFileAttributes.class);
var hash = java.security.MessageDigest.getInstance("SHA-256");
try (var in = Files.newInputStream(path)) {
byte[] b = new byte[65536];
for (int n; (n = in.read(b)) != -1; ) hash.update(b, 0, n);
}
return HexFormat.of().formatHex(hash.digest())
+ ":"
+ a.size()
+ ":"
+ a.lastModifiedTime()
+ ":"
+ a.fileKey();
}
static Properties capture(MavenProject project) throws Exception {
var p = new Properties();
int n = 0;
for (var a : project.getArtifacts()) {
Path path = a.getFile().toPath().toRealPath();
if (!Files.isRegularFile(path))
throw new IllegalArgumentException("Dependency is not a packaged file: " + path);
p.setProperty("artifact." + n + ".path", path.toString());
p.setProperty("artifact." + n + ".coordinates", a.getId());
p.setProperty("artifact." + n + ".signature", signature(path));
n++;
}
p.setProperty("artifact.count", Integer.toString(n));
return p;
}
static String id(MavenProject project) throws Exception {
return HexFormat.of()
.formatHex(
java.security.MessageDigest.getInstance("SHA-256")
.digest(
project
.getBasedir()
.getCanonicalPath()
.getBytes(java.nio.charset.StandardCharsets.UTF_8)));
}
static void verify(Properties p) throws Exception {
int n = Integer.parseInt(p.getProperty("artifact.count"));
for (int i = 0; i < n; i++)
if (!signature(Path.of(p.getProperty("artifact." + i + ".path")))
.equals(p.getProperty("artifact." + i + ".signature")))
throw new IllegalStateException("Dependency changed during Maven build");
}
}