Java X509 Certificate Example in Java
Java Code Examples for java.security.cert.X509Certificate
The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.
Example 1
From project backend-update-center2, under directory /src/main/java/org/jvnet/hudson/update_center/.
Source file: Signer.java
60
private X509Certificate loadCertificate(CertificateFactory cf,File f) throws CertificateException, IOException { FileInputStream in=new FileInputStream(f); try { X509Certificate c=(X509Certificate)cf.generateCertificate(in); c.checkValidity(); return c; } finally { in.close(); } }
Example 2
From project candlepin, under directory /src/main/java/org/candlepin/pki/.
Source file: PKIUtility.java
39
public static X509Certificate createCert(byte[] certData){ try { CertificateFactory cf=CertificateFactory.getInstance("X509"); X509Certificate cert=(X509Certificate)cf.generateCertificate(new ByteArrayInputStream(certData)); return cert; } catch ( Exception e) { throw new RuntimeException(e); } }
Example 3
From project azure-sdk-for-java-samples, under directory /WAAD.WebSSO.JAVA/java/code/libraries/waad-federation/src/main/java/com/microsoft/samples/federation/.
Source file: SamlTokenValidator.java
33
private static boolean validateIssuerUsingSubjectName(SignableSAMLObject samlToken,String subjectName) throws UnmarshallingException, ValidationException, CertificateException { Signature signature=samlToken.getSignature(); KeyInfo keyInfo=signature.getKeyInfo(); X509Certificate pubKey=KeyInfoHelper.getCertificates(keyInfo).get(0); String issuer=pubKey.getSubjectDN().getName(); return issuer.equals(subjectName); }
Example 4
From project caseconductor-platform, under directory /utest-webservice/utest-webservice-client/src/main/java/com/utest/webservice/client/rest/.
Source file: AuthSSLX509TrustManager.java
32
/** * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[], * String authType) */ public void checkClientTrusted(X509Certificate[] certificates,String authType) throws CertificateException { if (certificates != null) { for (int c=0; c < certificates.length; c++) { X509Certificate cert=certificates[c]; System.out.println(" Client certificate " + (c + 1) + ":"); System.out.println(" Subject DN: " + cert.getSubjectDN()); System.out.println(" Signature Algorithm: " + cert.getSigAlgName()); System.out.println(" Valid from: " + cert.getNotBefore()); System.out.println(" Valid until: " + cert.getNotAfter()); System.out.println(" Issuer: " + cert.getIssuerDN()); } } defaultTrustManager.checkClientTrusted(certificates,authType); }
Example 5
From project components-ness-httpclient, under directory /client/src/main/java/com/nesscomputing/httpclient/internal/.
Source file: HttpClientTrustManagerFactory.java
29
@Nonnull private static X509TrustManager trustManagerFromKeystore(final KeyStore keystore) throws GeneralSecurityException { final TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance("PKIX","SunJSSE"); trustManagerFactory.init(keystore); final TrustManager[] tms=trustManagerFactory.getTrustManagers(); for ( TrustManager tm : tms) { if (tm instanceof X509TrustManager) { final X509TrustManager manager=(X509TrustManager)tm; X509Certificate[] acceptedIssuers=manager.getAcceptedIssuers(); LOG.debug("Found TrustManager with %d authorities.",acceptedIssuers.length); for (int i=0; i < acceptedIssuers.length; i++) { X509Certificate issuer=acceptedIssuers[i]; LOG.trace("Issuer #%d, subject DN=<%s>, serial=<%s>",i,issuer.getSubjectDN(),issuer.getSerialNumber()); } return manager; } } throw new IllegalStateException("Could not find an X509TrustManager"); }
Example 6
From project android_external_oauth, under directory /core/src/main/java/net/oauth/signature/.
Source file: RSA_SHA1.java
28
private PublicKey getPublicKeyFromPemCert(String certObject) throws GeneralSecurityException { CertificateFactory fac=CertificateFactory.getInstance("X509"); ByteArrayInputStream in=new ByteArrayInputStream(certObject.getBytes()); X509Certificate cert=(X509Certificate)fac.generateCertificate(in); return cert.getPublicKey(); }
Example 7
From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/conn/ssl/.
Source file: AbstractVerifier.java
27
public final boolean verify(String host,SSLSession session){ try { Certificate[] certs=session.getPeerCertificates(); X509Certificate x509=(X509Certificate)certs[0]; verify(host,x509); return true; } catch ( SSLException e) { return false; } }
Example 8
From project capedwarf-blue, under directory /appidentity/src/main/java/org/jboss/capedwarf/appidentity/.
Source file: JBossAppIdentityService.java
27
private CertificateBundle createNewCertificate(){ KeyPair keyPair=CertificateGenerator.getInstance().generateKeyPair(); String domain=EnvironmentFactory.getEnvironment().getDomain(); X509Certificate certificate=CertificateGenerator.getInstance().generateCertificate(keyPair,domain); return new CertificateBundle(certificate.getSerialNumber().toString(),keyPair,certificate); }
Example 9
From project cas, under directory /cas-server-support-x509/src/main/java/org/jasig/cas/adaptors/x509/authentication/principal/.
Source file: X509CertificateCredentials.java
27
public String toString(){ X509Certificate cert=null; if (getCertificate() != null) { cert=getCertificate(); } else if (getCertificates() != null && getCertificates().length > 1) { cert=getCertificates()[0]; } if (cert != null) { return CertUtils.toString(cert); } return super.toString(); }
Example 10
From project IOCipherServer, under directory /src/info/guardianproject/iocipher/server/.
Source file: KeyStoreGenerator.java
27
public static void generateKeyStore(File keyStoreFile,String alias,int keyLength,String password,String cn,String o,String ou,String l,String st,String c) throws Exception { final java.security.KeyPairGenerator rsaKeyPairGenerator=java.security.KeyPairGenerator.getInstance("RSA"); rsaKeyPairGenerator.initialize(keyLength); final KeyPair rsaKeyPair=rsaKeyPairGenerator.generateKeyPair(); Provider[] ps=Security.getProviders(); final KeyStore ks=KeyStore.getInstance("BKS"); ks.load(null); final RSAPublicKey rsaPublicKey=(RSAPublicKey)rsaKeyPair.getPublic(); char[] pw=password.toCharArray(); final RSAPrivateKey rsaPrivateKey=(RSAPrivateKey)rsaKeyPair.getPrivate(); final java.security.cert.X509Certificate certificate=makeCertificate(rsaPrivateKey,rsaPublicKey,cn,o,ou,l,st,c); final java.security.cert.X509Certificate[] certificateChain={certificate}; ks.setKeyEntry(alias,rsaKeyPair.getPrivate(),pw,certificateChain); final FileOutputStream fos=new FileOutputStream(keyStoreFile); ks.store(fos,pw); fos.close(); }
Example 11
From project isohealth, under directory /Oauth/java/core/commons/src/main/java/net/oauth/signature/.
Source file: RSA_SHA1.java
27
private PublicKey getPublicKeyFromDerCert(byte[] certObject) throws GeneralSecurityException { CertificateFactory fac=CertificateFactory.getInstance("X509"); ByteArrayInputStream in=new ByteArrayInputStream(certObject); X509Certificate cert=(X509Certificate)fac.generateCertificate(in); return cert.getPublicKey(); }
Example 12
@Override protected List<CertHolder> doInBackground(Void... params){ Set<String> aliases=mTab.getAliases(mStore); int max=aliases.size(); int progress=0; List<CertHolder> certHolders=new ArrayList<CertHolder>(max); for ( String alias : aliases) { X509Certificate cert=(X509Certificate)mStore.getCertificate(alias,true); certHolders.add(new CertHolder(mStore,TrustedCertificateAdapter.this,mTab,alias,cert)); publishProgress(++progress,max); } Collections.sort(certHolders); return certHolders; }
Example 13
From project DTE, under directory /src/cl/nic/dte/examples/.
Source file: EnviaDocumento.java
26
/** * @param args */ public static void main(String[] args) throws Exception { CmdLineParser parser=new CmdLineParser(); CmdLineParser.Option certOpt=parser.addStringOption('c',"cert"); CmdLineParser.Option passOpt=parser.addStringOption('s',"password"); CmdLineParser.Option compaOpt=parser.addStringOption('f',"compania"); try { parser.parse(args); } catch ( CmdLineParser.OptionException e) { printUsage(); System.exit(2); } String certS=(String)parser.getOptionValue(certOpt); String passS=(String)parser.getOptionValue(passOpt); String compaS=(String)parser.getOptionValue(compaOpt); if (certS == null || passS == null || compaS == null) { printUsage(); System.exit(2); } String[] otherArgs=parser.getRemainingArgs(); if (otherArgs.length != 1) { printUsage(); System.exit(2); } ConexionSii con=new ConexionSii(); KeyStore ks=KeyStore.getInstance("PKCS12"); ks.load(new FileInputStream(certS),passS.toCharArray()); String alias=ks.aliases().nextElement(); System.out.println("Usando certificado " + alias + " del archivo PKCS12: "+ certS); X509Certificate x509=(X509Certificate)ks.getCertificate(alias); PrivateKey pKey=(PrivateKey)ks.getKey(alias,passS.toCharArray()); String token=con.getToken(pKey,x509); System.out.println("Token: " + token); String enviadorS=Utilities.getRutFromCertificate(x509); RECEPCIONDTEDocument recp=con.uploadEnvioCertificacion(enviadorS,compaS,new File(otherArgs[0]),token); System.out.println(recp.xmlText()); }
Example 14
From project eucalyptus, under directory /clc/modules/axis2-transport/src/edu/ucsb/eucalyptus/transport/.
Source file: Axis2InOutMessageReceiver.java
26
private void verifyUser(MessageContext msgContext,EucalyptusMessage msg) throws EucalyptusCloudException { Vector<WSHandlerResult> wsResults=(Vector<WSHandlerResult>)msgContext.getProperty(WSHandlerConstants.RECV_RESULTS); for ( WSHandlerResult wsResult : wsResults) if (wsResult.getResults() != null) for ( WSSecurityEngineResult engResult : (Vector<WSSecurityEngineResult>)wsResult.getResults()) if (engResult.containsKey(WSSecurityEngineResult.TAG_X509_CERTIFICATE)) { X509Certificate cert=(X509Certificate)engResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE); msg=this.msgReceiver.getProperties().getAuthenticator().authenticate(cert,msg); } }
Example 15
From project gengweibo, under directory /src/net/oauth/signature/.
Source file: RSA_SHA1.java
26
private PublicKey getPublicKeyFromDerCert(byte[] certObject) throws GeneralSecurityException { CertificateFactory fac=CertificateFactory.getInstance("X509"); ByteArrayInputStream in=new ByteArrayInputStream(certObject); X509Certificate cert=(X509Certificate)fac.generateCertificate(in); return cert.getPublicKey(); }
Example 16
From project httpClient, under directory /httpclient/src/main/java/org/apache/http/conn/ssl/.
Source file: AbstractVerifier.java
26
public final boolean verify(String host,SSLSession session){ try { Certificate[] certs=session.getPeerCertificates(); X509Certificate x509=(X509Certificate)certs[0]; verify(host,x509); return true; } catch ( SSLException e) { return false; } }
Example 17
From project jentrata-msh, under directory /Plugins/CorvusAS2/src/main/java/hk/hku/cecid/edi/as2/dao/.
Source file: PartnershipDataSourceDVO.java
26
private X509Certificate getX509Certificate(byte[] bs){ try { InputStream certStream=new ByteArrayInputStream(bs); X509Certificate cert=(X509Certificate)CertificateFactory.getInstance("X.509").generateCertificate(certStream); return cert; } catch ( Exception e) { return null; } }
Example 18
From project bbb-java, under directory /src/main/java/org/transdroid/util/.
Source file: FakeTrustManager.java
25
@Override public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException { if (this.certKey == null) { return; } String our_key=this.certKey.replaceAll("\\s+",""); try { X509Certificate ss_cert=chain[0]; String thumbprint=FakeTrustManager.getThumbPrint(ss_cert); if (our_key.equalsIgnoreCase(thumbprint)) { return; } else { throw new CertificateException("Certificate key [" + thumbprint + "] doesn't match expected value."); } } catch ( NoSuchAlgorithmException e) { throw new CertificateException("Unable to check self-signed cert, unknown algorithm. " + e.toString()); } }
Example 19
From project dnieprov, under directory /src/org/dnieprov/jce/provider/.
Source file: DnieKeyStore.java
25
@Override public Certificate engineGetCertificate(String alias){ try { updateCards(); DnieSession session=getDnieSession4SubjectDN(alias); if (session != null) { Enumeration<X509Certificate> certs=driver.getCerts(session); while (certs.hasMoreElements()) { X509Certificate cert=certs.nextElement(); if (alias.equals(cert.getSubjectDN().toString())) { return cert; } } } } catch ( DnieDriverException ex) { } catch ( DnieDriverPinException ex) { } catch ( InvalidCardException ex) { } return null; }
Example 20
public static void generateSelfSignedCertificate(String hostname,File keystore,String keystorePassword){ try { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); KeyPairGenerator kpGen=KeyPairGenerator.getInstance("RSA","BC"); kpGen.initialize(1024,new SecureRandom()); KeyPair pair=kpGen.generateKeyPair(); X500NameBuilder builder=new X500NameBuilder(BCStyle.INSTANCE); builder.addRDN(BCStyle.OU,Constants.NAME); builder.addRDN(BCStyle.O,Constants.NAME); builder.addRDN(BCStyle.CN,hostname); Date notBefore=new Date(System.currentTimeMillis() - TimeUtils.ONEDAY); Date notAfter=new Date(System.currentTimeMillis() + 10 * TimeUtils.ONEYEAR); BigInteger serial=BigInteger.valueOf(System.currentTimeMillis()); X509v3CertificateBuilder certGen=new JcaX509v3CertificateBuilder(builder.build(),serial,notBefore,notAfter,builder.build(),pair.getPublic()); ContentSigner sigGen=new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC).build(pair.getPrivate()); X509Certificate cert=new JcaX509CertificateConverter().setProvider(BC).getCertificate(certGen.build(sigGen)); cert.checkValidity(new Date()); cert.verify(cert.getPublicKey()); KeyStore store=KeyStore.getInstance("JKS"); if (keystore.exists()) { FileInputStream fis=new FileInputStream(keystore); store.load(fis,keystorePassword.toCharArray()); fis.close(); } else { store.load(null); } store.setKeyEntry(hostname,pair.getPrivate(),keystorePassword.toCharArray(),new java.security.cert.Certificate[]{cert}); FileOutputStream fos=new FileOutputStream(keystore); store.store(fos,keystorePassword.toCharArray()); fos.close(); } catch ( Throwable t) { t.printStackTrace(); throw new RuntimeException("Failed to generate self-signed certificate!",t); } }
Example 21
From project GNDMS, under directory /kit/test-src/de/zib/gndms/kit/security/test/.
Source file: PemReaderTest.java
25
public static CertStuffHolder readKeyPair(File privateKey,char[] keyPassword) throws IOException { FileReader fileReader=new FileReader(privateKey); PEMReader pemReader=new PEMReader(fileReader,new DefaultPasswordFinder(keyPassword)); try { Object obj; ArrayList<X509Certificate> chain=new ArrayList<X509Certificate>(1); KeyPair keyPair=null; CertStuffHolder csh=new CertStuffHolder(); while ((obj=pemReader.readObject()) != null) { if (obj instanceof X509Certificate) { X509Certificate cert=(X509Certificate)obj; System.out.println("read cert: " + cert.toString()); chain.add(cert); } if (obj instanceof KeyPair) { keyPair=(KeyPair)obj; System.out.println("read keypair: " + keyPair.toString()); System.out.println("read keypair: " + keyPair.getPrivate()); System.out.println("read keypair: " + keyPair.getPublic()); } } csh.setChain(chain); csh.setKeyPair(keyPair); return csh; } catch ( IOException ex) { throw new IOException("The private key could not be decrypted",ex); } finally { pemReader.close(); fileReader.close(); } }
Example 22
public void checkServerTrusted(X509Certificate[] certificates,String type) throws CertificateException { if (this.trustLevel.equals(TrustLevel.OPEN)) { return; } try { this.standardTrustManager.checkServerTrusted(certificates,type); if (this.trustLevel.equals(TrustLevel.STRICT)) { logger.severe(TrustLevel.STRICT + " not implemented."); } } catch ( CertificateException e) { if (this.trustLevel.equals(TrustLevel.LOOSE) && certificates != null && certificates.length == 1) { X509Certificate certificate=certificates[0]; certificate.checkValidity(); } else { throw e; } } }
Example 23
From project https-utils, under directory /src/main/java/org/italiangrid/utils/voms/.
Source file: VOMSSecurityContext.java
25
@Override public void setClientCertChain(X509Certificate[] certChain){ super.setClientCertChain(certChain); if (validator == null) validator=new VOMSValidator(certChain); else validator.setClientChain(certChain); validator.validate(); }
Example 24
From project jclouds-chef, under directory /core/src/main/java/org/jclouds/chef/config/.
Source file: ChefParserModule.java
25
@Override public X509Certificate deserialize(JsonElement json,Type typeOfT,JsonDeserializationContext context) throws JsonParseException { String keyText=json.getAsString().replaceAll("\\n","\n"); try { return Pems.x509Certificate(InputSuppliers.of(keyText),crypto.certFactory()); } catch ( UnsupportedEncodingException e) { Throwables.propagate(e); return null; } catch ( IOException e) { Throwables.propagate(e); return null; } catch ( CertificateException e) { Throwables.propagate(e); return null; } }
Example 25
From project android_build, under directory /tools/signapk/.
Source file: SignApk.java
24
private static X509Certificate readPublicKey(File file) throws IOException, GeneralSecurityException { FileInputStream input=new FileInputStream(file); try { CertificateFactory cf=CertificateFactory.getInstance("X.509"); return (X509Certificate)cf.generateCertificate(input); } finally { input.close(); } }
Example 26
From project ereviewboard, under directory /org.review_board.ereviewboard.core/src/org/apache/commons/httpclient/contrib/ssl/.
Source file: EasyX509TrustManager.java
24
/** * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String authType) */ public void checkServerTrusted(X509Certificate[] certificates,String authType) throws CertificateException { if ((certificates != null) && (certificates.length == 1)) { certificates[0].checkValidity(); } else { standardTrustManager.checkServerTrusted(certificates,authType); } }
Example 27
From project hawtdispatch, under directory /hawtdispatch-transport/src/main/java/org/fusesource/hawtdispatch/transport/.
Source file: SslProtocolCodec.java
24
public X509Certificate[] getPeerX509Certificates(){ if (engine == null) { return null; } try { ArrayList<X509Certificate> rc=new ArrayList<X509Certificate>(); for ( Certificate c : engine.getSession().getPeerCertificates()) { if (c instanceof X509Certificate) { rc.add((X509Certificate)c); } } return rc.toArray(new X509Certificate[rc.size()]); } catch ( SSLPeerUnverifiedException e) { return null; } }
Example 28
From project 4308Cirrus, under directory /tendril-android-lib/src/main/java/edu/colorado/cs/cirrus/android/ssl/.
Source file: EasySSLSocketFactory.java
23
public EasySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(truststore); TrustManager tm=new X509TrustManager(){ public void checkClientTrusted( X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted( X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers(){ return null; } } ; sslContext.init(null,new TrustManager[]{tm},null); }
Example 29
From project alljoyn_java, under directory /test/org/alljoyn/bus/.
Source file: AuthListenerTest.java
23
public boolean requested(String mechanism,String authPeer,int count,String userName,AuthRequest[] requests){ for ( AuthRequest request : requests) { if (request instanceof CertificateRequest) { ((CertificateRequest)request).setCertificateChain(certificate); } else if (request instanceof PrivateKeyRequest) { if (privateKey != null) { ((PrivateKeyRequest)request).setPrivateKey(privateKey); } } else if (request instanceof PasswordRequest) { if (password != null) { ((PasswordRequest)request).setPassword(password); } } else if (request instanceof VerifyRequest) { String subject=null; try { String chain=((VerifyRequest)request).getCertificateChain(); BufferedInputStream in=new BufferedInputStream(new ByteArrayInputStream(chain.getBytes())); List<X509Certificate> list=new ArrayList<X509Certificate>(); while (in.available() > 0) { list.add((X509Certificate)factory.generateCertificate(in)); } subject=list.get(0).getSubjectX500Principal().getName(X500Principal.CANONICAL).split(",")[0].split("=")[1]; CertPath path=factory.generateCertPath(list); PKIXParameters params=new PKIXParameters(trustAnchors); params.setRevocationEnabled(false); validator.validate(path,params); verified=subject; } catch ( Exception ex) { rejected=subject; return false; } } } return true; }
Example 30
From project bitfluids, under directory /src/test/java/at/bitcoin_austria/bitfluids/.
Source file: NetTest.java
23
public static HttpClient wrapClient(HttpClient base){ try { SSLContext ctx=SSLContext.getInstance("TLS"); X509TrustManager tm=new X509TrustManager(){ @Override public void checkClientTrusted( X509Certificate[] xcs, String string) throws CertificateException { } @Override public void checkServerTrusted( X509Certificate[] xcs, String string) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers(){ return null; } } ; ctx.init(null,new TrustManager[]{tm},null); SSLSocketFactory ssf=new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm=base.getConnectionManager(); SchemeRegistry sr=ccm.getSchemeRegistry(); sr.register(new Scheme("https",ssf,443)); return new DefaultHttpClient(ccm,base.getParams()); } catch ( Exception ex) { throw new RuntimeException(ex); } }
Example 31
public AndroidSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(truststore); TrustManager tm=new X509TrustManager(){ public void checkClientTrusted( X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted( X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers(){ return null; } } ; sslContext.init(null,new TrustManager[]{tm},null); }
Example 32
From project cipango, under directory /cipango-server/src/main/java/org/cipango/server/bio/.
Source file: TlsConnector.java
23
/** * Return the chain of X509 certificates used to negotiate the SSL Session. <p> Note: in order to do this we must convert a javax.security.cert.X509Certificate[], as used by JSSE to a java.security.cert.X509Certificate[],as required by the Servlet specs. * @param sslSession the javax.net.ssl.SSLSession to use as the source of the cert chain. * @return the chain of java.security.cert.X509Certificates used to negotiate the SSLconnection. <br> Will be null if the chain is missing or empty. */ private static X509Certificate[] getCertChain(SSLSession sslSession){ try { javax.security.cert.X509Certificate javaxCerts[]=sslSession.getPeerCertificateChain(); if (javaxCerts == null || javaxCerts.length == 0) return null; int length=javaxCerts.length; X509Certificate[] javaCerts=new X509Certificate[length]; java.security.cert.CertificateFactory cf=java.security.cert.CertificateFactory.getInstance("X.509"); for (int i=0; i < length; i++) { byte bytes[]=javaxCerts[i].getEncoded(); ByteArrayInputStream stream=new ByteArrayInputStream(bytes); javaCerts[i]=(X509Certificate)cf.generateCertificate(stream); } return javaCerts; } catch ( SSLPeerUnverifiedException pue) { return null; } catch ( Exception e) { LOG.warn(Log.EXCEPTION,e); return null; } }
Example 33
From project cloudbees-api-client, under directory /cloudbees-api-client/src/main/java/com/cloudbees/api/.
Source file: TrustAllSocketFactory.java
23
public static SSLSocketFactory create(){ try { SSLContext context=SSLContext.getInstance("SSL"); context.init(null,new TrustManager[]{new X509TrustManager(){ public void checkClientTrusted( X509Certificate[] x509Certificates, String authType) throws CertificateException { } public void checkServerTrusted( X509Certificate[] x509Certificates, String authType) throws CertificateException { if (LOGGER.isLoggable(FINE)) LOGGER.fine("Got the certificate: " + Arrays.asList(x509Certificates)); } public X509Certificate[] getAcceptedIssuers(){ return new X509Certificate[0]; } } },new SecureRandom()); return context.getSocketFactory(); } catch ( NoSuchAlgorithmException e) { throw new Error(e); } catch ( KeyManagementException e) { throw new Error(e); } }
Example 34
From project cloudify, under directory /rest-client/src/main/java/org/cloudifysource/restclient/.
Source file: RestSSLSocketFactory.java
23
/** * Ctor. * @param truststore a {@link KeyStore} containing one or several trustedcertificates to enable server authentication. * @throws NoSuchAlgorithmException Reporting failure to create SSLSocketFactory with the given trust-store and algorithm TLS or initialize the SSLContext. * @throws KeyManagementException Reporting failure to create SSLSocketFactory with the given trust-store and algorithm TLS or initialize the SSLContext. * @throws KeyStoreException Reporting failure to create SSLSocketFactory with the given trust-store and algorithm TLS or initialize the SSLContext. * @throws UnrecoverableKeyException Reporting failure to create SSLSocketFactory with the given trust-store and algorithm TLS or initialize the SSLContext. */ public RestSSLSocketFactory(final KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(truststore); TrustManager tm=new X509TrustManager(){ @Override public X509Certificate[] getAcceptedIssuers(){ return null; } @Override public void checkClientTrusted( final X509Certificate[] chain, final String authType) throws java.security.cert.CertificateException { } @Override public void checkServerTrusted( final X509Certificate[] chain, final String authType) throws java.security.cert.CertificateException { } } ; sslContext.init(null,new TrustManager[]{tm},null); }
Example 35
public void checkServerTrusted(X509Certificate[] certificates,String authType) throws CertificateException { if ((certificates != null) && (certificates.length == 1)) { certificates[0].checkValidity(); } else { mDefaultTrustManager.checkServerTrusted(certificates,authType); } }
Example 36
From project dcm4che, under directory /dcm4che-conf/dcm4che-conf-ldap/src/main/java/org/dcm4che/conf/ldap/.
Source file: LdapDicomConfiguration.java
23
private void updateCertificates(Device prev,Device device) throws CertificateException, NamingException { for ( String dn : device.getAuthorizedNodeCertificateRefs()) { X509Certificate[] prevCerts=prev.getAuthorizedNodeCertificates(dn); updateCertificates(dn,prevCerts != null ? prevCerts : loadCertificates(dn),device.getAuthorizedNodeCertificates(dn)); } for ( String dn : device.getThisNodeCertificateRefs()) { X509Certificate[] prevCerts=prev.getThisNodeCertificates(dn); updateCertificates(dn,prevCerts != null ? prevCerts : loadCertificates(dn),device.getThisNodeCertificates(dn)); } }
Example 37
/** * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[], * String authType) */ public void checkServerTrusted(X509Certificate[] certificates,String authType) throws CertificateException { if ((certificates != null) && (certificates.length == 1)) { certificates[0].checkValidity(); } else { mStandardTrustManager.checkServerTrusted(certificates,authType); } }
Example 38
From project friendica-for-android, under directory /mw-android-friendica-01/src/de/wikilab/android/friendica01/.
Source file: TwAjax.java
23
public IgnoreCertsSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(truststore); TrustManager tm=new X509TrustManager(){ public void checkClientTrusted( X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted( X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers(){ return null; } } ; sslContext.init(null,new TrustManager[]{tm},null); }
Example 39
From project generic-store-for-android, under directory /src/com/wareninja/opensource/common/.
Source file: WareNinjaUtils.java
23
public static void trustEveryone(){ if (LOGGING.DEBUG) Log.d(TAG,"trustEveryone()"); try { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){ public boolean verify( String hostname, SSLSession session){ return true; } } ); SSLContext context=SSLContext.getInstance("TLS"); context.init(null,new X509TrustManager[]{new X509TrustManager(){ public void checkClientTrusted( X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted( X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers(){ return new X509Certificate[0]; } } },new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); } catch ( Exception e) { e.printStackTrace(); } }
Example 40
From project Gibberbot, under directory /src/info/guardianproject/otr/app/im/plugin/xmpp/.
Source file: ServerTrustManager.java
23
private void showCertMessage(String title,String msg,X509Certificate cert,String fingerprint){ Intent nIntent=new Intent(context,CertDisplayActivity.class); nIntent.putExtra("issuer",cert.getIssuerDN().getName()); nIntent.putExtra("subject",cert.getSubjectDN().getName()); if (fingerprint != null) nIntent.putExtra("fingerprint",fingerprint); nIntent.putExtra("issued",cert.getNotBefore().toGMTString()); nIntent.putExtra("expires",cert.getNotAfter().toGMTString()); showMessage(title,msg,nIntent); }
Example 41
From project groundhog-reader, under directory /src/main/java/com/almarsoft/GroundhogReader/lib/.
Source file: DomainNameChecker.java
23
/** * Checks the site certificate against the domain name of the site being visited * @param certificate The certificate to check * @param thisDomain The domain name of the site being visited * @return True iff if there is a domain match as specified by RFC2818 */ public static boolean match(X509Certificate certificate,String thisDomain){ if (certificate == null || thisDomain == null || thisDomain.length() == 0) { return false; } thisDomain=thisDomain.toLowerCase(); if (!isIpAddress(thisDomain)) { return matchDns(certificate,thisDomain); } else { return matchIpAddress(certificate,thisDomain); } }
leverettfrook1940.blogspot.com
Source: http://www.javased.com/index.php?api=java.security.cert.X509Certificate
0 Response to "Java X509 Certificate Example in Java"
Post a Comment