コード例 #1
0
 /**
  * Permanently accepts a certificate for the INCOMING or OUTGOING direction by adding it to the
  * local key store.
  *
  * @param certificate
  */
 private void acceptCertificate(X509Certificate certificate) {
   try {
     mAccount.addCertificate(mDirection, certificate);
   } catch (CertificateException e) {
     showErrorDialog(
         R.string.account_setup_failed_dlg_certificate_message_fmt,
         e.getMessage() == null ? "" : e.getMessage());
   }
   AccountSetupCheckSettings.actionCheckSettings(
       AccountSetupCheckSettings.this, mAccount, mDirection);
 }
コード例 #2
0
  /**
   * Validate the server's certificate chain is trusted.
   *
   * @param certChain The ASN.1 DER encoded bytes for certificates.
   * @param authType The key exchange algorithm name (e.g. RSA)
   * @return true if the server is trusted
   * @throws CertificateException,KeyStoreException,NoSuchAlgorithmException on error initializing
   *     the TrustManager or reading the certChain
   */
  @CalledByNativeUnchecked
  public static boolean verifyServerCertificates(byte[][] certChain, String authType)
      throws CertificateException, KeyStoreException, NoSuchAlgorithmException {
    if (certChain == null || certChain.length == 0 || certChain[0] == null) {
      throw new IllegalArgumentException(
          "Expected non-null and non-empty certificate "
              + "chain passed as |certChain|. |certChain|="
              + certChain);
    }

    ensureInitialized();
    X509Certificate[] serverCertificates = new X509Certificate[certChain.length];
    for (int i = 0; i < certChain.length; ++i) {
      serverCertificates[i] =
          (X509Certificate)
              sCertificateFactory.get().generateCertificate(new ByteArrayInputStream(certChain[i]));
    }

    try {
      sDefaultTrustManager.get().checkServerTrusted(serverCertificates, authType);
      return true;
    } catch (CertificateException e) {
      Log.i(TAG, "failed to validate the certificate chain, error: " + e.getMessage());
    }
    return false;
  }
コード例 #3
0
  /**
   * ִ��http���á�true:�ɹ� false:ʧ��
   *
   * @return boolean
   */
  public boolean call() {

    boolean isRet = false;

    // http
    if (null == this.caFile && null == this.certFile) {
      try {
        this.callHttp();
        isRet = true;
      } catch (IOException e) {
        this.errInfo = e.getMessage();
      }
      return isRet;
    }

    // https
    try {
      this.callHttps();
      isRet = true;
    } catch (UnrecoverableKeyException e) {
      this.errInfo = e.getMessage();
    } catch (KeyManagementException e) {
      this.errInfo = e.getMessage();
    } catch (CertificateException e) {
      this.errInfo = e.getMessage();
    } catch (KeyStoreException e) {
      this.errInfo = e.getMessage();
    } catch (NoSuchAlgorithmException e) {
      this.errInfo = e.getMessage();
    } catch (IOException e) {
      this.errInfo = e.getMessage();
    }

    return isRet;
  }
コード例 #4
0
ファイル: SSLImpl.java プロジェクト: rhomobile/rhodes
  private static Certificate loadCertificate(File f) {
    X509Certificate cert = null;

    Logger.I(TAG, "Loading SSL certificate from PEM file: " + f.getAbsolutePath());

    try {

      byte[] fileBuf = fileToBytes(f);
      byte[] certBytes =
          parseDERFromPEM(fileBuf, "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----");
      cert = generateCertificateFromDER(certBytes);

      Logger.I(TAG, "SSL certificate loaded successfully");

    } catch (IOException e) {
      Logger.E(
          TAG,
          "Reading certificate file failed: "
              + e.getClass().getSimpleName()
              + ": "
              + e.getMessage());
    } catch (CertificateException e) {
      Logger.E(
          TAG,
          "Certificate generation failed: " + e.getClass().getSimpleName() + ": " + e.getMessage());
    }

    return cert;
  }
コード例 #5
0
ファイル: TrustFactory.java プロジェクト: 4DvAnCeBoY/dotCMS
 /*
  * Delegate to the default trust manager.
  */
 public void checkClientTrusted(X509Certificate[] chain, String authType)
     throws CertificateException {
   try {
     pkixTrustManager.checkClientTrusted(chain, authType);
   } catch (CertificateException excep) {
     Logger.error(this.getClass(), excep.getMessage());
     Logger.debug(this.getClass(), excep.getMessage(), excep);
   }
 }
コード例 #6
0
 /*     */ private void readObject(ObjectInputStream paramObjectInputStream)
     /*     */ throws IOException, ClassNotFoundException
       /*     */ {
   /* 553 */ Hashtable localHashtable = null;
   /*     */
   /* 555 */ paramObjectInputStream.defaultReadObject();
   /*     */
   /* 557 */ if (this.type == null) {
     /* 558 */ throw new NullPointerException("type can't be null");
     /*     */ }
   /*     */
   /* 561 */ int i = paramObjectInputStream.readInt();
   /* 562 */ if (i > 0)
   /*     */ {
     /* 565 */ localHashtable = new Hashtable(3);
     /* 566 */ this.certs = new Certificate[i];
     /*     */ }
   /*     */
   /* 569 */ for (int j = 0; j < i; j++)
   /*     */ {
     /* 572 */ String str = paramObjectInputStream.readUTF();
     /*     */ CertificateFactory localCertificateFactory;
     /* 573 */ if (localHashtable.containsKey(str))
     /*     */ {
       /* 575 */ localCertificateFactory = (CertificateFactory) localHashtable.get(str);
       /*     */ }
     /*     */ else {
       /*     */ try {
         /* 579 */ localCertificateFactory = CertificateFactory.getInstance(str);
         /*     */ } catch (CertificateException localCertificateException1) {
         /* 581 */ throw new ClassNotFoundException(
             "Certificate factory for " + str + " not found");
         /*     */ }
       /*     */
       /* 585 */ localHashtable.put(str, localCertificateFactory);
       /*     */ }
     /*     */
     /* 588 */ byte[] arrayOfByte = null;
     /*     */ try {
       /* 590 */ arrayOfByte = new byte[paramObjectInputStream.readInt()];
       /*     */ } catch (OutOfMemoryError localOutOfMemoryError) {
       /* 592 */ throw new IOException("Certificate too big");
       /*     */ }
     /* 594 */ paramObjectInputStream.readFully(arrayOfByte);
     /* 595 */ ByteArrayInputStream localByteArrayInputStream =
         new ByteArrayInputStream(arrayOfByte);
     /*     */ try {
       /* 597 */ this.certs[j] =
           localCertificateFactory.generateCertificate(localByteArrayInputStream);
       /*     */ } catch (CertificateException localCertificateException2) {
       /* 599 */ throw new IOException(localCertificateException2.getMessage());
       /*     */ }
     /* 601 */ localByteArrayInputStream.close();
     /*     */ }
   /*     */ }
コード例 #7
0
 private Subject createSubject() throws IOException {
   try {
     Certificate[] chain = engine.getSession().getPeerCertificates();
     CertPath certPath = cf.generateCertPath(asList(chain));
     return new Subject(false, Collections.<Principal>emptySet(), singleton(certPath), emptySet());
   } catch (SSLPeerUnverifiedException e) {
     throw new IOException("Failed to establish identity of SSL peer: " + e.getMessage(), e);
   } catch (CertificateException e) {
     throw new IOException("Certificate failure: " + e.getMessage(), e);
   }
 }
コード例 #8
0
  @Transient
  public X509Certificate getServerCertificate() {

    if (null == this.encodedServerCertificate) {
      return null;
    }
    try {
      CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
      InputStream certificateStream = new ByteArrayInputStream(this.encodedServerCertificate);
      return (X509Certificate) certificateFactory.generateCertificate(certificateStream);
    } catch (CertificateException e) {
      throw new RuntimeException("cert factory error: " + e.getMessage());
    }
  }
  private KeyStore getKeyStore(String keyStoreName, String password) {
    KeyStore ks = null;
    FileInputStream fis = null;
    try {
      ks = KeyStore.getInstance("JKS");
      char[] passwordArray = password.toCharArray();
      fis = new java.io.FileInputStream(keyStoreName);
      ks.load(fis, passwordArray);
      fis.close();

    } catch (CertificateException e) {
      logger.error(e.getMessage(), e);
      throw new RuntimeException(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
      logger.error(e.getMessage(), e);
      throw new RuntimeException(e.getMessage(), e);
    } catch (KeyStoreException e) {
      logger.error(e.getMessage(), e);
      throw new RuntimeException(e.getMessage(), e);
    } catch (FileNotFoundException e) {
      logger.error(e.getMessage(), e);
      throw new RuntimeException(e.getMessage(), e);
    } catch (IOException e) {
      logger.error(e.getMessage(), e);
      throw new RuntimeException(e.getMessage(), e);
    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (IOException e) {
          logger.error(e.getMessage(), e);
        }
      }
    }
    return ks;
  }
コード例 #10
0
  private void sslFileTransfer(String filename) {
    try {
      KeyStore trusted = KeyStore.getInstance("BKS");
      // Get the raw resource, which contains the keystore with
      // your trusted certificates (root and any intermediate certs)
      InputStream in =
          context.getResources().openRawResource(tracker.springversion1.R.raw.mykeystore);
      trusted.load(in, "mysecret".toCharArray());

      String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
      TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
      tmf.init(trusted);

      // Create an SSLContext that uses our TrustManager
      SSLContext context = SSLContext.getInstance("TLS");
      context.init(null, tmf.getTrustManagers(), null);

      URL url = new URL(host);
      HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
      urlConnection.setSSLSocketFactory(context.getSocketFactory());

      transfer(urlConnection, filename);

      //			SSLSocketFactory sf = new SSLSocketFactory(trusted);
      //			// Hostname verification from certificate
      //			// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
      //			sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
      //
      //			Socket sslsocket = sf.createSocket();
      //			sslsocket.setKeepAlive(true);
      //
      //			InetSocketAddress address = new InetSocketAddress(host, 443);
      //			sslsocket.connect(address);
      //
      //			OutputStream sout = sslsocket.getOutputStream();

    } catch (KeyStoreException e) {
      Log.v("mark", "KeyStoreException:" + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
      Log.v("mark", "NoSuchAlgorithmException:" + e.getMessage());
    } catch (CertificateException e) {
      Log.v("mark", "CertificateException:" + e.getMessage());
    } catch (IOException e) {
      Log.v("mark", "IOException:" + e.getMessage());
    } catch (KeyManagementException e) {
      Log.v("mark", "KeyManagementException:" + e.getMessage());
    }
  }
コード例 #11
0
ファイル: GenericXMLSignature.java プロジェクト: joselo/sri
  private KeyStore getKeyStore() throws CertificateException, IOException {
    KeyStore ks = null;

    try {
      ks = KeyStore.getInstance("PKCS12");
      ks.load(new FileInputStream(this.pathSignature), this.passSignature.toCharArray());
    } catch (KeyStoreException e) {
      throw new IOException("Error: " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
      throw new IOException("Error: " + e.getMessage());
    } catch (CertificateException e) {
      throw new IOException("Error: " + e.getMessage());
    } catch (IOException e) {
      throw new IOException("Error: " + e.getMessage());
    }
    return ks;
  }
コード例 #12
0
    private List<Certificate> readCertificateList(BufferedSource source) throws IOException {
      int length = readInt(source);
      if (length == -1) return Collections.emptyList(); // OkHttp v1.2 used -1 to indicate null.

      try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        List<Certificate> result = new ArrayList<>(length);
        for (int i = 0; i < length; i++) {
          String line = source.readUtf8LineStrict();
          Buffer bytes = new Buffer();
          bytes.write(ByteString.decodeBase64(line));
          result.add(certificateFactory.generateCertificate(bytes.inputStream()));
        }
        return result;
      } catch (CertificateException e) {
        throw new IOException(e.getMessage());
      }
    }
コード例 #13
0
 private Certificate[] readCertArray(StrictLineReader reader) throws IOException {
   int length = reader.readInt();
   if (length == -1) {
     return null;
   }
   try {
     CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
     Certificate[] result = new Certificate[length];
     for (int i = 0; i < result.length; i++) {
       String line = reader.readLine();
       byte[] bytes = Base64.decode(line, Base64.DEFAULT);
       result[i] = certificateFactory.generateCertificate(new ByteArrayInputStream(bytes));
     }
     return result;
   } catch (CertificateException e) {
     throw new IOException(e.getMessage());
   }
 }
コード例 #14
0
ファイル: CrlResource.java プロジェクト: jbowes/candlepin
  /**
   * Retrieves the Certificate Revocation List
   *
   * @return a String object
   * @throws CRLException if there is issue generating the CRL
   * @throws IOException if there is a problem serializing the CRL
   * @httpcode 200
   */
  @GET
  @Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN})
  public String getCurrentCrl(@Context Principal principal) throws CRLException, IOException {

    String filePath = getCrlFilePath();
    File crlFile = new File(filePath);

    byte[] encoded = null;

    try {
      X509CRL crl = crlFileUtil.readCRLFile(crlFile);
      crl = crlGenerator.syncCRLWithDB(crl);
      encoded = crlFileUtil.writeCRLFile(crlFile, crl);
    } catch (CertificateException e) {
      throw new IseException(e.getMessage(), e);
    }

    return new String(encoded);
  }
コード例 #15
0
ファイル: SecurityUtil.java プロジェクト: RalphC/upmp
 public static void initEncryptCert() {
   CertificateFactory cf = null;
   FileInputStream in = null;
   try {
     cf = CertificateFactory.getInstance("X.509");
     in = new FileInputStream(UPMPConstant.encryptCertPath);
     encryptCert = (X509Certificate) cf.generateCertificate(in);
   } catch (CertificateException e) {
     logger.error(e.getMessage());
   } catch (FileNotFoundException e) {
     logger.error(e.getMessage());
   } finally {
     if (null != in)
       try {
         in.close();
       } catch (IOException e) {
         logger.error(e.getMessage());
       }
   }
 }
コード例 #16
0
ファイル: CrlResource.java プロジェクト: jbowes/candlepin
  /**
   * Deletes a Certificate from the Revocation List
   *
   * @param serialIds list of certificate serial ids
   * @throws CRLException if there is a problem updating the CRL object
   * @throws IOException if there is a problem reading the CRL file
   */
  @DELETE
  @Produces(MediaType.APPLICATION_JSON)
  public void unrevoke(@QueryParam("serial") String[] serialIds) throws CRLException, IOException {

    String filePath = getCrlFilePath();
    File crlFile = new File(filePath);

    try {
      X509CRL crl = crlFileUtil.readCRLFile(crlFile);

      // get crl file if it exists
      // lookup entitlement, find CertificateSerial
      List<CertificateSerial> serials = certificateSerialCurator.listBySerialIds(serialIds);

      crl = crlGenerator.removeEntries(crl, serials);

      crlFileUtil.writeCRLFile(crlFile, crl);
    } catch (CertificateException e) {
      throw new IseException(e.getMessage(), e);
    }
  }
コード例 #17
0
  /**
   * parse arguments
   *
   * @param args arguments
   */
  private void parseArguments(String[] args) {
    // parse arguments
    int z = 0;
    while (z < args.length) {
      if (args[z].startsWith("-h") || args[z].startsWith("--help")) {
        printUsage();
        System.exit(0);
      } else if (args[z].startsWith("-p=") || args[z].startsWith("--port=")) {
        String value = args[z].substring(args[z].indexOf('=') + 1);
        try {
          serverPort = Integer.parseInt(value);
        } catch (NumberFormatException exception) {
          throw new Error(
              "Invalid value '"
                  + value
                  + "' for option --port (error: "
                  + exception.getMessage()
                  + ")!");
        }
        z += 1;
      } else if (args[z].equals("-p") || args[z].equals("--port")) {
        if ((z + 1) >= args.length) {
          throw new Error("Expected value for option --port!");
        }
        try {
          serverPort = Integer.parseInt(args[z + 1]);
        } catch (NumberFormatException exception) {
          throw new Error(
              "Invalid value '"
                  + args[z + 1]
                  + "' for option --port (error: "
                  + exception.getMessage()
                  + ")!");
        }
        z += 2;
      } else if (args[z].startsWith("--tls-port=")) {
        String value = args[z].substring(args[z].indexOf('=') + 1);
        try {
          serverTLSPort = Integer.parseInt(value);
        } catch (NumberFormatException exception) {
          throw new Error(
              "Invalid value '"
                  + value
                  + "' for option --tls-port (error: "
                  + exception.getMessage()
                  + ")!");
        }
        z += 1;
      } else if (args[z].equals("--tls-port")) {
        if ((z + 1) >= args.length) {
          throw new Error("Expected value for option --tls-port!");
        }
        try {
          serverTLSPort = Integer.parseInt(args[z + 1]);
        } catch (NumberFormatException exception) {
          throw new Error(
              "Invalid value '"
                  + args[z + 1]
                  + "' for option --tls-port (error: "
                  + exception.getMessage()
                  + ")!");
        }
        z += 2;
      } else if (args[z].startsWith("--login-dialog=")) {
        String value = args[z].substring(args[z].indexOf('=') + 1).toLowerCase();
        if (value.equals("yes") || value.equals("on") || value.equals("1")) {
          loginDialogFlag = true;
        } else if (value.equals("no") || value.equals("off") || value.equals("0")) {
          loginDialogFlag = false;
        } else {
          throw new Error(
              "Invalid value '"
                  + value
                  + "' for option --login-dialog (error: expected yes,on,1 or no,off,0)!");
        }
        z += 1;
      } else if (args[z].equals("--login-dialog")) {
        loginDialogFlag = true;
        z += 1;
      } else if (args[z].startsWith("--key-file=")) {
        serverKeyFileName = args[z].substring(args[z].indexOf('=') + 1);
        z += 1;
      } else if (args[z].equals("--key-file")) {
        if ((z + 1) >= args.length) {
          throw new Error("Expected value for option --key-file!");
        }
        serverKeyFileName = args[z + 1];
        z += 2;
      } else if (args[z].equals("--debug")) {
        debug = true;
        z += 1;
      } else if (args[z].equals("--bar-server-debug")) {
        BARServer.debug = true;
        z += 1;
      } else if (args[z].equals("--")) {
        z += 1;
        break;
      } else if (args[z].startsWith("--")) {
        throw new Error("Unknown option '" + args[z] + "'!");
      } else {
        serverName = args[z];
        z += 1;
      }
    }

    // check arguments
    if (serverKeyFileName != null) {
      // check if JKS file readable
      try {
        KeyStore keyStore = java.security.KeyStore.getInstance("JKS");
        keyStore.load(new java.io.FileInputStream(serverKeyFileName), null);
      } catch (java.security.NoSuchAlgorithmException exception) {
        throw new Error(exception.getMessage());
      } catch (java.security.cert.CertificateException exception) {
        throw new Error(exception.getMessage());
      } catch (java.security.KeyStoreException exception) {
        throw new Error(exception.getMessage());
      } catch (IOException exception) {
        throw new Error("not a JKS file '" + serverKeyFileName + "'");
      }
    }
  }
 public void actionPerformed(ActionEvent e) {
   final String S_ProcName = "actionPerformed";
   CFBamSwingMainJFrame mainJFrame = null;
   {
     Container cont = getParent();
     while ((cont != null) && (!(cont instanceof CFBamSwingMainJFrame))) {
       cont = cont.getParent();
     }
     if (cont != null) {
       mainJFrame = (CFBamSwingMainJFrame) cont;
     }
   }
   char pw[] = textKeystorePassword.getPassword();
   String keystorePassword;
   if (pw != null) {
     keystorePassword = new String(pw);
   } else {
     keystorePassword = null;
   }
   CFBamClientConfigurationFile configFile = swingSchema.getClientConfigurationFile();
   String keystoreFileName = configFile.getKeyStore();
   boolean exitApp = false;
   boolean exitForm = false;
   boolean creatingKeystore = false;
   KeyStore keyStore = null;
   File keystoreFile = new File(keystoreFileName);
   if (!keystoreFile.exists()) {
     int userOption = JOptionPane.NO_OPTION;
     try {
       userOption =
           JOptionPane.showOptionDialog(
               null,
               "Would you like to create the keystore \""
                   + keystoreFileName
                   + "\"?\n"
                   + "Selecting No will exit the application so you can edit the client configuration file and restart.",
               "Create Keystore?",
               JOptionPane.YES_NO_OPTION,
               JOptionPane.QUESTION_MESSAGE,
               null,
               null,
               null);
     } catch (HeadlessException x) {
       throw CFLib.getDefaultExceptionFactory()
           .newRuntimeException(
               getClass(), S_ProcName, "Caught HeadlessException -- " + x.getMessage(), x);
     }
     if (userOption == JOptionPane.YES_OPTION) {
       creatingKeystore = true;
       JInternalFrame nextForm = swingSchema.newCreateKeystoreJInternalFrame();
       getDesktopPane().add(nextForm);
       nextForm.setVisible(true);
       nextForm.show();
       Container cont = getParent();
       while ((cont != null) && (!(cont instanceof JInternalFrame))) {
         cont = cont.getParent();
       }
       if (cont != null) {
         JInternalFrame frame = (JInternalFrame) cont;
         try {
           frame.setClosed(true);
         } catch (Exception x) {
         }
       }
     } else {
       exitApp = true;
     }
   } else if (!keystoreFile.isFile()) {
     JOptionPane.showMessageDialog(
         null,
         "The referenced JCEKS keystore \"" + keystoreFileName + "\" is not a file.",
         "Error",
         JOptionPane.ERROR_MESSAGE,
         null);
     exitApp = true;
   } else if (!keystoreFile.canRead()) {
     JOptionPane.showMessageDialog(
         null,
         "Permission denied attempting to access JCEKS keystore \"" + keystoreFileName + "\".",
         "Error",
         JOptionPane.ERROR_MESSAGE,
         null);
     exitApp = true;
   }
   if ((!exitApp) && (!creatingKeystore)) {
     try {
       keyStore = KeyStore.getInstance("jceks");
       char[] caPassword = keystorePassword.toCharArray();
       FileInputStream input = new FileInputStream(keystoreFileName);
       keyStore.load(input, caPassword);
       input.close();
       swingSchema.setKeyStore(keyStore);
       exitForm = true;
     } catch (CertificateException x) {
       keyStore = null;
       JOptionPane.showMessageDialog(
           null,
           "Could not open keystore due to CertificateException -- " + x.getMessage(),
           "Error",
           JOptionPane.ERROR_MESSAGE,
           null);
       exitApp = true;
     } catch (IOException x) {
       keyStore = null;
       JOptionPane.showMessageDialog(
           null,
           "Could not open keystore due to IOException -- " + x.getMessage(),
           "Error",
           JOptionPane.ERROR_MESSAGE,
           null);
     } catch (KeyStoreException x) {
       keyStore = null;
       JOptionPane.showMessageDialog(
           null,
           "Could not open keystore due to KeyStoreException -- " + x.getMessage(),
           "Error",
           JOptionPane.ERROR_MESSAGE,
           null);
       exitApp = true;
     } catch (NoSuchAlgorithmException x) {
       keyStore = null;
       JOptionPane.showMessageDialog(
           null,
           "Could not open keystore due to NoSuchAlgorithmException -- " + x.getMessage(),
           "Error",
           JOptionPane.ERROR_MESSAGE,
           null);
       exitApp = true;
     }
   }
   if (exitApp) {
     swingSchema.setKeyStore(null);
     mainJFrame.exitApplication();
   } else if (exitForm) {
     JInternalFrame nextForm = swingSchema.newOpenDeviceKeyJInternalFrame();
     getDesktopPane().add(nextForm);
     nextForm.setVisible(true);
     nextForm.show();
     Container cont = getParent();
     while ((cont != null) && (!(cont instanceof JInternalFrame))) {
       cont = cont.getParent();
     }
     if (cont != null) {
       JInternalFrame frame = (JInternalFrame) cont;
       try {
         frame.setClosed(true);
       } catch (Exception x) {
       }
     }
   }
 }
コード例 #19
0
ファイル: APNSKeeper.java プロジェクト: plugin94/QPush
  public PushManager get(Product product) {

    if (StringUtils.isBlank(product.getDevCertPath())
        || StringUtils.isBlank(product.getDevCertPass())
        || StringUtils.isBlank(product.getCertPath())
        || StringUtils.isBlank(product.getCertPass())) {
      logger.error("Product iOS Push Service Miss Cert Path and Password. {}", product);
      return null;
    }

    PushManager service = mapping.get(product.getId());
    if (service == null) {

      ApnsEnvironment apnsEnvironment = null;
      SSLContext sslContext = null;

      try {
        if (sandBox) {
          apnsEnvironment = ApnsEnvironment.getSandboxEnvironment();
          sslContext =
              SSLContextUtil.createDefaultSSLContext(
                  product.getDevCertPath(), product.getDevCertPass());
        } else {
          apnsEnvironment = ApnsEnvironment.getProductionEnvironment();
          sslContext =
              SSLContextUtil.createDefaultSSLContext(product.getCertPath(), product.getCertPass());
        }
      } catch (KeyStoreException e) {
        logger.error(e.getMessage(), e);
      } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e);
      } catch (CertificateException e) {
        logger.error(e.getMessage(), e);
      } catch (UnrecoverableKeyException e) {
        logger.error(e.getMessage(), e);
      } catch (KeyManagementException e) {
        logger.error(e.getMessage(), e);
      } catch (IOException e) {
        logger.error(e.getMessage(), e);
      }

      PushManagerConfiguration configuration = new PushManagerConfiguration();
      configuration.setConcurrentConnectionCount(1);

      final PushManager<SimpleApnsPushNotification> pushManager =
          new PushManager<SimpleApnsPushNotification>(
              apnsEnvironment,
              sslContext,
              null, // Optional: custom event loop group
              null, // Optional: custom ExecutorService for calling listeners
              null, // Optional: custom BlockingQueue implementation
              configuration,
              "ApnsPushManager-" + product.getId());

      pushManager.registerRejectedNotificationListener(new PushRejectedNotificationListener());
      pushManager.registerFailedConnectionListener(new PushFailedConnectionListener());

      pushManager.start();

      //             ApnsServiceBuilder builder =  APNS.newService();
      //            if (sandBox){
      //                builder.withCert(product.getDevCertPath(), product.getDevCertPass());
      //                builder.withSandboxDestination();
      //            }else{
      //                builder.withCert(product.getCertPath(), product.getCertPass());
      //                builder.withProductionDestination();
      //            }
      //            service =
      // builder.asPool(10).withCacheLength(Integer.MAX_VALUE).withDelegate(delegateAdapter).asQueued().build();

      mapping.put(product.getId(), pushManager);
      service = pushManager;
    }

    return service;
  }
  @Override
  public void contextInitialized(ServletContextEvent arg0) {
    final String S_ProcName = "contextInitialized";

    Properties props = System.getProperties();
    if (null == CFBamSchemaPool.getSchemaPool()) {
      try {
        Context ctx = new InitialContext();
        String poolClassName = (String) ctx.lookup("java:comp/env/CFBam24PoolClass");
        if ((poolClassName == null) || (poolClassName.length() <= 0)) {
          throw CFLib.getDefaultExceptionFactory()
              .newNullArgumentException(
                  getClass(), S_ProcName, 0, "JNDI lookup for CFBam24PoolClass");
        }

        Class poolClass = Class.forName(poolClassName);
        if (poolClass == null) {
          throw CFLib.getDefaultExceptionFactory()
              .newNullArgumentException(
                  getClass(),
                  S_ProcName,
                  0,
                  "CFBam24PoolClass \"" + poolClassName + "\" not found.");
        }

        Object obj = poolClass.newInstance();
        if (obj instanceof CFBamSchemaPool) {
          CFBamSchemaPool newPool = (CFBamSchemaPool) obj;
          newPool.setConfigurationFile(null);
          newPool.setJndiName("java:comp/env/CFBam24Connection");
          CFBamSchemaPool.setSchemaPool(newPool);
        } else {
          throw CFLib.getDefaultExceptionFactory()
              .newRuntimeException(
                  getClass(), S_ProcName, "Problems constructing an instance of " + poolClassName);
        }

        String smtpHost = (String) ctx.lookup("java:comp/env/CFBam24SmtpHost");
        if ((smtpHost == null) || (smtpHost.length() <= 0)) {
          throw CFLib.getDefaultExceptionFactory()
              .newNullArgumentException(
                  getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpHost");
        }
        props.setProperty("mail.smtp.host", smtpHost);

        String smtpStartTLS = (String) ctx.lookup("java:comp/env/CFBam24SmtpStartTLS");
        if ((smtpHost == null) || (smtpHost.length() <= 0)) {
          throw CFLib.getDefaultExceptionFactory()
              .newNullArgumentException(
                  getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpStartTLS");
        }
        props.setProperty("mail.smtp.starttls.enable", smtpStartTLS);

        String smtpSocketFactoryClass =
            (String) ctx.lookup("java:comp/env/CFBam24SmtpSocketFactoryClass");
        if ((smtpSocketFactoryClass == null) || (smtpSocketFactoryClass.length() <= 0)) {
          throw CFLib.getDefaultExceptionFactory()
              .newNullArgumentException(
                  getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpSocketFactoryClass");
        }
        props.setProperty("mail.smtp.socketFactory.class", smtpSocketFactoryClass);

        props.setProperty("mail.smtp.socketFactory.fallback", "false");

        String smtpPort = (String) ctx.lookup("java:comp/env/CFBam24SmtpPort");
        if ((smtpPort == null) || (smtpPort.length() <= 0)) {
          throw CFLib.getDefaultExceptionFactory()
              .newNullArgumentException(
                  getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpPort");
        }
        props.setProperty("mail.smtp.port", smtpPort);
        props.setProperty("mail.smtp.socketFactory.port", smtpPort);

        props.setProperty("mail.smtps.auth", "true");

        props.put("mail.smtps.quitwait", "false");

        String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFBam24SmtpEmailFrom");
        if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
          throw CFLib.getDefaultExceptionFactory()
              .newNullArgumentException(
                  getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpEmailFrom");
        }

        smtpUsername = (String) ctx.lookup("java:comp/env/CFBam24SmtpUsername");
        if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
          throw CFLib.getDefaultExceptionFactory()
              .newNullArgumentException(
                  getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpUsername");
        }

        smtpPassword = (String) ctx.lookup("java:comp/env/CFBam24SmtpPassword");
        if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
          throw CFLib.getDefaultExceptionFactory()
              .newNullArgumentException(
                  getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpPassword");
        }

        String serverKeyStore;
        try {
          serverKeyStore = (String) ctx.lookup("java:comp/env/CFBam24ServerKeyStore");
        } catch (NamingException e) {
          serverKeyStore = null;
        }

        String keyStorePassword;
        try {
          keyStorePassword = (String) ctx.lookup("java:comp/env/CFBam24KeyStorePassword");
        } catch (NamingException e) {
          keyStorePassword = null;
        }

        String keyName;
        try {
          keyName = (String) ctx.lookup("java:comp/env/CFBam24KeyName");
        } catch (NamingException e) {
          keyName = null;
        }

        String keyPassword;
        try {
          keyPassword = (String) ctx.lookup("java:comp/env/CFBam24KeyPassword");
        } catch (NamingException e) {
          keyPassword = null;
        }

        if (((serverKeyStore != null) && (serverKeyStore.length() > 0))
            && (keyStorePassword != null)
            && ((keyName != null) && (keyName.length() > 0))
            && (keyPassword != null)) {
          KeyStore keyStore = null;
          File keystoreFile = new File(serverKeyStore);
          if (!keystoreFile.exists()) {
            throw CFLib.getDefaultExceptionFactory()
                .newUsageException(
                    getClass(),
                    S_ProcName,
                    "CFBam24ServerKeyStore file \"" + serverKeyStore + "\" does not exist.");
          } else if (!keystoreFile.isFile()) {
            throw CFLib.getDefaultExceptionFactory()
                .newUsageException(
                    getClass(),
                    S_ProcName,
                    "CFBam24ServerKeyStore file \"" + serverKeyStore + "\" is not a file.");
          } else if (!keystoreFile.canRead()) {
            throw CFLib.getDefaultExceptionFactory()
                .newUsageException(
                    getClass(),
                    S_ProcName,
                    "Permission denied attempting to read CFBam24ServerKeyStore file \""
                        + serverKeyStore
                        + "\".");
          }

          try {
            keyStore = KeyStore.getInstance("jceks");
            char[] caPassword = keyStorePassword.toCharArray();
            FileInputStream input = new FileInputStream(serverKeyStore);
            keyStore.load(input, caPassword);
            input.close();
            Certificate publicKeyCertificate = keyStore.getCertificate(keyName);
            if (publicKeyCertificate == null) {
              throw CFLib.getDefaultExceptionFactory()
                  .newUsageException(
                      getClass(),
                      S_ProcName,
                      "Could not read CFBam24KeyName \""
                          + keyName
                          + "\" from CFBam24ServerKeyStore file \""
                          + serverKeyStore
                          + "\".");
            }
            publicKey = publicKeyCertificate.getPublicKey();
            char[] caKeyPassword = keyPassword.toCharArray();
            Key key = keyStore.getKey(keyName, caKeyPassword);
            if (key instanceof PrivateKey) {
              privateKey = (PrivateKey) key;
            } else {
              throw CFLib.getDefaultExceptionFactory()
                  .newUnsupportedClassException(getClass(), S_ProcName, "key", key, "PrivateKey");
            }

            getServerInfo();
          } catch (CertificateException x) {
            publicKey = null;
            privateKey = null;
            throw CFLib.getDefaultExceptionFactory()
                .newRuntimeException(
                    getClass(),
                    S_ProcName,
                    "Could not open keystore due to CertificateException -- " + x.getMessage(),
                    x);
          } catch (IOException x) {
            publicKey = null;
            privateKey = null;
            throw CFLib.getDefaultExceptionFactory()
                .newRuntimeException(
                    getClass(),
                    S_ProcName,
                    "Could not open keystore due to IOException -- " + x.getMessage(),
                    x);
          } catch (KeyStoreException x) {
            publicKey = null;
            privateKey = null;
            throw CFLib.getDefaultExceptionFactory()
                .newRuntimeException(
                    getClass(),
                    S_ProcName,
                    "Could not open keystore due to KeyStoreException -- " + x.getMessage(),
                    x);
          } catch (NoSuchAlgorithmException x) {
            publicKey = null;
            privateKey = null;
            throw CFLib.getDefaultExceptionFactory()
                .newRuntimeException(
                    getClass(),
                    S_ProcName,
                    "Could not open keystore due to NoSuchAlgorithmException -- " + x.getMessage(),
                    x);
          } catch (UnrecoverableKeyException x) {
            publicKey = null;
            privateKey = null;
            throw CFLib.getDefaultExceptionFactory()
                .newRuntimeException(
                    getClass(),
                    S_ProcName,
                    "Could not access key due to UnrecoverableKeyException -- " + x.getMessage(),
                    x);
          } catch (RuntimeException x) {
            publicKey = null;
            privateKey = null;
            throw x;
          }
        } else if ((serverKeyStore != null)
            || (keyStorePassword != null)
            || (keyName != null)
            || (keyPassword != null)) {
          publicKey = null;
          privateKey = null;
          throw CFLib.getDefaultExceptionFactory()
              .newUsageException(
                  getClass(),
                  S_ProcName,
                  "All or none of CFBam24ServerKeyStore, "
                      + "CFBam24KeyStorePassword, "
                      + "CFBam24KeyName, and "
                      + "CFBam24KeyPassword must be configured");
        } else {
          getServerInfo();
          try {
            serverInfo.initServerKeys();
          } catch (Exception x) {
            throw CFLib.getDefaultExceptionFactory()
                .newRuntimeException(
                    getClass(),
                    S_ProcName,
                    "Caught "
                        + x.getClass().getName()
                        + " during initServerKeys() -- "
                        + x.getMessage(),
                    x);
          }
        }
      } catch (ClassNotFoundException e) {
        publicKey = null;
        privateKey = null;
        throw CFLib.getDefaultExceptionFactory()
            .newRuntimeException(
                getClass(), S_ProcName, "Caught ClassNotFoundException -- " + e.getMessage(), e);
      } catch (IllegalAccessException e) {
        publicKey = null;
        privateKey = null;
        throw CFLib.getDefaultExceptionFactory()
            .newRuntimeException(
                getClass(),
                S_ProcName,
                "Caught IllegalAccessException trying to construct newInstance() -- "
                    + e.getMessage(),
                e);
      } catch (InstantiationException e) {
        publicKey = null;
        privateKey = null;
        throw CFLib.getDefaultExceptionFactory()
            .newRuntimeException(
                getClass(),
                S_ProcName,
                "Caught InstantiationException trying to construct newInstance() -- "
                    + e.getMessage(),
                e);
      } catch (NamingException e) {
        publicKey = null;
        privateKey = null;
        throw CFLib.getDefaultExceptionFactory()
            .newRuntimeException(
                getClass(), S_ProcName, "Caught NamingException -- " + e.getMessage(), e);
      }
    }
  }
コード例 #21
0
  public List<VerifyResultDTO> verifySign(final VerifyingDTO verifyingDTO) {
    final List<VerifyResultDTO> result = new ArrayList<VerifyResultDTO>();
    try {
      if (verifyingDTO != null) {
        final String keyType =
            (String) nodeService.getProperty(verifyingDTO.getKeyFile(), SigningModel.PROP_KEYTYPE);

        final KeyStore ks = KeyStore.getInstance(keyType);
        final ContentReader keyContentReader = getReader(verifyingDTO.getKeyFile());
        if (keyContentReader != null && ks != null && verifyingDTO.getKeyPassword() != null) {

          // Get crypted secret key and decrypt it
          final Serializable encryptedPropertyValue =
              nodeService.getProperty(verifyingDTO.getKeyFile(), SigningModel.PROP_KEYCRYPTSECRET);
          final Serializable decryptedPropertyValue =
              metadataEncryptor.decrypt(SigningModel.PROP_KEYCRYPTSECRET, encryptedPropertyValue);

          // Decrypt key content
          final InputStream decryptedKeyContent =
              CryptUtils.decrypt(
                  decryptedPropertyValue.toString(), keyContentReader.getContentInputStream());

          ks.load(
              new ByteArrayInputStream(IOUtils.toByteArray(decryptedKeyContent)),
              verifyingDTO.getKeyPassword().toCharArray());

          final ContentReader fileToVerifyContentReader = getReader(verifyingDTO.getFileToVerify());
          if (fileToVerifyContentReader != null) {
            final PdfReader reader =
                new PdfReader(fileToVerifyContentReader.getContentInputStream());
            if (reader != null) {
              final AcroFields af = reader.getAcroFields();
              if (af != null) {
                final ArrayList<String> names = af.getSignatureNames();
                if (names != null) {
                  for (int k = 0; k < names.size(); ++k) {
                    final VerifyResultDTO verifyResultDTO = new VerifyResultDTO();
                    final String name = (String) names.get(k);
                    verifyResultDTO.setName(name);
                    verifyResultDTO.setSignatureCoversWholeDocument(
                        af.signatureCoversWholeDocument(name));
                    verifyResultDTO.setRevision(af.getRevision(name));
                    verifyResultDTO.setTotalRevision(af.getTotalRevisions());

                    final PdfPKCS7 pk = af.verifySignature(name);
                    if (pk != null) {
                      final Calendar cal = pk.getSignDate();
                      final Certificate[] pkc = pk.getCertificates();
                      Object fails[] = PdfPKCS7.verifyCertificates(pkc, ks, null, cal);
                      if (fails == null) {
                        verifyResultDTO.setIsSignValid(true);
                      } else {
                        verifyResultDTO.setIsSignValid(false);
                        verifyResultDTO.setFailReason(fails[1]);
                      }
                      verifyResultDTO.setSignSubject(
                          PdfPKCS7.getSubjectFields(pk.getSigningCertificate()).toString());
                      verifyResultDTO.setIsDocumentModified(!pk.verify());
                      verifyResultDTO.setSignDate(pk.getSignDate());
                      verifyResultDTO.setSignLocation(pk.getLocation());
                      verifyResultDTO.setSignInformationVersion(pk.getSigningInfoVersion());
                      verifyResultDTO.setSignReason(pk.getReason());
                      verifyResultDTO.setSignVersion(pk.getVersion());
                      verifyResultDTO.setSignName(pk.getSignName());

                      result.add(verifyResultDTO);
                    } else {
                      log.error("Unable to verify signature.");
                      throw new AlfrescoRuntimeException("Unable to verify signature.");
                    }
                  }
                } else {
                  log.error("Unable to get signature names.");
                  throw new AlfrescoRuntimeException("Unable to get signature names.");
                }
              } else {
                log.error("Unable to get PDF fields.");
                throw new AlfrescoRuntimeException("Unable to get PDF fields.");
              }
            }
          } else {
            log.error("Unable to get document to verify content.");
            throw new AlfrescoRuntimeException("Unable to get document to verify content.");
          }
        } else {
          log.error("Unable to get key content, key type or key password.");
          throw new AlfrescoRuntimeException(
              "Unable to get key content, key type or key password.");
        }
      } else {
        log.error("No object with verification informations.");
        throw new AlfrescoRuntimeException("No object with verification informations.");
      }
    } catch (KeyStoreException e) {
      log.error(e);
      throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (ContentIOException e) {
      log.error(e);
      throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
      log.error(e);
      throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (CertificateException e) {
      log.error(e);
      throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (IOException e) {
      log.error(e);
      throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (GeneralSecurityException e) {
      log.error(e);
      throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (Throwable e) {
      log.error(e);
      throw new AlfrescoRuntimeException(e.getMessage(), e);
    }

    return result;
  }
コード例 #22
0
  /**
   * Sign file.
   *
   * @param signingDTO sign informations
   * @param pdfSignedFile signed pdf returned
   */
  public void sign(final DigitalSigningDTO signingDTO) {
    if (signingDTO != null) {

      try {
        Security.addProvider(new BouncyCastleProvider());
        final File alfTempDir = TempFileProvider.getTempDir();

        if (alfTempDir != null) {
          final String keyType =
              (String) nodeService.getProperty(signingDTO.getKeyFile(), SigningModel.PROP_KEYTYPE);

          if (SigningConstants.KEY_TYPE_X509.equals(keyType)) {
            // Sign the file
            final KeyStore ks = KeyStore.getInstance("pkcs12");
            final ContentReader keyContentReader = getReader(signingDTO.getKeyFile());

            if (keyContentReader != null && ks != null && signingDTO.getKeyPassword() != null) {

              final List<AlfrescoRuntimeException> errors =
                  new ArrayList<AlfrescoRuntimeException>();

              // Get crypted secret key and decrypt it
              final Serializable encryptedPropertyValue =
                  nodeService.getProperty(
                      signingDTO.getKeyFile(), SigningModel.PROP_KEYCRYPTSECRET);
              final Serializable decryptedPropertyValue =
                  metadataEncryptor.decrypt(
                      SigningModel.PROP_KEYCRYPTSECRET, encryptedPropertyValue);

              // Decrypt key content
              InputStream decryptedKeyContent;
              try {
                decryptedKeyContent =
                    CryptUtils.decrypt(
                        decryptedPropertyValue.toString(),
                        keyContentReader.getContentInputStream());
              } catch (Throwable e) {
                log.error(e);
                throw new AlfrescoRuntimeException(e.getMessage(), e);
              }

              ks.load(
                  new ByteArrayInputStream(IOUtils.toByteArray(decryptedKeyContent)),
                  signingDTO.getKeyPassword().toCharArray());

              final String alias =
                  (String)
                      nodeService.getProperty(signingDTO.getKeyFile(), SigningModel.PROP_KEYALIAS);

              final PrivateKey key =
                  (PrivateKey) ks.getKey(alias, signingDTO.getKeyPassword().toCharArray());
              final Certificate[] chain = ks.getCertificateChain(alias);

              final Iterator<NodeRef> itFilesToSign = signingDTO.getFilesToSign().iterator();
              while (itFilesToSign.hasNext()) {
                final NodeRef nodeRefToSign = itFilesToSign.next();
                final AlfrescoRuntimeException exception =
                    signFile(nodeRefToSign, signingDTO, alfTempDir, alias, ks, key, chain);
                if (exception != null) {
                  // Error on the file process
                  errors.add(exception);
                }
              }

              if (errors != null && errors.size() > 0) {
                final StringBuffer allErrors = new StringBuffer();
                final Iterator<AlfrescoRuntimeException> itErrors = errors.iterator();
                if (errors.size() > 1) {
                  allErrors.append("\n");
                }
                while (itErrors.hasNext()) {
                  final AlfrescoRuntimeException alfrescoRuntimeException = itErrors.next();
                  allErrors.append(alfrescoRuntimeException.getMessage());
                  if (itErrors.hasNext()) {
                    allErrors.append("\n");
                  }
                }
                throw new RuntimeException(allErrors.toString());
              }

            } else {
              log.error("Unable to get key content, key type or key password.");
              throw new AlfrescoRuntimeException(
                  "Unable to get key content, key type or key password.");
            }
          }
        } else {
          log.error("Unable to get temporary directory.");
          throw new AlfrescoRuntimeException("Unable to get temporary directory.");
        }
      } catch (KeyStoreException e) {
        log.error(e);
        throw new AlfrescoRuntimeException(e.getMessage(), e);
      } catch (NoSuchAlgorithmException e) {
        log.error(e);
        throw new AlfrescoRuntimeException(e.getMessage(), e);
      } catch (CertificateException e) {
        log.error(e);
        throw new AlfrescoRuntimeException(e.getMessage(), e);
      } catch (IOException e) {
        log.error(e);
        throw new AlfrescoRuntimeException(e.getMessage(), e);
      } catch (UnrecoverableKeyException e) {
        log.error(e);
        throw new AlfrescoRuntimeException(e.getMessage(), e);
      }
    } else {
      log.error("No object with signing informations.");
      throw new AlfrescoRuntimeException("No object with signing informations.");
    }
  }