package be.iminds.ilabt.jfed.lowlevel.ssh_key_info.putty;

import be.iminds.ilabt.jfed.lowlevel.GeniUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;

/**
 * User: twalcari
 * Date: 10/10/2016
 * Time: 10:46
 */
public class PpkHelper {
    private static final Logger LOG = LoggerFactory.getLogger(PpkHelper.class);
    /**
     * makePpkIfNeeded and getUserEncryptedPPK are used to create PPK files with
     * the same private key and password as in the PEM private key + certificate file.
     */
    private static final Map<String, String> userUrnToEncryptedPPK = new HashMap<>();

    /**
     * forgets password on return
     */
    public static void makePpkIfNeeded(GeniUser user, String pass) {
        if (pass == null) {
            LOG.debug("No pass, so not storing encrypted PPK for user " + user.getUserUrnString());
            return;
        }
        try {
            if (!userUrnToEncryptedPPK.containsKey(user.getUserUrnString())) {
                String comment = "PPK-generated-from-PEM-by-jFed";
                RSAPublicKey publicKey = (RSAPublicKey) user.getPublicKey();
                RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) user.getPrivateKey();
                String ppkContent = PuTTYPrivateKeyFile.createContent(comment, publicKey, privateKey, pass);
                assert ppkContent.contains("aes256-cbc");
                userUrnToEncryptedPPK.put(user.getUserUrnString(), ppkContent);
                LOG.debug("Now storing encrypted PPK for user " + user.getUserUrnString());
            }
        } catch (Exception e) {
            LOG.error("Error in makePpkIfNeeded. Can safely be ignored. message: " + e.getMessage(), e);
        }
    }

    public static String getUserEncryptedPPK(GeniUser user) {
        return userUrnToEncryptedPPK.get(user.getUserUrnString());
    }
}
