package com.greenautomation.pkeytool;
import java.io.*;
import java.security.*;
import java.security.spec.*;
import java.security.cert.*;
import java.security.cert.Certificate;
import java.util.Map;
public class ImportKeyCommand implements Command {
public void run(Map args) throws Exception {
String keyfile = (String) args.get("-keyfile");
if (keyfile == null) {
throw new PKeyToolException("Must specify -keyfile");
}
String certfile = (String) args.get("-certfile");
if (certfile == null) {
throw new PKeyToolException("Must specify -certfile");
}
KeyStore keystore = Utils.openKeyStore(args, true, true);
String alias = (String) args.get("-alias");
if (alias == null) {
alias = "mykey";
}
String pass = (String) args.get("-keypass");
if (pass == null) {
System.err.println("Enter key password for <" + alias + ">");
pass = Utils.promptFor( " (RETURN if same as keystore password): ");
if (pass.length() == 0) {
pass = (String) args.get("-storepass"); }
}
char[] passChars = pass.toCharArray();
FileInputStream in = new FileInputStream(keyfile);
byte[] encodedKey = Utils.readArmored(in, "PRIVATE KEY");
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(encodedKey);
KeyFactory factory = KeyFactory.getInstance("DSA");
PrivateKey key;
try {
key = factory.generatePrivate(spec);
}
catch (InvalidKeySpecException ex) {
factory = KeyFactory.getInstance("RSA");
key = factory.generatePrivate(spec);
}
in = new FileInputStream(certfile);
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
Certificate cert = certFactory.generateCertificate(in);
keystore.setKeyEntry(alias, key, passChars, new Certificate[] {cert});
Utils.saveKeyStore(keystore, args);
}
public String getName() {
return "-importkey";
}
public String[] getParamsWithArgs() {
return new String[] {
"-keystore", "-storepass", "-alias", "-keypass", "-keyfile",
"-certfile", "-storetype"
};
}
public String[] getParamsWithoutArgs() {
return new String[] {};
}
public void printHelp(PrintStream s) {
s.println("-importkey -keyfile <keyfile> -certfile <certfile>");
s.println(" [-keystore <keystore>] [-storepass <storepass>]");
s.println(" [-alias <alias>] [-keypass <keypass>] [-storetype <storetype>]");
}
}