List of usage examples for java.security.cert CertificateFactory generateCertificate
public final Certificate generateCertificate(InputStream inStream) throws CertificateException
From source file:test.unit.be.agiv.security.handler.WSSecurityHandlerTest.java
private X509Certificate generateSelfSignedCertificate(KeyPair keyPair) throws Exception { X500Name issuer = new X500Name("CN=Test"); X500Name subject = issuer;//from w w w . jav a 2s .c om SecureRandom secureRandom = new SecureRandom(); byte[] serialValue = new byte[8]; secureRandom.nextBytes(serialValue); BigInteger serial = new BigInteger(serialValue); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusMonths(1); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore.toDate(), notAfter.toDate(), subject, publicKeyInfo); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter asymmetricKeyParameter = PrivateKeyFactory .createKey(keyPair.getPrivate().getEncoded()); ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId) .build(asymmetricKeyParameter); X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner); byte[] encodedCertificate = x509CertificateHolder.getEncoded(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(encodedCertificate)); return certificate; }
From source file:org.apache.hadoop.hdfsproxy.ProxyFilter.java
/** {@inheritDoc} */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest rqst = (HttpServletRequest) request; HttpServletResponse rsp = (HttpServletResponse) response; if (LOG.isDebugEnabled()) { StringBuilder b = new StringBuilder("Request from ").append(rqst.getRemoteHost()).append("/") .append(rqst.getRemoteAddr()).append(":").append(rqst.getRemotePort()); @SuppressWarnings("unchecked") Enumeration<String> e = rqst.getAttributeNames(); for (; e.hasMoreElements();) { String attribute = e.nextElement(); b.append("\n " + attribute + " => " + rqst.getAttribute(attribute)); }/*from ww w .j a v a 2 s. c o m*/ X509Certificate[] userCerts = (X509Certificate[]) rqst .getAttribute("javax.servlet.request.X509Certificate"); if (userCerts != null) for (X509Certificate cert : userCerts) b.append("\n Client certificate Subject Name is " + cert.getSubjectX500Principal().getName()); b.append("\n The Scheme is " + rqst.getScheme()); b.append("\n The Auth Type is " + rqst.getAuthType()); b.append("\n The Path Info is " + rqst.getPathInfo()); b.append("\n The Translated Path Info is " + rqst.getPathTranslated()); b.append("\n The Context Path is " + rqst.getContextPath()); b.append("\n The Query String is " + rqst.getQueryString()); b.append("\n The Remote User is " + rqst.getRemoteUser()); b.append("\n The User Principal is " + rqst.getUserPrincipal()); b.append("\n The Request URI is " + rqst.getRequestURI()); b.append("\n The Request URL is " + rqst.getRequestURL()); b.append("\n The Servlet Path is " + rqst.getServletPath()); LOG.debug(b.toString()); } boolean unitTest = false; if (rqst.getScheme().equalsIgnoreCase("http") && rqst.getParameter("UnitTest") != null) unitTest = true; if (rqst.getScheme().equalsIgnoreCase("https") || unitTest) { boolean isAuthorized = false; X509Certificate[] certs = (X509Certificate[]) rqst .getAttribute("javax.servlet.request.X509Certificate"); if (unitTest) { try { LOG.debug("==> Entering https unit test"); String SslPath = rqst.getParameter("SslPath"); InputStream inStream = new FileInputStream(SslPath); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream); inStream.close(); certs = new X509Certificate[] { cert }; } catch (Exception e) { // do nothing here } } if (certs == null || certs.length == 0) { rsp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No client SSL certificate received"); LOG.info("No Client SSL certificate received"); return; } for (X509Certificate cert : certs) { try { cert.checkValidity(); } catch (CertificateExpiredException e) { LOG.info("Received cert for " + cert.getSubjectX500Principal().getName() + " expired"); rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate expired"); return; } catch (CertificateNotYetValidException e) { LOG.info("Received cert for " + cert.getSubjectX500Principal().getName() + " is not yet valid"); rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate is not yet valid"); return; } } String[] tokens = certs[0].getSubjectX500Principal().getName().split("\\s*,\\s*"); String userID = null; for (String s : tokens) { if (s.startsWith("CN=")) { userID = s; break; } } if (userID == null || userID.length() < 4) { LOG.info("Can't retrieve user ID from SSL certificate"); rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Can't retrieve user ID from SSL certificate"); return; } userID = userID.substring(3); String servletPath = rqst.getServletPath(); if (unitTest) { servletPath = rqst.getParameter("TestSevletPathInfo"); LOG.info("this is for unit test purpose only"); } if (HFTP_PATTERN.matcher(servletPath).matches()) { // request is an HSFTP request if (FILEPATH_PATTERN.matcher(servletPath).matches()) { // file path as part of the URL isAuthorized = checkPath(userID, certs[0], rqst.getPathInfo() != null ? rqst.getPathInfo() : "/"); } else { // file path is stored in "filename" parameter isAuthorized = checkPath(userID, certs[0], rqst.getParameter("filename")); } } else if (RELOAD_PATTERN.matcher(servletPath).matches() && checkUser("Admin", certs[0])) { Configuration conf = new Configuration(false); conf.addResource("hdfsproxy-default.xml"); Map<String, Set<Path>> permsMap = getPermMap(conf); Map<String, Set<BigInteger>> certsMap = getCertsMap(conf); if (permsMap == null || certsMap == null) { LOG.warn("Permission files reloading failed"); rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Permission files reloading failed"); return; } ProxyFilter.permsMap = permsMap; ProxyFilter.certsMap = certsMap; LOG.info("User permissions and user certs files reloaded"); rsp.setStatus(HttpServletResponse.SC_OK); return; } if (!isAuthorized) { rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Unauthorized access"); return; } // request is authorized, set ugi for servlets UserGroupInformation ugi = UserGroupInformation.createRemoteUser(userID); rqst.setAttribute("authorized.ugi", ugi); rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.userID", userID); } else if (rqst.getScheme().equalsIgnoreCase("http")) { // http request, set ugi for servlets, only for testing purposes String ugi = rqst.getParameter("ugi"); if (ugi != null) { rqst.setAttribute("authorized.ugi", UserGroupInformation.createRemoteUser(ugi)); rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.userID", ugi.split(",")[0]); } } chain.doFilter(request, response); }
From source file:org.atricore.idbus.capabilities.clientcertauthn.X509CertificateAuthScheme.java
private X509Certificate buildX509Certificate(byte[] binaryCert) { X509Certificate cert = null;/*from www . j av a 2 s . co m*/ try { ByteArrayInputStream bais = new ByteArrayInputStream(binaryCert); CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(bais); if (logger.isDebugEnabled()) logger.debug("Building X.509 certificate result :\n " + cert); } catch (CertificateException ce) { logger.error("Error instantiating X.509 Certificate", ce); } return cert; }
From source file:com.chiorichan.http.ssl.CertificateWrapper.java
public CertificateWrapper(File sslCertFile, File sslKeyFile, String sslSecret) throws FileNotFoundException, CertificateException { if (!sslCertFile.exists()) throw new FileNotFoundException("The SSL Certificate '" + FileFunc.relPath(sslCertFile) + "' (aka. SSL Cert) file does not exist"); if (!sslKeyFile.exists()) throw new FileNotFoundException( "The SSL Key '" + FileFunc.relPath(sslKeyFile) + "' (aka. SSL Key) file does not exist"); this.sslCertFile = sslCertFile; this.sslKeyFile = sslKeyFile; this.sslSecret = sslSecret; CertificateFactory cf; try {/* w w w . j av a2s. c o m*/ cf = CertificateFactory.getInstance("X.509"); } catch (CertificateException e) { throw new IllegalStateException("Failed to initalize X.509 certificate factory."); } InputStream in = null; try { in = new FileInputStream(sslCertFile); cert = (X509Certificate) cf.generateCertificate(in); } finally { if (in != null) IOUtils.closeQuietly(in); } }
From source file:org.tolven.restful.AccountResourcesV0.java
/** * Add a user to a Tolven account//from w w w. j a v a2 s . c o m * The logged-in user must be a user on the account * Properties may also be added to the accountUser */ @Path("user/add") @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response addUser(@FormParam("user") String invitedUser, @FormParam("userX509Certificate") String invitedUserCertificate, @FormParam("account") String accountIdString, @FormParam("property") String property, @Context SecurityContext sc, MultivaluedMap<String, String> formParams) { if (invitedUser == null) { return Response.status(Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity("Missing User").build(); } if (accountIdString == null) { return Response.status(Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity("Missing Account Id") .build(); } Long accountId = null; try { accountId = Long.parseLong(accountIdString); } catch (Exception e) { return Response.status(Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity("Error parsing Account Id") .build(); } Account account = null; try { account = accountBean.findAccount(accountId); } catch (Exception e) { return Response.status(Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity("Invalid Account").build(); } // Make sure that the new user is not already an active member of the account AccountUser newAccountUser = accountBean.findAccountUser(invitedUser, accountId); if (newAccountUser != null) { return Response.status(Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN) .entity("User already a member of this account").build(); } Principal principal = request.getUserPrincipal(); AccountUser inviterAccountUser = accountBean.findAccountUser(principal.getName(), account.getId()); if (inviterAccountUser == null) { return Response.status(Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN) .entity("Inviting user must a member of this account").build(); } try { Date now = (Date) request.getAttribute("tolvenNow"); TolvenUser invitedTolvenUser = activationBean.findUser(invitedUser); if (invitedTolvenUser == null) { TolvenPerson tp = new TolvenPerson(); tp.setUid(invitedUser); invitedTolvenUser = loginBean.activate(tp, now); } String keyAlgorithm = propertyBean.getProperty(UserPrivateKey.USER_PRIVATE_KEY_ALGORITHM_PROP); TolvenSessionWrapper sessionWrapper = TolvenSessionWrapperFactory.getInstance(); PrivateKey inviterUserPrivateKey = sessionWrapper.getUserPrivateKey(keyAlgorithm); PublicKey invitedUserPublicKey = null; if (invitedUserCertificate != null) { byte[] userCertificateBytes = Base64 .decodeBase64(URLDecoder.decode(invitedUserCertificate, "UTF-8").getBytes("UTF-8")); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate x509Certificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(userCertificateBytes)); invitedUserPublicKey = x509Certificate.getPublicKey(); } /* * A userPublicKey is required for the added user, in order to protect the AccountPrivateKey, which will be associated with them * A null key means their data will not be encrypted in the account */ newAccountUser = accountBean.inviteAccountUser(account, inviterAccountUser, invitedTolvenUser, "tolven", inviterUserPrivateKey, now, false); //, invitedUserPublicKey } catch (Exception ex) { return Response.status(Status.INTERNAL_SERVER_ERROR).type(MediaType.TEXT_PLAIN) .entity("Adding a user to an Account must be done by a user with a UserPublicKey").build(); } URI uri = null; try { uri = new URI(URLEncoder.encode(Long.toString(newAccountUser.getId()), "UTF-8")); } catch (Exception e) { return Response.status(Status.INTERNAL_SERVER_ERROR).type(MediaType.TEXT_PLAIN) .entity(ExceptionFormatter.toSimpleString(e, "\\n")).build(); } return Response.created(uri).type(MediaType.TEXT_PLAIN).entity(String.valueOf(newAccountUser.getId())) .build(); }
From source file:com.zimbra.cs.service.authenticator.CertUtil.java
private void loadCert(String certFilePath) throws Exception { InputStream inStream = new FileInputStream(certFilePath); CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(inStream); inStream.close();/*from w w w . j a va2s.c o m*/ }
From source file:de.extra.client.plugins.outputplugin.transport.ExtraTransportHttp.java
/** * Sets up the Truststore./* ww w .ja v a 2 s . c o m*/ * * @param extraConnectData * @return */ private void setupTruststore(final HttpOutputPluginConnectConfiguration extraConnectData) throws ExtraTransportException { // Load TrustStoreLocation from properties String truststoreLocation = extraConnectData.getSslTruststoreLocation(); LOG.debug("TruststoreLoc: " + truststoreLocation); // If no location specified -> fallback to JRE default if (truststoreLocation == null || truststoreLocation.length() == 0) { truststoreLocation = System.getProperty("java.home") + File.separatorChar + "lib" + File.separatorChar + "security" + File.separatorChar + "cacerts"; } LOG.debug("TruststoreLoc: " + truststoreLocation); try { // Create keystore instance KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); // KeyStore ks = KeyStore.getInstance("PKCS12"); // Load keystore values FileInputStream fi = new FileInputStream(truststoreLocation); ks.load(fi, extraConnectData.getSslTruststorePassword().toCharArray()); fi.close(); // Create new certificate based on stored value java.security.cert.CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) certFactory .generateCertificate(new ByteArrayInputStream(extraConnectData.getSslCertificate().getBytes())); // Check if certificate is not already stored -> store and save if (extraConnectData.isSslCertificateRefresh() || ks.getCertificateAlias(cert) == null) { LOG.info("Zertifikat wird eingetragen"); ks.store(new FileOutputStream(truststoreLocation), extraConnectData.getSslTruststorePassword().toCharArray()); } // Set truststore location System.setProperty("javax.net.ssl.trustStore", truststoreLocation); } catch (KeyStoreException e) { throw new ExtraTransportException("Fehler bei Zugriff auf Keystore.", e); } catch (FileNotFoundException e) { throw new ExtraTransportException("Fehler beim Laden des Keystore.", e); } catch (NoSuchAlgorithmException e) { throw new ExtraTransportException("Fehler beim Laden des Crypto-Algorithmus.", e); } catch (CertificateException e) { throw new ExtraTransportException("Fehler beim Prfen des Zertifikats.", e); } catch (IOException e) { throw new ExtraTransportException("Fehler bei I/O-Operation.", e); } }
From source file:org.disrupted.rumble.database.statistics.StatisticManager.java
public void onEventAsync(LinkLayerStarted event) { if (!event.linkLayerIdentifier.equals(WifiLinkLayerAdapter.LinkLayerIdentifier)) return;//from ww w.j a va 2 s . co m if (RumblePreferences.UserOkWithSharingAnonymousData(RumbleApplication.getContext()) && RumblePreferences.isTimeToSync(RumbleApplication.getContext())) { if (!NetUtil.isURLReachable("http://disruptedsystems.org/")) return; try { // generate the JSON file byte[] json = generateStatJSON().toString().getBytes(); // configure SSL CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream caInput = new BufferedInputStream( RumbleApplication.getContext().getAssets().open("certs/disruptedsystemsCA.pem")); Certificate ca = cf.generateCertificate(caInput); String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); URL url = new URL("https://data.disruptedsystems.org/post"); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setSSLSocketFactory(sslContext.getSocketFactory()); // then configure the header urlConnection.setInstanceFollowRedirects(true); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setRequestProperty("charset", "utf-8"); urlConnection.setRequestProperty("Content-Length", Integer.toString(json.length)); urlConnection.setUseCaches(false); // connect and send the JSON urlConnection.setConnectTimeout(10 * 1000); urlConnection.connect(); urlConnection.getOutputStream().write(json); if (urlConnection.getResponseCode() != 200) throw new IOException("request failed"); // erase the database RumblePreferences.updateLastSync(RumbleApplication.getContext()); cleanDatabase(); } catch (Exception ex) { Log.e(TAG, "Failed to establish SSL connection to server: " + ex.toString()); } } }
From source file:FileSystemDirectoryCertStore.java
private void transverseDirToFindContent(File dir, Collection contentList, String[] certsFilesExts, String[] crlsFilesExts, CertificateFactory cf) throws CertificateException, CRLException { File[] dirContents = dir.listFiles(); for (int i = 0; i < dirContents.length; i++) { File f = dirContents[i];/*www . j a v a 2 s.c om*/ if (f.isDirectory()) transverseDirToFindContent(f, contentList, certsFilesExts, crlsFilesExts, cf); else if (f.isFile()) try { if (hasExt(f, certsFilesExts)) contentList.add((X509Certificate) cf.generateCertificate(new FileInputStream(f))); else if (hasExt(f, crlsFilesExts)) contentList.add((X509CRL) cf.generateCRL(new FileInputStream(f))); } catch (FileNotFoundException ex) { // The file existed right up there! If somehow it doesn't exist // now, nevermind. } } }
From source file:org.apache.nifi.web.security.x509.ocsp.OcspCertificateValidator.java
/** * Loads the ocsp certificate if specified. Null otherwise. * * @param properties nifi properties/*from ww w .j a v a 2 s. c om*/ * @return certificate */ private X509Certificate getOcspCertificate(final NiFiProperties properties) { X509Certificate validationAuthorityCertificate = null; final String validationAuthorityCertificatePath = properties .getProperty(NiFiProperties.SECURITY_OCSP_RESPONDER_CERTIFICATE); if (StringUtils.isNotBlank(validationAuthorityCertificatePath)) { try (final FileInputStream fis = new FileInputStream(validationAuthorityCertificatePath)) { final CertificateFactory cf = CertificateFactory.getInstance("X.509"); validationAuthorityCertificate = (X509Certificate) cf.generateCertificate(fis); } catch (final Exception e) { throw new IllegalStateException("Unable to load the validation authority certificate: " + e); } } return validationAuthorityCertificate; }