View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
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   * SHA
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  }