001/*
002 * Licensed under the Apache License, Version 2.0 (the "License");
003 * you may not use this file except in compliance with the License.
004 * You may obtain a copy of the License at
005 *
006 *     http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS,
010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
011 * See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014package org.gbif.ws.security;
015
016import org.gbif.ws.CommonRuntimeException;
017
018import java.io.IOException;
019import java.util.Base64;
020
021import org.apache.commons.codec.digest.DigestUtils;
022import org.slf4j.Logger;
023import org.slf4j.LoggerFactory;
024import org.springframework.stereotype.Service;
025
026import com.fasterxml.jackson.databind.ObjectMapper;
027
028@Service
029public class Md5EncodeServiceImpl implements Md5EncodeService {
030
031  private static final Logger LOG = LoggerFactory.getLogger(Md5EncodeServiceImpl.class);
032
033  private ObjectMapper mapper;
034
035  // See JacksonJsonObjectMapperProvider#getObjectMapper
036  public Md5EncodeServiceImpl(ObjectMapper mapper) {
037    this.mapper = mapper;
038  }
039
040  /**
041   * Generates the Base64 encoded 128 bit MD5 digest of the entire content string suitable for the
042   * Content-MD5 header value.
043   * See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.15
044   */
045  @Override
046  public String encode(Object entity) {
047    try {
048      byte[] content = mapper.writeValueAsBytes(entity);
049
050      // TODO: 2019-07-31 char encoding should be ASCII
051      return Base64.getEncoder().encodeToString(DigestUtils.md5(content));
052    } catch (IOException e) {
053      LOG.error("Failed to serialize http entity [{}]", entity);
054      throw new CommonRuntimeException(e);
055    }
056  }
057}