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.security.SecureRandom;
027import java.util.Base64;
028import java.util.Date;
029import java.util.HashMap;
030import java.util.Map;
031import java.util.Random;
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    protected static final Random RANDOM = new SecureRandom();
046
047    public static Map<String, String> getHeaders(String secretKey, String userName) {
048
049        Map<String, String> headers = new HashMap<String, String>();
050
051        Date timestamp = new Date();
052        int randomData = RANDOM.nextInt();
053
054        String clearToken = timestamp.getTime() + TOKEN_SEP + randomData + TOKEN_SEP + secretKey + TOKEN_SEP + userName;
055
056        byte[] hashedToken;
057
058        try {
059            hashedToken = MessageDigest.getInstance("MD5").digest(clearToken.getBytes());
060        } catch (NoSuchAlgorithmException e) {
061            return null;
062        }
063
064        String base64HashedToken = Base64.getEncoder().encodeToString(hashedToken);
065
066        headers.put(TS_HEADER, String.valueOf(timestamp.getTime()));
067        headers.put(RANDOM_HEADER, String.valueOf(randomData));
068        headers.put(TOKEN_HEADER, base64HashedToken);
069        headers.put(USER_HEADER, userName);
070
071        return headers;
072    }
073
074}