1 package org.eclipse.aether.internal.impl;
2
3 /*
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
19 * under the License.
20 */
21
22 import java.nio.charset.StandardCharsets;
23 import java.security.MessageDigest;
24 import java.security.NoSuchAlgorithmException;
25 import java.util.Arrays;
26
27 /**
28 * A simple digester for strings. It will traverse through a list of digest algorithms and pick the
29 * strongest one available.
30 */
31 class SimpleDigest
32 {
33
34 private static final String[] HASH_ALGOS = new String[] { "SHA-1", "MD5" };
35
36 private final MessageDigest digest;
37
38 SimpleDigest()
39 {
40 MessageDigest md = null;
41 for ( String hashAlgo : HASH_ALGOS )
42 {
43 try
44 {
45 md = MessageDigest.getInstance( hashAlgo );
46 break;
47 }
48 catch ( NoSuchAlgorithmException ne )
49 {
50 }
51 }
52 if ( md == null )
53 {
54 throw new IllegalStateException( "Not supported digests: " + Arrays.toString( HASH_ALGOS ) );
55 }
56 this.digest = md;
57 }
58
59 public void update( String data )
60 {
61 if ( data == null || data.isEmpty() )
62 {
63 return;
64 }
65 digest.update( data.getBytes( StandardCharsets.UTF_8 ) );
66 }
67
68 @SuppressWarnings( "checkstyle:magicnumber" )
69 public String digest()
70 {
71 StringBuilder buffer = new StringBuilder( 64 );
72
73 byte[] bytes = digest.digest();
74 for ( byte aByte : bytes )
75 {
76 int b = aByte & 0xFF;
77
78 if ( b < 0x10 )
79 {
80 buffer.append( '0' );
81 }
82
83 buffer.append( Integer.toHexString( b ) );
84 }
85
86 return buffer.toString();
87 }
88 }