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 java.nio.charset.StandardCharsets; 017import java.security.InvalidKeyException; 018import java.security.NoSuchAlgorithmException; 019import java.util.Base64; 020 021import javax.crypto.Mac; 022import javax.crypto.spec.SecretKeySpec; 023 024public abstract class BaseSigningService implements SigningService { 025 026 private static final String ALGORITHM = "HmacSHA1"; 027 028 /** 029 * Generates a Base64 encoded HMAC-SHA1 signature of the passed request data with the secret key. 030 * See Message Authentication Code specs http://tools.ietf.org/html/rfc2104 031 * 032 * @param requestDataToSign the request data to be signed 033 * @param secretKey the secret key 034 */ 035 @Override 036 public String buildSignature(RequestDataToSign requestDataToSign, String secretKey) { 037 try { 038 Mac mac = Mac.getInstance(ALGORITHM); 039 SecretKeySpec secret = 040 new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), ALGORITHM); 041 mac.init(secret); 042 byte[] digest = 043 mac.doFinal(requestDataToSign.stringToSign().getBytes(StandardCharsets.UTF_8)); 044 045 return new String(Base64.getEncoder().encode(digest), StandardCharsets.US_ASCII); 046 } catch (NoSuchAlgorithmException e) { 047 throw new RuntimeException("Cant find " + ALGORITHM + " message digester", e); 048 } catch (InvalidKeyException e) { 049 throw new RuntimeException("Invalid secret key " + secretKey, e); 050 } 051 } 052}