1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.buildcache.hash;
20
21 import java.io.IOException;
22 import java.nio.file.Files;
23 import java.nio.file.Path;
24 import java.security.MessageDigest;
25
26
27
28
29 public class SHA implements Hash.Factory {
30
31 private static final ThreadLocal<MessageDigest> ALGORITHM = new ThreadLocal<>();
32 private static final ThreadLocal<MessageDigest> CHECKSUM = new ThreadLocal<>();
33
34 private final String algorithm;
35
36 SHA(String algorithm) {
37 this.algorithm = algorithm;
38 }
39
40 @Override
41 public String getAlgorithm() {
42 return algorithm;
43 }
44
45 @Override
46 public Hash.Algorithm algorithm() {
47 return new SHA.Algorithm(ThreadLocalDigest.get(ALGORITHM, algorithm));
48 }
49
50 @Override
51 public Hash.Checksum checksum(int count) {
52 return new SHA.Checksum(ThreadLocalDigest.get(CHECKSUM, algorithm));
53 }
54
55 private static class Algorithm implements Hash.Algorithm {
56
57 private final MessageDigest digest;
58
59 private Algorithm(MessageDigest digest) {
60 this.digest = digest;
61 }
62
63 @Override
64 public byte[] hash(byte[] array) {
65 return digest.digest(array);
66 }
67
68 @Override
69 public byte[] hash(Path path) throws IOException {
70 return hash(Files.readAllBytes(path));
71 }
72 }
73
74 private static class Checksum implements Hash.Checksum {
75
76 private final MessageDigest digest;
77
78 private Checksum(MessageDigest digest) {
79 this.digest = digest;
80 }
81
82 @Override
83 public void update(byte[] hash) {
84 digest.update(hash);
85 }
86
87 @Override
88 public byte[] digest() {
89 return digest.digest();
90 }
91 }
92 }