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.wrapper;
20  
21  import java.io.InputStream;
22  import java.nio.file.Files;
23  import java.nio.file.Path;
24  import java.security.MessageDigest;
25  import java.util.Locale;
26  
27  /**
28   * @author Rafael Winterhalter
29   */
30  public class HashAlgorithmVerifier implements Verifier {
31  
32      @Override
33      public void verify(Path file, String property, String algorithm, String expectedSum) throws Exception {
34          MessageDigest digest = MessageDigest.getInstance(algorithm);
35          try (InputStream inputStream = Files.newInputStream(file)) {
36              byte[] buffer = new byte[1024 * 8];
37              int length;
38              while ((length = inputStream.read(buffer)) != -1) {
39                  digest.update(buffer, 0, length);
40              }
41          }
42          byte[] hash = digest.digest();
43          StringBuilder actualSum = new StringBuilder(hash.length * 2);
44          for (byte aByte : hash) {
45              actualSum.append(String.format("%02x", aByte));
46          }
47          if (expectedSum.contentEquals(actualSum)) {
48              Logger.info(String.format(
49                      Locale.ROOT, "Validated %s hash for %s to be equal (%s)", algorithm, file, expectedSum));
50          } else {
51              throw new RuntimeException(String.format(
52                      Locale.ROOT,
53                      "Failed to validate Maven distribution %s, your Maven distribution "
54                              + "might be compromised. If you updated your Maven version, you need to "
55                              + "update the specified %s property.",
56                      algorithm,
57                      property));
58          }
59      }
60  }