001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.eclipse.aether.util;
020
021import java.nio.charset.StandardCharsets;
022import java.security.MessageDigest;
023import java.security.NoSuchAlgorithmException;
024
025/**
026 * A simple digester utility for Strings. Uses {@link MessageDigest} for requested algorithm. Supports one-pass or
027 * several rounds of updates, and as result emits hex encoded String.
028 *
029 * @since 1.9.0
030 */
031public final class StringDigestUtil {
032    private final MessageDigest digest;
033
034    /**
035     * Constructs instance with given algorithm.
036     *
037     * @see #sha1()
038     * @see #sha1(String)
039     */
040    public StringDigestUtil(final String alg) {
041        try {
042            this.digest = MessageDigest.getInstance(alg);
043        } catch (NoSuchAlgorithmException e) {
044            throw new IllegalStateException("Not supported digest algorithm: " + alg);
045        }
046    }
047
048    /**
049     * Updates instance with passed in string.
050     */
051    public StringDigestUtil update(String data) {
052        if (data != null && !data.isEmpty()) {
053            digest.update(data.getBytes(StandardCharsets.UTF_8));
054        }
055        return this;
056    }
057
058    /**
059     * Returns the digest of all strings passed via {@link #update(String)} as hex string. There is no state preserved
060     * and due implementation of {@link MessageDigest#digest()}, same applies here: this instance "resets" itself.
061     * Hence, the digest hex encoded string is returned only once.
062     *
063     * @see MessageDigest#digest()
064     */
065    public String digest() {
066        return toHexString(digest.digest());
067    }
068
069    /**
070     * Helper method to create {@link StringDigestUtil} using SHA-1 digest algorithm.
071     */
072    public static StringDigestUtil sha1() {
073        return new StringDigestUtil("SHA-1");
074    }
075
076    /**
077     * Helper method to calculate SHA-1 digest and hex encode it.
078     */
079    public static String sha1(final String string) {
080        return sha1().update(string).digest();
081    }
082
083    /**
084     * Creates a hexadecimal representation of the specified bytes. Each byte is converted into a two-digit hex number
085     * and appended to the result with no separator between consecutive bytes.
086     *
087     * @param bytes The bytes to represent in hex notation, may be {@code null}.
088     * @return The hexadecimal representation of the input or {@code null} if the input was {@code null}.
089     * @since 2.0.0
090     */
091    @SuppressWarnings("checkstyle:magicnumber")
092    public static String toHexString(byte[] bytes) {
093        if (bytes == null) {
094            return null;
095        }
096
097        StringBuilder buffer = new StringBuilder(bytes.length * 2);
098
099        for (byte aByte : bytes) {
100            int b = aByte & 0xFF;
101            if (b < 0x10) {
102                buffer.append('0');
103            }
104            buffer.append(Integer.toHexString(b));
105        }
106
107        return buffer.toString();
108    }
109
110    /**
111     * Creates a byte array out of hexadecimal representation of the specified bytes. If input string is {@code null},
112     * {@code null} is returned. Input value must have even length (due hex encoding = 2 chars one byte).
113     *
114     * @param hexString The hexString to convert to byte array, may be {@code null}.
115     * @return The byte array of the input or {@code null} if the input was {@code null}.
116     * @since 2.0.0
117     */
118    @SuppressWarnings("checkstyle:magicnumber")
119    public static byte[] fromHexString(String hexString) {
120        if (hexString == null) {
121            return null;
122        }
123        if (hexString.isEmpty()) {
124            return new byte[] {};
125        }
126        int len = hexString.length();
127        if (len % 2 != 0) {
128            throw new IllegalArgumentException("hexString length not even");
129        }
130        byte[] data = new byte[len / 2];
131        for (int i = 0; i < len; i += 2) {
132            data[i / 2] = (byte)
133                    ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
134        }
135        return data;
136    }
137}