/**
   * @param config The Properties holding a username, password etc.
   * @param properties Properties holding server settings and configuration
   */
  public ComposeMailScreen(Properties config) {
    this.username = config.getProperty("username");
    Authenticator authenticator =
        new Authenticator() {
          @Override
          protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
          }
        };

    this.keyWords = new ArrayList<String>();
    this.session = Session.getInstance(config, authenticator);
    // The password which will be decrypted
    String passwordDec = config.getProperty("password");
    try {
      passwordDec = ProtectedPassword.decrypt(passwordDec);
    } catch (GeneralSecurityException ex) {
      JOptionPane.showMessageDialog(
          rootPane, ex.toString(), "GeneralSecurityException", JOptionPane.ERROR_MESSAGE);
    } catch (IOException ex) {
      JOptionPane.showMessageDialog(
          rootPane, ex.toString(), "GeneralSecurityException", JOptionPane.ERROR_MESSAGE);
    }

    this.password = passwordDec;
    initComponents();
    this.setLocationRelativeTo(null);
  }
Exemplo n.º 2
0
 private static void writePemEncrypted(
     BufferedWriter out, String pemHeader, byte[] encoding, CipherSpec cipher, char[] passwd)
     throws IOException {
   Cipher c = cipher.getCipher();
   byte[] iv = new byte[c.getBlockSize()];
   random.nextBytes(iv);
   byte[] salt = new byte[8];
   System.arraycopy(iv, 0, salt, 0, 8);
   OpenSSLPBEParametersGenerator pGen = new OpenSSLPBEParametersGenerator();
   pGen.init(PBEParametersGenerator.PKCS5PasswordToBytes(passwd), salt);
   KeyParameter param = (KeyParameter) pGen.generateDerivedParameters(cipher.getKeyLenInBits());
   SecretKey secretKey =
       new SecretKeySpec(
           param.getKey(), org.jruby.ext.openssl.Cipher.Algorithm.getAlgorithmBase(c));
   byte[] encData = null;
   try {
     c.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv));
     encData = c.doFinal(encoding);
   } catch (GeneralSecurityException gse) {
     throw new IOException("exception using cipher: " + gse.toString());
   }
   out.write(BEF_G + pemHeader + AFT);
   out.newLine();
   out.write("Proc-Type: 4,ENCRYPTED");
   out.newLine();
   out.write("DEK-Info: " + cipher.getOsslName() + ",");
   writeHexEncoded(out, iv);
   out.newLine();
   out.newLine();
   writeEncoded(out, encData);
   out.write(BEF_E + pemHeader + AFT);
   out.flush();
 }
Exemplo n.º 3
0
  private X509Certificate[] doBuild(X509Certificate[] chain, Collection otherCerts)
      throws CertificateException {
    try {
      PKIXBuilderParameters params = (PKIXBuilderParameters) parameterTemplate.clone();
      setDate(params);

      // setup target constraints
      X509CertSelector selector = new X509CertSelector();
      selector.setCertificate(chain[0]);
      params.setTargetCertConstraints(selector);

      // setup CertStores
      Collection certs = new ArrayList();
      certs.addAll(Arrays.asList(chain));
      if (otherCerts != null) {
        certs.addAll(otherCerts);
      }
      CertStore store =
          CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs));
      params.addCertStore(store);

      // do the build
      CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
      PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult) builder.build(params);

      return toArray(result.getCertPath(), result.getTrustAnchor());
    } catch (GeneralSecurityException e) {
      throw new ValidatorException("PKIX path building failed: " + e.toString(), e);
    }
  }
  @Override
  protected void handleIntent() {
    TermService service = getTermService();
    if (service == null) {
      finish();
      return;
    }

    Intent myIntent = getIntent();
    String action = myIntent.getAction();
    if (action.equals(ACTION_RUN_SHORTCUT)) {
      String encCommand = myIntent.getStringExtra(EXTRA_SHORTCUT_COMMAND);
      if (encCommand == null) {
        Log.e(TermDebug.LOG_TAG, "No command provided in shortcut!");
        finish();
        return;
      }

      // Decrypt and verify the command
      ShortcutEncryption.Keys keys = ShortcutEncryption.getKeys(this);
      if (keys == null) {
        // No keys -- no valid shortcuts can exist
        Log.e(TermDebug.LOG_TAG, "No shortcut encryption keys found!");
        finish();
        return;
      }
      String command;
      try {
        command = ShortcutEncryption.decrypt(encCommand, keys);
      } catch (GeneralSecurityException e) {
        Log.e(TermDebug.LOG_TAG, "Invalid shortcut: " + e.toString());
        finish();
        return;
      }

      String handle = myIntent.getStringExtra(EXTRA_WINDOW_HANDLE);
      if (handle != null) {
        // Target the request at an existing window if open
        handle = appendToWindow(handle, command);
      } else {
        // Open a new window
        handle = openNewWindow(command);
      }
      Intent result = new Intent();
      result.putExtra(EXTRA_WINDOW_HANDLE, handle);
      setResult(RESULT_OK, result);
    }

    finish();
  }
Exemplo n.º 5
0
  /**
   * Performs the <i>Basic Access Control</i> protocol.
   *
   * @param bacKey the key based on the document number, the card holder's birth date, and the
   *     document's expiry date
   * @throws CardServiceException if authentication failed
   */
  public synchronized void doBAC(BACKeySpec bacKey) throws CardServiceException {
    try {
      byte[] keySeed = computeKeySeedForBAC(bacKey);
      SecretKey kEnc = Util.deriveKey(keySeed, Util.ENC_MODE);
      SecretKey kMac = Util.deriveKey(keySeed, Util.MAC_MODE);

      try {
        doBAC(kEnc, kMac);
      } catch (CardServiceException cse) {
        LOGGER.warning("BAC failed for BAC key \"" + bacKey + "\"");
        throw cse;
      }
    } catch (GeneralSecurityException gse) {
      throw new CardServiceException(gse.toString());
    }
  }
Exemplo n.º 6
0
  private void setParam() {

    if (anon) {
      try {
        ctx.init(null, null, null);
      } catch (KeyManagementException e) {
        throw new AuthFailureException(e.toString());
      }
    } else {
      try {
        TrustManager[] myTM = new TrustManager[] {new MyX509TrustManager()};
        ctx.init(null, myTM, null);
      } catch (java.security.GeneralSecurityException e) {
        throw new AuthFailureException(e.toString());
      }
    }
    SSLSocketFactory sslfactory = ctx.getSocketFactory();
    engine = ctx.createSSLEngine(client.getServerName(), client.getServerPort());
    engine.setUseClientMode(true);

    if (anon) {
      String[] supported;
      ArrayList<String> enabled = new ArrayList<String>();

      supported = engine.getSupportedCipherSuites();

      for (int i = 0; i < supported.length; i++)
        if (supported[i].matches("TLS_DH_anon.*")) enabled.add(supported[i]);

      engine.setEnabledCipherSuites(enabled.toArray(new String[0]));
    } else {
      engine.setEnabledCipherSuites(engine.getSupportedCipherSuites());
    }

    engine.setEnabledProtocols(new String[] {"SSLv3", "TLSv1"});
  }
Exemplo n.º 7
0
  private X509Certificate[] doValidate(X509Certificate[] chain, PKIXBuilderParameters params)
      throws CertificateException {
    try {
      setDate(params);

      // do the validation
      CertPathValidator validator = CertPathValidator.getInstance("PKIX");
      CertPath path = factory.generateCertPath(Arrays.asList(chain));
      certPathLength = chain.length;
      PKIXCertPathValidatorResult result =
          (PKIXCertPathValidatorResult) validator.validate(path, params);

      return toArray(path, result.getTrustAnchor());
    } catch (GeneralSecurityException e) {
      if (e instanceof CertPathValidatorException) {
        // check cause
        Throwable cause = e.getCause();
        if (cause != null && cause instanceof OCSPResponse.UnreliableException) {
          throw new ValidatorException(ValidatorException.T_OCSP_RESPONSE_UNRELIABLE);
        }
      }
      throw new ValidatorException("PKIX path validation failed: " + e.toString(), e);
    }
  }
Exemplo n.º 8
0
  /**
   * Perform CA (Chip Authentication) part of EAC (version 1). For details see TR-03110 ver. 1.11.
   * In short, we authenticate the chip with (EC)DH key agreement protocol and create new secure
   * messaging keys.
   *
   * @param keyId passport's public key id (stored in DG14), -1 if none
   * @param publicKey passport's public key (stored in DG14)
   * @return the chip authentication result
   * @throws CardServiceException if CA failed or some error occurred
   */
  public synchronized ChipAuthenticationResult doCA(BigInteger keyId, PublicKey publicKey)
      throws CardServiceException {
    if (publicKey == null) {
      throw new IllegalArgumentException("Public key is null");
    }
    try {
      String agreementAlg = Util.inferKeyAgreementAlgorithm(publicKey);
      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(agreementAlg);
      AlgorithmParameterSpec params = null;
      if ("DH".equals(agreementAlg)) {
        DHPublicKey dhPublicKey = (DHPublicKey) publicKey;
        params = dhPublicKey.getParams();
      } else if ("ECDH".equals(agreementAlg)) {
        ECPublicKey ecPublicKey = (ECPublicKey) publicKey;
        params = ecPublicKey.getParams();
      } else {
        throw new IllegalStateException("Unsupported algorithm \"" + agreementAlg + "\"");
      }
      keyPairGenerator.initialize(params);
      KeyPair keyPair = keyPairGenerator.generateKeyPair();

      KeyAgreement agreement = KeyAgreement.getInstance(agreementAlg);
      agreement.init(keyPair.getPrivate());
      agreement.doPhase(publicKey, true);

      byte[] secret = agreement.generateSecret();

      // TODO: this SHA1ing may have to be removed?
      // TODO: this hashing is needed for our Java Card passport applet implementation
      // byte[] secret = md.digest(secret);

      byte[] keyData = null;
      byte[] idData = null;
      byte[] keyHash = new byte[0];
      if ("DH".equals(agreementAlg)) {
        DHPublicKey dhPublicKey = (DHPublicKey) keyPair.getPublic();
        keyData = dhPublicKey.getY().toByteArray();
        // TODO: this is probably wrong, what should be hashed?
        MessageDigest md = MessageDigest.getInstance("SHA1");
        md = MessageDigest.getInstance("SHA1");
        keyHash = md.digest(keyData);
      } else if ("ECDH".equals(agreementAlg)) {
        org.bouncycastle.jce.interfaces.ECPublicKey ecPublicKey =
            (org.bouncycastle.jce.interfaces.ECPublicKey) keyPair.getPublic();
        keyData = ecPublicKey.getQ().getEncoded();
        byte[] t = Util.i2os(ecPublicKey.getQ().getX().toBigInteger());
        keyHash =
            Util.alignKeyDataToSize(t, ecPublicKey.getParameters().getCurve().getFieldSize() / 8);
      }
      keyData = Util.wrapDO((byte) 0x91, keyData);
      if (keyId.compareTo(BigInteger.ZERO) >= 0) {
        byte[] keyIdBytes = keyId.toByteArray();
        idData = Util.wrapDO((byte) 0x84, keyIdBytes);
      }
      sendMSEKAT(wrapper, keyData, idData);

      SecretKey ksEnc = Util.deriveKey(secret, Util.ENC_MODE);
      SecretKey ksMac = Util.deriveKey(secret, Util.MAC_MODE);
      long ssc = 0;

      wrapper = new DESedeSecureMessagingWrapper(ksEnc, ksMac, ssc);
      state = CA_AUTHENTICATED_STATE;
      return new ChipAuthenticationResult(keyId, publicKey, keyHash, keyPair);
    } catch (GeneralSecurityException e) {
      throw new CardServiceException(e.toString());
    }
  }