Ejemplo n.º 1
0
  public static KeyPair getPrivateKey(String alias, char[] password)
      throws FileNotFoundException, IOException, CertificateException {
    try {

      KeyStore ks = KeyStore.getInstance("JKS");

      char[] passPhrase = "123456".toCharArray();
      // BASE64Encoder myB64 = new BASE64Encoder();

      File certificateFile = new File("C:\\Temp\\repositorio.jks");
      ks.load(new FileInputStream(certificateFile), passPhrase);

      // Get private key
      Key key = ks.getKey(alias, password);
      if (key instanceof PrivateKey) {
        // Get certificate of public key
        Certificate cert = ks.getCertificate(alias);

        // Get public key
        PublicKey publicKey = cert.getPublicKey();

        // Return a key pair
        return new KeyPair(publicKey, (PrivateKey) key);
      }
    } catch (UnrecoverableKeyException e) {
      System.out.print(e.getMessage());
    } catch (NoSuchAlgorithmException e) {
      System.out.print(e.getMessage());
    } catch (KeyStoreException e) {
      System.out.print(e.getMessage());
    }
    return null;
  }
  /**
   * ִ��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;
  }
 private SSLSocketFactory getSSLSocketFactory(String keyStoreName, String password) {
   KeyStore ks = getKeyStore(keyStoreName, password);
   KeyManagerFactory keyManagerFactory = null;
   try {
     keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
     keyManagerFactory.init(ks, password.toCharArray());
     SSLContext context = SSLContext.getInstance("TLS");
     context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
     return context.getSocketFactory();
   } 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 (UnrecoverableKeyException e) {
     logger.error(e.getMessage(), e);
     throw new RuntimeException(e.getMessage(), e);
   } catch (KeyManagementException e) {
     logger.error(e.getMessage(), e);
     throw new RuntimeException(e.getMessage(), e);
   }
 }
Ejemplo n.º 4
0
  /**
   * Performs test signatures for the specified keys or for all if "all" specified.
   *
   * @param keyStore Loaded keystore to read keys from
   * @param alias Alias of key to test or "all" to test all
   * @param authCode Key password (if used, ie for JKS only)
   * @param signatureProvider Provider for creating the signature
   * @return The results for each key found
   * @throws CryptoTokenOfflineException In case the key could not be used
   */
  public static Collection<KeyTestResult> testKey(
      KeyStore keyStore, String alias, char[] authCode, String signatureProvider)
      throws CryptoTokenOfflineException {
    if (LOG.isDebugEnabled()) {
      LOG.debug("testKey for alias: " + alias);
    }

    final Collection<KeyTestResult> result = new LinkedList<KeyTestResult>();

    try {
      final Enumeration<String> e = keyStore.aliases();
      while (e.hasMoreElements()) {
        final String keyAlias = e.nextElement();
        if (alias.equalsIgnoreCase(ICryptoToken.ALL_KEYS) || alias.equals(keyAlias)) {
          if (LOG.isDebugEnabled()) {
            LOG.debug("checking keyAlias: " + keyAlias);
          }

          if (keyStore.isKeyEntry(keyAlias)) {
            String status;
            String publicKeyHash = null;
            boolean success = false;
            try {
              final PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, authCode);
              final Certificate entryCert = keyStore.getCertificate(keyAlias);
              if (entryCert != null) {
                final PublicKey publicKey = entryCert.getPublicKey();
                publicKeyHash = createKeyHash(publicKey);
                testSignAndVerify(privateKey, publicKey, signatureProvider);
                success = true;
                status = "";
              } else {
                status = "Not testing keys with alias " + keyAlias + ". No certificate exists.";
              }
            } catch (ClassCastException ce) {
              status = "Not testing keys with alias " + keyAlias + ". Not a private key.";
            } catch (InvalidKeyException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            } catch (KeyStoreException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            } catch (NoSuchAlgorithmException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            } catch (NoSuchProviderException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            } catch (SignatureException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            } catch (UnrecoverableKeyException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            }
            result.add(new KeyTestResult(keyAlias, success, status, publicKeyHash));
          }
        }
      }
    } catch (KeyStoreException ex) {
      throw new CryptoTokenOfflineException(ex);
    }

    if (LOG.isDebugEnabled()) {
      LOG.debug("<testKey");
    }
    return result;
  }
  @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);
      }
    }
  }
Ejemplo n.º 6
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.");
    }
  }
Ejemplo n.º 7
0
  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;
  }