package de.jeha.s3srv.common.security;

import com.google.common.base.Strings;
import org.apache.commons.lang3.StringUtils;

import java.security.SignatureException;
import java.util.Locale;

/**
 * @author jenshadlich@googlemail.com
 */
public class AuthorizationUtils {

    public static boolean checkAuthorization(String givenAuthorization, Credentials credentials,
                                             String httpVerb, String contentMD5, String contentType,
                                             String date, String resource) {
        final String stringToSign =
                String.format(Locale.US,
                        "%s\n%s\n%s\n%s\n%s",
                        httpVerb,
                        Strings.nullToEmpty(contentMD5),
                        Strings.nullToEmpty(contentType),
                        date,
                        resource);

        String hmac;
        try {
            hmac = SignatureUtils.calculateHmacSha1(stringToSign, credentials.getSecretKey());
        } catch (SignatureException e) {
            return false;
        }

        return givenAuthorization.equals("AWS " + credentials.getAccessKey() + ":" + hmac);
    }

    public static String extractAccessKey(String authorization) {
        final String accessKeySigPair = StringUtils.substringAfter(authorization, "AWS ");
        if (accessKeySigPair != null) {
            String parts[] = StringUtils.split(accessKeySigPair, ':');
            if (parts != null && parts.length == 2) {
                return parts[0];
            }
        }
        return null;
    }

}

@@ -116,16 +116,73 @@
 ngUtils;
+%0Aimport org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;
 %0A%0Aimport
@@ -323,16 +323,106 @@
 tils %7B%0A%0A
+    private static final Logger LOG = LoggerFactory.getLogger(AuthorizationUtils.class);%0A%0A
     publ
@@ -1024,16 +1024,74 @@
 source);
+%0A        LOG.debug(%22String to sign = '%7B%7D'%22, stringToSign);
 %0A%0A      
@@ -1226,40 +1226,158 @@
     
-%7D catch (SignatureException e) %7B
+    LOG.debug(%22Calculated HMAC-SHA1 = '%7B%7D'%22, hmac);%0A        %7D catch (SignatureException e) %7B%0A            LOG.warn(%22Could not calculate HMAC-SHA1%22, e);
 %0A   

add more logging