/*
    BEEM is a videoconference application on the Android Platform.

    Copyright (C) 2009-2012 by Frederic-Charles Barthelery,
                               Nikita Kozlov,
                               Vincent Veronis.

    This file is part of BEEM.

    BEEM is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    BEEM is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with BEEM.  If not, see <http://www.gnu.org/licenses/>.

    Please send bug reports with examples or suggestions to
    contact@beem-project.com or http://www.beem-project.com/

*/
package com.beem.project.beem.service.auth;

import android.content.Context;

import com.beem.project.beem.utils.EncryptionManager;

import org.jivesoftware.smack.util.Base64;

/**
 * An Authenticator which look for credentials stored in preferences and decrypt them.
 */
public class EncryptedPasswordPreferenceAuthenticator extends PreferenceAuthenticator {
    private final String encryptionKeyAlias;
    private final String base64Iv;
    private final EncryptionManager encryptionManager;

    /**
     * Create a PreferenceAuthenticator.
     *
     * @param context the Android context.
     * @param encryptionKeyAlias the alias of the encryption key in the Android keystore
     * @param base64Iv the encryption IV encoded in base64
     */
    public EncryptedPasswordPreferenceAuthenticator(Context context, String encryptionKeyAlias, String base64Iv) {
        super(context);
        this.encryptionKeyAlias = encryptionKeyAlias;
        this.base64Iv = base64Iv;
        encryptionManager = new EncryptionManager();
    }

    @Override
    protected String getPassword() {
        String password = super.getPassword();
        byte[] encryptionIv = Base64.decode(base64Iv);
        return encryptionManager.decryptString(password, encryptionKeyAlias, encryptionIv);
    }
}
