Example usage for java.security KeyPair getPublic

List of usage examples for java.security KeyPair getPublic

Introduction

In this page you can find the example usage for java.security KeyPair getPublic.

Prototype

public PublicKey getPublic() 

Source Link

Document

Returns a reference to the public key component of this key pair.

Usage

From source file:com.thoughtworks.go.server.util.HttpTestUtil.java

private X509Certificate generateCert(final KeyPair keyPair) {
    Date startDate = day(-1);/*from   w  w  w .  ja  v a2s . c o  m*/
    Date expiryDate = day(+1);
    BigInteger serialNumber = new BigInteger("1000200030004000");

    X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
    X500Principal dnName = new X500Principal("CN=Test CA Certificate");

    certGen.setSerialNumber(serialNumber);
    certGen.setIssuerDN(dnName);
    certGen.setNotBefore(startDate);
    certGen.setNotAfter(expiryDate);
    certGen.setSubjectDN(dnName); // note: same as issuer
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm("SHA1WITHRSA");

    try {
        return certGen.generate(keyPair.getPrivate());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.loklak.data.DAO.java

/**
 * initialize the DAO/* w  ww .  j av  a2s.  c  o m*/
 * @param configMap
 * @param dataPath the path to the data directory
 */
public static void init(Map<String, String> configMap, Path dataPath) throws Exception {

    log("initializing loklak DAO");

    config = configMap;
    conf_dir = new File("conf");
    bin_dir = new File("bin");
    html_dir = new File("html");

    // wake up susi
    File susiinitpath = new File(conf_dir, "susi");
    File sudiwatchpath = new File(new File("data"), "susi");
    susi = new SusiMind(susiinitpath, sudiwatchpath);
    String susi_boilerplate_name = "susi_cognition_boilerplate.json";
    File susi_boilerplate_file = new File(sudiwatchpath, susi_boilerplate_name);
    if (!susi_boilerplate_file.exists())
        Files.copy(new File(conf_dir, "susi/" + susi_boilerplate_name + ".example"), susi_boilerplate_file);

    // initialize public and private keys
    public_settings = new Settings(new File("data/settings/public.settings.json"));
    File private_file = new File("data/settings/private.settings.json");
    private_settings = new Settings(private_file);
    OS.protectPath(private_file.toPath());

    if (!private_settings.loadPrivateKey() || !public_settings.loadPublicKey()) {
        log("Can't load key pair. Creating new one");

        // create new key pair
        KeyPairGenerator keyGen;
        try {
            String algorithm = "RSA";
            keyGen = KeyPairGenerator.getInstance(algorithm);
            keyGen.initialize(2048);
            KeyPair keyPair = keyGen.genKeyPair();
            private_settings.setPrivateKey(keyPair.getPrivate(), algorithm);
            public_settings.setPublicKey(keyPair.getPublic(), algorithm);
        } catch (NoSuchAlgorithmException e) {
            throw e;
        }
        log("Key creation finished. Peer hash: " + public_settings.getPeerHashAlgorithm() + " "
                + public_settings.getPeerHash());
    } else {
        log("Key pair loaded from file. Peer hash: " + public_settings.getPeerHashAlgorithm() + " "
                + public_settings.getPeerHash());
    }

    File datadir = dataPath.toFile();
    // check if elasticsearch shall be accessed as external cluster
    String transport = configMap.get("elasticsearch_transport.enabled");
    if (transport != null && "true".equals(transport)) {
        String cluster_name = configMap.get("elasticsearch_transport.cluster.name");
        String transport_addresses_string = configMap.get("elasticsearch_transport.addresses");
        if (transport_addresses_string != null && transport_addresses_string.length() > 0) {
            String[] transport_addresses = transport_addresses_string.split(",");
            elasticsearch_client = new ElasticsearchClient(transport_addresses, cluster_name);
        }
    } else {
        // use all config attributes with a key starting with "elasticsearch." to set elasticsearch settings

        ESLoggerFactory.setDefaultFactory(new Slf4jESLoggerFactory());
        org.elasticsearch.common.settings.Settings.Builder settings = org.elasticsearch.common.settings.Settings
                .builder();
        for (Map.Entry<String, String> entry : config.entrySet()) {
            String key = entry.getKey();
            if (key.startsWith("elasticsearch."))
                settings.put(key.substring(14), entry.getValue());
        }
        // patch the home path
        settings.put("path.home", datadir.getAbsolutePath());
        settings.put("path.data", datadir.getAbsolutePath());
        settings.build();

        // start elasticsearch
        elasticsearch_client = new ElasticsearchClient(settings);
    }

    // open AAA storage
    Path settings_dir = dataPath.resolve("settings");
    settings_dir.toFile().mkdirs();
    Path authentication_path = settings_dir.resolve("authentication.json");
    authentication = new JsonTray(authentication_path.toFile(), 10000);
    OS.protectPath(authentication_path);
    Path authorization_path = settings_dir.resolve("authorization.json");
    authorization = new JsonTray(authorization_path.toFile(), 10000);
    OS.protectPath(authorization_path);
    Path passwordreset_path = settings_dir.resolve("passwordreset.json");
    passwordreset = new JsonTray(passwordreset_path.toFile(), 10000);
    OS.protectPath(passwordreset_path);
    Path accounting_path = settings_dir.resolve("accounting.json");
    accounting = new JsonTray(accounting_path.toFile(), 10000);
    OS.protectPath(accounting_path);
    Path login_keys_path = settings_dir.resolve("login-keys.json");
    login_keys = new JsonFile(login_keys_path.toFile());
    OS.protectPath(login_keys_path);

    Log.getLog().info("Initializing user roles");

    Path userRoles_path = settings_dir.resolve("userRoles.json");
    userRoles = new UserRoles(new JsonFile(userRoles_path.toFile()));
    OS.protectPath(userRoles_path);

    try {
        userRoles.loadUserRolesFromObject();
        Log.getLog().info("Loaded user roles from file");
    } catch (IllegalArgumentException e) {
        Log.getLog().info("Load default user roles");
        userRoles.loadDefaultUserRoles();
    }

    // open index
    Path index_dir = dataPath.resolve("index");
    if (index_dir.toFile().exists())
        OS.protectPath(index_dir); // no other permissions to this path

    // define the index factories
    messages = new MessageFactory(elasticsearch_client, IndexName.messages.name(), CACHE_MAXSIZE,
            EXIST_MAXSIZE);
    messages_hour = new MessageFactory(elasticsearch_client, IndexName.messages_hour.name(), CACHE_MAXSIZE,
            EXIST_MAXSIZE);
    messages_day = new MessageFactory(elasticsearch_client, IndexName.messages_day.name(), CACHE_MAXSIZE,
            EXIST_MAXSIZE);
    messages_week = new MessageFactory(elasticsearch_client, IndexName.messages_week.name(), CACHE_MAXSIZE,
            EXIST_MAXSIZE);
    users = new UserFactory(elasticsearch_client, IndexName.users.name(), CACHE_MAXSIZE, EXIST_MAXSIZE);
    accounts = new AccountFactory(elasticsearch_client, IndexName.accounts.name(), CACHE_MAXSIZE,
            EXIST_MAXSIZE);
    queries = new QueryFactory(elasticsearch_client, IndexName.queries.name(), CACHE_MAXSIZE, EXIST_MAXSIZE);
    importProfiles = new ImportProfileFactory(elasticsearch_client, IndexName.import_profiles.name(),
            CACHE_MAXSIZE, EXIST_MAXSIZE);

    // create indices and set mapping (that shows how 'elastic' elasticsearch is: it's always good to define data types)
    File mappingsDir = new File(new File(conf_dir, "elasticsearch"), "mappings");
    int shards = Integer.parseInt(configMap.get("elasticsearch.index.number_of_shards"));
    int replicas = Integer.parseInt(configMap.get("elasticsearch.index.number_of_replicas"));
    for (IndexName index : IndexName.values()) {
        log("initializing index '" + index.name() + "'...");
        try {
            elasticsearch_client.createIndexIfNotExists(index.name(), shards, replicas);
        } catch (Throwable e) {
            Log.getLog().warn(e);
        }
        try {
            elasticsearch_client.setMapping(index.name(), new File(mappingsDir, index.getSchemaFilename()));
        } catch (Throwable e) {
            Log.getLog().warn(e);
        }
    }
    // elasticsearch will probably take some time until it is started up. We do some other stuff meanwhile..

    // create and document the data dump dir
    assets = new File(datadir, "assets");
    external_data = new File(datadir, "external");
    dictionaries = new File(external_data, "dictionaries");
    dictionaries.mkdirs();

    // create message dump dir
    String message_dump_readme = "This directory contains dump files for messages which arrived the platform.\n"
            + "There are three subdirectories for dump files:\n"
            + "- own:      for messages received with this peer. There is one file for each month.\n"
            + "- import:   hand-over directory for message dumps to be imported. Drop dumps here and they are imported.\n"
            + "- imported: dump files which had been processed from the import directory are moved here.\n"
            + "You can import dump files from other peers by dropping them into the import directory.\n"
            + "Each dump file must start with the prefix '" + MESSAGE_DUMP_FILE_PREFIX
            + "' to be recognized.\n";
    message_dump_dir = dataPath.resolve("dump");
    message_dump = new JsonRepository(message_dump_dir.toFile(), MESSAGE_DUMP_FILE_PREFIX, message_dump_readme,
            JsonRepository.COMPRESSED_MODE, true, Runtime.getRuntime().availableProcessors());

    account_dump_dir = dataPath.resolve("accounts");
    account_dump_dir.toFile().mkdirs();
    OS.protectPath(account_dump_dir); // no other permissions to this path
    account_dump = new JsonRepository(account_dump_dir.toFile(), ACCOUNT_DUMP_FILE_PREFIX, null,
            JsonRepository.REWRITABLE_MODE, false, Runtime.getRuntime().availableProcessors());

    File user_dump_dir = new File(datadir, "accounts");
    user_dump_dir.mkdirs();
    user_dump = new JsonDataset(user_dump_dir, USER_DUMP_FILE_PREFIX,
            new JsonDataset.Column[] { new JsonDataset.Column("id_str", false),
                    new JsonDataset.Column("screen_name", true) },
            "retrieval_date", DateParser.PATTERN_ISO8601MILLIS, JsonRepository.REWRITABLE_MODE, false,
            Integer.MAX_VALUE);
    followers_dump = new JsonDataset(user_dump_dir, FOLLOWERS_DUMP_FILE_PREFIX,
            new JsonDataset.Column[] { new JsonDataset.Column("screen_name", true) }, "retrieval_date",
            DateParser.PATTERN_ISO8601MILLIS, JsonRepository.REWRITABLE_MODE, false, Integer.MAX_VALUE);
    following_dump = new JsonDataset(user_dump_dir, FOLLOWING_DUMP_FILE_PREFIX,
            new JsonDataset.Column[] { new JsonDataset.Column("screen_name", true) }, "retrieval_date",
            DateParser.PATTERN_ISO8601MILLIS, JsonRepository.REWRITABLE_MODE, false, Integer.MAX_VALUE);

    Path log_dump_dir = dataPath.resolve("log");
    log_dump_dir.toFile().mkdirs();
    OS.protectPath(log_dump_dir); // no other permissions to this path
    access = new AccessTracker(log_dump_dir.toFile(), ACCESS_DUMP_FILE_PREFIX, 60000, 3000);
    access.start(); // start monitor

    import_profile_dump_dir = dataPath.resolve("import-profiles");
    import_profile_dump = new JsonRepository(import_profile_dump_dir.toFile(), IMPORT_PROFILE_FILE_PREFIX, null,
            JsonRepository.COMPRESSED_MODE, false, Runtime.getRuntime().availableProcessors());

    // load schema folder
    conv_schema_dir = new File("conf/conversion");
    schema_dir = new File("conf/schema");

    // load dictionaries if they are embedded here
    // read the file allCountries.zip from http://download.geonames.org/export/dump/allCountries.zip
    //File allCountries = new File(dictionaries, "allCountries.zip");
    File cities1000 = new File(dictionaries, "cities1000.zip");
    if (!cities1000.exists()) {
        // download this file
        ClientConnection.download("http://download.geonames.org/export/dump/cities1000.zip", cities1000);
    }

    if (cities1000.exists()) {
        try {
            geoNames = new GeoNames(cities1000, new File(conf_dir, "iso3166.json"), 1);
        } catch (IOException e) {
            Log.getLog().warn(e.getMessage());
            cities1000.delete();
            geoNames = null;
        }
    }

    // finally wait for healthy status of elasticsearch shards
    ClusterHealthStatus required_status = ClusterHealthStatus
            .fromString(config.get("elasticsearch_requiredClusterHealthStatus"));
    boolean ok;
    do {
        log("Waiting for elasticsearch " + required_status.name() + " status");
        ok = elasticsearch_client.wait_ready(60000l, required_status);
    } while (!ok);
    /**
    do {
    log("Waiting for elasticsearch green status");
    health = elasticsearch_client.admin().cluster().prepareHealth().setWaitForGreenStatus().execute().actionGet();
    } while (health.isTimedOut());
    **/
    log("elasticsearch has started up!");

    // start the classifier
    new Thread() {
        public void run() {
            log("initializing the classifier...");
            try {
                Classifier.init(10000, 1000);
            } catch (Throwable e) {
                Log.getLog().warn(e);
            }
            log("classifier initialized!");
        }
    }.start();

    log("initializing queries...");
    File harvestingPath = new File(datadir, "queries");
    if (!harvestingPath.exists())
        harvestingPath.mkdirs();
    String[] list = harvestingPath.list();
    for (String queryfile : list) {
        if (queryfile.startsWith(".") || queryfile.endsWith("~"))
            continue;
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(new File(harvestingPath, queryfile))));
            String line;
            List<IndexEntry<QueryEntry>> bulkEntries = new ArrayList<>();
            while ((line = reader.readLine()) != null) {
                line = line.trim().toLowerCase();
                if (line.length() == 0)
                    continue;
                if (line.charAt(0) <= '9') {
                    // truncate statistic
                    int p = line.indexOf(' ');
                    if (p < 0)
                        continue;
                    line = line.substring(p + 1).trim();
                }
                // write line into query database
                if (!existQuery(line)) {
                    bulkEntries.add(new IndexEntry<QueryEntry>(line, SourceType.TWITTER,
                            new QueryEntry(line, 0, 60000, SourceType.TWITTER, false)));
                }
                if (bulkEntries.size() > 1000) {
                    queries.writeEntries(bulkEntries);
                    bulkEntries.clear();
                }
            }
            queries.writeEntries(bulkEntries);
            reader.close();
        } catch (IOException e) {
            Log.getLog().warn(e);
        }
    }
    log("queries initialized.");

    log("finished DAO initialization");
}

From source file:com.sshtools.j2ssh.transport.kex.GssGroup1Sha1.java

/**
 *
 *
 * @param clientId//w  ww .j a va 2  s . c  o  m
 * @param serverId
 * @param clientKexInit
 * @param serverKexInit
 *
 * @throws IOException
 * @throws AlgorithmOperationException
 * @throws KeyExchangeException
 */
public void performClientExchange(String clientId, String serverId, byte[] clientKexInit, byte[] serverKexInit,
        boolean firstPacketFollows, boolean useFirstPacket, boolean firstExch) throws IOException {
    try {
        log.info("Starting client side key exchange.");
        transport.getMessageStore().registerMessage(SshMsgKexGssInit.SSH_MSG_KEXGSS_INIT,
                SshMsgKexGssInit.class);

        transport.getMessageStore().registerMessage(SshMsgKexGssContinue.SSH_MSG_KEXGSS_CONTINUE,
                SshMsgKexGssContinue.class);
        transport.getMessageStore().registerMessage(SshMsgKexGssComplete.SSH_MSG_KEXGSS_COMPLETE,
                SshMsgKexGssComplete.class);

        transport.getMessageStore().registerMessage(SshMsgKexGssHostKey.SSH_MSG_KEXGSS_HOSTKEY,
                SshMsgKexGssHostKey.class);
        transport.getMessageStore().registerMessage(SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR,
                SshMsgKexGssError.class);
        this.clientId = clientId;
        this.serverId = serverId;
        this.clientKexInit = clientKexInit;
        this.serverKexInit = serverKexInit;

        //int minBits = g.bitLength();
        //int maxBits = q.bitLength();
        //Random rnd = ConfigurationLoader.getRND();
        // Generate a random bit count for the random x value

        /*int genBits = (int) ( ( (maxBits - minBits + 1) * rnd.nextFloat())
         + minBits);
              x = new BigInteger(genBits, rnd);
              // Calculate e
              e = g.modPow(x, p);*/
        try {
            DHParameterSpec dhSkipParamSpec = new DHParameterSpec(p, g);
            dhKeyPairGen.initialize(dhSkipParamSpec);

            KeyPair dhKeyPair = dhKeyPairGen.generateKeyPair();
            dhKeyAgreement.init(dhKeyPair.getPrivate());
            x = ((DHPrivateKey) dhKeyPair.getPrivate()).getX();
            e = ((DHPublicKey) dhKeyPair.getPublic()).getY();
        } catch (InvalidKeyException ex) {
            throw new AlgorithmOperationException("Failed to generate DH value");
        } catch (InvalidAlgorithmParameterException ex) {
            throw new AlgorithmOperationException("Failed to generate DH value");
        }
        //C calls GSS_Init_sec_context!
        log.info("Generating shared context with server...");
        GlobusGSSManagerImpl globusgssmanagerimpl = new GlobusGSSManagerImpl();

        HostAuthorization gssAuth = new HostAuthorization(null);
        GSSName targetName = gssAuth.getExpectedName(null, hostname);
        GSSCredential gsscredential = null;
        GSSContext gsscontext = null;
        if (theCredential == null) {
            gsscredential = UserGridCredential.getUserCredential(properties);
            theCredential = gsscredential;
        } else {
            gsscredential = theCredential;
            try {
                ((GlobusGSSCredentialImpl) gsscredential).getGlobusCredential().verify();
            } catch (NullPointerException e) {
                e.printStackTrace();
            } catch (GlobusCredentialException e) {
                e.printStackTrace();
                javax.swing.JOptionPane.showMessageDialog(properties.getWindow(),
                        "The credentials that you authenticated with have expired, please re-authenticate.",
                        "GSI-SSH Terminal", javax.swing.JOptionPane.WARNING_MESSAGE);
                gsscredential = UserGridCredential.getUserCredential(properties);
                theCredential = gsscredential;
            }
        }
        gsscontext = globusgssmanagerimpl.createContext(targetName, GSSConstants.MECH_OID, gsscredential,
                GSSCredential.DEFAULT_LIFETIME);

        gsscontext.requestCredDeleg(true);
        gsscontext.requestMutualAuth(true);
        gsscontext.requestInteg(true);
        //gsscontext.requestAnonymity(false);
        // gsscontext.requestReplayDet(false);
        //gsscontext.requestSequenceDet(false);
        // gsscontext.requestConf(false);
        Object type = GSIConstants.DELEGATION_TYPE_LIMITED;
        String cur = "None";
        if (properties instanceof SshToolsConnectionProfile) {
            cur = ((SshToolsConnectionProfile) properties)
                    .getApplicationProperty(SshTerminalPanel.PREF_DELEGATION_TYPE, "Full");
            if (cur.equals("full")) {
                type = GSIConstants.DELEGATION_TYPE_FULL;
            } else if (cur.equals("limited")) {
                type = GSIConstants.DELEGATION_TYPE_LIMITED;
            } else if (cur.equals("none")) {
                type = GSIConstants.DELEGATION_TYPE_LIMITED;
                gsscontext.requestCredDeleg(false);
            }
        }
        log.debug("Enabling delegation setting: " + cur);
        ((ExtendedGSSContext) gsscontext).setOption(GSSConstants.DELEGATION_TYPE, type);

        log.debug("Starting GSS token exchange.");
        byte abyte2[] = new byte[0];
        Object obj = null;
        boolean firsttime = true;
        hostKey = null;
        do {
            if (gsscontext.isEstablished())
                break;
            byte abyte3[] = gsscontext.initSecContext(abyte2, 0, abyte2.length);
            if (gsscontext.isEstablished() && !gsscontext.getMutualAuthState()) {
                // bad authenitcation 
                throw new KeyExchangeException(
                        "Context established without mutual authentication in gss-group1-sha1-* key exchange.");
            }
            if (gsscontext.isEstablished() && !gsscontext.getIntegState()) {
                // bad authenitcation 
                throw new KeyExchangeException(
                        "Context established without integrety protection in gss-group1-sha1-* key exchange.");
            }
            if (abyte3 != null) {
                if (firsttime) {
                    SshMsgKexGssInit msg = new SshMsgKexGssInit(e, /*bytearraywriter1.toByteArray()*/abyte3);
                    transport.sendMessage(msg, this);
                } else {
                    SshMsgKexGssContinue msg = new SshMsgKexGssContinue(
                            /*bytearraywriter1.toByteArray()*/abyte3);
                    transport.sendMessage(msg, this);
                }
            } else {
                throw new KeyExchangeException("Expecting a non-zero length token from GSS_Init_sec_context.");
            }
            if (!gsscontext.isEstablished()) {
                int[] messageId = new int[3];
                messageId[0] = SshMsgKexGssHostKey.SSH_MSG_KEXGSS_HOSTKEY;
                messageId[1] = SshMsgKexGssContinue.SSH_MSG_KEXGSS_CONTINUE;
                messageId[2] = SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR;
                SshMessage msg = transport.readMessage(messageId);
                if (msg.getMessageId() == SshMsgKexGssHostKey.SSH_MSG_KEXGSS_HOSTKEY) {
                    if (!firsttime) {
                        throw new KeyExchangeException(
                                "Not expecting a SSH_MSG_KEXGS_HOSTKEY message at this time.");
                    }
                    SshMsgKexGssHostKey reply = (SshMsgKexGssHostKey) msg;
                    hostKey = reply.getHostKey();
                    messageId = new int[2];
                    messageId[0] = SshMsgKexGssContinue.SSH_MSG_KEXGSS_CONTINUE;
                    messageId[1] = SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR;
                    msg = transport.readMessage(messageId);
                    if (msg.getMessageId() == SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR)
                        errormsg(msg);
                } else if (msg.getMessageId() == SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR) {
                    errormsg(msg);
                }
                SshMsgKexGssContinue reply = (SshMsgKexGssContinue) msg;
                abyte2 = reply.getToken();
            }
            firsttime = false;
        } while (true);
        log.debug("Sending gssapi exchange complete.");
        int[] messageId = new int[2];
        messageId[0] = SshMsgKexGssComplete.SSH_MSG_KEXGSS_COMPLETE;
        messageId[1] = SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR;
        SshMessage msg = transport.readMessage(messageId);
        if (msg.getMessageId() == SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR)
            errormsg(msg);
        SshMsgKexGssComplete reply = (SshMsgKexGssComplete) msg;
        if (reply.hasToken()) {
            ByteArrayReader bytearrayreader1 = new ByteArrayReader(reply.getToken());
            abyte2 = bytearrayreader1.readBinaryString();
            byte abyte3[] = gsscontext.initSecContext(abyte2, 0, abyte2.length);
            if (abyte3 != null) {
                throw new KeyExchangeException("Expecting zero length token.");
            }
            if (gsscontext.isEstablished() && !gsscontext.getMutualAuthState()) {
                // bad authenitcation 
                throw new KeyExchangeException(
                        "Context established without mutual authentication in gss-group1-sha1-* key exchange.");
            }
            if (gsscontext.isEstablished() && !gsscontext.getIntegState()) {
                // bad authenitcation 
                throw new KeyExchangeException(
                        "Context established without integrety protection in gss-group1-sha1-* key exchange.");
            }
        }

        byte per_msg_token[] = reply.getMIC();
        f = reply.getF();

        // Calculate diffe hellman k value
        secret = f.modPow(x, p);

        // Calculate the exchange hash
        calculateExchangeHash();

        gsscontext.verifyMIC(per_msg_token, 0, per_msg_token.length, exchangeHash, 0, exchangeHash.length,
                null);

        gssContext = gsscontext;
    } catch (GSSException g) {
        String desc = g.toString();
        if (desc.startsWith(
                "GSSException: Failure unspecified at GSS-API level (Mechanism level: GSS Major Status: Authentication Failed")
                && desc.indexOf("an unknown error occurred") >= 0) {
            throw new KeyExchangeException(
                    "Error from GSS layer: \n Probably due to your proxy credential being expired or signed by a CA unknown by the server or your clock being set wrong.",
                    g);
        } else {
            if (desc.indexOf("From Server") >= 0) {
                throw new KeyExchangeException("GSS Error from server", g);
            } else {
                throw new KeyExchangeException("Error from GSS layer", g);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java

/**
 * Creates a key pair./*w w  w  . ja  va2  s. c  om*/
 *
 * @return the key pair
 * @throws NoSuchAlgorithmException
 *             if the required algorithm for the key pair does not exist
 */
private final KeyPair getKeyPair() throws NoSuchAlgorithmException {
    final KeyPairGenerator keyPairGenerator; // Key pair generator
    final KeyPair keypair; // Key pair

    keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024, new SecureRandom());

    keypair = keyPairGenerator.generateKeyPair();

    LOGGER.debug("Created key pair with private key {} {} and public key {} {}",
            keypair.getPrivate().getAlgorithm(), Arrays.asList(keypair.getPrivate().getEncoded()),
            keypair.getPublic().getAlgorithm(), Arrays.asList(keypair.getPublic().getEncoded()));

    return keypair;
}

From source file:org.apache.nifi.registry.security.util.CertificateUtils.java

/**
 * Generates an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
 *
 * @param dn the distinguished name to use
 * @param publicKey the public key to issue the certificate to
 * @param extensions extensions extracted from the CSR
 * @param issuer the issuer's certificate
 * @param issuerKeyPair the issuer's keypair
 * @param signingAlgorithm the signing algorithm to use
 * @param days the number of days it should be valid for
 * @return an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
 * @throws CertificateException if there is an error issuing the certificate
 *//*w  w  w  . j  av a2s  .  c o  m*/
public static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, Extensions extensions,
        X509Certificate issuer, KeyPair issuerKeyPair, String signingAlgorithm, int days)
        throws CertificateException {
    try {
        ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm)
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerKeyPair.getPrivate());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
        Date startDate = new Date();
        Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(days));

        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
                reverseX500Name(new X500Name(issuer.getSubjectX500Principal().getName())),
                getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo);

        certBuilder.addExtension(Extension.subjectKeyIdentifier, false,
                new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey));

        certBuilder.addExtension(Extension.authorityKeyIdentifier, false,
                new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(issuerKeyPair.getPublic()));
        // Set certificate extensions
        // (1) digitalSignature extension
        certBuilder.addExtension(Extension.keyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment
                        | KeyUsage.keyAgreement | KeyUsage.nonRepudiation));

        certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));

        // (2) extendedKeyUsage extension
        certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(
                new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));

        // (3) subjectAlternativeName
        if (extensions != null && extensions.getExtension(Extension.subjectAlternativeName) != null) {
            certBuilder.addExtension(Extension.subjectAlternativeName, false,
                    extensions.getExtensionParsedValue(Extension.subjectAlternativeName));
        }

        X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                .getCertificate(certificateHolder);
    } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new CertificateException(e);
    }
}

From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java

/**
 * Create a keystore for this user to be used for document signing, store it associated with the user's
 * person node/*ww  w .  j ava  2 s.c om*/
 * 
 * @param person
 * @param password
 * 
 * @return a Java KeyStore object suitable for document signing
 * @throws NoSuchAlgorithmException 
 * @throws NoSuchProviderException 
 * @throws KeyStoreException 
 * @throws IOException 
 * @throws CertificateException 
 */
private KeyStore createUserKeyStore(NodeRef person, String password) throws NoSuchAlgorithmException,
        NoSuchProviderException, KeyStoreException, CertificateException, IOException {

    // get the alias from the configuration
    String alias = config.getProperty(RepositoryManagedSignatureProviderFactory.ALIAS);

    // initialize key generator
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
    keyGen.initialize(2048, random);

    // generate a keypair
    KeyPair pair = keyGen.generateKeyPair();
    PrivateKey priv = pair.getPrivate();
    PublicKey pub = pair.getPublic();

    // generate the user certificate
    Certificate cert = generateCertificate(pair, person);

    // get the ca cert used to sign and create cert chain
    KeyStore trustedKs = getTrustedKeyStore();
    Certificate[] caChain = getCaCertChain(trustedKs);
    Certificate[] certChain = new Certificate[caChain.length + 1];
    certChain[0] = cert;
    for (int i = 0; i < caChain.length; i++) {
        certChain[i + 1] = caChain[i];
    }

    // create keystore, adding private key and cert chain
    KeyStore ks = KeyStore.getInstance("pkcs12");
    ks.load(null, password.toCharArray());
    ks.setKeyEntry(alias, priv, password.toCharArray(), certChain);

    // save the keystore
    saveUserKeyStore(person, ks, password);

    // also save the public key separately, will need it 
    // for later validaiton activities
    saveUserPublicKey(person, pub);

    // return the generated keystore
    return ks;

}

From source file:org.opendaylight.aaa.cert.impl.ODLKeyTool.java

public boolean createKeyStoreWithSelfSignCert(final String keyStoreName, final String keyStorePwd,
        final String dName, final String keyAlias, final int validity) {
    try {/*from   w ww.ja v a  2 s  . c  o m*/
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator
                .getInstance(KeyStoreConstant.DEFAULT_KEY_ALG);
        keyPairGenerator.initialize(KeyStoreConstant.DEFAULT_KEY_SIZE);
        final KeyPair keyPair = keyPairGenerator.generateKeyPair();
        final X509V3CertificateGenerator x509V3CertGen = new X509V3CertificateGenerator();
        x509V3CertGen.setSerialNumber(getSecureRandomeInt());
        x509V3CertGen.setIssuerDN(new X509Principal(dName));
        x509V3CertGen.setNotBefore(new Date(System.currentTimeMillis()));
        x509V3CertGen
                .setNotAfter(new Date(System.currentTimeMillis() + (KeyStoreConstant.DAY_TIME * validity)));
        x509V3CertGen.setSubjectDN(new X509Principal(dName));
        x509V3CertGen.setPublicKey(keyPair.getPublic());
        x509V3CertGen.setSignatureAlgorithm(KeyStoreConstant.DEFAULT_SIGN_ALG);
        final X509Certificate x509Cert = x509V3CertGen.generateX509Certificate(keyPair.getPrivate());
        final KeyStore ctlKeyStore = KeyStore.getInstance("JKS");
        ctlKeyStore.load(null, keyStorePwd.toCharArray());
        ctlKeyStore.setKeyEntry(keyAlias, keyPair.getPrivate(), keyStorePwd.toCharArray(),
                new java.security.cert.Certificate[] { x509Cert });
        final FileOutputStream fOutputStream = new FileOutputStream(workingDir + keyStoreName);
        ctlKeyStore.store(fOutputStream, keyStorePwd.toCharArray());
        LOG.info("{} is created", keyStoreName);
        return true;
    } catch (NoSuchAlgorithmException | InvalidKeyException | SecurityException | SignatureException
            | KeyStoreException | CertificateException | IOException e) {
        LOG.error("Fatal error creating key", e);
        return false;
    }
}

From source file:dk.itst.oiosaml.sp.configuration.ConfigurationHandler.java

public void handlePost(RequestContext context) throws ServletException, IOException {
    HttpServletRequest request = context.getRequest();
    HttpServletResponse response = context.getResponse();

    if (!checkConfiguration(response))
        return;/*from w  ww.  j  av a  2 s .co m*/

    List<?> parameters = extractParameterList(request);

    String orgName = extractParameter("organisationName", parameters);
    String orgUrl = extractParameter("organisationUrl", parameters);
    String email = extractParameter("email", parameters);
    String entityId = extractParameter("entityId", parameters);
    final String password = extractParameter("keystorePassword", parameters);
    byte[] metadata = extractFile("metadata", parameters).get();
    FileItem ksData = extractFile("keystore", parameters);
    byte[] keystore = null;
    if (ksData != null) {
        keystore = ksData.get();
    }
    if (!checkNotNull(orgName, orgUrl, email, password, metadata, entityId) || metadata.length == 0
            || (keystore == null && !Boolean.valueOf(extractParameter("createkeystore", parameters)))) {
        Map<String, Object> params = getStandardParameters(request);
        params.put("error", "All fields must be filled.");
        params.put("organisationName", orgName);
        params.put("organisationUrl", orgUrl);
        params.put("email", email);
        params.put("keystorePassword", password);
        params.put("entityId", entityId);
        log.info("Parameters not correct: " + params);
        log.info("Metadata: " + new String(metadata));

        String res = renderTemplate("configure.vm", params, true);
        sendResponse(response, res);
        return;
    }

    Credential credential = context.getCredential();
    if (keystore != null && keystore.length > 0) {
        credential = CredentialRepository.createCredential(new ByteArrayInputStream(keystore), password);
    } else if (Boolean.valueOf(extractParameter("createkeystore", parameters))) {
        try {
            BasicX509Credential cred = new BasicX509Credential();
            KeyPair kp = dk.itst.oiosaml.security.SecurityHelper
                    .generateKeyPairFromURI("http://www.w3.org/2001/04/xmlenc#rsa-1_5", 1024);
            cred.setPrivateKey(kp.getPrivate());
            cred.setPublicKey(kp.getPublic());
            credential = cred;

            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(null, null);
            X509Certificate cert = dk.itst.oiosaml.security.SecurityHelper.generateCertificate(credential,
                    getEntityId(request));
            cred.setEntityCertificate(cert);

            ks.setKeyEntry("oiosaml", credential.getPrivateKey(), password.toCharArray(),
                    new Certificate[] { cert });
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ks.store(bos, password.toCharArray());

            keystore = bos.toByteArray();
            bos.close();
        } catch (Exception e) {
            log.error("Unable to generate credential", e);
            throw new RuntimeException("Unable to generate credential", e);
        }
    }

    EntityDescriptor descriptor = generateSPDescriptor(getBaseUrl(request), entityId, credential, orgName,
            orgUrl, email, Boolean.valueOf(extractParameter("enableArtifact", parameters)),
            Boolean.valueOf(extractParameter("enablePost", parameters)),
            Boolean.valueOf(extractParameter("enableSoap", parameters)),
            Boolean.valueOf(extractParameter("enablePostSLO", parameters)),
            Boolean.valueOf(extractParameter("supportOCESAttributeProfile", parameters)));
    File zipFile = generateZipFile(request.getContextPath(), password, metadata, keystore, descriptor);

    byte[] configurationContents = saveConfigurationInSession(request, zipFile);
    boolean written = writeConfiguration(getHome(servletContext), configurationContents);

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("home", getHome(servletContext));
    params.put("written", written);
    sendResponse(response, renderTemplate("done.vm", params, true));
}

From source file:org.ejbca.ui.web.pub.CertRequestHttpTest.java

/** type 1 = ie (pkcs10)
 *  type 2 = csr (pkcs10req)/*from  w  w  w.  j a v  a 2s . c  o m*/
 */
private String sendCsrRequest(int type) throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidAlgorithmParameterException, IOException, InvalidKeyException, SignatureException,
        OperatorCreationException, MalformedURLException, ProtocolException, UnsupportedEncodingException {
    // Create a PKCS10 request
    KeyPair rsakeys = KeyTools.genKeys("512", "RSA");
    PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest("SHA1WithRSA",
            CertTools.stringToBcX500Name("C=SE, O=AnaTom, CN=foo"), rsakeys.getPublic(), new DERSet(),
            rsakeys.getPrivate(), null);
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(req.toASN1Structure());
    dOut.close();
    final StringBuilder request = new StringBuilder();
    if (type == 2) {
        request.append("-----BEGIN CERTIFICATE REQUEST-----\n");
    }
    request.append(new String(Base64.encode(bOut.toByteArray())));
    if (type == 2) {
        request.append("\n-----END CERTIFICATE REQUEST-----\n");
    }
    String p10 = request.toString();
    // System.out.println(p10);

    // POST the OCSP request
    URL url = new URL(httpReqPath + '/' + resourceReq);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    // we are going to do a POST
    con.setDoOutput(true);
    con.setRequestMethod("POST");

    // POST it
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    OutputStream os = con.getOutputStream();
    final StringBuilder buf = new StringBuilder("user=" + TEST_USERNAME + "&password=foo123&");
    switch (type) {
    case 1:
        buf.append("pkcs10=");
        break;
    case 2:
        buf.append("resulttype=1&pkcs10req=");
        break;
    default:
        break;
    }
    buf.append(URLEncoder.encode(p10, "UTF-8"));
    os.write(buf.toString().getBytes("UTF-8"));
    os.close();
    assertEquals("Response code", 200, con.getResponseCode());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // This works for small requests, and PKCS7 responses are small
    InputStream in = con.getInputStream();
    int b = in.read();
    while (b != -1) {
        baos.write(b);
        b = in.read();
    }
    baos.flush();
    in.close();
    byte[] respBytes = baos.toByteArray();
    assertTrue(respBytes.length > 0);

    String resp = new String(respBytes);
    return resp;
}

From source file:org.opendaylight.aaa.cert.impl.ODLMdsalKeyTool.java

public KeyStore createKeyStoreWithSelfSignCert(final String keyStoreName, final String keyStorePwd,
        final String dName, final String keyAlias, final int validity, final String keyAlg, final int keySize,
        final String signAlg) {
    try {//  ww w  . j  a v  a 2  s  . c o  m
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(keyAlg);
        keyPairGenerator.initialize(keySize);
        final KeyPair keyPair = keyPairGenerator.generateKeyPair();
        final X509V3CertificateGenerator x509V3CertGen = new X509V3CertificateGenerator();
        x509V3CertGen.setSerialNumber(getSecureRandomeInt());
        x509V3CertGen.setIssuerDN(new X509Principal(dName));
        x509V3CertGen.setNotBefore(new Date(System.currentTimeMillis()));
        x509V3CertGen
                .setNotAfter(new Date(System.currentTimeMillis() + (KeyStoreConstant.DAY_TIME * validity)));
        x509V3CertGen.setSubjectDN(new X509Principal(dName));
        x509V3CertGen.setPublicKey(keyPair.getPublic());
        x509V3CertGen.setSignatureAlgorithm(signAlg);
        final X509Certificate x509Cert = x509V3CertGen.generateX509Certificate(keyPair.getPrivate());
        final KeyStore ctlKeyStore = KeyStore.getInstance("JKS");
        ctlKeyStore.load(null, keyStorePwd.toCharArray());
        ctlKeyStore.setKeyEntry(keyAlias, keyPair.getPrivate(), keyStorePwd.toCharArray(),
                new java.security.cert.Certificate[] { x509Cert });
        LOG.info("{} is created", keyStoreName);
        return ctlKeyStore;
    } catch (final NoSuchAlgorithmException | InvalidKeyException | SecurityException | SignatureException
            | KeyStoreException | CertificateException | IOException e) {
        LOG.error("Fatal error creating keystore", e);
        return null;
    }
}