View Javadoc
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.
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              digest.update( data.getBytes( StandardCharsets.UTF_8 ) );
65          }
66          else
67          {
68              hash = hash * 31 + data.hashCode();
69          }
70      }
71  
72      public String digest()
73      {
74          if ( digest != null )
75          {
76              StringBuilder buffer = new StringBuilder( 64 );
77  
78              byte[] bytes = digest.digest();
79              for ( byte aByte : bytes )
80              {
81                  int b = aByte & 0xFF;
82  
83                  if ( b < 0x10 )
84                  {
85                      buffer.append( '0' );
86                  }
87  
88                  buffer.append( Integer.toHexString( b ) );
89              }
90  
91              return buffer.toString();
92          }
93          else
94          {
95              return Long.toHexString( hash );
96          }
97      }
98  
99  }