1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one 3 * or more contributor license agreements. See the NOTICE file 4 * distributed with this work for additional information 5 * regarding copyright ownership. The ASF licenses this file 6 * to you under the Apache License, Version 2.0 (the 7 * "License"); you may not use this file except in compliance 8 * with the License. You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, 13 * software distributed under the License is distributed on an 14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 * KIND, either express or implied. See the License for the 16 * specific language governing permissions and limitations 17 * under the License. 18 */ 19 package org.eclipse.aether.util; 20 21 import java.nio.charset.StandardCharsets; 22 import java.security.MessageDigest; 23 import java.security.NoSuchAlgorithmException; 24 25 /** 26 * A simple digester utility for Strings. Uses {@link MessageDigest} for requested algorithm. Supports one-pass or 27 * several rounds of updates, and as result emits hex encoded String. 28 * 29 * @since 1.9.0 30 */ 31 public final class StringDigestUtil { 32 private final MessageDigest digest; 33 34 /** 35 * Constructs instance with given algorithm. 36 * 37 * @see #sha1() 38 * @see #sha1(String) 39 */ 40 public StringDigestUtil(final String alg) { 41 try { 42 this.digest = MessageDigest.getInstance(alg); 43 } catch (NoSuchAlgorithmException e) { 44 throw new IllegalStateException("Not supported digest algorithm: " + alg); 45 } 46 } 47 48 /** 49 * Updates instance with passed in string. 50 */ 51 public StringDigestUtil update(String data) { 52 if (data != null && !data.isEmpty()) { 53 digest.update(data.getBytes(StandardCharsets.UTF_8)); 54 } 55 return this; 56 } 57 58 /** 59 * Returns the digest of all strings passed via {@link #update(String)} as hex string. There is no state preserved 60 * and due implementation of {@link MessageDigest#digest()}, same applies here: this instance "resets" itself. 61 * Hence, the digest hex encoded string is returned only once. 62 * 63 * @see MessageDigest#digest() 64 */ 65 public String digest() { 66 return ChecksumUtils.toHexString(digest.digest()); 67 } 68 69 /** 70 * Helper method to create {@link StringDigestUtil} using SHA-1 digest algorithm. 71 */ 72 public static StringDigestUtil sha1() { 73 return new StringDigestUtil("SHA-1"); 74 } 75 76 /** 77 * Helper method to calculate SHA-1 digest and hex encode it. 78 */ 79 public static String sha1(final String string) { 80 return sha1().update(string).digest(); 81 } 82 }