コード例 #1
0
  private void enableEncryption(boolean tls) throws Exception {
    SSLContext context = this.config.getCustomSSLContext();
    KeyStore ks = null;
    KeyManager[] kms = null;
    PasswordCallback pcb = null;

    if (config.getCallbackHandler() == null) {
      ks = null;
    } else if (context == null) {
      // System.out.println("Keystore type: "+configuration.getKeystoreType());
      if (config.getKeystoreType().equals("NONE")) {
        ks = null;
        pcb = null;
      } else if (config.getKeystoreType().equals("PKCS11")) {
        try {
          Constructor c =
              Class.forName("sun.security.pkcs11.SunPKCS11").getConstructor(InputStream.class);
          String pkcs11Config = "name = SmartCard\nlibrary = " + config.getPKCS11Library();
          ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes());
          Provider p = (Provider) c.newInstance(config);
          Security.addProvider(p);
          ks = KeyStore.getInstance("PKCS11", p);
          pcb = new PasswordCallback("PKCS11 Password: "******"Apple")) {
        ks = KeyStore.getInstance("KeychainStore", "Apple");
        ks.load(null, null);
        // pcb = new PasswordCallback("Apple Keychain",false);
        // pcb.setPassword(null);
      } else {
        ks = KeyStore.getInstance(config.getKeystoreType());
        try {
          pcb = new PasswordCallback("Keystore Password: "******"SunX509");
      try {
        if (pcb == null) {
          kmf.init(ks, null);
        } else {
          kmf.init(ks, pcb.getPassword());
          pcb.clearPassword();
        }
        kms = kmf.getKeyManagers();
      } catch (NullPointerException npe) {
        kms = null;
      }
    }

    // Verify certificate presented by the server
    if (context == null) {
      context = SSLContext.getInstance("TLS");
      boolean chainCheck = config.isVerifyChainEnabled();
      boolean domainCheck = config.isNotMatchingDomainCheckEnabled();
      boolean allowSelfSigned = config.isSelfSignedCertificateEnabled();
      if (config.isExpiredCertificatesCheckEnabled() != chainCheck
          || config.isVerifyRootCAEnabled() != chainCheck) throw new IllegalStateException();
      context.init(
          kms,
          new TrustManager[] {
            new XMPPTrustManager(
                KeyStoreManager.getOrCreateKeyStore(config),
                getServiceName(),
                config.getCertificateListener(),
                chainCheck,
                domainCheck,
                allowSelfSigned)
          },
          SECURE_RANDOM);
    }
    Socket plain = socket;
    // Secure the plain connection
    socket =
        context
            .getSocketFactory()
            .createSocket(plain, plain.getInetAddress().getHostAddress(), plain.getPort(), true);
    // socket.setSoTimeout(0);
    // socket.setKeepAlive(true);
  }