/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.sshd.common.util.security.xbib;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.sshd.common.NamedResource;
import org.apache.sshd.common.config.keys.FilePasswordProvider;
import org.apache.sshd.common.config.keys.loader.KeyPairResourceParser;
import org.apache.sshd.common.session.SessionContext;
import org.xbib.net.security.PrivateKeyReader;

/**
 * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
 */
public class XbibKeyPairResourceParser implements KeyPairResourceParser {

    public static final XbibKeyPairResourceParser INSTANCE = new XbibKeyPairResourceParser();

    public XbibKeyPairResourceParser() {
    }

    @Override
    public boolean canExtractKeyPairs(NamedResource resourceKey, List<String> lines) {
        return true;
    }

    @Override
    public Collection<KeyPair> loadKeyPairs(SessionContext session,
                                            NamedResource resourceKey,
                                            FilePasswordProvider passwordProvider,
                                            List<String> lines) throws IOException, GeneralSecurityException {
        PrivateKeyReader privateKeyReader = new PrivateKeyReader();
        InputStream inputStream = new ByteArrayInputStream(String.join("\n", lines).getBytes(StandardCharsets.US_ASCII));
        String password = passwordProvider.getPassword(session, resourceKey, 0);
        return Collections.singleton(privateKeyReader.generateFrom(inputStream, password));
    }
}
