2 * Copyright © 2019 Damyan Ivanov.
3 * This file is part of MoLe.
4 * MoLe is free software: you can distribute it and/or modify it
5 * under the term of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your opinion), any later version.
9 * MoLe is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License terms for details.
14 * You should have received a copy of the GNU General Public License
15 * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
18 package net.ktnx.mobileledger.utils;
20 import java.nio.ByteBuffer;
21 import java.security.DigestException;
22 import java.security.MessageDigest;
23 import java.security.NoSuchAlgorithmException;
26 private MessageDigest digest;
27 public Digest(String type) throws NoSuchAlgorithmException {
28 digest = MessageDigest.getInstance(type);
30 public static char[] hexDigitsFor(byte x) {
31 return hexDigitsFor(((x < 0) ? 256 + x : x));
33 public static char[] hexDigitsFor(int x) {
34 if ((x < 0) || (x > 255)) throw new ArithmeticException(
35 String.format("Hex digits must be between 0 and 255 (argument: %d)", x));
36 char[] result = new char[]{0, 0};
37 result[0] = hexDigitFor(x / 16);
38 result[1] = hexDigitFor(x % 16);
42 public static char hexDigitFor(int x) {
43 if (x < 0) throw new ArithmeticException(
44 String.format("Hex digits can't be negative (argument: %d)", x));
45 if (x < 10) return (char) ('0' + x);
46 if (x < 16) return (char) ('a' + x - 10);
47 throw new ArithmeticException(
48 String.format("Hex digits can't be greater than 15 (argument: %d)", x));
50 public void update(byte input) {
53 public void update(byte[] input, int offset, int len) {
54 digest.update(input, offset, len);
56 public void update(byte[] input) {
59 public void update(ByteBuffer input) {
62 public byte[] digest() {
63 return digest.digest();
65 public int digest(byte[] buf, int offset, int len) throws DigestException {
66 return digest.digest(buf, offset, len);
68 public byte[] digest(byte[] input) {
69 return digest.digest(input);
71 public String digestToHexString() {
72 byte[] digest = digest();
73 StringBuilder result = new StringBuilder();
74 for (int i = 0; i < getDigestLength(); i++) {
75 result.append(hexDigitsFor(digest[i]));
77 return result.toString();
82 public int getDigestLength() {
83 return digest.getDigestLength();
86 public Object clone() throws CloneNotSupportedException {
87 return digest.clone();