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
26 /**
27 * A simple digester for strings. It will traverse through a list of digest algorithms and pick the
28 * strongest one available.
29 */
30 class SimpleDigest
31 {
32
33 private static final String[] HASH_ALGOS = new String[] { "SHA-1", "MD5" };
34
35 private MessageDigest digest;
36
37 private long hash;
38
39 SimpleDigest()
40 {
41 for ( String hashAlgo : HASH_ALGOS )
42 {
43 try
44 {
45 digest = MessageDigest.getInstance( hashAlgo );
46 hash = 0;
47 break;
48 }
49 catch ( NoSuchAlgorithmException ne )
50 {
51 digest = null;
52 hash = 13;
53 }
54 }
55 }
56
57 public void update( String data )
58 {
59 if ( data == null || data.length() <= 0 )
60 {
61 return;
62 }
63 if ( digest != null )
64 {
65 digest.update( data.getBytes( StandardCharsets.UTF_8 ) );
66 }
67 else
68 {
69 hash = hash * 31 + data.hashCode();
70 }
71 }
72
73 @SuppressWarnings( "checkstyle:magicnumber" )
74 public String digest()
75 {
76 if ( digest != null )
77 {
78 StringBuilder buffer = new StringBuilder( 64 );
79
80 byte[] bytes = digest.digest();
81 for ( byte aByte : bytes )
82 {
83 int b = aByte & 0xFF;
84
85 if ( b < 0x10 )
86 {
87 buffer.append( '0' );
88 }
89
90 buffer.append( Integer.toHexString( b ) );
91 }
92
93 return buffer.toString();
94 }
95 else
96 {
97 return Long.toHexString( hash );
98 }
99 }
100
101 }