View Javadoc
1   /*
2    * Licensed under the Apache License, Version 2.0 (the "License");
3    * you may not use this file except in compliance with the License.
4    * You may obtain a copy of the License at
5    *
6    *     http://www.apache.org/licenses/LICENSE-2.0
7    *
8    * Unless required by applicable law or agreed to in writing, software
9    * distributed under the License is distributed on an "AS IS" BASIS,
10   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11   * See the License for the specific language governing permissions and
12   * limitations under the License.
13   */
14  package org.gbif.ws.security;
15  
16  import org.gbif.ws.CommonRuntimeException;
17  
18  import java.io.IOException;
19  import java.util.Base64;
20  
21  import org.apache.commons.codec.digest.DigestUtils;
22  import org.slf4j.Logger;
23  import org.slf4j.LoggerFactory;
24  import org.springframework.stereotype.Service;
25  
26  import com.fasterxml.jackson.databind.ObjectMapper;
27  
28  @Service
29  public class Md5EncodeServiceImpl implements Md5EncodeService {
30  
31    private static final Logger LOG = LoggerFactory.getLogger(Md5EncodeServiceImpl.class);
32  
33    private ObjectMapper mapper;
34  
35    // See JacksonJsonObjectMapperProvider#getObjectMapper
36    public Md5EncodeServiceImpl(ObjectMapper mapper) {
37      this.mapper = mapper;
38    }
39  
40    /**
41     * Generates the Base64 encoded 128 bit MD5 digest of the entire content string suitable for the
42     * Content-MD5 header value.
43     * See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.15
44     */
45    @Override
46    public String encode(Object entity) {
47      try {
48        byte[] content = mapper.writeValueAsBytes(entity);
49  
50        // TODO: 2019-07-31 char encoding should be ASCII
51        return Base64.getEncoder().encodeToString(DigestUtils.md5(content));
52      } catch (IOException e) {
53        LOG.error("Failed to serialize http entity [{}]", entity);
54        throw new CommonRuntimeException(e);
55      }
56    }
57  }