comparison src/com/tmate/hgkit/ll/DigestHelper.java @ 9:d6d2a630f4a6

Access to underlaying file data wrapped into own Access object, implemented with FileChannel and ByteBuffer
author Artem Tikhomirov <tikhomirov.artem@gmail.com>
date Sat, 25 Dec 2010 04:45:59 +0100
parents
children 571e1b2cc3f7
comparison
equal deleted inserted replaced
8:a78c980749e3 9:d6d2a630f4a6
1 /**
2 * Copyright (c) 2010 Artem Tikhomirov
3 */
4 package com.tmate.hgkit.ll;
5
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.security.MessageDigest;
9 import java.security.NoSuchAlgorithmException;
10
11 /**
12 *
13 * @author artem
14 */
15 public class DigestHelper {
16 private MessageDigest sha1;
17
18 public DigestHelper() {
19 }
20
21 private MessageDigest getSHA1() {
22 if (sha1 == null) {
23 try {
24 sha1 = MessageDigest.getInstance("SHA-1");
25 } catch (NoSuchAlgorithmException ex) {
26 // could hardly happen, JDK from Sun always has sha1.
27 ex.printStackTrace(); // FIXME log error
28 }
29 }
30 return sha1;
31 }
32
33 // XXX perhaps, digest functions should throw an exception, as it's caller responsibility to deal with eof, etc
34 public String sha1(byte[] data) {
35 MessageDigest alg = getSHA1();
36 byte[] digest = alg.digest(data);
37 assert digest.length == 20;
38 return toHexString(digest, 0, 20);
39 }
40
41 public byte[] sha1(InputStream is /*ByteBuffer*/) throws IOException {
42 MessageDigest alg = getSHA1();
43 byte[] buf = new byte[1024];
44 int c;
45 while ((c = is.read(buf)) != -1) {
46 alg.update(buf, 0, c);
47 }
48 byte[] digest = alg.digest();
49 return digest;
50 }
51
52 public String toHexString(byte[] data, final int offset, final int count) {
53 char[] result = new char[count << 1];
54 final String hexDigits = "0123456789abcdef";
55 final int end = offset+count;
56 for (int i = offset, j = 0; i < end; i++) {
57 result[j++] = hexDigits.charAt((data[i] >>> 4) & 0x0F);
58 result[j++] = hexDigits.charAt(data[i] & 0x0F);
59 }
60 return new String(result);
61 }
62 }