001package com.gigya.android.sdk.utils;
002
003import android.util.Base64;
004
005import com.gigya.android.sdk.GigyaLogger;
006
007import java.io.UnsupportedEncodingException;
008import java.security.InvalidKeyException;
009import java.security.NoSuchAlgorithmException;
010import java.util.TreeMap;
011
012import javax.crypto.Mac;
013import javax.crypto.spec.SecretKeySpec;
014
015public class SigUtils {
016
017    private static final String ENCODING_ALGORITHM = "HmacSHA1";
018
019    @SuppressWarnings("StringBufferReplaceableByString")
020    public static String getSignature(String secret, String httpMethod, String url, TreeMap<String, Object> params) {
021        if (params == null || url == null || httpMethod == null || secret == null) {
022            return null;
023        }
024        try {
025            StringBuilder normalizedUrl = new StringBuilder();
026            java.net.URL u = new java.net.URL(url);
027
028            normalizedUrl.append(u.getProtocol().toLowerCase());
029            normalizedUrl.append("://");
030            normalizedUrl.append(u.getHost().toLowerCase());
031            if ((u.getProtocol().toUpperCase().equals("HTTP") && u.getPort() != 80 && u.getPort() != -1)
032                    || (u.getProtocol().toUpperCase().equals("HTTPS") && u.getPort() != 443 && u.getPort() != -1)) {
033                normalizedUrl.append(':');
034                normalizedUrl.append(u.getPort());
035            }
036            normalizedUrl.append(u.getPath());
037
038            String baseSignature = new StringBuilder()
039                    .append(httpMethod.toUpperCase())
040                    .append("&")
041                    .append(UrlUtils.urlEncode(normalizedUrl.toString()))
042                    .append("&")
043                    .append(UrlUtils.urlEncode(UrlUtils.buildEncodedQuery(params)))
044                    .toString();
045
046            return encodeSignature(baseSignature, secret);
047        } catch (Exception ex) {
048            ex.printStackTrace();
049            GigyaLogger.error("SigUtils", "getSignature: Exception while generating signature");
050        }
051        return null;
052    }
053
054    private static String encodeSignature(String baseSignature, String secret) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
055        byte[] keyBytes = Base64.decode(secret, Base64.DEFAULT);
056        byte[] textData = baseSignature.getBytes("UTF-8");
057        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, ENCODING_ALGORITHM);
058        Mac mac = Mac.getInstance(ENCODING_ALGORITHM);
059        mac.init(signingKey);
060        byte[] rawHmac = mac.doFinal(textData);
061        return Base64.encodeToString(rawHmac, Base64.NO_WRAP | Base64.URL_SAFE);
062    }
063}