001/*
002 * (C) Copyright 2006-2007 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Nuxeo - initial API and implementation
016 *
017 * $Id: JOOoConvertPluginImpl.java 18651 2007-05-13 20:28:53Z sfermigier $
018 */
019
020package org.nuxeo.ecm.http.client.authentication;
021
022import java.security.MessageDigest;
023import java.security.NoSuchAlgorithmException;
024import java.util.Date;
025import java.util.HashMap;
026import java.util.Map;
027import java.util.Random;
028
029import com.noelios.restlet.util.Base64;
030
031public class PortalSSOAuthenticationProvider {
032
033    private static final String TOKEN_SEP = ":";
034
035    private static final String TS_HEADER = "NX_TS";
036
037    private static final String RANDOM_HEADER = "NX_RD";
038
039    private static final String TOKEN_HEADER = "NX_TOKEN";
040
041    private static final String USER_HEADER = "NX_USER";
042
043    public static Map<String, String> getHeaders(String secretKey, String userName) {
044
045        Map<String, String> headers = new HashMap<String, String>();
046
047        Date timestamp = new Date();
048        int randomData = new Random(timestamp.getTime()).nextInt();
049
050        String clearToken = timestamp.getTime() + TOKEN_SEP + randomData + TOKEN_SEP + secretKey + TOKEN_SEP + userName;
051
052        byte[] hashedToken;
053
054        try {
055            hashedToken = MessageDigest.getInstance("MD5").digest(clearToken.getBytes());
056        } catch (NoSuchAlgorithmException e) {
057            return null;
058        }
059
060        String base64HashedToken = Base64.encodeBytes(hashedToken);
061
062        headers.put(TS_HEADER, String.valueOf(timestamp.getTime()));
063        headers.put(RANDOM_HEADER, String.valueOf(randomData));
064        headers.put(TOKEN_HEADER, base64HashedToken);
065        headers.put(USER_HEADER, userName);
066
067        return headers;
068    }
069
070}