001/*
002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Thierry Delprat
018 */
019package org.nuxeo.segment.io.web;
020
021import java.security.MessageDigest;
022import java.security.NoSuchAlgorithmException;
023
024import org.apache.commons.logging.Log;
025import org.apache.commons.logging.LogFactory;
026import org.nuxeo.runtime.api.Framework;
027import org.nuxeo.segment.io.SegmentIO;
028
029public class MarketoHelper {
030
031    public static final String SECRET_KEY_NAME = "MARKETO_SECRET";
032
033    private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
034
035    protected static final Log log = LogFactory.getLog(MarketoHelper.class);
036
037    protected static String toHexString(byte[] data) {
038        StringBuilder buf = new StringBuilder(2 * data.length);
039        for (byte b : data) {
040            buf.append(HEX_DIGITS[(0xF0 & b) >> 4]);
041            buf.append(HEX_DIGITS[0x0F & b]);
042        }
043        return buf.toString();
044    }
045
046    protected static String getSecret() {
047        SegmentIO service = Framework.getLocalService(SegmentIO.class);
048        return service.getGlobalParameters().get(SECRET_KEY_NAME);
049    }
050
051    public static String getLeadHash(String leadEmail)  {
052
053        try {
054           String digestInput = getSecret() + leadEmail;
055           MessageDigest md = MessageDigest.getInstance("SHA-1");
056           byte[] digest = md.digest(digestInput.getBytes());
057           return toHexString(digest);
058        }
059        catch (NoSuchAlgorithmException t) {
060            log.error("Error while computing Marketo digest", t);
061            return null;
062        }
063    }
064}