List of usage examples for java.security KeyPair getPrivate
public PrivateKey getPrivate()
From source file:com.google.jenkins.plugins.credentials.oauth.P12ServiceAccountConfigTestUtil.java
private static X509Certificate generateCertificate(KeyPair keyPair) throws OperatorCreationException, CertificateException { Calendar endCalendar = Calendar.getInstance(); endCalendar.add(Calendar.YEAR, 10); X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder( new X500Name("CN=localhost"), BigInteger.valueOf(1), Calendar.getInstance().getTime(), endCalendar.getTime(), new X500Name("CN=localhost"), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())); ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").build(keyPair.getPrivate()); X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(x509CertificateHolder); }
From source file:org.apache.hadoop.security.ssl.RpcTLSUtils.java
public static TestCryptoMaterial setupTLSMaterial(Configuration conf, TLSSetup tlsSetup, Class callingClass) throws GeneralSecurityException, IOException { // Generate Server certificate KeyPair serverKeyPair = KeyStoreTestUtil.generateKeyPair(tlsSetup.keyAlgorithm); X509Certificate serverCert = KeyStoreTestUtil.generateCertificate("CN=Server", serverKeyPair, 60, tlsSetup.signatureAlgorithm); // Create server keystore and truststore KeyStoreTestUtil.createKeyStore(tlsSetup.serverKstore.toString(), tlsSetup.serverStorePassword, "server", serverKeyPair.getPrivate(), serverCert); KeyStoreTestUtil.createTrustStore(tlsSetup.serverTstore.toString(), tlsSetup.serverStorePassword, "server", serverCert);//from w w w.j a va 2s . c o m // Generate client certificate signed by server KeyPair clientKeyPair = KeyStoreTestUtil.generateKeyPair(tlsSetup.keyAlgorithm); X509Certificate clientCert = KeyStoreTestUtil.generateSignedCertificate("CN=" + tlsSetup.clientUserName, clientKeyPair, 30, tlsSetup.signatureAlgorithm, serverKeyPair.getPrivate(), serverCert); // Create client keystore and truststore KeyStoreTestUtil.createKeyStore(tlsSetup.clientKstore.toString(), tlsSetup.clientStorePassword, "client", clientKeyPair.getPrivate(), clientCert); Map<String, X509Certificate> clientTrustedCerts = new HashMap<>(2); clientTrustedCerts.put("client", clientCert); clientTrustedCerts.put("server", serverCert); KeyStoreTestUtil.createTrustStore(tlsSetup.clientTstore.toString(), tlsSetup.clientStorePassword, clientTrustedCerts); FileUtils.writeStringToFile(tlsSetup.clientPasswordLocation.toFile(), tlsSetup.clientStorePassword); conf.set(CommonConfigurationKeysPublic.HADOOP_RPC_SOCKET_FACTORY_CLASS_DEFAULT_KEY, "org.apache.hadoop.net.HopsSSLSocketFactory"); conf.setBoolean(CommonConfigurationKeysPublic.IPC_SERVER_SSL_ENABLED, true); conf.set(SSLFactory.SSL_HOSTNAME_VERIFIER_KEY, "ALLOW_ALL"); String superUser = UserGroupInformation.getCurrentUser().getUserName(); conf.set(ProxyUsers.CONF_HADOOP_PROXYUSER + "." + superUser, "*"); Configuration sslServerConf = KeyStoreTestUtil.createServerSSLConfig(tlsSetup.serverKstore.toString(), tlsSetup.serverStorePassword, tlsSetup.serverStorePassword, tlsSetup.serverTstore.toString(), tlsSetup.serverStorePassword, ""); KeyStoreTestUtil.saveConfig(tlsSetup.sslServerConf.toFile(), sslServerConf); conf.set(SSLFactory.SSL_SERVER_CONF_KEY, callingClass.getSimpleName() + ".ssl-server.xml"); return new TestCryptoMaterial(serverKeyPair, serverCert, clientKeyPair, clientCert); }
From source file:MainClass.java
public static PKCS10CertificationRequest generateRequest(KeyPair pair) throws Exception { GeneralNames subjectAltName = new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test")); Vector oids = new Vector(); Vector values = new Vector(); oids.add(X509Extensions.SubjectAlternativeName); values.add(new X509Extension(false, new DEROctetString(subjectAltName))); X509Extensions extensions = new X509Extensions(oids, values); Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new DERSet(extensions)); return new PKCS10CertificationRequest("SHA256withRSA", new X500Principal("CN=Requested Test Certificate"), pair.getPublic(), new DERSet(attribute), pair.getPrivate()); }
From source file:MainClass.java
public static X509Certificate generateV1Certificate(KeyPair pair) throws InvalidKeyException, NoSuchProviderException, SignatureException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); X509V1CertificateGenerator certGen = new X509V1CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(new X500Principal("CN=Test Certificate")); certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 10000)); certGen.setSubjectDN(new X500Principal("CN=Test Certificate")); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); return certGen.generateX509Certificate(pair.getPrivate(), "BC"); }
From source file:cloudeventbus.cli.Certs.java
private static void chainCertificate(ChainCertificateCommand command) throws Exception { final CertificateChain certificates = CertificateUtils.loadCertificateChain(command.existingCertificate); final PrivateKey privateKey = CertificateUtils.loadPrivateKey(command.existingPrivateKey); final KeyPair keyPair = CertificateUtils.generateKeyPair(); final Certificate certificate = CertificateUtils.generateSignedCertificate(certificates.getLast(), privateKey, keyPair.getPublic(), certificates.getLast().getType(), getExpirationDate(command.expirationDate), Subject.list(command.subscribePermissions), Subject.list(command.publishPermissions), command.comment); certificates.add(certificate);/* w w w . ja va2 s . c om*/ CertificateUtils.saveCertificates(command.certificate, certificates); CertificateUtils.savePrivateKey(keyPair.getPrivate(), command.privateKey); }
From source file:MainClass.java
public static X509Certificate generateV1Certificate(KeyPair pair) throws InvalidKeyException, NoSuchProviderException, SignatureException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); X509V1CertificateGenerator certGen = new X509V1CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(new X500Principal("CN=Test Certificate")); certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 10000)); certGen.setSubjectDN(new X500Principal("CN=Test Certificate")); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); return certGen.generateX509Certificate(pair.getPrivate(), "BC"); }
From source file:gov.niem.ws.util.SecurityUtil.java
public static KeyManager[] createKeyManagers(KeyPair clientKey, X509Certificate clientCert) throws GeneralSecurityException, IOException { // Create a new empty key store. KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null);/* w ww. j a v a 2 s . co m*/ Certificate[] chain = { clientCert }; // The KeyStore requires a password for key entries. char[] password = { ' ' }; // Since we never write out the key store, we don't bother protecting // the key. ks.setEntry("client-key", new KeyStore.PrivateKeyEntry(clientKey.getPrivate(), chain), new KeyStore.PasswordProtection(password)); // Shove the key store in a KeyManager. KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, password); return kmf.getKeyManagers(); }
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 a v a2 s . co 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.apache.nifi.registry.security.util.CertificateUtils.java
/** * Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority. * * @param keyPair the {@link KeyPair} to generate the {@link X509Certificate} for * @param dn the distinguished name to user for the {@link X509Certificate} * @param signingAlgorithm the signing algorithm to use for the {@link X509Certificate} * @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid * @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority * @throws CertificateException if there is an generating the new certificate *///from w w w . j av a2 s. c o m public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays) throws CertificateException { try { ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm) .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); Date startDate = new Date(); Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays)); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(reverseX500Name(new X500Name(dn)), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo); // Set certificate extensions // (1) digitalSignature extension certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign)); certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true)); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic())); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic())); // (2) extendedKeyUsage extension certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage( new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth })); // Sign the certificate 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.umit.icm.mobile.utils.ProfilerRun.java
private static void profileRSAPrivateEncrypt() { Profiler profiler = new Profiler(); profiler.runProfiler(new TaskInterface() { public void task() { try { KeyPair keyPair = RSACrypto.generateKey(); RSACrypto.encryptPrivate(keyPair.getPrivate(), "This is a test string"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace();/*w ww. ja v a 2 s.com*/ } } public String taskName() { return "RSA Private Encryption"; } }); }