001/*
002 * (C) Copyright 2006-2007 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 *     Nuxeo - initial API and implementation
018 *
019 * $Id: JOOoConvertPluginImpl.java 18651 2007-05-13 20:28:53Z sfermigier $
020 */
021
022package org.nuxeo.ecm.http.client.authentication;
023
024import java.security.MessageDigest;
025import java.security.NoSuchAlgorithmException;
026import java.util.Date;
027import java.util.HashMap;
028import java.util.Map;
029import java.util.Random;
030
031import com.noelios.restlet.util.Base64;
032
033public class PortalSSOAuthenticationProvider {
034
035    private static final String TOKEN_SEP = ":";
036
037    private static final String TS_HEADER = "NX_TS";
038
039    private static final String RANDOM_HEADER = "NX_RD";
040
041    private static final String TOKEN_HEADER = "NX_TOKEN";
042
043    private static final String USER_HEADER = "NX_USER";
044
045    public static Map<String, String> getHeaders(String secretKey, String userName) {
046
047        Map<String, String> headers = new HashMap<String, String>();
048
049        Date timestamp = new Date();
050        int randomData = new Random(timestamp.getTime()).nextInt();
051
052        String clearToken = timestamp.getTime() + TOKEN_SEP + randomData + TOKEN_SEP + secretKey + TOKEN_SEP + userName;
053
054        byte[] hashedToken;
055
056        try {
057            hashedToken = MessageDigest.getInstance("MD5").digest(clearToken.getBytes());
058        } catch (NoSuchAlgorithmException e) {
059            return null;
060        }
061
062        String base64HashedToken = Base64.encodeBytes(hashedToken);
063
064        headers.put(TS_HEADER, String.valueOf(timestamp.getTime()));
065        headers.put(RANDOM_HEADER, String.valueOf(randomData));
066        headers.put(TOKEN_HEADER, base64HashedToken);
067        headers.put(USER_HEADER, userName);
068
069        return headers;
070    }
071
072}