it.scoppelletti.security.keypairgen.KeyPairGeneratorBean.java Source code

Java tutorial

Introduction

Here is the source code for it.scoppelletti.security.keypairgen.KeyPairGeneratorBean.java

Source

/*
 * Copyright (C) 2010 Dario Scoppelletti, <http://www.scoppelletti.it/>.
 * 
 * Licensed 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 it.scoppelletti.security.keypairgen;

import java.io.*;
import java.security.*;
import java.util.*;
import javax.annotation.*;
import org.springframework.beans.factory.annotation.*;
import it.scoppelletti.programmerpower.*;
import it.scoppelletti.programmerpower.io.*;
import it.scoppelletti.programmerpower.reflect.*;
import it.scoppelletti.programmerpower.security.*;
import it.scoppelletti.programmerpower.ui.*;

/**
 * Generazione di una coppia di chiavi di crittografia asimmetrica.
 * 
 * @since 1.0.0
 */
@Final
public class KeyPairGeneratorBean implements Runnable {
    private File myConfigFile;
    private String myPrefix;
    private File myPublicFile;
    private File myPrivateFile;
    private boolean myOverwrite;
    private boolean myEncoded;

    @Resource(name = UserInterfaceProvider.BEAN_NAME)
    private UserInterfaceProvider myUI;

    /**
     * Costruttore.
     */
    public KeyPairGeneratorBean() {
    }

    /**
     * Imposta il file di configurazione.
     * 
     * @param file File.
     */
    @Required
    public void setConfigFile(File file) {
        myConfigFile = file;
    }

    /**
     * Imposta il prefisso da applicare alle propriet&agrave; da interrogare.
     * 
     * @param prefix Valore.
     */
    public void setPrefix(String prefix) {
        myPrefix = prefix;
    }

    /**
     * Imposta il file di output della chiave pubblica.
     * 
     * @param                       file File.
     * @it.scoppelletti.tag.default      {@code stdout}
     */
    @Required
    public void setPublicFile(File file) {
        myPublicFile = file;
    }

    /**
     * Imposta il file di output della chiave privata.
     * 
     * @param                       file File.
     * @it.scoppelletti.tag.default      {@code stdout}
     */
    @Required
    public void setPrivateFile(File file) {
        myPrivateFile = file;
    }

    /**
     * Imposta l&rsquo;indicatore di sovrascrittura del file di output anche se
     * esiste gi&agrave;
     * 
     * @param                       value Valore.
     * @it.scoppelletti.tag.default       {@code false}
     */
    public void setOverwrite(boolean value) {
        myOverwrite = value;
    }

    /**
     * Imposta l&rsquo;indicatore di formato di output codificato.
     * 
     * @param                       value Valore.
     * @it.scoppelletti.tag.default       {@code false}
     */
    public void setEncoded(boolean value) {
        myEncoded = value;
    }

    /**
     * Esegue l&rsquo;operazione.
     */
    public void run() {
        Properties props;
        OutputStream publicOut = null;
        OutputStream privateOut = null;
        KeyPair keyPair;
        KeyPairGenerator keyGen;

        if (myConfigFile == null) {
            throw new PropertyNotSetException(toString(), "configFile");
        }
        if (myPublicFile == null) {
            throw new PropertyNotSetException(toString(), "publicFile");
        }
        if (myPrivateFile == null) {
            throw new PropertyNotSetException(toString(), "privateFile");
        }

        try {
            props = loadConfig();
            publicOut = openOutput(myPublicFile);
            if (publicOut == null) {
                return;
            }
            privateOut = openOutput(myPrivateFile);
            if (privateOut == null) {
                return;
            }

            keyGen = CryptoUtils.getKeyPairGenerator(props, myPrefix);
            keyPair = keyGen.generateKeyPair();

            props = CryptoUtils.toProperties(keyPair.getPublic(), myEncoded);
            props.store(publicOut, null);

            props = CryptoUtils.toProperties(keyPair.getPrivate(), myEncoded);
            props.store(privateOut, null);
        } catch (IOException ex) {
            throw new IOOperationException(ex);
        } finally {
            if (publicOut != null) {
                IOUtils.close(publicOut);
                publicOut = null;
            }
            if (privateOut != null) {
                IOUtils.close(privateOut);
                privateOut = null;
            }
        }
    }

    /**
     * Legge le propriet&agrave; di configurazione.
     * 
     * @return Collezione.
     */
    private Properties loadConfig() throws IOException {
        InputStream in = null;
        Properties props = new Properties();

        try {
            in = new FileInputStream(myConfigFile);
            props.load(in);
        } finally {
            if (in != null) {
                in.close();
                in = null;
            }
        }

        return props;
    }

    /**
     * Apre un flusso di output.
     * 
     * @param  Nome del file.
     * @return Flusso.
     */
    private OutputStream openOutput(File file) throws IOException {
        OutputStream out;
        IOResources ioRes = new IOResources();

        if (file.exists()) {
            if (myOverwrite) {
                myUI.display(MessageType.WARNING, ioRes.getFileOverwriteMessage(file.toString()));
            } else {
                throw new FileAlreadyExistException(file.toString());
            }
        }

        out = new PrintStream(file);

        return out;
    }
}