Example usage for java.security KeyPair getPrivate

List of usage examples for java.security KeyPair getPrivate

Introduction

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

Prototype

public PrivateKey getPrivate() 

Source Link

Document

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

Usage

From source file:org.guanxi.sp.engine.form.RegisterGuardFormController.java

/**
 * Creates an authenticated certificate chain for the specified X509 name
 *
 * @param x509DN X509 name to for which to create a certificate chain
 * @param keyType The type of the key, e.g. "RSA", "DSA"
 * @return Returns a CABean instance encapsulating certificate chain and key information
 * or null if an error occurred//w  ww  .j av a  2s .c o  m
 */
private CABean createSignedCertificateChain(String x509DN, String keyType) {
    try {
        // Create a public/private keypair...
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(keyType);
        keyGen.initialize(1024, new SecureRandom());
        KeyPair keypair = keyGen.generateKeyPair();
        PrivateKey clientPrivateKey = keypair.getPrivate();
        PublicKey clientPublicKey = keypair.getPublic();

        // ...and a CSR from them...
        PKCS10CertificationRequest csr = generateRequest(x509DN, clientPublicKey, clientPrivateKey, keyType);

        // ...sign it
        KeyStore rootKS = loadRootKeyStore();
        X509Certificate rootCert = (X509Certificate) rootKS.getCertificate(rootCAKeystoreAlias);
        if (rootCert == null) {
            logger.error("Can't get root certificate from CA keystore");
            return null;
        }
        PrivateKey rootPrivKey = (PrivateKey) rootKS.getKey(rootCAKeystoreAlias,
                rootCAKeystorePassword.toCharArray());
        X509Certificate[] signedChain = createSignedCert(rootCert, rootPrivKey, csr, keyType);

        //...package up the result...
        CABean caBean = new CABean();
        caBean.setChain(signedChain);
        caBean.setCSRPrivateKey(clientPrivateKey);
        caBean.setSubjectDN(x509DN);

        // ...and send it back
        return caBean;
    } catch (Exception e) {
        logger.error(e);
        return null;
    }
}

From source file:cybervillains.ca.KeyStoreManager.java

private synchronized void rememberKeyPair(final KeyPair kp) {
    _rememberedPrivateKeys.put(kp.getPublic(), kp.getPrivate());
    if (persistImmediately) {
        persistKeyPairMap();/*  www  .  jav a  2 s.c o m*/
    }
}

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

/**
 * Creates a key pair.//from  ww w  .  ja va  2s.c o  m
 *
 * @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.ejbca.core.model.ca.catoken.BaseCAToken.java

public PrivateKey getPrivateKey(int purpose) throws CATokenOfflineException {
    autoActivate();//www .  java 2  s . co m
    String keystring = this.keyStrings.getString(purpose);
    KeyPair keyPair = this.mKeys != null ? (KeyPair) this.mKeys.get(keystring) : null;
    if (keyPair == null) {
        String msg = intres.getLocalizedMessage("catoken.errornosuchkey", keystring, purpose);
        throw new CATokenOfflineException(msg);
    }
    return keyPair.getPrivate();
}

From source file:mamo.vanillaVotifier.JsonConfig.java

@Override
public synchronized void load() throws IOException, InvalidKeySpecException {
    if (!configFile.exists()) {
        BufferedInputStream in = new BufferedInputStream(JsonConfig.class.getResourceAsStream("config.json"));
        StringBuilder stringBuilder = new StringBuilder();
        int i;/*w w  w .  ja  v a 2  s  .  c  o  m*/
        while ((i = in.read()) != -1) {
            stringBuilder.append((char) i);
        }
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(configFile));
        for (char c : stringBuilder.toString()
                .replaceAll("\\u000D\\u000A|[\\u000A\\u000B\\u000C\\u000D\\u0085\\u2028\\u2029]",
                        System.getProperty("line.separator"))
                .toCharArray()) {
            out.write((int) c);
        }
        out.flush();
        out.close();
    }
    BufferedInputStream in = new BufferedInputStream(JsonConfig.class.getResourceAsStream("config.json"));
    JSONObject defaultConfig = new JSONObject(new JSONTokener(in));
    in.close();
    JSONObject config = new JSONObject(
            new JSONTokener(new BufferedInputStream(new FileInputStream(configFile))));
    boolean save = JsonUtils.merge(defaultConfig, config);
    configVersion = config.getInt("config-version");
    if (configVersion == 2) {
        v2ToV3(config);
        configVersion = 3;
        save = true;
    }
    logFile = new File(config.getString("log-file"));
    inetSocketAddress = new InetSocketAddress(config.getString("ip"), config.getInt("port"));
    publicKeyFile = new File(config.getJSONObject("key-pair-files").getString("public"));
    privateKeyFile = new File(config.getJSONObject("key-pair-files").getString("private"));
    if (!publicKeyFile.exists() && !privateKeyFile.exists()) {
        KeyPair keyPair = RsaUtils.genKeyPair();
        PemWriter publicPemWriter = new PemWriter(new BufferedWriter(new FileWriter(publicKeyFile)));
        publicPemWriter.writeObject(new PemObject("PUBLIC KEY", keyPair.getPublic().getEncoded()));
        publicPemWriter.flush();
        publicPemWriter.close();
        PemWriter privatePemWriter = new PemWriter(new BufferedWriter(new FileWriter(privateKeyFile)));
        privatePemWriter.writeObject(new PemObject("RSA PRIVATE KEY", keyPair.getPrivate().getEncoded()));
        privatePemWriter.flush();
        privatePemWriter.close();
    }
    if (!publicKeyFile.exists()) {
        throw new PublicKeyFileNotFoundException();
    }
    if (!privateKeyFile.exists()) {
        throw new PrivateKeyFileNotFoundException();
    }
    PemReader publicKeyPemReader = new PemReader(new BufferedReader(new FileReader(publicKeyFile)));
    PemReader privateKeyPemReader = new PemReader(new BufferedReader(new FileReader(privateKeyFile)));
    PemObject publicPemObject = publicKeyPemReader.readPemObject();
    if (publicPemObject == null) {
        throw new InvalidPublicKeyFileException();
    }
    PemObject privatePemObject = privateKeyPemReader.readPemObject();
    if (privatePemObject == null) {
        throw new InvalidPrivateKeyFileException();
    }
    keyPair = new KeyPair(RsaUtils.bytesToPublicKey(publicPemObject.getContent()),
            RsaUtils.bytesToPrivateKey(privatePemObject.getContent()));
    publicKeyPemReader.close();
    privateKeyPemReader.close();
    rconConfigs = new ArrayList<RconConfig>();
    for (int i = 0; i < config.getJSONArray("rcon-list").length(); i++) {
        JSONObject jsonObject = config.getJSONArray("rcon-list").getJSONObject(i);
        RconConfig rconConfig = new RconConfig(
                new InetSocketAddress(jsonObject.getString("ip"), jsonObject.getInt("port")),
                jsonObject.getString("password"));
        for (int j = 0; j < jsonObject.getJSONArray("commands").length(); j++) {
            rconConfig.getCommands().add(jsonObject.getJSONArray("commands").getString(j));
        }
        rconConfigs.add(rconConfig);
    }
    loaded = true;
    if (save) {
        save();
    }
}

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

/**
 * initialize the DAO//from www.  j a  v  a  2 s  . c om
 * @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:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java

private X509Certificate createSelfSignedCertificate(KeyStore keyStore, String dn, String alias) {
    try {// w ww .j a  va2 s.c  o  m
        // create new key pair for the node
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(keySize, new SecureRandom());
        KeyPair keypair = keyGen.generateKeyPair();
        PublicKey publicKey = keypair.getPublic();
        PrivateKey privateKey = keypair.getPrivate();

        Certificate cert = certificateService.generateCertificate(dn, publicKey, privateKey);
        keyStore.setKeyEntry(alias, privateKey, getKeyStorePassword().toCharArray(),
                new Certificate[] { cert });
        saveKeyStore(keyStore);
        return (X509Certificate) cert;
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateException("Error setting up node key pair", e);
    } catch (KeyStoreException e) {
        throw new CertificateException("Error setting up node key pair", e);
    }
}

From source file:net.lightbody.bmp.proxy.selenium.KeyStoreManager.java

/**
 * Creates, writes and loads a new keystore and CA root certificate.
 *///w w w  .j ava2  s.co  m
protected void createKeystore() {

    java.security.cert.Certificate signingCert = null;
    PrivateKey caPrivKey = null;

    if (_caCert == null || _caPrivKey == null) {
        try {
            log.debug("Keystore or signing cert & keypair not found.  Generating...");

            KeyPair caKeypair = getRSAKeyPair();
            caPrivKey = caKeypair.getPrivate();
            signingCert = CertificateCreator.createTypicalMasterCert(caKeypair);

            log.debug("Done generating signing cert");
            log.debug(signingCert);

            _ks.load(null, _keystorepass);

            _ks.setCertificateEntry(_caCertAlias, signingCert);
            _ks.setKeyEntry(_caPrivKeyAlias, caPrivKey, _keypassword,
                    new java.security.cert.Certificate[] { signingCert });

            File caKsFile = new File(root, _caPrivateKeystore);

            OutputStream os = new FileOutputStream(caKsFile);
            _ks.store(os, _keystorepass);

            log.debug("Wrote JKS keystore to: " + caKsFile.getAbsolutePath());

            // also export a .cer that can be imported as a trusted root
            // to disable all warning dialogs for interception

            File signingCertFile = new File(root, EXPORTED_CERT_NAME);

            FileOutputStream cerOut = new FileOutputStream(signingCertFile);

            byte[] buf = signingCert.getEncoded();

            log.debug("Wrote signing cert to: " + signingCertFile.getAbsolutePath());

            cerOut.write(buf);
            cerOut.flush();
            cerOut.close();

            _caCert = (X509Certificate) signingCert;
            _caPrivKey = caPrivKey;
        } catch (Exception e) {
            log.error("Fatal error creating/storing keystore or signing cert.", e);
            throw new Error(e);
        }
    } else {
        log.debug("Successfully loaded keystore.");
        log.debug(_caCert);

    }

}

From source file:org.candlepin.util.X509CRLStreamWriterTest.java

@Test
public void testSignatureKeyChange() throws Exception {
    KeyPair differentKeyPair = generator.generateKeyPair();

    ContentSigner otherSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC)
            .build(differentKeyPair.getPrivate());

    X509v2CRLBuilder crlBuilder = createCRLBuilder();
    X509CRLHolder holder = crlBuilder.build(otherSigner);

    File crlToChange = writeCRL(holder);

    X509CRLStreamWriter stream = new X509CRLStreamWriter(crlToChange, (RSAPrivateKey) keyPair.getPrivate(),
            (RSAPublicKey) keyPair.getPublic());
    stream.preScan(crlToChange).lock();//www. j a v a2s . c  o  m
    OutputStream o = new BufferedOutputStream(new FileOutputStream(outfile));
    stream.write(o);
    o.close();

    // No SignatureException should be thrown
    readCRL();
}

From source file:org.candlepin.util.X509CRLStreamWriterTest.java

@Test
public void testKeySizeChange() throws Exception {
    int[] sizes = { 1024, 4096 };

    for (int size : sizes) {
        X509CRLHolder holder = createCRL();
        File crlToChange = writeCRL(holder);

        generator.initialize(size);//from  ww w. ja va2s . c om
        KeyPair differentKeyPair = generator.generateKeyPair();

        X509CRLStreamWriter stream = new X509CRLStreamWriter(crlToChange,
                (RSAPrivateKey) differentKeyPair.getPrivate(), (RSAPublicKey) differentKeyPair.getPublic());
        stream.preScan(crlToChange).lock();
        OutputStream o = new BufferedOutputStream(new FileOutputStream(outfile));
        stream.write(o);
        o.close();

        X509CRL originalCrl = new JcaX509CRLConverter().setProvider(BC).getCRL(holder);
        X509CRL changedCrl = readCRL(differentKeyPair.getPublic());

        Set<BigInteger> discoveredSerials = new HashSet<BigInteger>();

        for (X509CRLEntry entry : changedCrl.getRevokedCertificates()) {
            discoveredSerials.add(entry.getSerialNumber());
        }

        Set<BigInteger> expected = new HashSet<BigInteger>();
        expected.add(new BigInteger("100"));
        assertEquals(expected, discoveredSerials);

        // Since the key changed, the authorityKeyIdentifier must change
        byte[] oldAkiBytes = originalCrl.getExtensionValue(X509Extension.authorityKeyIdentifier.getId());
        byte[] newAkiBytes = changedCrl.getExtensionValue(X509Extension.authorityKeyIdentifier.getId());

        AuthorityKeyIdentifierStructure oldAki = new AuthorityKeyIdentifierStructure(oldAkiBytes);
        AuthorityKeyIdentifierStructure newAki = new AuthorityKeyIdentifierStructure(newAkiBytes);

        assertArrayEquals(oldAki.getKeyIdentifier(),
                new AuthorityKeyIdentifierStructure(keyPair.getPublic()).getKeyIdentifier());

        assertArrayEquals(newAki.getKeyIdentifier(),
                new AuthorityKeyIdentifierStructure(differentKeyPair.getPublic()).getKeyIdentifier());
    }
}