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.io.UnsupportedEncodingException;
23 import java.security.MessageDigest;
24 import java.security.NoSuchAlgorithmException;
25
26 /**
27 * A simple digester for strings.
28 */
29 class SimpleDigest
30 {
31
32 private MessageDigest digest;
33
34 private long hash;
35
36 public SimpleDigest()
37 {
38 try
39 {
40 digest = MessageDigest.getInstance( "SHA-1" );
41 }
42 catch ( NoSuchAlgorithmException e )
43 {
44 try
45 {
46 digest = MessageDigest.getInstance( "MD5" );
47 }
48 catch ( NoSuchAlgorithmException ne )
49 {
50 digest = null;
51 hash = 13;
52 }
53 }
54 }
55
56 public void update( String data )
57 {
58 if ( data == null || data.length() <= 0 )
59 {
60 return;
61 }
62 if ( digest != null )
63 {
64 try
65 {
66 digest.update( data.getBytes( "UTF-8" ) );
67 }
68 catch ( UnsupportedEncodingException e )
69 {
70 // broken JVM
71 }
72 }
73 else
74 {
75 hash = hash * 31 + data.hashCode();
76 }
77 }
78
79 public String digest()
80 {
81 if ( digest != null )
82 {
83 StringBuilder buffer = new StringBuilder( 64 );
84
85 byte[] bytes = digest.digest();
86 for ( byte aByte : bytes )
87 {
88 int b = aByte & 0xFF;
89
90 if ( b < 0x10 )
91 {
92 buffer.append( '0' );
93 }
94
95 buffer.append( Integer.toHexString( b ) );
96 }
97
98 return buffer.toString();
99 }
100 else
101 {
102 return Long.toHexString( hash );
103 }
104 }
105
106 }