]> git.argeo.org Git - lgpl/argeo-commons.git/blob - src/org/argeo/util/DigestUtils.java
Prepare next development cycle
[lgpl/argeo-commons.git] / src / org / argeo / util / DigestUtils.java
1 package org.argeo.util;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.nio.ByteBuffer;
8 import java.nio.channels.FileChannel;
9 import java.nio.channels.FileChannel.MapMode;
10 import java.nio.file.Files;
11 import java.nio.file.Path;
12 import java.security.MessageDigest;
13 import java.security.NoSuchAlgorithmException;
14
15 /** Utilities around cryptographic digests */
16 public class DigestUtils {
17 public final static String MD5 = "MD5";
18 public final static String SHA1 = "SHA1";
19 public final static String SHA256 = "SHA-256";
20 public final static String SHA512 = "SHA-512";
21
22 private static Boolean debug = false;
23 // TODO: make it writable
24 private final static Integer byteBufferCapacity = 100 * 1024;// 100 KB
25
26 public static byte[] sha1(byte[] bytes) {
27 try {
28 MessageDigest digest = MessageDigest.getInstance(SHA1);
29 digest.update(bytes);
30 byte[] checksum = digest.digest();
31 return checksum;
32 } catch (Exception e) {
33 throw new UtilsException("Cannot SHA1 digest", e);
34 }
35 }
36
37 public static String digest(String algorithm, byte[] bytes) {
38 try {
39 MessageDigest digest = MessageDigest.getInstance(algorithm);
40 digest.update(bytes);
41 byte[] checksum = digest.digest();
42 String res = encodeHexString(checksum);
43 return res;
44 } catch (Exception e) {
45 throw new UtilsException("Cannot digest with algorithm " + algorithm, e);
46 }
47 }
48
49 public static String digest(String algorithm, InputStream in) {
50 try {
51 MessageDigest digest = MessageDigest.getInstance(algorithm);
52 // ReadableByteChannel channel = Channels.newChannel(in);
53 // ByteBuffer bb = ByteBuffer.allocateDirect(byteBufferCapacity);
54 // while (channel.read(bb) > 0)
55 // digest.update(bb);
56 byte[] buffer = new byte[byteBufferCapacity];
57 int read = 0;
58 while ((read = in.read(buffer)) > 0) {
59 digest.update(buffer, 0, read);
60 }
61
62 byte[] checksum = digest.digest();
63 String res = encodeHexString(checksum);
64 return res;
65 } catch (Exception e) {
66 throw new UtilsException("Cannot digest with algorithm " + algorithm, e);
67 } finally {
68 StreamUtils.closeQuietly(in);
69 }
70 }
71
72 public static String digest(String algorithm, File file) {
73 FileInputStream fis = null;
74 FileChannel fc = null;
75 try {
76 fis = new FileInputStream(file);
77 fc = fis.getChannel();
78
79 // Get the file's size and then map it into memory
80 int sz = (int) fc.size();
81 ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);
82 return digest(algorithm, bb);
83 } catch (IOException e) {
84 throw new UtilsException("Cannot digest " + file + " with algorithm " + algorithm, e);
85 } finally {
86 StreamUtils.closeQuietly(fis);
87 if (fc.isOpen())
88 try {
89 fc.close();
90 } catch (IOException e) {
91 // silent
92 }
93 }
94 }
95
96 protected static String digest(String algorithm, ByteBuffer bb) {
97 long begin = System.currentTimeMillis();
98 try {
99 MessageDigest digest = MessageDigest.getInstance(algorithm);
100 digest.update(bb);
101 byte[] checksum = digest.digest();
102 String res = encodeHexString(checksum);
103 long end = System.currentTimeMillis();
104 if (debug)
105 System.out.println((end - begin) + " ms / " + ((end - begin) / 1000) + " s");
106 return res;
107 } catch (NoSuchAlgorithmException e) {
108 throw new UtilsException("Cannot digest with algorithm " + algorithm, e);
109 }
110 }
111
112 public static String sha1hex(Path path) {
113 return digest(SHA1, path, byteBufferCapacity);
114 }
115
116 public static String digest(String algorithm, Path path, long bufferSize) {
117 byte[] digest = digestRaw(algorithm, path, bufferSize);
118 return encodeHexString(digest);
119 }
120
121 public static byte[] digestRaw(String algorithm, Path file, long bufferSize) {
122 long begin = System.currentTimeMillis();
123 try {
124 MessageDigest md = MessageDigest.getInstance(algorithm);
125 FileChannel fc = FileChannel.open(file);
126 long fileSize = Files.size(file);
127 if (fileSize <= bufferSize) {
128 ByteBuffer bb = fc.map(MapMode.READ_ONLY, 0, fileSize);
129 md.update(bb);
130 } else {
131 long lastCycle = (fileSize / bufferSize) - 1;
132 long position = 0;
133 for (int i = 0; i <= lastCycle; i++) {
134 ByteBuffer bb;
135 if (i != lastCycle) {
136 bb = fc.map(MapMode.READ_ONLY, position, bufferSize);
137 position = position + bufferSize;
138 } else {
139 bb = fc.map(MapMode.READ_ONLY, position, fileSize - position);
140 position = fileSize;
141 }
142 md.update(bb);
143 }
144 }
145 long end = System.currentTimeMillis();
146 if (debug)
147 System.out.println((end - begin) + " ms / " + ((end - begin) / 1000) + " s");
148 return md.digest();
149 } catch (Exception e) {
150 throw new UtilsException("Cannot digest " + file + " with algorithm " + algorithm, e);
151 }
152 }
153
154 public static void main(String[] args) {
155 File file;
156 if (args.length > 0)
157 file = new File(args[0]);
158 else {
159 System.err.println("Usage: <file> [<algorithm>]" + " (see http://java.sun.com/j2se/1.5.0/"
160 + "docs/guide/security/CryptoSpec.html#AppA)");
161 return;
162 }
163
164 if (args.length > 1) {
165 String algorithm = args[1];
166 System.out.println(digest(algorithm, file));
167 } else {
168 String algorithm = "MD5";
169 System.out.println(algorithm + ": " + digest(algorithm, file));
170 algorithm = "SHA";
171 System.out.println(algorithm + ": " + digest(algorithm, file));
172 System.out.println(algorithm + ": " + sha1hex(file.toPath()));
173 algorithm = "SHA-256";
174 System.out.println(algorithm + ": " + digest(algorithm, file));
175 algorithm = "SHA-512";
176 System.out.println(algorithm + ": " + digest(algorithm, file));
177 }
178 }
179
180 final private static char[] hexArray = "0123456789abcdef".toCharArray();
181
182 /**
183 * From
184 * http://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to
185 * -a-hex-string-in-java
186 */
187 public static String encodeHexString(byte[] bytes) {
188 char[] hexChars = new char[bytes.length * 2];
189 for (int j = 0; j < bytes.length; j++) {
190 int v = bytes[j] & 0xFF;
191 hexChars[j * 2] = hexArray[v >>> 4];
192 hexChars[j * 2 + 1] = hexArray[v & 0x0F];
193 }
194 return new String(hexChars);
195 }
196
197 }