List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
From source file:com.aqnote.shared.cryptology.cert.gen.CertGenerator.java
private X509Certificate createEndCert(X500Name subject, PublicKey pubKey, KeyPair pKeyPair, X500Name issuer) throws Exception { PublicKey pPubKey = pKeyPair.getPublic(); PrivateKey pPrivKey = pKeyPair.getPrivate(); BigInteger sno = BigInteger.valueOf(System.currentTimeMillis()); Date nb = new Date(System.currentTimeMillis() - HALF_DAY); Date na = new Date(nb.getTime() + FIVE_YEAR); X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, sno, nb, na, subject, pubKey);//from w ww . j a va2 s .c o m addSubjectKID(certBuilder, pubKey); addAuthorityKID(certBuilder, pPubKey); certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(BASE_EKU)); certBuilder.addExtension(Extension.keyUsage, false, new KeyUsage(END_KEY_USAGE)); X509Certificate certificate = signCert(certBuilder, pPrivKey); certificate.checkValidity(new Date()); certificate.verify(pPubKey); setPKCS9Info(certificate); return certificate; }
From source file:com.joyent.manta.client.AuthAwareConfigContextTest.java
private void differentKeyPairsSameContent(final KeyPair keyPairFromContent, final KeyPair keyPairFromFile) { // different instances Assert.assertNotSame(keyPairFromContent, keyPairFromFile); // same key//w w w.ja va 2 s. c o m AssertJUnit.assertArrayEquals(keyPairFromContent.getPrivate().getEncoded(), keyPairFromFile.getPrivate().getEncoded()); AssertJUnit.assertArrayEquals(keyPairFromContent.getPublic().getEncoded(), keyPairFromFile.getPublic().getEncoded()); }
From source file:com.subgraph.vega.internal.http.proxy.ssl.CertificateCreator.java
private HostCertificateData createSelfSignedCertificateDataFor(X500Principal subject, KeyPair subjectKeys) throws CertificateException { final X509Certificate[] chain = new X509Certificate[1]; chain[0] = generateCertificate(subject, subjectKeys.getPublic(), subject, subjectKeys.getPublic(), subjectKeys.getPrivate(), false); return new HostCertificateData(subject.getName(), subjectKeys.getPrivate(), chain); }
From source file:com.subgraph.vega.internal.http.proxy.ssl.CertificateCreator.java
private HostCertificateData createCaSignedCertificateDataFor(X500Principal subject, KeyPair subjectKeys) throws CertificateException { final X509Certificate[] chain = new X509Certificate[2]; chain[0] = generateCertificate(subject, subjectKeys.getPublic(), caSubject, caPublicKey, caPrivateKey, false);// w w w.j av a2 s . c om chain[1] = caCertificate; return new HostCertificateData(subject.getName(), subjectKeys.getPrivate(), chain); }
From source file:com.thoughtworks.go.server.util.HttpTestUtil.java
private KeyPair generateKeyPair() { try {//from w ww. ja v a2 s . c o m KeyPair seed = KeyPairGenerator.getInstance("RSA", "BC").generateKeyPair(); RSAPrivateKey privateSeed = (RSAPrivateKey) seed.getPrivate(); RSAPublicKey publicSeed = (RSAPublicKey) seed.getPublic(); KeyFactory fact = KeyFactory.getInstance("RSA", "BC"); RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(privateSeed.getModulus(), privateSeed.getPrivateExponent()); RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(publicSeed.getModulus(), publicSeed.getPublicExponent()); return new KeyPair(fact.generatePublic(publicKeySpec), fact.generatePrivate(privateKeySpec)); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.cesecore.keys.util.KeyTools.java
/** * Generates a keypair//from w w w . j av a 2s . co m * * @param keySpec * string specification of keys to generate, typical value is 2048 for RSA keys, * 1024 for DSA keys, secp256r1 for ECDSA keys, or null if algspec is to be used. * @param algSpec * AlgorithmParameterSpec of keys to generate, typically an EXParameterSpec for EC keys, or null if keySpec is to be used. * @param keyAlg * algorithm of keys to generate, typical value is RSA, DSA or ECDSA, see AlgorithmConstants.KEYALGORITHM_XX * * @see org.cesecore.certificates.util.core.model.AlgorithmConstants * @see org.bouncycastle.asn1.x9.X962NamedCurves * @see org.bouncycastle.asn1.nist.NISTNamedCurves * @see org.bouncycastle.asn1.sec.SECNamedCurves * * @return KeyPair the generated keypair * @throws InvalidAlgorithmParameterException * @see org.cesecore.certificates.util.AlgorithmConstants#KEYALGORITHM_RSA */ public static KeyPair genKeys(final String keySpec, final AlgorithmParameterSpec algSpec, final String keyAlg) throws InvalidAlgorithmParameterException { if (log.isTraceEnabled()) { log.trace(">genKeys(" + keySpec + ", " + keyAlg + ")"); } KeyPairGenerator keygen; try { keygen = KeyPairGenerator.getInstance(keyAlg, BouncyCastleProvider.PROVIDER_NAME); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Algorithm " + keyAlg + "was not recognized.", e); } catch (NoSuchProviderException e) { throw new IllegalStateException("BouncyCastle was not found as a provider.", e); } if (StringUtils.equals(keyAlg, AlgorithmConstants.KEYALGORITHM_ECDSA)) { AlgorithmParameterSpec ecSpec = null; if ((keySpec != null) && !StringUtils.equals(keySpec, "implicitlyCA")) { log.debug("Generating named curve ECDSA key pair: " + keySpec); // We have EC keys ECGenParameterSpec bcSpec = new ECGenParameterSpec(keySpec); keygen.initialize(bcSpec, new SecureRandom()); // The old code should work in BC v1.50b6 and later, but in vesions prior to that the below produces a key with explicit parameter encoding instead of named curves. // There is a test for this in KeyToolsTest.testGenKeysECDSAx9 // ecSpec = ECNamedCurveTable.getParameterSpec(keySpec); // if (ecSpec == null) { // throw new InvalidAlgorithmParameterException("keySpec " + keySpec + " is invalid for ECDSA."); // } // keygen.initialize(ecSpec, new SecureRandom()); } else if (algSpec != null) { log.debug("Generating ECDSA key pair from AlgorithmParameterSpec: " + algSpec); ecSpec = algSpec; keygen.initialize(ecSpec, new SecureRandom()); } else if (StringUtils.equals(keySpec, "implicitlyCA")) { log.debug("Generating implicitlyCA encoded ECDSA key pair"); // If the keySpec is null, we have "implicitlyCA" defined EC parameters // The parameters were already installed when we installed the provider // We just make sure that ecSpec == null here keygen.initialize(ecSpec, new SecureRandom()); } else { throw new InvalidAlgorithmParameterException("No keySpec no algSpec and no implicitlyCA specified"); } } else if (keyAlg.equals(AlgorithmConstants.KEYALGORITHM_ECGOST3410)) { AlgorithmParameterSpec ecSpec = null; if (keySpec != null) { log.debug("Generating keys from given key specifications : " + keySpec); ecSpec = ECGOST3410NamedCurveTable.getParameterSpec(keySpec); if (ecSpec == null) throw new InvalidAlgorithmParameterException( "Key specification " + keySpec + " is invalid for ECGOST3410"); } else if (algSpec != null) { log.debug("Generating keys from given algorithm parameters : " + algSpec); ecSpec = algSpec; } else { throw new InvalidAlgorithmParameterException("No key or algorithm specifications"); } keygen.initialize(ecSpec, new SecureRandom()); } else if (keyAlg.equals(AlgorithmConstants.KEYALGORITHM_DSTU4145)) { AlgorithmParameterSpec ecSpec = null; if (keySpec != null) { log.debug("Generating keys from given key specifications : " + keySpec); ecSpec = dstuOidToAlgoParams(keySpec); if (ecSpec == null) throw new InvalidAlgorithmParameterException( "Key specification " + keySpec + " is invalid for DSTU4145"); } else if (algSpec != null) { log.debug("Generating keys from given algorithm parameters : " + algSpec); ecSpec = algSpec; } else { throw new InvalidAlgorithmParameterException("No key or algorithm specifications"); } keygen.initialize(ecSpec, new SecureRandom()); } else if (keySpec.startsWith("DSA")) { // DSA key with "DSA" in keyspec final int keysize = Integer.parseInt(keySpec.substring(3)); keygen.initialize(keysize); } else { // RSA or DSA key where keyspec is simply the key length final int keysize = Integer.parseInt(keySpec); keygen.initialize(keysize); } final KeyPair keys = keygen.generateKeyPair(); if (log.isDebugEnabled()) { final PublicKey pk = keys.getPublic(); final int len = getKeyLength(pk); log.debug("Generated " + keys.getPublic().getAlgorithm() + " keys with length " + len); } log.trace("<genKeys()"); return keys; }
From source file:net.firejack.platform.installation.processor.SetupSystemProcessor.java
/***/ public void setupSystem() { String domainUrl = OpenFlameConfig.DOMAIN_URL.getValue(); Integer port = Integer.parseInt(OpenFlameConfig.PORT.getValue()); String contextUrl = OpenFlameConfig.CONTEXT_URL.getValue(); if (domainUrl != null && port != null && contextUrl != null) { Env.FIREJACK_URL.setValue(WebUtils.getNormalizedUrl(domainUrl, port, contextUrl)); }/* w w w . ja va 2s.c om*/ RootDomainModel rootDomain = rootDomainStore.findByLookup(OpenFlame.ROOT_DOMAIN); if (rootDomain == null) { rootDomain = new RootDomainModel(); rootDomain.setName(DiffUtils.findRootDomainName(OpenFlame.ROOT_DOMAIN)); rootDomain.setLookup(OpenFlame.ROOT_DOMAIN); rootDomainStore.save(rootDomain); } try { Environments<Environment> environments = EnvironmentsUtils.deserialize(InstallUtils.getXmlEnv()); if (environments != null && !environments.isEmpty()) { for (Environment environment : environments.getEnvironments()) { if (rootDomain.getLookup().equals(environment.getSystem().getPath())) { environmentStore.save(rootDomain, environment); } } } loadRepositories(); File contentXmlInstallationFile = FileUtils.getResource("dbupdate", PackageFileType.CONTENT_XML.getOfrFileName()); // File resourceZipInstallationFile = FileUtils.getResource("dbupdate", PackageFileType.RESOURCE_ZIP.getOfrFileName()); FileInputStream stream = new FileInputStream(contentXmlInstallationFile); importContentProcessor.importContent(stream, null); IOUtils.closeQuietly(stream); if (environments != null && !environments.isEmpty()) { for (Environment environment : environments.getEnvironments()) { if (rootDomain.getLookup().equals(environment.getSystem().getPath())) { for (ServerModel model : environment.getServers()) { if (model.getName().equals("server")) { String name = InetAddress.getLocalHost().getHostName(); KeyPair pair = KeyUtils.generate(EnvironmentsUtils.getKeyStore()); byte[] encodedPubKey = Base64.encode(pair.getPublic().getEncoded()); model.setName(name); model.setPublicKey(new String(encodedPubKey)); serverStore.merge(model); KeyUtils.add(EnvironmentsUtils.getKeyStore(), pair, ""); } } } } } } catch (Exception e) { logger.error(e, e); throw new BusinessFunctionException("Occurred error in initialize content.", e); } }
From source file:cloud.google.com.windows.example.ExampleCode.java
@SuppressWarnings("unchecked") private JSONObject jsonEncode(KeyPair keys) throws NoSuchAlgorithmException, InvalidKeySpecException { KeyFactory factory = KeyFactory.getInstance("RSA"); // Get the RSA spec for key manipulation. RSAPublicKeySpec pubSpec = factory.getKeySpec(keys.getPublic(), RSAPublicKeySpec.class); // Extract required parts of the key. BigInteger modulus = pubSpec.getModulus(); BigInteger exponent = pubSpec.getPublicExponent(); // Grab an encoder for the modulus and exponent to encode using RFC 3548; // Java SE 7 requires an external library (Google's Guava used here) // Java SE 8 has a built-in Base64 class that can be used instead. Apache also has an RFC 3548 // encoder./*w ww .j a va2s.com*/ BaseEncoding stringEncoder = BaseEncoding.base64(); // Strip out the leading 0 byte in the modulus. byte[] arr = Arrays.copyOfRange(modulus.toByteArray(), 1, modulus.toByteArray().length); JSONObject returnJson = new JSONObject(); // Encode the modulus, add to returned JSON object. String modulusString = stringEncoder.encode(arr).replaceAll("\n", ""); returnJson.put("modulus", modulusString); // Encode exponent, add to returned JSON object. String exponentString = stringEncoder.encode(exponent.toByteArray()).replaceAll("\n", ""); returnJson.put("exponent", exponentString); return returnJson; }
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;//from w w w . j a v a 2 s . c om 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:com.atlassian.jira.security.auth.trustedapps.DefaultCurrentApplicationStore.java
@Override public void setCurrentApplication(String applicationId, KeyPair pair) { notBlank("applicationId cannot be blank.", applicationId); Assertions.notNull("pair cannot be null.", pair); Assertions.notNull("pair.private cannot be null.", pair.getPrivate()); Assertions.notNull("pair.public cannot be null.", pair.getPublic()); accessLock.lock();/*from www .ja va 2s .c o m*/ try { applicationProperties.setText(Keys.PRIVATE_KEY_DATA, KeyFactory.encode(pair.getPrivate())); applicationProperties.setText(Keys.PUBLIC_KEY_DATA, KeyFactory.encode(pair.getPublic())); applicationProperties.setString(Keys.UID, applicationId); cache.reset(); } finally { accessLock.unlock(); } }