1 /*
2 * This file is part of dependency-check-core.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * Copyright (c) 2014 Jeremy Long. All Rights Reserved.
17 */
18 package org.owasp.dependencycheck.utils;
19
20 import java.io.File;
21 import java.io.FileInputStream;
22 import java.io.IOException;
23 import java.nio.MappedByteBuffer;
24 import java.nio.channels.FileChannel;
25 import java.security.MessageDigest;
26 import java.security.NoSuchAlgorithmException;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
29
30 /**
31 * Includes methods to generate the MD5 and SHA1 checksum.
32 *
33 * @author Jeremy Long <jeremy.long@owasp.org>
34 *
35 */
36 public final class Checksum {
37
38 /**
39 * The logger.
40 */
41 private static final Logger LOGGER = Logger.getLogger(Checksum.class.getName());
42
43 /**
44 * Private constructor for a utility class.
45 */
46 private Checksum() {
47 }
48
49 /**
50 * <p>
51 * Creates the cryptographic checksum of a given file using the specified algorithm.</p>
52 *
53 * @param algorithm the algorithm to use to calculate the checksum
54 * @param file the file to calculate the checksum for
55 * @return the checksum
56 * @throws IOException when the file does not exist
57 * @throws NoSuchAlgorithmException when an algorithm is specified that does not exist
58 */
59 @SuppressWarnings("empty-statement")
60 public static byte[] getChecksum(String algorithm, File file) throws NoSuchAlgorithmException, IOException {
61 MessageDigest digest = MessageDigest.getInstance(algorithm);
62 FileInputStream fis = null;
63 try {
64 fis = new FileInputStream(file);
65 FileChannel ch = fis.getChannel();
66 long remainingToRead = file.length();
67 long start = 0;
68 while (remainingToRead > 0) {
69 long amountToRead;
70 if (remainingToRead > Integer.MAX_VALUE) {
71 remainingToRead -= Integer.MAX_VALUE;
72 amountToRead = Integer.MAX_VALUE;
73 } else {
74 amountToRead = remainingToRead;
75 remainingToRead = 0;
76 }
77 MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, start, amountToRead);
78 digest.update(byteBuffer);
79 start += amountToRead;
80 }
81
82 // BufferedInputStream bis = new BufferedInputStream(fis);
83 // DigestInputStream dis = new DigestInputStream(bis, digest);
84 // //yes, we are reading in a buffer for performance reasons - 1 byte at a time is SLOW
85 // byte[] buffer = new byte[8192];
86 // while (dis.read(buffer) != -1);
87 } finally {
88 if (fis != null) {
89 try {
90 fis.close();
91 } catch (IOException ex) {
92 LOGGER.log(Level.FINEST, "Error closing file '" + file.getName() + "'.", ex);
93 }
94 }
95 }
96 return digest.digest();
97 }
98
99 /**
100 * Calculates the MD5 checksum of a specified file.
101 *
102 * @param file the file to generate the MD5 checksum
103 * @return the hex representation of the MD5 hash
104 * @throws IOException when the file passed in does not exist
105 * @throws NoSuchAlgorithmException when the MD5 algorithm is not available
106 */
107 public static String getMD5Checksum(File file) throws IOException, NoSuchAlgorithmException {
108 byte[] b = getChecksum("MD5", file);
109 return getHex(b);
110 }
111
112 /**
113 * Calculates the SHA1 checksum of a specified file.
114 *
115 * @param file the file to generate the MD5 checksum
116 * @return the hex representation of the SHA1 hash
117 * @throws IOException when the file passed in does not exist
118 * @throws NoSuchAlgorithmException when the SHA1 algorithm is not available
119 */
120 public static String getSHA1Checksum(File file) throws IOException, NoSuchAlgorithmException {
121 byte[] b = getChecksum("SHA1", file);
122 return getHex(b);
123 }
124 /**
125 * Hex code characters used in getHex.
126 */
127 private static final String HEXES = "0123456789ABCDEF";
128
129 /**
130 * <p>
131 * Converts a byte array into a hex string.</p>
132 *
133 * <p>
134 * This method was copied from <a
135 * href="http://www.rgagnon.com/javadetails/java-0596.html">http://www.rgagnon.com/javadetails/java-0596.html</a></p>
136 *
137 * @param raw a byte array
138 * @return the hex representation of the byte array
139 */
140 public static String getHex(byte[] raw) {
141 if (raw == null) {
142 return null;
143 }
144 final StringBuilder hex = new StringBuilder(2 * raw.length);
145 for (final byte b : raw) {
146 hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt(b & 0x0F));
147 }
148 return hex.toString();
149 }
150 }