List of usage examples for java.security Security addProvider
public static int addProvider(Provider provider)
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
/** * Integration test for automatic recovery of a {@link PrivateKey} instance. * <p/>// www . ja va 2 s.c o m * Automatic recovery should work on the same eID card. * <p/> * When inserting another eID card however, the automatic recovery should * fail. * * @throws Exception */ @Test public void testAutoRecovery() throws Exception { Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); BeIDKeyStoreParameter keyStoreParameter = new BeIDKeyStoreParameter(); keyStoreParameter.setAutoRecovery(true); keyStoreParameter.setCardReaderStickiness(true); keyStore.load(keyStoreParameter); PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); PublicKey authnPublicKey = keyStore.getCertificate("Authentication").getPublicKey(); final Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(authnPrivateKey); final byte[] toBeSigned = "hello world".getBytes(); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); signature.initVerify(authnPublicKey); signature.update(toBeSigned); assertTrue(signature.verify(signatureValue)); JOptionPane.showMessageDialog(null, "Please remove/insert eID card..."); signature.initSign(authnPrivateKey); signature.update(toBeSigned); signatureValue = signature.sign(); signature.initVerify(authnPublicKey); signature.update(toBeSigned); assertTrue(signature.verify(signatureValue)); }
From source file:test.integ.be.fedict.commons.eid.client.BeIDCardTest.java
@Test public void testPSSSignature() throws Exception { final BeIDCard beIDCard = getBeIDCard(); final byte[] toBeSigned = new byte[10]; final SecureRandom secureRandom = new SecureRandom(); secureRandom.nextBytes(toBeSigned);//www . j av a2 s .c o m final X509Certificate authnCertificate = beIDCard.getAuthenticationCertificate(); final MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); final byte[] digestValue = messageDigest.digest(toBeSigned); byte[] signatureValue; try { signatureValue = beIDCard.sign(digestValue, BeIDDigest.SHA_1_PSS, FileType.AuthentificationCertificate, false); } finally { beIDCard.close(); } Security.addProvider(new BouncyCastleProvider()); final BeIDIntegrity beIDIntegrity = new BeIDIntegrity(); final boolean result = beIDIntegrity.verifySignature("SHA1withRSAandMGF1", signatureValue, authnCertificate.getPublicKey(), toBeSigned); assertTrue(result); }
From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.enrollment.EnrollmentManager.java
/** * Method to control the entire enrollment flow. This method calls the method to create the Private-Public Key * Pair, calls the specific method to generate the Certificate-Sign-Request, creates a one time self signed * certificate to present to the SCEP server with the initial CSR, calls the specific method to connect to the * SCEP Server and to get the SCEP Certificate and also calls the method that requests the SCEP Server for its * PublicKey for future payload encryption. * * @throws AgentCoreOperationException if the private method generateCertSignRequest() fails with an error or if * there is an error creating a self-sign certificate to present to the * server (whilst trying to get the CSR signed) *///from w ww. j a v a2 s .c om public void beginEnrollmentFlow() throws AgentCoreOperationException { Security.addProvider(new BouncyCastleProvider()); KeyPair keyPair = generateKeyPair(); this.privateKey = keyPair.getPrivate(); this.publicKey = keyPair.getPublic(); if (log.isDebugEnabled()) { log.info(AgentConstants.LOG_APPENDER + "DevicePrivateKey:\n[\n" + privateKey + "\n]\n"); log.info(AgentConstants.LOG_APPENDER + "DevicePublicKey:\n[\n" + publicKey + "\n]\n"); } PKCS10CertificationRequest certSignRequest = generateCertSignRequest(); /** * ----------------------------------------------------------------------------------------------- * Generate an ephemeral self-signed certificate. This is needed to present to the CA in the SCEP request. * In the future, add proper EKU and attributes in the request. The CA does NOT have to honour any of this. * ----------------------------------------------------------------------------------------------- */ X500Name issuer = new X500Name("CN=Temporary Issuer"); BigInteger serial = new BigInteger(32, new SecureRandom()); Date fromDate = new Date(); Date toDate = new Date(System.currentTimeMillis() + (CERT_VALIDITY * 86400000L)); // Build the self-signed cert using BC, sign it with our private key (self-signed) X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serial, fromDate, toDate, certSignRequest.getSubject(), certSignRequest.getSubjectPublicKeyInfo()); ContentSigner sigGen; X509Certificate tmpCert; try { sigGen = new JcaContentSignerBuilder(SIGNATURE_ALG).setProvider(PROVIDER).build(keyPair.getPrivate()); tmpCert = new JcaX509CertificateConverter().setProvider(PROVIDER) .getCertificate(certBuilder.build(sigGen)); } catch (OperatorCreationException e) { String errorMsg = "Error occurred whilst creating a ContentSigner for the Temp-Self-Signed Certificate."; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } catch (CertificateException e) { String errorMsg = "Error occurred whilst trying to create Temp-Self-Signed Certificate."; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } /** * ----------------------------------------------------------------------------------------------- */ this.SCEPCertificate = getSignedCertificateFromServer(tmpCert, certSignRequest); this.serverPublicKey = initPublicKeyOfServer(); if (log.isDebugEnabled()) { log.info(AgentConstants.LOG_APPENDER + "TemporaryCertPublicKey:\n[\n" + tmpCert.getPublicKey() + "\n]\n"); log.info(AgentConstants.LOG_APPENDER + "ServerPublicKey:\n[\n" + serverPublicKey + "\n]\n"); } }
From source file:org.xwiki.contrib.ldap.XWikiLDAPConnection.java
/** * Open LDAP connection.//from w ww .java 2 s.c o m * * @param ldapHost the host of the server to connect to. * @param ldapPort the port of the server to connect to. * @param loginDN the user DN to connect to LDAP server. * @param password the password to connect to LDAP server. * @param pathToKeys the path to SSL keystore to use. * @param ssl if true connect using SSL. * @param context the XWiki context. * @return true if the connection succeed, false otherwise. * @throws XWikiLDAPException error when trying to open connection. */ public boolean open(String ldapHost, int ldapPort, String loginDN, String password, String pathToKeys, boolean ssl, XWikiContext context) throws XWikiLDAPException { int port = ldapPort; if (port <= 0) { port = ssl ? LDAPConnection.DEFAULT_SSL_PORT : LDAPConnection.DEFAULT_PORT; } setBinaryAttributes(this.configuration.getBinaryAttributes()); try { if (ssl) { // Dynamically set JSSE as a security provider Security.addProvider(this.configuration.getSecureProvider()); if (pathToKeys != null && pathToKeys.length() > 0) { // Dynamically set the property that JSSE uses to identify // the keystore that holds trusted root certificates System.setProperty("javax.net.ssl.trustStore", pathToKeys); // obviously unnecessary: sun default pwd = "changeit" // System.setProperty("javax.net.ssl.trustStorePassword", sslpwd); } LDAPSocketFactory ssf = new LDAPJSSESecureSocketFactory(); // Set the socket factory as the default for all future connections // LDAPConnection.setSocketFactory(ssf); // Note: the socket factory can also be passed in as a parameter // to the constructor to set it for this connection only. this.connection = new LDAPConnection(ssf); } else { this.connection = new LDAPConnection(); } // connect connect(ldapHost, port); // set referral following LDAPSearchConstraints constraints = new LDAPSearchConstraints(this.connection.getConstraints()); constraints.setTimeLimit(getTimeout(context)); constraints.setMaxResults(getMaxResults(context)); constraints.setReferralFollowing(true); constraints.setReferralHandler(new LDAPPluginReferralHandler(loginDN, password, context)); this.connection.setConstraints(constraints); // bind bind(loginDN, password); } catch (UnsupportedEncodingException e) { throw new XWikiLDAPException("LDAP bind failed with UnsupportedEncodingException.", e); } catch (LDAPException e) { throw new XWikiLDAPException("LDAP bind failed with LDAPException.", e); } return true; }
From source file:io.bitsquare.app.BitsquareApp.java
@Override public void start(Stage stage) throws IOException { BitsquareApp.primaryStage = stage;//from w w w .j ava 2s .c o m String logPath = Paths.get(env.getProperty(AppOptionKeys.APP_DATA_DIR_KEY), "bitsquare").toString(); Log.setup(logPath); log.info("Log files under: " + logPath); Version.printVersion(); Utilities.printSysInfo(); Log.setLevel(Level.toLevel(env.getRequiredProperty(CommonOptionKeys.LOG_LEVEL_KEY))); UserThread.setExecutor(Platform::runLater); UserThread.setTimerClass(UITimer.class); shutDownHandler = this::stop; // setup UncaughtExceptionHandler Thread.UncaughtExceptionHandler handler = (thread, throwable) -> { // Might come from another thread if (throwable.getCause() != null && throwable.getCause().getCause() != null && throwable.getCause().getCause() instanceof BlockStoreException) { log.error(throwable.getMessage()); } else if (throwable instanceof ClassCastException && "sun.awt.image.BufImgSurfaceData cannot be cast to sun.java2d.xr.XRSurfaceData" .equals(throwable.getMessage())) { log.warn(throwable.getMessage()); } else { log.error("Uncaught Exception from thread " + Thread.currentThread().getName()); log.error("throwableMessage= " + throwable.getMessage()); log.error("throwableClass= " + throwable.getClass()); log.error("Stack trace:\n" + ExceptionUtils.getStackTrace(throwable)); throwable.printStackTrace(); UserThread.execute(() -> showErrorPopup(throwable, false)); } }; Thread.setDefaultUncaughtExceptionHandler(handler); Thread.currentThread().setUncaughtExceptionHandler(handler); try { Utilities.checkCryptoPolicySetup(); } catch (NoSuchAlgorithmException | LimitedKeyStrengthException e) { e.printStackTrace(); UserThread.execute(() -> showErrorPopup(e, true)); } Security.addProvider(new BouncyCastleProvider()); try { // Guice bitsquareAppModule = new BitsquareAppModule(env, primaryStage); injector = Guice.createInjector(bitsquareAppModule); injector.getInstance(InjectorViewFactory.class).setInjector(injector); Version.setBtcNetworkId(injector.getInstance(BitsquareEnvironment.class).getBitcoinNetwork().ordinal()); if (Utilities.isLinux()) System.setProperty("prism.lcdtext", "false"); Storage.setDatabaseCorruptionHandler((String fileName) -> { corruptedDatabaseFiles.add(fileName); if (mainView != null) mainView.setPersistedFilesCorrupted(corruptedDatabaseFiles); }); // load the main view and create the main scene CachingViewLoader viewLoader = injector.getInstance(CachingViewLoader.class); mainView = (MainView) viewLoader.load(MainView.class); mainView.setPersistedFilesCorrupted(corruptedDatabaseFiles); /* Storage.setDatabaseCorruptionHandler((String fileName) -> { corruptedDatabaseFiles.add(fileName); if (mainView != null) mainView.setPersistedFilesCorrupted(corruptedDatabaseFiles); });*/ scene = new Scene(mainView.getRoot(), 1200, 700); //740 Font.loadFont(getClass().getResource("/fonts/Verdana.ttf").toExternalForm(), 13); Font.loadFont(getClass().getResource("/fonts/VerdanaBold.ttf").toExternalForm(), 13); Font.loadFont(getClass().getResource("/fonts/VerdanaItalic.ttf").toExternalForm(), 13); Font.loadFont(getClass().getResource("/fonts/VerdanaBoldItalic.ttf").toExternalForm(), 13); scene.getStylesheets().setAll("/io/bitsquare/gui/bitsquare.css", "/io/bitsquare/gui/images.css", "/io/bitsquare/gui/CandleStickChart.css"); // configure the system tray SystemTray.create(primaryStage, shutDownHandler); primaryStage.setOnCloseRequest(event -> { event.consume(); stop(); }); scene.addEventHandler(KeyEvent.KEY_RELEASED, keyEvent -> { if (new KeyCodeCombination(KeyCode.W, KeyCombination.SHORTCUT_DOWN).match(keyEvent) || new KeyCodeCombination(KeyCode.W, KeyCombination.CONTROL_DOWN).match(keyEvent)) { stop(); } else if (new KeyCodeCombination(KeyCode.Q, KeyCombination.SHORTCUT_DOWN).match(keyEvent) || new KeyCodeCombination(KeyCode.Q, KeyCombination.CONTROL_DOWN).match(keyEvent)) { stop(); } else if (new KeyCodeCombination(KeyCode.E, KeyCombination.SHORTCUT_DOWN).match(keyEvent) || new KeyCodeCombination(KeyCode.E, KeyCombination.CONTROL_DOWN).match(keyEvent)) { showEmptyWalletPopup(); } else if (new KeyCodeCombination(KeyCode.M, KeyCombination.ALT_DOWN).match(keyEvent)) { showSendAlertMessagePopup(); } else if (new KeyCodeCombination(KeyCode.F, KeyCombination.ALT_DOWN).match(keyEvent)) { showFilterPopup(); } else if (new KeyCodeCombination(KeyCode.F, KeyCombination.ALT_DOWN).match(keyEvent)) { showFPSWindow(); } else if (new KeyCodeCombination(KeyCode.J, KeyCombination.ALT_DOWN).match(keyEvent)) { WalletService walletService = injector.getInstance(WalletService.class); if (walletService.getWallet() != null) new ShowWalletDataWindow(walletService).information("Wallet raw data").show(); else new Popup<>().warning("The wallet is not initialized yet").show(); } else if (new KeyCodeCombination(KeyCode.G, KeyCombination.ALT_DOWN).match(keyEvent)) { TradeWalletService tradeWalletService = injector.getInstance(TradeWalletService.class); WalletService walletService = injector.getInstance(WalletService.class); if (walletService.getWallet() != null) new SpendFromDepositTxWindow(tradeWalletService).information("Emergency wallet tool") .show(); else new Popup<>().warning("The wallet is not initialized yet").show(); } else if (DevFlags.DEV_MODE && new KeyCodeCombination(KeyCode.D, KeyCombination.SHORTCUT_DOWN).match(keyEvent)) { showDebugWindow(); } }); // configure the primary stage primaryStage.setTitle(env.getRequiredProperty(APP_NAME_KEY)); primaryStage.setScene(scene); primaryStage.setMinWidth(1000); // 1190 primaryStage.setMinHeight(620); // on windows the title icon is also used as task bar icon in a larger size // on Linux no title icon is supported but also a large task bar icon is derived from that title icon String iconPath; if (Utilities.isOSX()) iconPath = ImageUtil.isRetina() ? "/images/window_icon@2x.png" : "/images/window_icon.png"; else if (Utilities.isWindows()) iconPath = "/images/task_bar_icon_windows.png"; else iconPath = "/images/task_bar_icon_linux.png"; primaryStage.getIcons().add(new Image(getClass().getResourceAsStream(iconPath))); // make the UI visible primaryStage.show(); if (!Utilities.isCorrectOSArchitecture()) { String osArchitecture = Utilities.getOSArchitecture(); // We don't force a shutdown as the osArchitecture might in strange cases return a wrong value. // Needs at least more testing on different machines... new Popup<>() .warning("You probably have the wrong Bitsquare version for this computer.\n" + "Your computer's architecture is: " + osArchitecture + ".\n" + "The Bitsquare binary you installed is: " + Utilities.getJVMArchitecture() + ".\n" + "Please shut down and re-install the correct version (" + osArchitecture + ").") .show(); } UserThread.runPeriodically(() -> Profiler.printSystemLoad(log), LOG_MEMORY_PERIOD_MIN, TimeUnit.MINUTES); } catch (Throwable throwable) { showErrorPopup(throwable, false); } }
From source file:test.integ.be.e_contract.mycarenet.ehbox.EHealthBoxClientTest.java
@Test public void testDecryptMessages() throws Exception { // STS//from w w w. j ava 2 s.co m EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService"); Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null); PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication"); KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12"); FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path()); eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray()); Enumeration<String> aliasesEnum = eHealthKeyStore.aliases(); String alias = aliasesEnum.nextElement(); X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias); PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias, this.config.getEHealthPKCS12Password().toCharArray()); String encryptionAlias = aliasesEnum.nextElement(); X509Certificate encryptionCertificate = (X509Certificate) eHealthKeyStore.getCertificate(encryptionAlias); PrivateKey encryptionPrivateKey = (PrivateKey) eHealthKeyStore.getKey(encryptionAlias, this.config.getEHealthPKCS12Password().toCharArray()); List<Attribute> attributes = new LinkedList<Attribute>(); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>(); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributeDesignators .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth", "urn:be:fgov:person:ssin:nurse:boolean")); Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate, eHealthPrivateKey, attributes, attributeDesignators); assertNotNull(assertion); String assertionString = client.toString(assertion); // eHealthBox EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient( "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3"); eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString); GetMessageListResponseType messageList = eHealthBoxClient.getMessagesList(); for (Message message : messageList.getMessage()) { String messageId = message.getMessageId(); LOG.debug("message id: " + messageId); GetFullMessageResponseType getFullMessageResponse = eHealthBoxClient.getMessage(messageId); DataHandler dataHandler = getFullMessageResponse.getMessage().getContentContext().getContent() .getDocument().getEncryptableBinaryContent(); byte[] data; if (null != dataHandler) { data = IOUtils.toByteArray(dataHandler.getInputStream()); } else { data = getFullMessageResponse.getMessage().getContentContext().getContent().getDocument() .getEncryptableTextContent(); } LOG.debug("data size: " + data.length); Unsealer unsealer = new Unsealer(encryptionPrivateKey, encryptionCertificate); unsealer.unseal(data); } }
From source file:ch.admin.suis.msghandler.config.ClientConfigurationFactory.java
/** * Initialize the factory with a XML file located at the given path. This is a relative path to a location somewhere * in the classpath.// w w w . j a v a2 s. c o m * Has to be called! */ @SuppressWarnings("unchecked") public void init() throws ConfigurationException { // set the unlimited policy directly. Siehe https://golb.hplar.ch/p/JCE-policy-changes-in-Java-SE-8u151-and-8u152 Security.setProperty("crypto.policy", "unlimited"); // load the BouncyCastle provider Security.addProvider(new BouncyCastleProvider()); checkSigningOutboxDirSet.clear(); // clear set... checkSigningProcessedDirSet.clear(); clientConfiguration.setSedexAdapterConfiguration(createSedexAdapterConfig(xmlConfig)); LOG.info("Sedex adapter configuration added, " + clientConfiguration.getSedexAdapterConfiguration()); final String baseDir = createBaseDir(xmlConfig); clientConfiguration.setWorkingDir(createWorkingDir(xmlConfig)); // SEDEX-175 - cleans the working dir up. cleanUpWorkingDir(clientConfiguration.getWorkingDir()); // Sets the outbox limit long secondsControllerBeforeSendingStuff = xmlConfig.getLong("messageHandler.minimumFileAge[@waitFor]", 0); if (secondsControllerBeforeSendingStuff == 0) { LOG.warn( "No delayer has been set with the key messageHandler.minimumFileAge.waitFor, which means every file " + "will be sent ASAP instead of waiting for a bit ! This is usually a bad idea for big files as " + "they tend to be slow..."); } Outbox.secondsBeforeSending = secondsControllerBeforeSendingStuff; //Sets the inbox limit long maximumInboxFiles = xmlConfig.getLong("messageHandler.maximumIncomingMessages[@accept]", Long.MAX_VALUE); if (maximumInboxFiles == 0) { LOG.error( "MessageHandler is configured to accept a maximum of 0 documents in each inbox. This is unacceptable."); throw new ConfigurationException("Cannot put 0 as a throttle for inboxes."); } Inbox.incomingMessageLimit = maximumInboxFiles; // **************** receiver-specific settings ReceiverConfiguration receiverConfiguration = setupReceiver(); // **************** checker-specific settings StatusCheckerConfiguration statusCheckerConfiguration = setupChecker(); final String defaultSenderCronValue = xmlConfig.getString("messageHandler.defaultOutboxCheck[@cron]"); if (StringUtils.isBlank(defaultSenderCronValue)) { throw new ConfigurationException("Missing attribute: messageHandler.defaultOutboxCheck[@cron]"); } // create default sender configuration - with the default cron final SenderConfiguration defaultSenderConfiguration = new SenderConfiguration(defaultSenderCronValue); setupNativeApps(defaultSenderConfiguration, baseDir, receiverConfiguration); if (!defaultSenderConfiguration.getOutboxes().isEmpty()) { // if the default config contains at least one outbox, add it to the client config clientConfiguration.addSenderConfiguration(defaultSenderConfiguration); // MANTIS 5023 LOG.info("sender added, " + defaultSenderConfiguration); } // Setting up transparent apps... setupTransparentApps(defaultSenderCronValue, baseDir, receiverConfiguration, statusCheckerConfiguration); // Launching jetty... setupHttpServer(); }
From source file:com.google.code.commons.checksum.digest.TestDigestUtils.java
@Before public void addBouncyCastleProvider() throws Exception { Security.addProvider(new BouncyCastleProvider()); }
From source file:mx.bigdata.sat.cfdi.TFDv1_v32.java
String getSignature(PrivateKey key) throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); byte[] bytes = getOriginalBytes(); Signature sig = Signature.getInstance("SHA1withRSA"); sig.initSign(key);//from w w w. j a v a 2s . com sig.update(bytes); byte[] signed = sig.sign(); Base64 b64 = new Base64(-1); return b64.encodeToString(signed); }
From source file:org.dataone.proto.trove.net.SocketFactoryManager.java
/** * Load PEM file contents into in-memory keystore NOTE: this implementation uses Bouncy Castle security provider * * @return the keystore that will provide the material * @throws KeyStoreException// ww w . j a va 2s. c o m * @throws CertificateException * @throws NoSuchAlgorithmException * @throws IOException */ private KeyStore getKeyStore() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { // if the location has been set, use it KeyStore keyStore = null; Object pemObject = null; keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, keyStorePassword.toCharArray()); // get the private key and certificate from the PEM // TODO: find a way to do this with default Java provider (not Bouncy Castle)? Security.addProvider(new BouncyCastleProvider()); PEMParser pemReader = new PEMParser(new FileReader(clientCertificateLocation)); X509Certificate certificate = null; PrivateKey privateKey = null; KeyPair keyPair = null; while ((pemObject = pemReader.readObject()) != null) { if (pemObject instanceof PrivateKey) { privateKey = (PrivateKey) pemObject; } else if (pemObject instanceof KeyPair) { keyPair = (KeyPair) pemObject; privateKey = keyPair.getPrivate(); } else if (pemObject instanceof X509Certificate) { certificate = (X509Certificate) pemObject; } } if (certificate == null) { log.warn("Certificate is null"); } else { if (certificate.getSubjectX500Principal().getName(X500Principal.RFC2253) .equals(certificate.getIssuerX500Principal().getName(X500Principal.RFC2253))) { log.warn("Certificate is Self Signed"); } } Certificate[] chain = new Certificate[] { certificate }; // set the entry keyStore.setKeyEntry("cilogon", privateKey, keyStorePassword.toCharArray(), chain); return keyStore; }