Java Code Examples for java.security.cert.CertificateException

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 groundhog-reader, under directory /src/main/java/com/almarsoft/GroundhogReader/lib/.

Source file: TrustManagerFactory.java

  33 
vote

public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException {
  try {
    mTrustManager.checkServerTrusted(chain,authType);
  }
 catch (  CertificateException ce) {
    logCertificates(chain,"Failed server",true);
    throw ce;
  }
  if (!DomainNameChecker.match(chain[0],mHost)) {
    logCertificates(chain,"Failed domain name",true);
    throw new CertificateException("Certificate domain name does not match " + mHost);
  }
}
 

Example 2

From project components-ness-httpclient, under directory /client/src/main/java/com/nesscomputing/httpclient/internal/.

Source file: MultiTrustManager.java

  31 
vote

@Override public void checkClientTrusted(final X509Certificate[] chain,final String authType) throws CertificateException {
  if (trustManagers.isEmpty()) {
    throw new CertificateException("No trust managers installed!");
  }
  CertificateException ce=null;
  for (  X509TrustManager trustManager : trustManagers) {
    try {
      trustManager.checkClientTrusted(chain,authType);
      return;
    }
 catch (    CertificateException trustCe) {
      ce=trustCe;
    }
  }
  throw ce;
}
 

Example 3

From project jentrata-msh, under directory /Commons/src/main/java/hk/hku/cecid/piazza/commons/security/.

Source file: KeyStoreTrustManager.java

  31 
vote

/** 
 * Checks if any certificate in the certificate chain is stored in the key store.
 * @param chain the certificate chain.
 * @return true if any certificate in the certificate chain is stored in the key store.
 * @throws IllegalArgumentException if null or zero-length chain is passed in for the chain parameter or if null or zero-length string is passed in  for the authType parameter. 
 * @throws CertificateException if the certificate chain is not trusted by this TrustManager.
 */
private void checkTrusted(X509Certificate[] chain) throws CertificateException {
  if (chain == null || chain.length == 0) {
    throw new IllegalArgumentException("Null or zero length chain");
  }
  if (!isChainTrusted(chain)) {
    throw new CertificateException("Certificate chain not trusted");
  }
}
 

Example 4

From project JGlobus, under directory /ssl-proxies/src/main/java/org/globus/gsi/bc/.

Source file: BouncyCastleUtil.java

  31 
vote

/** 
 * Returns certificate type of the given certificate.  Please see  {@link #getCertificateType(TBSCertificateStructure,TrustedCertificates) getCertificateType} for details for determining the certificate type.
 * @param cert the certificate to get the type of.
 * @param trustedCerts the trusted certificates to double check the {@link GSIConstants#EEC GSIConstants.EEC} certificate against.
 * @return the certificate type as determined by {@link #getCertificateType(TBSCertificateStructure,TrustedCertificates) getCertificateType}.
 * @exception CertificateException if something goes wrong.
 * @deprecated
 */
public static GSIConstants.CertificateType getCertificateType(X509Certificate cert,TrustedCertificates trustedCerts) throws CertificateException {
  try {
    return getCertificateType(cert,TrustedCertificatesUtil.createCertStore(trustedCerts));
  }
 catch (  Exception e) {
    throw new CertificateException("",e);
  }
}
 

Example 5

From project serengeti-ws, under directory /vcext/src/main/java/com/vmware/serengeti/.

Source file: ThumbprintTrustManager.java

  31 
vote

@Override public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException {
  if (chain.length == 0) {
    logger.warn("No certificates in chain");
    throw new CertificateException();
  }
  String tp=certificateToThumbprint(chain[0]);
  if (!hasThumbprint(tp)) {
    logger.warn("Invalid SSL thumbprint received: " + tp);
    throw new CertificateException();
  }
}
 

Example 6

From project bbb-java, under directory /src/main/java/org/transdroid/util/.

Source file: FakeTrustManager.java

  30 
vote

@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 7

From project jftp, under directory /src/main/java/com/myjavaworld/jftp/ssl/.

Source file: JFTPTrustManager.java

  30 
vote

public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException {
  if (this.chain != null) {
    if (Arrays.equals(chain,this.chain)) {
      return;
    }
  }
  boolean validDate=isValidDate(chain);
  boolean validHost=isValidHost(chain);
  boolean trusted=isTrusted(chain);
  if (!validDate || !validHost || !trusted) {
    int userOption=SecurityWarningDlg.showDialog(jftp,chain,validDate,validHost,trusted);
    if (userOption != SecurityWarningDlg.YES_OPTION) {
      throw new CertificateException("No trusted certificate found. ");
    }
    this.chain=chain;
  }
 else {
    this.chain=chain;
  }
}
 

Example 8

From project k-9, under directory /src/com/fsck/k9/mail/store/.

Source file: TrustManagerFactory.java

  30 
vote

public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException {
  TrustManagerFactory.setLastCertChain(chain);
  try {
    defaultTrustManager.checkServerTrusted(chain,authType);
  }
 catch (  CertificateException e) {
    localTrustManager.checkServerTrusted(new X509Certificate[]{chain[0]},authType);
  }
  if (!DomainNameChecker.match(chain[0],mHost)) {
    try {
      String dn=chain[0].getSubjectDN().toString();
      if ((dn != null) && (dn.equalsIgnoreCase(keyStore.getCertificateAlias(chain[0])))) {
        return;
      }
    }
 catch (    KeyStoreException e) {
      throw new CertificateException("Certificate cannot be verified; KeyStore Exception: " + e);
    }
    throw new CertificateException("Certificate domain name does not match " + mHost);
  }
}
 

Example 9

From project picketbox-keystore, under directory /src/main/java/org/picketbox/keystore/util/.

Source file: CertificateUtil.java

  30 
vote

/** 
 * Create a X509 V1  {@link Certificate}
 * @param pair {@link KeyPair}
 * @param numberOfDays Number of days the certificate will be valid
 * @param DN The DN of the subject
 * @return
 * @throws CertificateException
 */
public Certificate createX509V1Certificate(KeyPair pair,int numberOfDays,String DN) throws CertificateException {
  try {
    AlgorithmIdentifier sigAlgId=new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
    AlgorithmIdentifier digAlgId=new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter privateKeyAsymKeyParam=PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
    SubjectPublicKeyInfo subPubKeyInfo=SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
    ContentSigner sigGen=new BcRSAContentSignerBuilder(sigAlgId,digAlgId).build(privateKeyAsymKeyParam);
    Date startDate=new Date(System.currentTimeMillis() - 24 * 60 * 60* 1000);
    Date endDate=new Date(System.currentTimeMillis() + numberOfDays * 24 * 60* 60* 1000);
    X500Name name=new X500Name(DN);
    BigInteger serialNum=createSerialNumber();
    X509v1CertificateBuilder v1CertGen=new X509v1CertificateBuilder(name,serialNum,startDate,endDate,name,subPubKeyInfo);
    X509CertificateHolder certificateHolder=v1CertGen.build(sigGen);
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
  }
 catch (  CertificateException e1) {
    throw e1;
  }
catch (  Exception e) {
    throw new CertificateException(e);
  }
}
 

Example 10

From project QuasselDroid, under directory /src/com/iskrembilen/quasseldroid/io/.

Source file: CustomTrustManager.java

  30 
vote

public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException, NewCertificateException {
  try {
    defaultTrustManager.checkServerTrusted(chain,authType);
  }
 catch (  CertificateException excep) {
    String hashedCert=hash(chain[0].getEncoded());
    SharedPreferences preferences=this.coreConnection.service.getSharedPreferences("CertificateStorage",Context.MODE_PRIVATE);
    if (preferences.contains("certificate")) {
      if (!preferences.getString("certificate","lol").equals(hashedCert)) {
        throw new CertificateException();
      }
    }
 else {
      throw new NewCertificateException(hashedCert);
    }
  }
}
 

Example 11

From project skmclauncher, under directory /src/main/java/com/sk89q/mclauncher/security/.

Source file: X509KeyStore.java

  30 
vote

/** 
 * Check if a server certificate chain is trusted.
 */
@Override public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException {
  for (  X509Certificate cert : chain) {
    cert.checkValidity();
    if (cert.hasUnsupportedCriticalExtension()) {
      throw new CertificateException("Unsupported critical extension found");
    }
  }
  try {
    verify(chain);
  }
 catch (  CertificateVerificationException e) {
    throw new CertificateException("Verification error: " + e.getMessage(),e);
  }
catch (  CertPathBuilderException e) {
    throw new CertificateException(e.getMessage(),e);
  }
}
 

Example 12

From project SMSSync, under directory /smssync/src/org/addhen/smssync/net/.

Source file: TrustManagerFactory.java

  30 
vote

public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException {
  TrustManagerFactory.setLastCertChain(chain);
  try {
    defaultTrustManager.checkServerTrusted(chain,authType);
  }
 catch (  CertificateException e) {
    localTrustManager.checkServerTrusted(new X509Certificate[]{chain[0]},authType);
  }
  try {
    String dn=chain[0].getSubjectDN().toString();
    if ((dn != null) && (dn.equalsIgnoreCase(keyStore.getCertificateAlias(chain[0])))) {
      return;
    }
  }
 catch (  KeyStoreException e) {
    throw new CertificateException("Certificate cannot be verified; KeyStore Exception: " + e);
  }
  throw new CertificateException("Certificate domain name does not match " + mHost);
}
 

Example 13

From project spring-security-saml, under directory /saml2-core/src/main/java/org/springframework/security/saml/trust/.

Source file: X509TrustManager.java

  30 
vote

public void checkServerTrusted(X509Certificate[] x509Certificates,String s) throws CertificateException {
  if (x509Certificates == null || x509Certificates.length == 0) {
    throw new IllegalArgumentException("Null or empty certificates list");
  }
  BasicX509Credential credential=new BasicX509Credential();
  X509Certificate x509Certificate=x509Certificates[0];
  credential.setEntityCertificate(x509Certificate);
  credential.setEntityCertificateChain(Arrays.asList(x509Certificates));
  credential.setUsageType(UsageType.UNSPECIFIED);
  credential.setEntityId(criteriaSet.get(EntityIDCriteria.class).getEntityID());
  try {
    log.debug("Checking server trust");
    if (trustEngine.validate(credential,criteriaSet)) {
      log.debug("Server certificate trust verified");
    }
 else {
      Principal issuerDN=x509Certificate.getIssuerDN();
      Principal subjectDN=x509Certificate.getSubjectDN();
      StringBuilder sb=new StringBuilder(120);
      sb.append("Peer SSL/TLS certificate '").append(subjectDN).append("' ");
      sb.append("issued by '").append(issuerDN).append("' ");
      sb.append("is not trusted, add the certificate or it's CA to your trust store and optionally update tlsKey in extended metadata with the certificate's alias");
      throw new UntrustedCertificateException(sb.toString(),x509Certificates);
    }
  }
 catch (  org.opensaml.xml.security.SecurityException e) {
    throw new CertificateException("Error validating certificate",e);
  }
}
 

Example 14

From project 4308Cirrus, under directory /tendril-android-lib/src/main/java/edu/colorado/cs/cirrus/android/ssl/.

Source file: EasySSLSocketFactory.java

  29 
vote

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 15

From project androidpn, under directory /androidpn-server-bin-tomcat/src/org/androidpn/server/xmpp/ssl/.

Source file: SSLKeyManagerFactory.java

  29 
vote

public static KeyManager[] getKeyManagers(String storeType,String keystore,String keypass) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException {
  KeyManager[] keyManagers;
  if (keystore == null) {
    keyManagers=null;
  }
 else {
    if (keypass == null) {
      keypass="";
    }
    KeyStore keyStore=KeyStore.getInstance(storeType);
    keyStore.load(new FileInputStream(keystore),keypass.toCharArray());
    KeyManagerFactory keyFactory=KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyFactory.init(keyStore,keypass.toCharArray());
    keyManagers=keyFactory.getKeyManagers();
  }
  return keyManagers;
}
 

Example 16

From project android_packages_apps_Exchange, under directory /src/com/android/exchange/.

Source file: EasSyncService.java

  29 
vote

/** 
 * Create an EasSyncService for the specified account
 * @param context the caller's context
 * @param account the account
 * @return the service, or null if the account is on hold or hasn't been initialized
 */
public static EasSyncService setupServiceForAccount(Context context,Account account){
  if ((account.mFlags & Account.FLAGS_SECURITY_HOLD) != 0) {
    return null;
  }
  String protocolVersion=account.mProtocolVersion;
  if (protocolVersion == null) {
    return null;
  }
  EasSyncService svc=new EasSyncService("OutOfBand");
  HostAuth ha=HostAuth.restoreHostAuthWithId(context,account.mHostAuthKeyRecv);
  svc.mProtocolVersion=protocolVersion;
  svc.mProtocolVersionDouble=Eas.getProtocolVersionDouble(protocolVersion);
  svc.mContext=context;
  svc.mHostAddress=ha.mAddress;
  svc.mUserName=ha.mLogin;
  svc.mPassword=ha.mPassword;
  try {
    svc.setConnectionParameters((ha.mFlags & HostAuth.FLAG_SSL) != 0,(ha.mFlags & HostAuth.FLAG_TRUST_ALL) != 0,ha.mClientCertAlias);
    svc.mDeviceId=ExchangeService.getDeviceId(context);
  }
 catch (  IOException e) {
    return null;
  }
catch (  CertificateException e) {
    return null;
  }
  svc.mAccount=account;
  return svc;
}
 

Example 17

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

  29 
vote

private static boolean validateToken(SignableSAMLObject samlToken) throws SecurityException, ValidationException, ConfigurationException, UnmarshallingException, CertificateException, KeyException {
  samlToken.validate(true);
  Signature signature=samlToken.getSignature();
  KeyInfo keyInfo=signature.getKeyInfo();
  X509Certificate pubKey=(X509Certificate)KeyInfoHelper.getCertificates(keyInfo).get(0);
  BasicX509Credential cred=new BasicX509Credential();
  cred.setEntityCertificate(pubKey);
  cred.setEntityId("signing-entity-ID");
  ArrayList<Credential> trustedCredentials=new ArrayList<Credential>();
  trustedCredentials.add(cred);
  CollectionCredentialResolver credResolver=new CollectionCredentialResolver(trustedCredentials);
  KeyInfoCredentialResolver kiResolver=SecurityTestHelper.buildBasicInlineKeyInfoResolver();
  ExplicitKeySignatureTrustEngine engine=new ExplicitKeySignatureTrustEngine(credResolver,kiResolver);
  CriteriaSet criteriaSet=new CriteriaSet();
  criteriaSet.add(new EntityIDCriteria("signing-entity-ID"));
  return engine.validate(signature,criteriaSet);
}
 

Example 18

From project backend-update-center2, under directory /src/main/java/org/jvnet/hudson/update_center/.

Source file: Signer.java

  29 
vote

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 19

From project bitfluids, under directory /src/test/java/at/bitcoin_austria/bitfluids/.

Source file: NetTest.java

  29 
vote

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 20

From project BombusLime, under directory /src/org/bombusim/networking/.

Source file: AndroidSSLSocketFactory.java

  29 
vote

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 21

From project candlepin, under directory /src/main/java/org/candlepin/pinsetter/tasks/.

Source file: CertificateRevocationListTask.java

  29 
vote

@Override public void execute(JobExecutionContext ctx) throws JobExecutionException {
  String filePath=config.getString(ConfigProperties.CRL_FILE_PATH);
  log.info("Executing CRL Job. CRL filePath=" + filePath);
  if (filePath == null) {
    throw new JobExecutionException("Invalid " + ConfigProperties.CRL_FILE_PATH,false);
  }
  try {
    File crlFile=new File(filePath);
    X509CRL crl=crlFileUtil.readCRLFile(crlFile);
    crl=crlGenerator.syncCRLWithDB(crl);
    crlFileUtil.writeCRLFile(crlFile,crl);
  }
 catch (  CRLException e) {
    log.error(e);
    throw new JobExecutionException(e,false);
  }
catch (  CertificateException e) {
    log.error(e);
    throw new JobExecutionException(e,false);
  }
catch (  IOException e) {
    log.error(e);
    throw new JobExecutionException(e,false);
  }
}
 

Example 22

From project capedwarf-blue, under directory /appidentity/src/main/java/org/jboss/capedwarf/appidentity/.

Source file: CertificateGenerator.java

  29 
vote

public X509Certificate generateCertificate(KeyPair pair,String dn){
  try {
    X509v3CertificateBuilder builder=new X509v3CertificateBuilder(new X500Name("CN=" + dn),BigInteger.valueOf(new SecureRandom().nextLong()),new Date(System.currentTimeMillis() - 10000),new Date(System.currentTimeMillis() + 24L * 3600 * 1000),new X500Name("CN=" + dn),SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded()));
    builder.addExtension(X509Extension.basicConstraints,true,new BasicConstraints(false));
    builder.addExtension(X509Extension.keyUsage,true,new KeyUsage(KeyUsage.digitalSignature));
    builder.addExtension(X509Extension.extendedKeyUsage,true,new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
    X509CertificateHolder holder=builder.build(createContentSigner(pair));
    Certificate certificate=holder.toASN1Structure();
    return convertToJavaCertificate(certificate);
  }
 catch (  CertificateEncodingException e) {
    throw new RuntimeException("Cannot generate X509 certificate",e);
  }
catch (  OperatorCreationException e) {
    throw new RuntimeException("Cannot generate X509 certificate",e);
  }
catch (  CertIOException e) {
    throw new RuntimeException("Cannot generate X509 certificate",e);
  }
catch (  IOException e) {
    throw new RuntimeException("Cannot generate X509 certificate",e);
  }
catch (  CertificateException e) {
    throw new RuntimeException("Cannot generate X509 certificate",e);
  }
}
 

Example 23

From project cas, under directory /cas-server-support-x509/src/main/java/org/jasig/cas/adaptors/x509/util/.

Source file: CertUtils.java

  29 
vote

/** 
 * Gets a certificate factory for creating X.509 artifacts.
 * @return X509 certificate factory.
 */
public static CertificateFactory getCertificateFactory(){
  try {
    return CertificateFactory.getInstance(X509_CERTIFICATE_TYPE);
  }
 catch (  final CertificateException e) {
    throw new IllegalStateException("X509 certificate type not supported by default provider.");
  }
}
 

Example 24

From project caseconductor-platform, under directory /utest-webservice/utest-webservice-client/src/main/java/com/utest/webservice/client/rest/.

Source file: AuthSSLProtocolSocketFactory.java

  29 
vote

private static KeyStore createKeyStore(final URL url,final String password) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
  if (url == null) {
    throw new IllegalArgumentException("Keystore url may not be null");
  }
  KeyStore keystore=KeyStore.getInstance("jks");
  InputStream is=null;
  try {
    is=url.openStream();
    keystore.load(is,password != null ? password.toCharArray() : null);
  }
  finally {
    if (is != null)     is.close();
  }
  return keystore;
}
 

Example 25

From project cloudbees-api-client, under directory /cloudbees-api-client/src/main/java/com/cloudbees/api/.

Source file: TrustAllSocketFactory.java

  29 
vote

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 26

From project cloudify, under directory /esc/src/main/java/org/cloudifysource/esc/driver/provisioning/azure/client/.

Source file: MicrosoftAzureSSLHelper.java

  29 
vote

/** 
 * @return .
 * @throws NoSuchAlgorithmException .
 * @throws KeyStoreException .
 * @throws CertificateException .
 * @throws IOException .
 * @throws UnrecoverableKeyException .
 * @throws KeyManagementException .
 */
public SSLContext createSSLContext() throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException {
  InputStream pfxFile=null;
  SSLContext context=null;
  try {
    pfxFile=new FileInputStream(new File(pathToPfxFile));
    KeyManagerFactory keyManagerFactory=KeyManagerFactory.getInstance(SUN_X_509_ALGORITHM);
    KeyStore keyStore=KeyStore.getInstance(KEY_STORE_CONTEXT);
    keyStore.load(pfxFile,pfxPassword.toCharArray());
    pfxFile.close();
    keyManagerFactory.init(keyStore,pfxPassword.toCharArray());
    context=SSLContext.getInstance("SSL");
    context.init(keyManagerFactory.getKeyManagers(),null,new SecureRandom());
    return context;
  }
  finally {
    if (pfxFile != null) {
      pfxFile.close();
    }
  }
}
 

Example 27

From project Cours-3eme-ann-e, under directory /Java/FerryInpres/src/identity_server/.

Source file: IdentityServer.java

  29 
vote

private void login(ObjectInputStream in,ObjectOutputStream out,Cipher cryptor,Cipher decryptor) throws IOException, IllegalBlockSizeException, BadPaddingException, ClassNotFoundException, SQLException, NoSuchAlgorithmException, KeyStoreException, CertificateException, UnrecoverableKeyException, KeyManagementException {
  int serverSalt=(new Random()).nextInt();
  byte[] d=Utils.cryptObject(new LoginServer(serverSalt),cryptor);
  out.writeObject(d);
  out.flush();
  LoginClient response=(LoginClient)Utils.decryptObject((byte[])in.readObject(),decryptor);
  PreparedStatement instruc=this._con.prepareStatement("SELECT mot_de_passe " + "FROM agent " + "WHERE nom = ?");
  instruc.setString(1,response.getName());
  ResultSet rs=instruc.executeQuery();
  byte[] hashedPassword;
  if (rs.next()) {
    String password=rs.getString("mot_de_passe");
    hashedPassword=Utils.hashPassword(password,response.getClient_salt(),serverSalt);
  }
 else {
    hashedPassword=null;
  }
  if (hashedPassword != null && Arrays.equals(hashedPassword,response.getPassword_hashed())) {
    out.writeObject(Utils.cryptObject(new Ack(),cryptor));
    out.flush();
    verifId(in,out,cryptor,decryptor);
  }
 else {
    out.writeObject(Utils.cryptObject(new Fail(),cryptor));
    out.flush();
  }
}
 

Example 28

From project cp-common-utils, under directory /src/com/clarkparsia/common/net/.

Source file: BasicX509TrustManager.java

  29 
vote

public void checkServerTrusted(X509Certificate[] certificates,String authType) throws CertificateException {
  if ((certificates != null) && (certificates.length == 1)) {
    certificates[0].checkValidity();
  }
 else {
    mDefaultTrustManager.checkServerTrusted(certificates,authType);
  }
}
 

Example 29

From project dcm4che, under directory /dcm4che-conf/dcm4che-conf-ldap/src/main/java/org/dcm4che/conf/ldap/.

Source file: ExtendedLdapDicomConfiguration.java

  29 
vote

@Override protected void loadFrom(Device device,Attributes attrs) throws NamingException, CertificateException {
  super.loadFrom(device,attrs);
  if (!hasObjectClass(attrs,"dcmDevice"))   return;
  device.setLimitOpenAssociations(intValue(attrs.get("dcmLimitOpenAssociations"),0));
  device.setTrustStoreURL(stringValue(attrs.get("dcmTrustStoreURL")));
  device.setTrustStoreType(stringValue(attrs.get("dcmTrustStoreType")));
  device.setTrustStorePin(stringValue(attrs.get("dcmTrustStorePin")));
  device.setTrustStorePinProperty(stringValue(attrs.get("dcmTrustStorePinProperty")));
  device.setKeyStoreURL(stringValue(attrs.get("dcmKeyStoreURL")));
  device.setKeyStoreType(stringValue(attrs.get("dcmKeyStoreType")));
  device.setKeyStorePin(stringValue(attrs.get("dcmKeyStorePin")));
  device.setKeyStorePinProperty(stringValue(attrs.get("dcmKeyStorePinProperty")));
  device.setKeyStoreKeyPin(stringValue(attrs.get("dcmKeyStoreKeyPin")));
  device.setKeyStoreKeyPinProperty(stringValue(attrs.get("dcmKeyStoreKeyPinProperty")));
}
 

Example 30

From project dnieprov, under directory /src/org/dnieprov/driver/.

Source file: DnieDriver.java

  29 
vote

private void setCerts(DnieInterface inter,DnieCardImpl card) throws DnieDriverException, InvalidCardException {
  byte[] zlibCert=null;
  byte[] unzCert=null;
  try {
    Iterator<DnieP15Record> iterator=card.getInfo();
    CertificateFactory cf=CertificateFactory.getInstance("X.509");
    while (iterator.hasNext()) {
      DnieP15Record rec=iterator.next();
      ParamReference param=new ParamReference();
      int apduError=inter.getCertificate(rec.getPath(),param);
      if (apduError != ApduCommand.SW_OK) {
        throw new ApduErrorException(apduError);
      }
      zlibCert=(byte[])param.getValue();
      unzCert=deflate(zlibCert);
      card.addCertificate(rec.getCkaId(),(X509Certificate)cf.generateCertificate(new ByteArrayInputStream(unzCert)));
      Arrays.fill(zlibCert,DnieInterface.NULL_BYTE);
      Arrays.fill(unzCert,DnieInterface.NULL_BYTE);
      zlibCert=null;
      unzCert=null;
    }
  }
 catch (  CertificateException ex) {
    card.removeCerts();
    throw new DnieUnexpectedException("Error decoding compressed certificate",ex);
  }
catch (  CardException ex) {
    card.removeCerts();
    throw new DnieDriverException(ex);
  }
catch (  ApduErrorException ex) {
    card.removeCerts();
    throw new DnieDriverException(ex);
  }
 finally {
    if (zlibCert != null)     Arrays.fill(zlibCert,DnieInterface.NULL_BYTE);
    if (unzCert != null)     Arrays.fill(unzCert,DnieInterface.NULL_BYTE);
  }
}
 

Example 31

From project dreamDroid, under directory /src/net/reichholf/dreamdroid/helpers/.

Source file: EasyX509TrustManager.java

  29 
vote

/** 
 * @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 32

From project ereviewboard, under directory /org.review_board.ereviewboard.core/src/org/apache/commons/httpclient/contrib/ssl/.

Source file: EasyX509TrustManager.java

  29 
vote

/** 
 * @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 33

From project friendica-for-android, under directory /mw-android-friendica-01/src/de/wikilab/android/friendica01/.

Source file: TwAjax.java

  29 
vote

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 34

From project generic-store-for-android, under directory /src/com/wareninja/opensource/common/.

Source file: WareNinjaUtils.java

  29 
vote

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 35

From project GNDMS, under directory /common/src/de/zib/gndms/common/kit/security/.

Source file: SetupSSL.java

  29 
vote

public void prepareKeyStore(final String keyStorePassword,final String keyStoreType) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException {
  if (null == keyStoreLocation) {
    keyStore=KeyStore.getInstance(keyStoreType);
    keyStore.load(null,keyStorePassword.toCharArray());
  }
 else {
    InputStream kis=new FileInputStream(keyStoreLocation);
    keyStore=KeyStore.getInstance(keyStoreType);
    keyStore.load(kis,keyStorePassword.toCharArray());
  }
}
 

Example 36

From project Haven-and-Hearth-client-modified-by-Ender, under directory /src/haven/.

Source file: SslHelper.java

  29 
vote

public synchronized void loadCredsPkcs12(InputStream in,char[] pw) throws IOException, CertificateException {
  clear();
  try {
    creds=KeyStore.getInstance("PKCS12");
    creds.load(in,pw);
    this.pw=pw;
  }
 catch (  KeyStoreException e) {
    throw (new Error(e));
  }
catch (  NoSuchAlgorithmException e) {
    throw (new Error(e));
  }
}
 

Example 37

From project heritrix3, under directory /commons/src/main/java/org/archive/httpclient/.

Source file: ConfigurableX509TrustManager.java

  29 
vote

public void checkClientTrusted(X509Certificate[] certificates,String type) throws CertificateException {
  if (this.trustLevel.equals(TrustLevel.OPEN)) {
    return;
  }
  this.standardTrustManager.checkClientTrusted(certificates,type);
}
 

Example 38

From project hqapi, under directory /hqapi1/src/main/java/org/hyperic/hq/hqapi1/.

Source file: HQConnection.java

  29 
vote

private KeyStore getKeyStore(String keyStorePath,String keyStorePassword) throws KeyStoreException, IOException {
  FileInputStream keyStoreFileInputStream=null;
  try {
    KeyStore keystore=KeyStore.getInstance(KeyStore.getDefaultType());
    File file=new File(keyStorePath);
    char[] password=null;
    if (!file.exists()) {
      if (StringUtils.hasText(keyStorePath)) {
        throw new IOException("User specified keystore [" + keyStorePath + "] does not exist.");
      }
      password=keyStorePassword.toCharArray();
    }
    keyStoreFileInputStream=new FileInputStream(file);
    keystore.load(keyStoreFileInputStream,password);
    return keystore;
  }
 catch (  NoSuchAlgorithmException e) {
    throw new KeyStoreException(e);
  }
catch (  CertificateException e) {
    throw new KeyStoreException(e);
  }
 finally {
    if (keyStoreFileInputStream != null) {
      keyStoreFileInputStream.close();
      keyStoreFileInputStream=null;
    }
  }
}
 

Example 39

From project httpClient, under directory /httpclient/src/test/java/org/apache/http/conn/ssl/.

Source file: TestSSLSocketFactory.java

  29 
vote

@Test public void testSSLTrustVerificationOverride() throws Exception {
  SSLContext defaultsslcontext=SSLContext.getInstance("TLS");
  defaultsslcontext.init(null,null,null);
  SSLSocketFactory socketFactory=new SSLSocketFactory(new TrustStrategy(){
    public boolean isTrusted(    final X509Certificate[] chain,    final String authType) throws CertificateException {
      return chain.length == 1;
    }
  }
,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  HttpParams params=new BasicHttpParams();
  SSLSocket socket=(SSLSocket)socketFactory.createSocket(params);
  InetSocketAddress address=this.localServer.getServiceAddress();
  socketFactory.connectSocket(socket,address,null,params);
}
 

Example 40

From project https-utils, under directory /src/test/java/org/italiangrid/utils/test/.

Source file: ConnectionTest.java

  29 
vote

/** 
 * Connect using a certificate released from a trusted CA.
 */
@Test public void trustedCertificateAgain() throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
  HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier(){
    public boolean verify(    String hostname,    javax.net.ssl.SSLSession sslSession){
      if (hostname.equals("localhost")) {
        return true;
      }
      return false;
    }
  }
);
  PEMCredential credential=new PEMCredential("certs/voms-client-key.pem","certs/voms-client-cert.pem","pass".toCharArray());
  OpensslCertChainValidator validator=new OpensslCertChainValidator("certs/ca",NamespaceCheckingMode.EUGRIDPMA_AND_GLOBUS,60000L);
  SSLContext context=SocketFactoryCreator.getSSLContext(credential,validator,null);
  URL url=new URL("https://localhost:" + port);
  HttpsURLConnection connection=(HttpsURLConnection)url.openConnection();
  connection.setSSLSocketFactory(context.getSocketFactory());
  connection.connect();
  Assert.assertEquals(200,connection.getResponseCode());
  connection.disconnect();
}
 

Example 41

From project httpserver, under directory /src/test/java/.

Source file: SimpleSSLContext.java

  29 
vote

SimpleSSLContext(String dir) throws IOException {
  try {
    String file=dir + "/testkeys";
    char[] passphrase="passphrase".toCharArray();
    KeyStore ks=KeyStore.getInstance("JKS");
    ks.load(new FileInputStream(file),passphrase);
    KeyManagerFactory kmf=KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks,passphrase);
    TrustManagerFactory tmf=TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);
    ssl=SSLContext.getInstance("TLS");
    ssl.init(kmf.getKeyManagers(),tmf.getTrustManagers(),null);
  }
 catch (  KeyManagementException e) {
    throw new RuntimeException(e.getMessage());
  }
catch (  KeyStoreException e) {
    throw new RuntimeException(e.getMessage());
  }
catch (  UnrecoverableKeyException e) {
    throw new RuntimeException(e.getMessage());
  }
catch (  CertificateException e) {
    throw new RuntimeException(e.getMessage());
  }
catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e.getMessage());
  }
}
 

Example 42

From project IOCipherServer, under directory /src/info/guardianproject/iocipher/server/.

Source file: CACertManager.java

  29 
vote

public void save(File fileNew,String password) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
  if (fileNew.exists() && (!fileNew.canWrite()))   throw new FileNotFoundException("Cannot write to: " + fileNew.getAbsolutePath());
 else   if (fileNew.getParentFile().exists() && (!fileNew.getParentFile().canWrite()))   throw new FileNotFoundException("Cannot write to: " + fileNew.getAbsolutePath());
  OutputStream trustStoreStream=new FileOutputStream(fileNew);
  ksCACert.store(trustStoreStream,password.toCharArray());
}
 

Example 43

From project jclouds-abiquo, under directory /core/src/test/java/org/jclouds/abiquo/http/filters/.

Source file: AbiquoAuthenticationTest.java

  29 
vote

public void testBasicAuthentication() throws UnsupportedEncodingException, NoSuchAlgorithmException, CertificateException {
  HttpRequest request=HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")).build();
  AbiquoAuthentication filter=new AbiquoAuthentication("identity","credential","false");
  HttpRequest filtered=filter.filter(request);
  HttpRequest expected=request.toBuilder().replaceHeader(HttpHeaders.AUTHORIZATION,AbiquoAuthentication.basicAuth("identity","credential")).build();
  assertFalse(filtered.getHeaders().containsKey(HttpHeaders.COOKIE));
  assertEquals(filtered,expected);
}
 

Example 44

From project jclouds-chef, under directory /core/src/main/java/org/jclouds/chef/config/.

Source file: ChefParserModule.java

  29 
vote

@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 45

From project jetty-project, under directory /jetty-integration-tests/src/test/java/org/mortbay/jetty/integration/ssl/.

Source file: SSLContextTest.java

  29 
vote

/** 
 * Returns a collection of CRLs to be used by the tests. This is loaded from 'newca.crl'.
 * @return CRLs
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 * @throws CertificateException
 * @throws CRLException
 */
public Collection<X509CRL> getLocalCRLs() throws IOException, NoSuchAlgorithmException, KeyStoreException, CertificateException, CRLException {
  InputStream inStream=ClassLoader.getSystemResourceAsStream(TEST_KEYSTORES_PATH + "newca.crl");
  CertificateFactory cf=CertificateFactory.getInstance("X.509");
  X509CRL crl=(X509CRL)cf.generateCRL(inStream);
  inStream.close();
  ArrayList<X509CRL> crls=new ArrayList<X509CRL>();
  crls.add(crl);
  return crls;
}
 

Example 46

From project jnrpe-lib, under directory /jnrpe-lib/src/main/java/it/jnrpe/.

Source file: JNRPEListenerThread.java

  29 
vote

/** 
 * Creates an SSLServerSocketFactory.
 * @return the newly creates SSL Server Socket Factory
 * @throws KeyStoreException
 * @throws CertificateException
 * @throws IOException
 * @throws UnrecoverableKeyException
 * @throws KeyManagementException
 */
private SSLServerSocketFactory getSSLSocketFactory() throws KeyStoreException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException {
  StreamManager h=new StreamManager();
  SSLContext ctx;
  KeyManagerFactory kmf;
  try {
    InputStream ksStream=getClass().getClassLoader().getResourceAsStream(KEYSTORE_NAME);
    h.handle(ksStream);
    ctx=SSLContext.getInstance("SSLv3");
    kmf=KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    KeyStore ks=KeyStore.getInstance("JKS");
    char[] passphrase=KEYSTORE_PWD.toCharArray();
    ks.load(ksStream,passphrase);
    kmf.init(ks,passphrase);
    ctx.init(kmf.getKeyManagers(),null,new java.security.SecureRandom());
  }
 catch (  NoSuchAlgorithmException e) {
    throw new SSLException("Unable to initialize SSLSocketFactory.\n" + e.getMessage());
  }
 finally {
    h.closeAll();
  }
  return ctx.getServerSocketFactory();
}
 

Example 47

From project jupload, under directory /src/wjhk/jupload2/upload/.

Source file: InteractiveTrustManager.java

  29 
vote

/** 
 * @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[],java.lang.String)
 */
public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException {
  if ((this.mode & SERVER) != 0) {
    if (null == chain || chain.length == 0)     throw new IllegalArgumentException("Certificate chain is null or empty");
    int i;
    TrustManager[] mgrs=this.tmf.getTrustManagers();
    for (i=0; i < mgrs.length; i++) {
      if (mgrs[i] instanceof X509TrustManager) {
        X509TrustManager m=(X509TrustManager)(mgrs[i]);
        try {
          m.checkServerTrusted(chain,authType);
          return;
        }
 catch (        Exception e) {
        }
      }
    }
    CertDialog(chain[0]);
  }
}
 

Example 48

From project litle-sdk-for-java, under directory /lib/apache-cxf-2.5.2/samples/jax_rs/basic_https/src/main/java/org/apache/commons/httpclient/contrib/ssl/.

Source file: AuthSSLProtocolSocketFactory.java

  29 
vote

private static KeyStore createKeyStore(final URL url,final String password) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
  if (url == null) {
    throw new IllegalArgumentException("Keystore url may not be null");
  }
  LOG.debug("Initializing key store");
  KeyStore keystore=KeyStore.getInstance("jks");
  InputStream is=null;
  try {
    is=url.openStream();
    keystore.load(is,password != null ? password.toCharArray() : null);
  }
  finally {
    if (is != null)     is.close();
  }
  return keystore;
}
 

Example 49

From project LRJavaLib, under directory /src/com/navnorth/learningregistry/util/.

Source file: SelfSignSSLSocketFactory.java

  29 
vote

public SelfSignSSLSocketFactory(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 50

From project Maimonides, under directory /src/com/codeko/apps/maimonides/dnie/.

Source file: DNIe.java

  29 
vote

private X509Certificate getCertCAIntermedia(X509Certificate cert) throws CertificateException, FileNotFoundException {
  String issuerCN=cert.getIssuerX500Principal().getName("CANONICAL");
  CertificateFactory cfIssuer=CertificateFactory.getInstance("X.509");
  X509Certificate certCA=null;
  if (issuerCN.contains("cn=ac dnie 001")) {
    certCA=(X509Certificate)cfIssuer.generateCertificate(this.getClass().getResourceAsStream("certs/ACDNIE001-SHA1.crt"));
  }
 else   if (issuerCN.contains("cn=ac dnie 002")) {
    certCA=(X509Certificate)cfIssuer.generateCertificate(this.getClass().getResourceAsStream("certs/ACDNIE002-SHA1.crt"));
  }
 else   if (issuerCN.contains("cn=ac dnie 003")) {
    certCA=(X509Certificate)cfIssuer.generateCertificate(this.getClass().getResourceAsStream("certs/ACDNIE003-SHA1.crt"));
  }
  return certCA;
}
 

Example 51

From project masa, under directory /plugins/maven-apkbuilder-plugin/src/main/java/org/jvending/masa/plugin/apkbuilder/.

Source file: ApkBuilderMojo.java

  29 
vote

private SigningInfo loadKeyEntry(String osKeyStorePath,String storeType,char[] keyStorePassword,char[] privateKeyPassword,String alias) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableEntryException {
  try {
    KeyStore keyStore=KeyStore.getInstance(storeType != null ? storeType : KeyStore.getDefaultType());
    FileInputStream fis=new FileInputStream(osKeyStorePath);
    keyStore.load(fis,keyStorePassword);
    fis.close();
    KeyStore.PrivateKeyEntry store=(KeyStore.PrivateKeyEntry)keyStore.getEntry(alias,new KeyStore.PasswordProtection(privateKeyPassword));
    return new SigningInfo(store.getPrivateKey(),(X509Certificate)store.getCertificate());
  }
 catch (  FileNotFoundException e) {
    getLog().error("Failed to load key: alias = " + alias + ", path = "+ osKeyStorePath);
    e.printStackTrace();
  }
  return null;
}
 

Example 52

From project maven-wagon, under directory /wagon-providers/wagon-http-shared4/src/main/java/org/apache/maven/wagon/shared/http4/.

Source file: EasyX509TrustManager.java

  29 
vote

/** 
 * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[], String authType)
 */
public void checkServerTrusted(X509Certificate[] certificates,String authType) throws CertificateException {
  if ((certificates != null) && (certificates.length == 1)) {
    try {
      certificates[0].checkValidity();
    }
 catch (    CertificateExpiredException e) {
      if (!AbstractHttpClientWagon.IGNORE_SSL_VALIDITY_DATES) {
        throw e;
      }
    }
catch (    CertificateNotYetValidException e) {
      if (!AbstractHttpClientWagon.IGNORE_SSL_VALIDITY_DATES) {
        throw e;
      }
    }
  }
 else {
    standardTrustManager.checkServerTrusted(certificates,authType);
  }
}
 

Example 53

From project miso-lims, under directory /core/src/main/java/uk/ac/bbsrc/tgac/miso/core/manager/.

Source file: ERASubmissionManager.java

  29 
vote

/** 
 * Builds a "trusting" trust manager. This is totally horrible and basically ignores everything that SSL stands for. This allows connection to self-signed certificate hosts, bypassing the normal validation exceptions that occur. <p/> Use at your own risk - again, this is horrible!
 */
public DefaultHttpClient getEvilTrustingTrustManager(DefaultHttpClient httpClient){
  try {
    X509TrustManager trustManager=new X509TrustManager(){
      public void checkClientTrusted(      X509Certificate[] chain,      String authType) throws CertificateException {
        log.warn("BYPASSING CLIENT TRUSTED CHECK!");
      }
      public void checkServerTrusted(      X509Certificate[] chain,      String authType) throws CertificateException {
        log.warn("BYPASSING SERVER TRUSTED CHECK!");
      }
      public X509Certificate[] getAcceptedIssuers(){
        log.warn("BYPASSING CERTIFICATE ISSUER CHECKS!");
        return null;
      }
    }
;
    SSLContext sslcontext=SSLContext.getInstance("TLS");
    sslcontext.init(null,new TrustManager[]{trustManager},null);
    SSLSocketFactory sf=new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm=httpClient.getConnectionManager();
    SchemeRegistry schemeRegistry=ccm.getSchemeRegistry();
    schemeRegistry.register(new Scheme("https",sf,443));
    return new DefaultHttpClient(ccm,httpClient.getParams());
  }
 catch (  Throwable t) {
    log.warn("Something nasty happened with the EvilTrustingTrustManager. Warranty is null and void!");
    t.printStackTrace();
    return null;
  }
}
 

Example 54

From project MobiPerf, under directory /android/src/com/mobiperf/speedometer/.

Source file: Checkin.java

  29 
vote

public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
  super(truststore);
  X509TrustManager tm=new X509TrustManager(){
    public X509Certificate[] getAcceptedIssuers(){
      return null;
    }
    @Override public void checkClientTrusted(    X509Certificate[] chain,    String authType) throws CertificateException {
    }
    @Override public void checkServerTrusted(    X509Certificate[] chain,    String authType) throws CertificateException {
    }
  }
;
  sslContext.init(null,new TrustManager[]{tm},null);
}
 

Example 55

From project Mujina, under directory /mujina-common/src/main/java/nl/surfnet/mujina/model/.

Source file: CommonConfigurationImpl.java

  29 
vote

private void injectKeyStore(String alias,String pemCert,String pemKey) throws Exception {
  CertificateFactory certFact;
  Certificate cert;
  String wrappedCert="-----BEGIN CERTIFICATE-----\n" + pemCert + "\n-----END CERTIFICATE-----";
  ByteArrayInputStream certificateInputStream=new ByteArrayInputStream(wrappedCert.getBytes());
  try {
    certFact=CertificateFactory.getInstance("X.509");
    cert=certFact.generateCertificate(certificateInputStream);
  }
 catch (  CertificateException e) {
    throw new Exception("Could not instantiate cert",e);
  }
  IOUtils.closeQuietly(certificateInputStream);
  ArrayList<Certificate> certs=new ArrayList<Certificate>();
  certs.add(cert);
  final byte[] key=Base64.decodeBase64(pemKey);
  KeyFactory keyFactory=KeyFactory.getInstance("RSA");
  KeySpec ks=new PKCS8EncodedKeySpec(key);
  RSAPrivateKey privKey=(RSAPrivateKey)keyFactory.generatePrivate(ks);
  final Certificate[] certificates=new Certificate[1];
  certificates[0]=certs.get(0);
  keyStore.setKeyEntry(alias,privKey,keystorePassword.toCharArray(),certificates);
}
 

Example 56

From project Opal, under directory /opal-struct/src/main/java/com/lyndir/lhunath/opal/network/.

Source file: SSLFactory.java

  29 
vote

private SSLFactory(final File keyStore,final String password){
  InputStream keyStoreStream=null;
  try {
    KeyStore store=KeyStore.getInstance("JKS");
    store.load(keyStoreStream=new FileInputStream(keyStore),password.toCharArray());
    TrustManagerFactory tFactory=TrustManagerFactory.getInstance("SunX509");
    tFactory.init(store);
    context=SSLContext.getInstance("TLS");
    context.init(null,tFactory.getTrustManagers(),null);
  }
 catch (  KeyStoreException e) {
    throw new IllegalArgumentException("Keystore type not supported or keystore could not be used to initialize trust.",e);
  }
catch (  NoSuchAlgorithmException e) {
    throw new IllegalStateException("Key algorithm not supported.",e);
  }
catch (  CertificateException e) {
    throw new IllegalArgumentException("Keystore could not be loaded.",e);
  }
catch (  FileNotFoundException e) {
    throw new IllegalArgumentException("Keystore not found.",e);
  }
catch (  IOException e) {
    throw new RuntimeException("Could not read the keys from the keystore.",e);
  }
catch (  KeyManagementException e) {
    throw new RuntimeException("Could not use the keys for trust.",e);
  }
 finally {
    Closeables.closeQuietly(keyStoreStream);
  }
}
 

Example 57

From project OpenID-Connect-Java-Spring-Server, under directory /openid-connect-common/src/main/java/org/mitre/key/fetch/.

Source file: KeyFetcher.java

  29 
vote

public PublicKey retrieveX509Key(OIDCServerConfiguration serverConfig){
  PublicKey key=null;
  try {
    InputStream x509Stream=restTemplate.getForObject(serverConfig.getX509SigningUrl(),InputStream.class);
    CertificateFactory factory=CertificateFactory.getInstance("X.509");
    X509Certificate cert=(X509Certificate)factory.generateCertificate(x509Stream);
    key=cert.getPublicKey();
  }
 catch (  HttpClientErrorException e) {
    logger.error("HttpClientErrorException in KeyFetcher.java: ",e);
  }
catch (  CertificateException e) {
    logger.error("CertificateException in KeyFetcher.java: ",e);
  }
  return key;
}
 

Example 58

From project OpenMEAP, under directory /java-shared/openmeap-shared-jdk5/src/com/openmeap/util/.

Source file: SSLUtils.java

  29 
vote

public static KeyStore loadKeyStore(String keyStoreFileName,String password) throws CertificateException, IOException, NoSuchAlgorithmException, KeyStoreException {
  KeyStore ks=null;
  FileInputStream fis=null;
  try {
    fis=new FileInputStream(keyStoreFileName);
    ks=loadKeyStore(fis,password);
  }
  finally {
    if (fis != null) {
      fis.close();
    }
  }
  return ks;
}
 

Example 59

From project org.openscada.atlantis, under directory /org.openscada.core.net/src/org/openscada/core/net/.

Source file: ConnectionHelper.java

  29 
vote

private static KeyManager[] getKeyManagers(final ConnectionInformation connectionInformation,final boolean isClient) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, CertificateException, IOException {
  if (isClient) {
    return null;
  }
  final KeyStore keyStore;
  keyStore=createKeyStore(connectionInformation);
  final String keyManagerFactory=KeyManagerFactory.getDefaultAlgorithm();
  final KeyManagerFactory kmf=KeyManagerFactory.getInstance(keyManagerFactory);
  kmf.init(keyStore,getPassword(connectionInformation,"sslCertPassword"));
  return kmf.getKeyManagers();
}
 

Example 60

From project OWASP-WebScarab, under directory /src/org/owasp/webscarab/httpclient/.

Source file: AbstractCertificateRepository.java

  29 
vote

public int loadPKCS12Certificate(String filename,String ksPassword) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException {
  InputStream is=new FileInputStream(filename);
  if (is == null) {
    throw new FileNotFoundException(filename + " could not be found");
  }
  KeyStore ks=KeyStore.getInstance("PKCS12");
  ks.load(is,ksPassword == null ? null : ksPassword.toCharArray());
  return addKeyStore(ks,"PKCS#12 - " + filename);
}
 

Example 61

From project pdftk, under directory /java/com/lowagie/text/pdf/.

Source file: PdfPKCS7.java

  29 
vote

/** 
 * Verifies a signature using the sub-filter adbe.x509.rsa_sha1.
 * @param contentsKey the /Contents key
 * @param certsKey the /Cert key
 * @param provider the provider or <code>null</code> for the default provider
 * @throws SecurityException on error
 * @throws CRLException on error
 * @throws InvalidKeyException on error
 * @throws CertificateException on error
 * @throws NoSuchProviderException on error
 * @throws NoSuchAlgorithmException on error
 * @throws IOException on error
 */
public PdfPKCS7(byte[] contentsKey,byte[] certsKey,String provider) throws SecurityException, CRLException, InvalidKeyException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, IOException {
  CertificateFactory cf;
  if (provider == null)   cf=CertificateFactory.getInstance("X.509");
 else   cf=CertificateFactory.getInstance("X.509",provider);
  if (provider == null)   certs=cf.generateCertificates(new ByteArrayInputStream(certsKey));
  signCert=(X509Certificate)certs.iterator().next();
  crls=new ArrayList();
  ASN1InputStream in=new ASN1InputStream(new ByteArrayInputStream(contentsKey));
  digest=((DEROctetString)in.readObject()).getOctets();
  if (provider == null)   sig=Signature.getInstance("SHA1withRSA");
 else   sig=Signature.getInstance("SHA1withRSA",provider);
  sig.initVerify(signCert.getPublicKey());
}
 

Example 62

From project PenguinCMS, under directory /PenguinCMS/tests/vendor/sahi/src/net/sf/sahi/ssl/.

Source file: SSLHelper.java

  29 
vote

public static KeyManagerFactory getKeyManagerFactoryForRemoteFetch() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, FileNotFoundException, CertificateException, IOException {
  String fileWithPath=Configuration.getSSLClientCertPath();
  logger.info(fileWithPath == null ? "No SSL Client Cert specified" : ("\n----\nSSL Client Cert Path = " + fileWithPath + "\n----"));
  String password=Configuration.getSSLClientCertPassword();
  return getKeyManagerFactory(fileWithPath,password,Configuration.getSSLClientKeyStoreType());
}
 

Example 63

From project phonegap-simjs, under directory /src/com/phonegap/.

Source file: FileTransfer.java

  29 
vote

/** 
 * This function will install a trust manager that will blindly trust all SSL  certificates.  The reason this code is being added is to enable developers  to do development using self signed SSL certificates on their web server. The standard HttpsURLConnection class will throw an exception on self  signed certificates if this code is not run.
 */
private void trustAllHosts(){
  TrustManager[] trustAllCerts=new TrustManager[]{new X509TrustManager(){
    public java.security.cert.X509Certificate[] getAcceptedIssuers(){
      return new java.security.cert.X509Certificate[]{};
    }
    public void checkClientTrusted(    X509Certificate[] chain,    String authType) throws CertificateException {
    }
    public void checkServerTrusted(    X509Certificate[] chain,    String authType) throws CertificateException {
    }
  }
};
  try {
    defaultSSLSocketFactory=HttpsURLConnection.getDefaultSSLSocketFactory();
    SSLContext sc=SSLContext.getInstance("TLS");
    sc.init(null,trustAllCerts,new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  }
 catch (  Exception e) {
    System.out.println(e.getMessage());
  }
}
 

Example 64

From project picketlink-integration-tests, under directory /unit-tests/saml/src/test/java/org/picketlink/test/integration/saml2/.

Source file: SAML2EncryptionUnitTestCase.java

  29 
vote

@Deployment(name="employee-sig",testable=false) @TargetsContainer("jboss") public static WebArchive createEmployeeSigDeployment() throws KeyStoreException, FileNotFoundException, NoSuchAlgorithmException, CertificateException, GeneralSecurityException, IOException {
  WebArchive sp=MavenArtifactUtil.getQuickstartsMavenArchive("employee-sig");
  changeIdentityURL(sp,getTargetURL("/idp-enc/"));
  addValidatingAlias(sp,getServerAddress(),getServerAddress());
  addKeyStoreAlias(sp,getServerAddress());
  return sp;
}
 

Example 65

From project Pitbull, under directory /pitbull-core/src/main/java/org/jboss/pitbull/client/.

Source file: HttpConnectionFactory.java

  29 
vote

public static ClientConnection https(String host,int port,long timeout,TimeUnit unit) throws IOException {
  java.lang.System.setProperty("sun.security.ssl.allowUnsafeRenegotiation","true");
  X509TrustManager trustManager=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 sslContext=null;
  try {
    sslContext=SSLContext.getInstance("SSL");
    sslContext.init(null,new TrustManager[]{trustManager},new SecureRandom());
    SSLEngine engine=sslContext.createSSLEngine();
    engine.setUseClientMode(true);
    SocketChannel channel=createSocket(host,port,timeout,unit);
    ClientSSLChannel sslChannel=new ClientSSLChannel(channel,engine);
    return new ClientConnectionImpl(sslChannel,host,port);
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 66

From project PocketVDC, under directory /src/libomv/utils/.

Source file: Helpers.java

  29 
vote

/** 
 * Retrieves the default keystore
 * @return The current KeyStore
 * @throws IOException
 * @throws KeyStoreException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 */
public static KeyStore getExtendedKeyStore() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
  KeyStore ks=null;
  File file=new File("jssecacerts");
  if (file.isFile() == false) {
    char SEP=File.separatorChar;
    File dir=new File(System.getProperty("java.home") + SEP + "lib"+ SEP+ "security");
    file=new File(dir,"jssecacerts");
    if (file.isFile() == false) {
      file=new File(dir,"cacerts");
    }
  }
  ks=KeyStore.getInstance(KeyStore.getDefaultType());
  InputStream in=new FileInputStream(file);
  try {
    ks.load(in,null);
  }
 catch (  IOException ex) {
    throw ex;
  }
catch (  NoSuchAlgorithmException ex) {
    throw ex;
  }
catch (  CertificateException ex) {
    throw ex;
  }
 finally {
    in.close();
  }
  return ks;
}
 

Example 67

From project portal, under directory /portal-core/src/main/java/org/devproof/portal/core/module/common/util/httpclient/ssl/.

Source file: EasyX509TrustManager.java

  29 
vote

/** 
 * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],
     *      String authType)
 */
public void checkServerTrusted(X509Certificate[] certificates,String authType) throws CertificateException {
  if ((certificates != null) && logger.isDebugEnabled()) {
    logger.debug("Server certificate chain:");
    for (int i=0; i < certificates.length; i++) {
      logger.debug("X509Certificate[" + i + "]="+ certificates[i]);
    }
  }
  if ((certificates != null) && (certificates.length == 1)) {
    certificates[0].checkValidity();
  }
 else {
    standardTrustManager.checkServerTrusted(certificates,authType);
  }
}
 

Example 68

From project PSXperia, under directory /src/com/yifanlu/PSXperiaTool/.

Source file: ApkBuilder.java

  29 
vote

private KeyStore getKeyStore() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
  KeyStore ks=KeyStore.getInstance(KeyStore.getDefaultType());
  InputStream is=PSXperiaTool.class.getResourceAsStream("/resources/signApk.keystore");
  ks.load(is,KEYSTORE_PASSWORD);
  return ks;
}
 

Example 69

From project QuotaForAndroid, under directory /Quota/src/com/southfreo/quota/utils/.

Source file: OpenSSLFactory.java

  29 
vote

public OpenSSLFactory(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 70

From project rain-workload-toolkit, under directory /src/radlab/rain/util/.

Source file: HttpTransport.java

  29 
vote

public static HttpClient wrapClient(HttpClient base){
  try {
    SSLContext ctx=SSLContext.getInstance("TLS");
    X509TrustManager tm=new X509TrustManager(){
      public void checkClientTrusted(      X509Certificate[] xcs,      String string) throws CertificateException {
      }
      public void checkServerTrusted(      X509Certificate[] xcs,      String string) throws CertificateException {
      }
      public X509Certificate[] getAcceptedIssuers(){
        return null;
      }
    }
;
    ctx.init(null,new TrustManager[]{tm},null);
    SSLSocketFactory ssf=new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm=base.getConnectionManager();
    SchemeRegistry sr=ccm.getSchemeRegistry();
    sr.register(new Scheme("https",443,ssf));
    return new DefaultHttpClient(ccm,base.getParams());
  }
 catch (  Exception ex) {
    return null;
  }
}
 

Example 71

From project recordloader, under directory /src/java/com/marklogic/recordloader/xcc/.

Source file: XccConfiguration.java

  29 
vote

protected static SecurityOptions newTrustAnyoneOptions() throws KeyManagementException, NoSuchAlgorithmException {
  TrustManager[] trust=new TrustManager[]{new X509TrustManager(){
    public java.security.cert.X509Certificate[] getAcceptedIssuers(){
      return new X509Certificate[0];
    }
    /** 
 * @throws CertificateException
 */
    public void checkClientTrusted(    java.security.cert.X509Certificate[] certs,    String authType) throws CertificateException {
    }
    /** 
 * @throws CertificateException
 */
    public void checkServerTrusted(    java.security.cert.X509Certificate[] certs,    String authType) throws CertificateException {
    }
  }
};
  SSLContext sslContext=SSLContext.getInstance("SSLv3");
  sslContext.init(null,trust,null);
  return new SecurityOptions(sslContext);
}
 

Example 72

From project rundeck, under directory /core/src/main/java/com/dtolabs/rundeck/core/utils/.

Source file: JARVerifier.java

  29 
vote

/** 
 * Construct a JARVerifier with a keystore and alias and password.
 * @param keystore filepath to the keystore
 * @param alias    alias name of the cert chain to verify with
 * @param passwd   password to use to verify the keystore, or null
 * @return
 * @throws IOException
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 */
public static JARVerifier create(String keystore,String alias,char[] passwd) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
  KeyStore keyStore=KeyStore.getInstance("JKS");
  FileInputStream fileIn=null;
  try {
    fileIn=new FileInputStream(keystore);
    keyStore.load(fileIn,passwd);
  }
  finally {
    if (null != fileIn) {
      fileIn.close();
    }
  }
  Certificate[] chain=keyStore.getCertificateChain(alias);
  if (chain == null) {
    Certificate cert=keyStore.getCertificate(alias);
    if (cert == null) {
      throw new IllegalArgumentException("No trusted certificate or chain found for alias: " + alias);
    }
    chain=new Certificate[]{cert};
  }
  X509Certificate certChain[]=new X509Certificate[chain.length];
  CertificateFactory cf=CertificateFactory.getInstance("X.509");
  for (int count=0; count < chain.length; count++) {
    ByteArrayInputStream certIn=new ByteArrayInputStream(chain[count].getEncoded());
    X509Certificate cert=(X509Certificate)cf.generateCertificate(certIn);
    certChain[count]=cert;
  }
  JARVerifier jarVerifier=new JARVerifier(certChain);
  return jarVerifier;
}
 

Example 73

From project rundeck-api-java-client, under directory /src/main/java/org/rundeck/api/.

Source file: ApiCall.java

  29 
vote

/** 
 * Instantiate a new  {@link HttpClient} instance, configured to accept all SSL certificates
 * @return an {@link HttpClient} instance - won't be null
 */
private HttpClient instantiateHttpClient(){
  DefaultHttpClient httpClient=new DefaultHttpClient();
  HttpProtocolParams.setUserAgent(httpClient.getParams(),"RunDeck API Java Client " + RundeckClient.API_VERSION);
  SSLSocketFactory socketFactory=null;
  try {
    socketFactory=new SSLSocketFactory(new TrustStrategy(){
      @Override public boolean isTrusted(      X509Certificate[] chain,      String authType) throws CertificateException {
        return true;
      }
    }
,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  }
 catch (  KeyManagementException e) {
    throw new RuntimeException(e);
  }
catch (  UnrecoverableKeyException e) {
    throw new RuntimeException(e);
  }
catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
catch (  KeyStoreException e) {
    throw new RuntimeException(e);
  }
  httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https",443,socketFactory));
  System.setProperty("java.net.useSystemProxies","true");
  httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(httpClient.getConnectionManager().getSchemeRegistry(),ProxySelector.getDefault()));
  httpClient.addRequestInterceptor(new HttpRequestInterceptor(){
    @Override public void process(    HttpRequest request,    HttpContext context) throws HttpException, IOException {
      if (client.getToken() != null) {
        request.addHeader(AUTH_TOKEN_HEADER,client.getToken());
      }
    }
  }
);
  return httpClient;
}
 

Example 74

From project salem, under directory /src/haven/.

Source file: SslHelper.java

  29 
vote

public synchronized void loadCredsPkcs12(InputStream in,char[] pw) throws IOException, CertificateException {
  clear();
  try {
    creds=KeyStore.getInstance("PKCS12");
    creds.load(in,pw);
    this.pw=pw;
  }
 catch (  KeyStoreException e) {
    throw (new Error(e));
  }
catch (  NoSuchAlgorithmException e) {
    throw (new Error(e));
  }
}
 

Example 75

From project sandbox, under directory /xeclipse/org.xwiki.eclipse.core/src/main/java/org/xwiki/eclipse/core/.

Source file: CorePlugin.java

  29 
vote

public void start(BundleContext context) throws Exception {
  super.start(context);
  plugin=this;
  TrustManager[] trustAllCertificates=new TrustManager[]{new X509TrustManager(){
    public X509Certificate[] getAcceptedIssuers(){
      return null;
    }
    public void checkClientTrusted(    X509Certificate[] arg0,    String arg1) throws CertificateException {
    }
    public void checkServerTrusted(    X509Certificate[] arg0,    String arg1) throws CertificateException {
    }
  }
};
  SSLContext sc=SSLContext.getInstance("SSL");
  HostnameVerifier hv=new HostnameVerifier(){
    public boolean verify(    String arg0,    SSLSession arg1){
      return true;
    }
  }
;
  sc.init(null,trustAllCertificates,new java.security.SecureRandom());
  HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
 

Example 76

From project security, under directory /external/src/test/java/org/jboss/seam/security/externaltest/module/.

Source file: SamlSignatureUtilForPostBindingTest.java

  29 
vote

@Before public void setup() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException {
  samlSignatureUtilForPostBinding=new SamlSignatureUtilForPostBinding();
  InputStream keyStoreStream=getClass().getClassLoader().getResourceAsStream("test_keystore.jks");
  KeyStore keyStore=KeyStore.getInstance(KeyStore.getDefaultType());
  keyStore.load(keyStoreStream,"store456".toCharArray());
  X509Certificate certificate=(X509Certificate)keyStore.getCertificate("servercert");
  PublicKey publicKey=certificate.getPublicKey();
  PrivateKey privateKey=(PrivateKey)keyStore.getKey("servercert","pass456".toCharArray());
  keyPair=new KeyPair(publicKey,privateKey);
}
 

Example 77

From project sensei, under directory /sensei-core/src/main/java/com/senseidb/dataprovider/http/.

Source file: HttpsClientDecorator.java

  29 
vote

public static DefaultHttpClient decorate(DefaultHttpClient base){
  try {
    SSLContext ctx=SSLContext.getInstance("TLS");
    X509TrustManager tm=new X509TrustManager(){
      public void checkClientTrusted(      X509Certificate[] xcs,      String string) throws CertificateException {
      }
      public void checkServerTrusted(      X509Certificate[] xcs,      String string) throws CertificateException {
      }
      public X509Certificate[] getAcceptedIssuers(){
        return null;
      }
    }
;
    ctx.init(null,new TrustManager[]{tm},null);
    SSLSocketFactory ssf=new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm=base.getConnectionManager();
    SchemeRegistry sr=ccm.getSchemeRegistry();
    sr.register(new Scheme("https",443,ssf));
    return new DefaultHttpClient(ccm,base.getParams());
  }
 catch (  Exception ex) {
    logger.error(ex.getMessage(),ex);
    return null;
  }
}
 

Example 78

From project sisu-goodies, under directory /crypto/src/main/java/org/sonatype/sisu/goodies/crypto/internal/.

Source file: CryptoHelperImpl.java

  29 
vote

@Override public CertificateFactory createCertificateFactory(final String type) throws CertificateException {
  checkNotNull(type);
  CertificateFactory obj;
  try {
    obj=CertificateFactory.getInstance(type,getProvider());
  }
 catch (  CertificateException e) {
    logFallback(e);
    obj=CertificateFactory.getInstance(type);
  }
  if (log.isTraceEnabled()) {
    log.trace("Created certificate-factory: {} ({})",obj.getType(),obj.getProvider().getName());
  }
  return obj;
}
 

Example 79

From project Speedometer, under directory /android/src/com/google/wireless/speed/speedometer/.

Source file: Checkin.java

  29 
vote

public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
  super(truststore);
  X509TrustManager tm=new X509TrustManager(){
    public X509Certificate[] getAcceptedIssuers(){
      return null;
    }
    @Override public void checkClientTrusted(    X509Certificate[] chain,    String authType) throws CertificateException {
    }
    @Override public void checkServerTrusted(    X509Certificate[] chain,    String authType) throws CertificateException {
    }
  }
;
  sslContext.init(null,new TrustManager[]{tm},null);
}
 

Example 80

From project spring-crypto-utils, under directory /src/main/java/com/springcryptoutils/core/keystore/.

Source file: Base64EncodedKeyStoreFactoryBean.java

  29 
vote

public void afterPropertiesSet() throws KeyStoreException, IOException, NoSuchAlgorithmException, NoSuchProviderException, CertificateException {
  if ((provider == null) || (provider.length() == 0)) {
    keystore=KeyStore.getInstance(type);
  }
 else {
    keystore=KeyStore.getInstance(type,provider);
  }
  ByteArrayInputStream in=new ByteArrayInputStream(Base64.decodeBase64(base64EncodedKeyStoreFile.getBytes()));
  keystore.load(in,password.toCharArray());
}
 

Example 81

From project spring-security-oauth, under directory /spring-security-oauth/src/main/java/org/springframework/security/oauth/config/.

Source file: ConsumerDetailsFactoryBean.java

  29 
vote

public ConsumerDetails getObject() throws Exception {
  if ("rsa-cert".equals(typeOfSecret)) {
    try {
      Certificate cert=CertificateFactory.getInstance("X.509").generateCertificate(resourceLoader.getResource(secret).getInputStream());
      consumer.setSignatureSecret(new RSAKeySecret(cert.getPublicKey()));
    }
 catch (    IOException e) {
      throw new BeanCreationException("RSA certificate not found at " + secret + ".",e);
    }
catch (    CertificateException e) {
      throw new BeanCreationException("Invalid RSA certificate at " + secret + ".",e);
    }
catch (    NullPointerException e) {
      throw new BeanCreationException("Could not load RSA certificate at " + secret + ".",e);
    }
  }
 else {
    consumer.setSignatureSecret(new SharedConsumerSecretImpl(secret));
  }
  return consumer;
}
 

Example 82

From project stone-for-Android, under directory /src/jp/klab/stone/certinstaller/.

Source file: CredentialHelper.java

  29 
vote

private void parseCert(byte[] bytes){
  if (bytes == null)   return;
  try {
    CertificateFactory certFactory=CertificateFactory.getInstance("X.509");
    X509Certificate cert=(X509Certificate)certFactory.generateCertificate(new ByteArrayInputStream(bytes));
    if (isCa(cert)) {
      Log.d(TAG,"got a CA cert");
      mCaCerts.add(cert);
    }
 else {
      Log.d(TAG,"got a user cert");
      mUserCert=cert;
    }
  }
 catch (  CertificateException e) {
    Log.w(TAG,"parseCert(): " + e);
  }
}