Changeset 3633
- Timestamp:
- 12/27/10 12:27:43 (13 years ago)
- Location:
- branches/2.2/security
- Files:
-
- 5 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/2.2/security/ExpressoCert/src/br/gov/serpro/cert/DigitalCertificate.java
r3413 r3633 81 81 82 82 private TokenCollection tokens; 83 private String selectedCertificateAlias; 83 84 private Certificate cert; // Certificado extraído da KeyStore. Pode ser nulo. 84 85 private KeyStore keyStore; // KeyStore que guarda o certificado do usuário. Pode ser nulo. … … 233 234 234 235 this.cert = null; 236 this.selectedCertificateAlias = null; 235 237 this.keyStore = null; 236 238 this.hostAddress = null; … … 343 345 if (pin != null) { 344 346 openKeyStore(pin.toCharArray()); 345 privateKey = this.keyStore.getKey(keyStore.aliases().nextElement(), pin.toCharArray()); 347 if (this.selectedCertificateAlias == null){ 348 return null; 349 } 350 privateKey = this.keyStore.getKey(this.selectedCertificateAlias, pin.toCharArray()); 346 351 } else { 347 352 return null; … … 521 526 if (pin != null) { 522 527 openKeyStore(pin.toCharArray()); 523 privateKey = this.keyStore.getKey(keyStore.aliases().nextElement(), pin.toCharArray()); 528 if (this.selectedCertificateAlias == null){ 529 return null; 530 } 531 privateKey = this.keyStore.getKey(this.selectedCertificateAlias, pin.toCharArray()); 524 532 } else { 525 533 return null; … … 601 609 ByteArrayOutputStream oStream = new ByteArrayOutputStream(); 602 610 decriptedBodyPart.writeTo(oStream); 603 decriptedBodyPart = null; 611 612 decriptedBodyPart = null; 604 613 encriptedMsg = null; 605 614 … … 609 618 610 619 } else { 620 611 621 encriptedMsg.setContent(decriptedBodyPart.getContent(), decriptedBodyPart.getContentType()); 612 622 encriptedMsg.saveChanges(); … … 650 660 String[] resposta = null; 651 661 662 if (this.selectedCertificateAlias == null){ 663 return resposta; 664 } 665 652 666 if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 653 667 System.out.println("Proxy Configurado no browser: " + System.getProperty("http.proxyHost") + ":" + System.getProperty("http.proxyPort")); … … 710 724 711 725 // Pega a chave privada do primeiro certificado armazenado na KeyStore 712 Enumeration<String> en = this.keyStore.aliases(); 713 String certAlias = en.nextElement(); 714 Key privateKey = this.keyStore.getKey(certAlias, pin.toCharArray()); 726 Key privateKey = this.keyStore.getKey(selectedCertificateAlias, pin.toCharArray()); 715 727 716 728 // Inicializa os cipher com os parâmetros corretos para realizar a decriptação … … 745 757 */ 746 758 public void openKeyStore(char[] pin) throws IOException { 747 759 // TODO: Verify if object DigitalCertificate was initiated 748 760 try { 749 761 … … 754 766 } 755 767 756 this.cert = this.keyStore.getCertificate(this.keyStore.aliases().nextElement()); 757 758 System.out.println("Aliases (" + this.keyStore.size() + "): "); 759 if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 760 for (Enumeration alias = this.keyStore.aliases(); alias.hasMoreElements();) { 761 System.out.println(alias.nextElement()); 762 } 763 } 768 List<String> aliases = new ArrayList<String>(); 769 for (Enumeration<String> certificateList = keyStore.aliases(); certificateList.hasMoreElements();){ 770 aliases.add(certificateList.nextElement()); 771 } 772 773 // selecionador de certificado 774 this.selectedCertificateAlias = DialogBuilder.showCertificateSelector(this.parentFrame, this.setup, aliases); 775 if (this.selectedCertificateAlias != null){ 776 this.cert = this.keyStore.getCertificate(this.selectedCertificateAlias); 777 778 System.out.println("Aliases (" + this.keyStore.size() + "): "); 779 if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 780 for (Enumeration alias = this.keyStore.aliases(); alias.hasMoreElements();) { 781 System.out.println(alias.nextElement()); 782 } 783 } 784 } 764 785 765 786 } catch (GeneralSecurityException e) { -
branches/2.2/security/ExpressoCert/src/br/gov/serpro/ui/DialogBuilder.java
r1174 r3633 3 3 import br.gov.serpro.setup.Setup; 4 4 import java.awt.BorderLayout; 5 import java.awt.Color; 5 6 import java.awt.Dimension; 6 7 import java.awt.FlowLayout; … … 18 19 19 20 import java.util.List; 21 import javax.swing.BorderFactory; 20 22 import javax.swing.JButton; 21 23 import javax.swing.JDialog; … … 25 27 import javax.swing.JPanel; 26 28 import javax.swing.JPasswordField; 29 import javax.swing.JScrollPane; 27 30 import javax.swing.ListSelectionModel; 28 31 import javax.swing.SwingUtilities; 29 32 import javax.swing.WindowConstants; 30 33 31 public final class DialogBuilder extends JDialog implements PropertyChangeListener {32 33 34 public final class DialogBuilder extends JDialog implements PropertyChangeListener { 35 36 private Setup setup; 34 37 private static Object lock = new Object(); 35 private String pin = new String();36 private String certificateSubject = n ew String();38 private String pin = null; 39 private String certificateSubject = null; 37 40 //private List<String> certificatelist = new ArrayList<String>(); 38 private boolean ok = false; 39 private boolean locked = true; 40 private JOptionPane optionPane; 41 41 private boolean ok = false; 42 private boolean locked = true; 43 private JOptionPane optionPane; 42 44 // private DialogBuilder myself; 43 private EventManager em = new EventManager(); 44 45 /** 46 * Gerado automaticamente 47 */ 48 private static final long serialVersionUID = 1003857725229120014L; 49 45 private EventManager em = new EventManager(); 46 /** 47 * Gerado automaticamente 48 */ 49 private static final long serialVersionUID = 1003857725229120014L; 50 50 private int dialogType = -1; 51 52 //JPanel pNorte, pCentro, pSul; 53 //JButton btOk, btCancel; 54 //JLabel lTitle, lTitle2, lPin; 55 JPasswordField pfPin; 51 //JPanel pNorte, pCentro, pSul; 52 //JButton btOk, btCancel; 53 //JLabel lTitle, lTitle2, lPin; 54 JPasswordField pfPin; 56 55 JList lCertificatesList; 57 58 56 public static final int PIN_NEEDED_DIALOG = 0; 59 public static final int CERTI CATE_SELECTOR_DIALOG = 1;60 61 private DialogBuilder(Frame parent, Setup setup){62 63 57 public static final int CERTIFICATE_SELECTOR_DIALOG = 1; 58 59 private DialogBuilder(Frame parent, Setup setup) { 60 61 super(parent, true); 64 62 this.setup = setup; 63 this.setResizable(false); 65 64 // this.myself = this; 66 65 67 68 69 70 71 private void buildPinDialog(){66 //this.setVisible(true); 67 68 } 69 70 private void buildPinDialog() { 72 71 73 72 this.dialogType = DialogBuilder.PIN_NEEDED_DIALOG; 74 73 75 74 this.setContentPane(new JPanel()); 76 77 78 79 80 81 82 83 84 85 86 87 88 75 this.setLayout(new BorderLayout()); 76 this.setTitle(this.setup.getLang("ExpressoCertMessages", "pin")); 77 this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); 78 this.setModal(true); 79 80 JPanel pNorte = new JPanel(new FlowLayout(FlowLayout.CENTER)); 81 this.add(pNorte, BorderLayout.NORTH); 82 JPanel pCentro = new JPanel(new FlowLayout(FlowLayout.CENTER)); 83 this.add(pCentro, BorderLayout.CENTER); 84 JPanel pSul = new JPanel(new FlowLayout(FlowLayout.CENTER)); 85 this.add(pSul, BorderLayout.SOUTH); 86 87 //JLabel lTitle = new JLabel("Entre com o seu PIN:"); 89 88 JLabel lTitle = new JLabel(this.setup.getLang("ExpressoCertMessages", "DialogBuilder001")); 90 pNorte.add(lTitle); 91 92 JLabel lPin = new JLabel(this.setup.getLang("ExpressoCertMessages", "pin")+":"); 93 this.pfPin = new JPasswordField(30); 94 this.pfPin.requestFocusInWindow(); 95 this.pfPin.addKeyListener(this.em); 96 pCentro.add(lPin); 97 pCentro.add(this.pfPin); 98 99 JButton btOk = new JButton(this.setup.getLang("ExpressoCertMessages", "ok")); 100 btOk.setMnemonic(KeyEvent.VK_ENTER); 101 btOk.setActionCommand("ok"); 102 103 btOk.addActionListener(this.em); 104 105 JButton btCancel = new JButton(this.setup.getLang("ExpressoCertMessages", "cancel")); 106 btCancel.setMnemonic(KeyEvent.VK_ESCAPE); 107 btCancel.setActionCommand("cancel"); 108 btCancel.addActionListener(this.em); 109 110 pSul.add(btOk); 111 pSul.add(btCancel); 112 113 this.addWindowListener(this.em); 114 this.pack(); 115 116 //Posicionando no centro da tela. 117 Dimension mySize = this.getSize(); 118 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 119 //System.out.println("ScreenSize: " + screenSize.toString()+"\nMySize: " +mySize.toString()); 120 this.setLocation(screenSize.width/2 - (mySize.width/2), screenSize.height/2 - (mySize.height/2)); 121 122 setVisible(true); 123 //this.repaint(); 124 125 } 126 127 /* 128 private void buildPinNotNeededDialog(){ 129 130 this.setContentPane(new JPanel()); 131 this.setLayout(new BorderLayout()); 132 this.setTitle("PIN"); 133 this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); 134 this.setModal(true); 135 136 JPanel pNorte = new JPanel(new FlowLayout(FlowLayout.CENTER)); 137 this.add(pNorte, BorderLayout.NORTH); 138 JPanel pCentro = new JPanel(new FlowLayout(FlowLayout.CENTER)); 139 this.add(pCentro, BorderLayout.CENTER); 140 JPanel pSul = new JPanel(new FlowLayout(FlowLayout.CENTER)); 141 this.add(pSul, BorderLayout.SOUTH); 142 143 JLabel lTitle = new JLabel("Token inserido e desbloqueado"); 144 pNorte.add(lTitle); 145 146 JLabel lTitle2 = new JLabel("foi detectado"); 147 pCentro.add(lTitle2); 148 149 JButton btOk = new JButton("Ok"); 150 btOk.setMnemonic(KeyEvent.VK_ENTER); 151 btOk.setActionCommand("prosseguir"); 152 btOk.addActionListener(em); 153 154 pSul.add(btOk); 155 156 this.addWindowListener(em); 157 this.pack(); 158 159 //Posicionando no centro da tela. 160 Dimension mySize = this.getSize(); 161 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 162 //System.out.println("ScreenSize: " + screenSize.toString()+"\nMySize: " +mySize.toString()); 163 this.setLocation(screenSize.width/2 - (mySize.width/2), screenSize.height/2 - (mySize.height/2)); 164 165 setVisible(true); 166 //this.repaint(); 167 } 168 */ 169 170 private void buildCertificateSelector(List<String> subjectList){ 171 172 dialogType = DialogBuilder.CERTICATE_SELECTOR_DIALOG; 89 pNorte.add(lTitle); 90 91 JLabel lPin = new JLabel(this.setup.getLang("ExpressoCertMessages", "pin") + ":"); 92 this.pfPin = new JPasswordField(30); 93 this.pfPin.requestFocusInWindow(); 94 this.pfPin.addKeyListener(this.em); 95 pCentro.add(lPin); 96 pCentro.add(this.pfPin); 97 98 JButton btOk = new JButton(this.setup.getLang("ExpressoCertMessages", "ok")); 99 btOk.setMnemonic(KeyEvent.VK_ENTER); 100 btOk.setActionCommand("ok"); 101 102 btOk.addActionListener(this.em); 103 104 JButton btCancel = new JButton(this.setup.getLang("ExpressoCertMessages", "cancel")); 105 btCancel.setMnemonic(KeyEvent.VK_ESCAPE); 106 btCancel.setActionCommand("cancel"); 107 btCancel.addActionListener(this.em); 108 109 pSul.add(btOk); 110 pSul.add(btCancel); 111 112 this.addWindowListener(this.em); 113 this.pack(); 114 115 //Posicionando no centro da tela. 116 Dimension mySize = this.getSize(); 117 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 118 //System.out.println("ScreenSize: " + screenSize.toString()+"\nMySize: " +mySize.toString()); 119 this.setLocation(screenSize.width / 2 - (mySize.width / 2), screenSize.height / 2 - (mySize.height / 2)); 120 121 setVisible(true); 122 //this.repaint(); 123 124 } 125 126 private void buildCertificateSelector(List<String> subjectList) { 127 128 dialogType = DialogBuilder.CERTIFICATE_SELECTOR_DIALOG; 173 129 174 130 this.setContentPane(new JPanel()); … … 176 132 this.setTitle(this.setup.getLang("ExpressoCertMessages", "certificate")); 177 133 this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); 178 134 this.setModal(true); 179 135 180 136 JPanel pNorte = new JPanel(new FlowLayout(FlowLayout.CENTER)); 181 182 183 184 185 137 this.add(pNorte, BorderLayout.NORTH); 138 JPanel pCentro = new JPanel(new FlowLayout(FlowLayout.CENTER)); 139 this.add(pCentro, BorderLayout.CENTER); 140 JPanel pSul = new JPanel(new FlowLayout(FlowLayout.CENTER)); 141 this.add(pSul, BorderLayout.SOUTH); 186 142 187 143 JLabel lTitle = new JLabel(this.setup.getLang("ExpressoCertMessages", "DialogBuilder002")); … … 190 146 lCertificatesList = new JList(subjectList.toArray()); 191 147 lCertificatesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 192 pCentro.add(lCertificatesList); 148 lCertificatesList.setLayoutOrientation(JList.HORIZONTAL_WRAP); 149 lCertificatesList.setBorder(BorderFactory.createLoweredBevelBorder()); 150 JScrollPane listScroller = new JScrollPane(lCertificatesList); 151 listScroller.setPreferredSize(new Dimension(500, 80)); 152 listScroller.setAlignmentX(LEFT_ALIGNMENT); 153 154 pCentro.add(listScroller); 155 //pCentro.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2)); 193 156 194 157 JButton bSelect = new JButton(this.setup.getLang("ExpressoCertMessages", "select")); 195 158 bSelect.setMnemonic(KeyEvent.VK_ENTER); 196 bSelect.setActionCommand("selecionar");197 159 bSelect.setActionCommand("select"); 160 bSelect.addActionListener(em); 198 161 pSul.add(bSelect); 199 162 200 163 JButton btCancel = new JButton(this.setup.getLang("ExpressoCertMessages", "cancel")); 201 164 btCancel.setMnemonic(KeyEvent.VK_ESCAPE); 202 203 165 btCancel.setActionCommand("cancel"); 166 btCancel.addActionListener(this.em); 204 167 pSul.add(btCancel); 205 168 206 169 this.addWindowListener(em); 207 this.pack(); 208 209 } 210 211 private void cancelButtonActionPerformed(){ 212 this.setVisible(false); 213 this.pin = null; // hack para saber que diálogo foi cancelado. 214 this.unlock(); 215 //this.dispose(); 216 } 217 218 private void okButtonActionPerformed(){ 219 this.setVisible(false); 220 this.unlock(); 221 //this.dispose(); 222 } 223 224 protected String getPin() { 225 return this.pin; 226 } 227 228 protected void setPin(String pin) { 229 this.pin = pin; 230 } 170 this.pack(); 171 172 //Posicionando no centro da tela. 173 Dimension mySize = this.getSize(); 174 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 175 //System.out.println("ScreenSize: " + screenSize.toString()+"\nMySize: " +mySize.toString()); 176 this.setLocation(screenSize.width / 2 - (mySize.width / 2), screenSize.height / 2 - (mySize.height / 2)); 177 178 this.setVisible(true); 179 180 } 181 182 // TODO: Lançar e implementar exceção ActionCanceled 183 private void cancelButtonActionPerformed() { 184 this.setVisible(false); 185 this.pin = null; // hack para saber que diálogo foi cancelado. 186 this.certificateSubject = null; 187 this.unlock(); 188 //this.dispose(); 189 } 190 191 private void okButtonActionPerformed() { 192 this.setVisible(false); 193 this.unlock(); 194 //this.dispose(); 195 } 196 197 protected String getPin() { 198 return this.pin; 199 } 200 201 protected void setPin(String pin) { 202 this.pin = pin; 203 } 231 204 232 205 protected String getCertificateSubject() { … … 238 211 } 239 212 240 protected boolean isLocked(){ 241 synchronized (DialogBuilder.lock) { 242 return this.locked; 243 } 244 } 245 246 private void setLocked(boolean locked) { 247 synchronized (DialogBuilder.lock) { 248 this.locked = locked; 249 } 250 251 } 252 253 private void unlock(){ 254 synchronized (DialogBuilder.lock) { 255 setLocked(false); 256 DialogBuilder.lock.notifyAll(); 257 } 258 } 259 260 static public int showMessageDialog(Frame parent, Object message, Setup setup){ 261 262 return DialogBuilder.showDialog(parent, message, JOptionPane.INFORMATION_MESSAGE, JOptionPane.DEFAULT_OPTION, setup); 263 264 } 265 266 static public int showMessageDialog(Frame parent, Object message, int messageType, Setup setup){ 267 268 return DialogBuilder.showDialog(parent, message, messageType, JOptionPane.DEFAULT_OPTION, setup); 269 270 } 271 272 static public int showConfirmDialog(Frame parent, Object message, int messageType, int optionType, Setup setup){ 273 274 return DialogBuilder.showDialog(parent, message, messageType, optionType, setup); 275 276 } 277 278 static public int showDialog(Frame parent, Object message, int messageType, int optionType, Setup setup){ 279 280 DialogBuilder dialog = new DialogBuilder(parent, setup); 281 int valor = dialog.buildDialog(message, messageType, optionType); 282 283 dialog.dispose(); 284 285 return valor; 286 287 /* 288 JOptionPane optionPane = new JOptionPane(message, messageType, optionType); 289 JDialog dialog = new JDialog(parent, true); 290 dialog.setContentPane(optionPane); 291 optionPane.addPropertyChangeListener(this); 292 dialog.setTitle("Teste"); 293 dialog.pack(); 294 295 //Posicionando no centro da tela. 296 Dimension mySize = dialog.getSize(); 297 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 298 dialog.setLocation(screenSize.width/2 - (mySize.width/2), screenSize.height/2 - (mySize.height/2)); 299 dialog.setVisible(true); 300 301 Object selectedValue = optionPane.getValue(); 302 int resultado = JOptionPane.CLOSED_OPTION; 303 if (selectedValue != null){ 304 resultado = JOptionPane.CLOSED_OPTION; 305 } 306 else if (selectedValue instanceof Integer){ 307 resultado = ((Integer)selectedValue).intValue(); 308 } 309 310 dialog.dispose(); 311 312 return resultado; 313 */ 314 } 315 316 private int buildDialog(Object message, int messageType, int optionType){ 317 318 this.optionPane = new JOptionPane(message, messageType, optionType); 319 this.setModal(true); 320 this.setContentPane(this.optionPane); 321 this.optionPane.addPropertyChangeListener(this); 322 //this.setTitle("Teste"); 323 this.pack(); 324 325 //Posicionando no centro da tela. 326 Dimension mySize = this.getSize(); 327 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 328 this.setLocation(screenSize.width/2 - (mySize.width/2), screenSize.height/2 - (mySize.height/2)); 329 this.setVisible(true); 330 331 Object selectedValue = this.optionPane.getValue(); 332 int resultado = JOptionPane.CLOSED_OPTION; 333 if (selectedValue != null){ 334 resultado = JOptionPane.CLOSED_OPTION; 335 } 336 else if (selectedValue instanceof Integer){ 337 resultado = ((Integer)selectedValue).intValue(); 338 } 339 340 //this.dispose(); 341 342 return resultado; 343 344 } 345 346 public void propertyChange(PropertyChangeEvent evt) { 347 // TODO Stub de método gerado automaticamente 348 String property = evt.getPropertyName(); 349 350 if (this.isVisible() && 351 evt.getSource() == optionPane && 352 JOptionPane.VALUE_PROPERTY.equals(property)){ 353 354 this.setVisible(false); 355 } 356 357 } 358 359 static public String showPinDialog(Frame parent, Setup setup) { 360 DialogBuilder pinCodeDialog = new DialogBuilder(parent, setup); 361 362 try { 363 SwingUtilities.invokeAndWait(pinCodeDialog.new PinCodeNeededBuilder()); 364 } catch (InterruptedException e1) { 365 // TODO Bloco catch gerado automaticamente 366 e1.printStackTrace(); 367 } catch (InvocationTargetException e1) { 368 // TODO Bloco catch gerado automaticamente 369 e1.printStackTrace(); 370 } 371 372 synchronized (DialogBuilder.lock) { 373 374 while (pinCodeDialog.isLocked()){ 375 try { 376 DialogBuilder.lock.wait(); 377 } catch (InterruptedException e) { 378 // TODO Bloco catch gerado automaticamente 379 } 380 } 381 382 String pin = pinCodeDialog.getPin(); 383 pinCodeDialog.dispose(); 384 pinCodeDialog = null; 385 386 return pin; 387 } 388 } 389 390 /* 391 static public boolean showPinNotNeededDialog(Frame parent){ 392 DialogBuilder pinCodeDialog = new DialogBuilder(parent); 393 394 try { 395 SwingUtilities.invokeAndWait(pinCodeDialog.new PinCodeNotNeededBuilder()); 396 } catch (InterruptedException e1) { 397 // TODO Bloco catch gerado automaticamente 398 e1.printStackTrace(); 399 } catch (InvocationTargetException e1) { 400 // TODO Bloco catch gerado automaticamente 401 e1.printStackTrace(); 402 } 403 404 synchronized (DialogBuilder.lock) { 405 406 while (pinCodeDialog.isLocked()){ 407 try { 408 DialogBuilder.lock.wait(); 409 } catch (InterruptedException e) { 410 // TODO Bloco catch gerado automaticamente 411 } 412 } 413 414 boolean ok = pinCodeDialog.isOk(); 415 pinCodeDialog.dispose(); 416 pinCodeDialog = null; 417 418 return ok; 419 } 420 } 421 */ 422 423 /* 424 synchronized static public boolean showTryAgainDialog(Frame parent) { 425 //JOptionPane(Object message, int messageType, int optionType); 426 JOptionPane tryAgainOptionPane = new JOptionPane("Não foi possível carregar dispositivo " + 427 "ou arquivo de chaves privadas. Tentar novamente?", 428 JOptionPane.INFORMATION_MESSAGE, JOptionPane.YES_NO_OPTION); 429 430 JDialog tryAgainDialog = tryAgainOptionPane.createDialog(parent, ""); 431 tryAgainDialog.setContentPane(tryAgainOptionPane); 432 tryAgainDialog.setVisible(true); 433 434 435 436 try { 437 SwingUtilities.invokeAndWait(pinCodeDialog.new PinCodeNotNeededBuilder()); 438 } catch (InterruptedException e1) { 439 // TODO Bloco catch gerado automaticamente 440 e1.printStackTrace(); 441 } catch (InvocationTargetException e1) { 442 // TODO Bloco catch gerado automaticamente 443 e1.printStackTrace(); 444 } 445 446 while (pinCodeDialog.isLocked()){ 447 try { 448 pinCodeDialog.wait(); 449 } catch (InterruptedException e) { 450 // TODO Bloco catch gerado automaticamente 451 } 452 } 453 454 boolean tryAgain = pinCodeDialog.isOk(); 455 pinCodeDialog.dispose(); 456 pinCodeDialog = null; 457 458 return tryAgain; 459 460 } 461 */ 462 463 synchronized private boolean isOk() { 464 return ok; 465 } 466 467 synchronized private void setOk(boolean ok) { 468 this.ok = ok; 469 } 470 471 private class PinCodeNeededBuilder implements Runnable { 472 473 public void run() { 474 buildPinDialog(); 475 } 476 } 477 478 /* 479 private class PinCodeNotNeededBuilder implements Runnable { 480 481 public void run() { 482 buildPinNotNeededDialog(); 483 } 484 } 485 */ 486 487 private final class EventManager implements ActionListener, KeyListener, WindowListener{ 488 489 public void keyPressed(KeyEvent keyEvt) { 490 int keyPressed = keyEvt.getKeyCode(); 491 492 if (keyPressed == KeyEvent.VK_ENTER){ 493 //System.out.println("Tecla ENTER pressionada"); 494 if (lCertificatesList != null){ 495 // é uma lista de certificados 213 protected boolean isLocked() { 214 synchronized (DialogBuilder.lock) { 215 return this.locked; 216 } 217 } 218 219 private void setLocked(boolean locked) { 220 synchronized (DialogBuilder.lock) { 221 this.locked = locked; 222 } 223 224 } 225 226 private void unlock() { 227 synchronized (DialogBuilder.lock) { 228 setLocked(false); 229 DialogBuilder.lock.notifyAll(); 230 } 231 } 232 233 static public int showMessageDialog(Frame parent, Object message, Setup setup) { 234 235 return DialogBuilder.showDialog(parent, message, JOptionPane.INFORMATION_MESSAGE, JOptionPane.DEFAULT_OPTION, setup); 236 237 } 238 239 static public int showMessageDialog(Frame parent, Object message, int messageType, Setup setup) { 240 241 return DialogBuilder.showDialog(parent, message, messageType, JOptionPane.DEFAULT_OPTION, setup); 242 243 } 244 245 static public int showConfirmDialog(Frame parent, Object message, int messageType, int optionType, Setup setup) { 246 247 return DialogBuilder.showDialog(parent, message, messageType, optionType, setup); 248 249 } 250 251 static public int showDialog(Frame parent, Object message, int messageType, int optionType, Setup setup) { 252 253 DialogBuilder dialog = new DialogBuilder(parent, setup); 254 int valor = dialog.buildDialog(message, messageType, optionType); 255 256 dialog.dispose(); 257 258 return valor; 259 260 } 261 262 private int buildDialog(Object message, int messageType, int optionType) { 263 264 this.optionPane = new JOptionPane(message, messageType, optionType); 265 this.setModal(true); 266 this.setContentPane(this.optionPane); 267 this.optionPane.addPropertyChangeListener(this); 268 this.pack(); 269 270 //Posicionando no centro da tela. 271 Dimension mySize = this.getSize(); 272 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 273 this.setLocation(screenSize.width / 2 - (mySize.width / 2), screenSize.height / 2 - (mySize.height / 2)); 274 this.setVisible(true); 275 276 Object selectedValue = this.optionPane.getValue(); 277 int resultado = JOptionPane.CLOSED_OPTION; 278 if (selectedValue != null) { 279 resultado = JOptionPane.CLOSED_OPTION; 280 } else if (selectedValue instanceof Integer) { 281 resultado = ((Integer) selectedValue).intValue(); 282 } 283 284 //this.dispose(); 285 286 return resultado; 287 288 } 289 290 public void propertyChange(PropertyChangeEvent evt) { 291 // TODO Stub de método gerado automaticamente 292 String property = evt.getPropertyName(); 293 294 if (this.isVisible() && 295 evt.getSource() == optionPane && 296 JOptionPane.VALUE_PROPERTY.equals(property)) { 297 298 this.setVisible(false); 299 } 300 301 } 302 303 static public String showPinDialog(Frame parent, Setup setup) { 304 DialogBuilder pinCodeDialog = new DialogBuilder(parent, setup); 305 306 try { 307 SwingUtilities.invokeAndWait(pinCodeDialog.new PinCodeNeededBuilder()); 308 } catch (InterruptedException e1) { 309 // TODO Bloco catch gerado automaticamente 310 e1.printStackTrace(); 311 } catch (InvocationTargetException e1) { 312 // TODO Bloco catch gerado automaticamente 313 e1.printStackTrace(); 314 } 315 316 synchronized (DialogBuilder.lock) { 317 318 while (pinCodeDialog.isLocked()) { 319 try { 320 DialogBuilder.lock.wait(); 321 } catch (InterruptedException e) { 322 // TODO Bloco catch gerado automaticamente 496 323 } 497 else { 324 } 325 326 String pin = pinCodeDialog.getPin(); 327 pinCodeDialog.dispose(); 328 pinCodeDialog = null; 329 330 return pin; 331 } 332 } 333 334 static public String showCertificateSelector(Frame parent, Setup setup, List<String> certificateList) { 335 DialogBuilder certificateSelectorDialog = new DialogBuilder(parent, setup); 336 337 try { 338 SwingUtilities.invokeAndWait(certificateSelectorDialog.new CertificateSelectorBuilder(certificateList)); 339 } catch (InterruptedException e1) { 340 // TODO Bloco catch gerado automaticamente 341 e1.printStackTrace(); 342 } catch (InvocationTargetException e1) { 343 // TODO Bloco catch gerado automaticamente 344 e1.printStackTrace(); 345 } 346 347 synchronized (DialogBuilder.lock) { 348 349 while (certificateSelectorDialog.isLocked()) { 350 try { 351 DialogBuilder.lock.wait(); 352 } catch (InterruptedException e) { 353 // TODO Bloco catch gerado automaticamente 354 } 355 } 356 357 String subject = certificateSelectorDialog.getCertificateSubject(); 358 certificateSelectorDialog.dispose(); 359 certificateSelectorDialog = null; 360 361 return subject; 362 } 363 } 364 365 synchronized private boolean isOk() { 366 return ok; 367 } 368 369 synchronized private void setOk(boolean ok) { 370 this.ok = ok; 371 } 372 373 private class PinCodeNeededBuilder implements Runnable { 374 375 public void run() { 376 buildPinDialog(); 377 } 378 } 379 380 private class CertificateSelectorBuilder implements Runnable{ 381 382 private List<String> certificateList; 383 384 public CertificateSelectorBuilder(List<String> certificateList){ 385 this.certificateList = certificateList; 386 } 387 388 public void run() { 389 buildCertificateSelector(this.certificateList); 390 } 391 } 392 393 private final class EventManager implements ActionListener, KeyListener, WindowListener { 394 395 public void keyPressed(KeyEvent keyEvt) { 396 int keyPressed = keyEvt.getKeyCode(); 397 398 if (keyPressed == KeyEvent.VK_ENTER) { 399 //System.out.println("Tecla ENTER pressionada"); 400 if (dialogType == CERTIFICATE_SELECTOR_DIALOG) { 401 this.actionPerformed(new ActionEvent(keyEvt.getSource(), keyEvt.getID(), "select")); 402 } else { 498 403 this.actionPerformed(new ActionEvent(keyEvt.getSource(), keyEvt.getID(), "ok")); 499 404 } 500 } 501 else if (keyPressed == KeyEvent.VK_ESCAPE){ 502 //System.out.println("Tecla ESC pressionada"); 503 this.actionPerformed(new ActionEvent(keyEvt.getSource(), keyEvt.getID(), "cancel")); 504 } 505 } 506 507 public void keyReleased(KeyEvent arg0) { 508 } 509 510 public void keyTyped(KeyEvent keyEvt) { 511 } 512 513 public void windowActivated(WindowEvent arg0) { 514 } 515 516 public void windowClosed(WindowEvent arg0) { 517 //System.out.println("Window Closed: Fechando diálogo!"); 518 } 519 520 public void windowClosing(WindowEvent arg0) { 521 //System.out.println("Window Closing: Fechando diálogo!"); 522 cancelButtonActionPerformed(); 523 } 524 525 public void windowDeactivated(WindowEvent arg0) { 526 } 527 528 public void windowDeiconified(WindowEvent arg0) { 529 } 530 531 public void windowIconified(WindowEvent arg0) { 532 } 533 534 public void windowOpened(WindowEvent arg0) { 535 } 536 537 public void actionPerformed(ActionEvent evt) { 538 539 String command = evt.getActionCommand(); 540 541 // Atribui o valor digitado para o campo 542 // senha e esconde a interface e assina o certificado 543 if (command.equals("ok")){ 544 545 //if (pfPin != null && pfPin.getPassword().length <= 0){ 546 // Mostra um aviso de que o campo PIN não foi preenchido 547 //JOptionPane.showMessageDialog(null, "Campo PIN não foi preenchido!", 548 // "Aviso", JOptionPane.INFORMATION_MESSAGE); 549 //} 550 //else { 551 setPin(String.valueOf(pfPin.getPassword())); 552 okButtonActionPerformed(); 553 //} 554 555 } 556 else if (command.equals("cancel")){ 557 cancelButtonActionPerformed(); 558 } 559 else if (command.equals("prosseguir")){ 560 setOk(true); 561 okButtonActionPerformed(); 562 } 563 } 564 565 /* private Frame findParentFrame(Component source){ 566 567 Component parent = source.getParent(); 568 569 while (parent != null){ 570 if (parent instanceof Frame){ 571 return (Frame) parent; 572 } 573 } 574 575 return (Frame) null; 576 577 578 } 579 */ 580 } 581 405 } else if (keyPressed == KeyEvent.VK_ESCAPE) { 406 //System.out.println("Tecla ESC pressionada"); 407 this.actionPerformed(new ActionEvent(keyEvt.getSource(), keyEvt.getID(), "cancel")); 408 } 409 } 410 411 public void keyReleased(KeyEvent arg0) { 412 } 413 414 public void keyTyped(KeyEvent keyEvt) { 415 } 416 417 public void windowActivated(WindowEvent arg0) { 418 } 419 420 public void windowClosed(WindowEvent arg0) { 421 //System.out.println("Window Closed: Fechando diálogo!"); 422 } 423 424 public void windowClosing(WindowEvent arg0) { 425 //System.out.println("Window Closing: Fechando diálogo!"); 426 cancelButtonActionPerformed(); 427 } 428 429 public void windowDeactivated(WindowEvent arg0) { 430 } 431 432 public void windowDeiconified(WindowEvent arg0) { 433 } 434 435 public void windowIconified(WindowEvent arg0) { 436 } 437 438 public void windowOpened(WindowEvent arg0) { 439 } 440 441 public void actionPerformed(ActionEvent evt) { 442 443 String command = evt.getActionCommand(); 444 445 // Atribui o valor digitado para o campo 446 // senha e esconde a interface e assina o certificado 447 if (command.equals("ok")) { 448 449 //if (pfPin != null && pfPin.getPassword().length <= 0){ 450 // Mostra um aviso de que o campo PIN não foi preenchido 451 //JOptionPane.showMessageDialog(null, "Campo PIN não foi preenchido!", 452 // "Aviso", JOptionPane.INFORMATION_MESSAGE); 453 //} 454 //else { 455 setPin(String.valueOf(pfPin.getPassword())); 456 okButtonActionPerformed(); 457 //} 458 459 } else if (command.equals("select")){ 460 setCertificateSubject((String) lCertificatesList.getSelectedValue()); 461 okButtonActionPerformed(); 462 } 463 else if (command.equals("cancel")) { 464 cancelButtonActionPerformed(); 465 } else if (command.equals("prosseguir")) { 466 setOk(true); 467 okButtonActionPerformed(); 468 } 469 } 470 } 582 471 } -
branches/2.2/security/ExpressoCertLogin/src/LoginApplet.java
r1574 r3633 24 24 * @author Mário César Kolling - mario.kolling@serpro.gov.br 25 25 */ 26 public class LoginApplet extends JApplet{ 27 28 /** 29 * Valor gerado aleatoriamente 30 */ 31 32 //TODO: Alterar a cor e fonte dos labels e das caixas de texto e senha. 33 private static final long serialVersionUID = -6204158613173951516L; 34 35 //private PinCodePanel pinPanel; 36 //private LoginPanel loginPanel; 37 //private PinCodePanel alreadyLoadedPanel; 38 //private int useCertificate = DigitalCertificate.KEYSTORE_DETECTED; 39 // private String uid; 40 private DigitalCertificate dc; 26 public class LoginApplet extends JApplet { 27 28 /** 29 * Valor gerado aleatoriamente 30 */ 31 //TODO: Alterar a cor e fonte dos labels e das caixas de texto e senha. 32 private static final long serialVersionUID = -6204158613173951516L; 33 private DigitalCertificate dc; 41 34 private Setup setup; 42 35 43 44 45 46 47 48 36 /* (non-Javadoc) 37 * @see java.applet.Applet#init() 38 */ 39 public void init() { 40 super.init(); 41 this.setSize(0, 0); 49 42 this.setup = new Setup(this); 50 43 this.setup.addLanguageResource("ExpressoCertLoginMessages"); 51 } 52 53 /* (non-Javadoc) 54 * @see java.applet.Applet#start() 55 */ 56 @Override 57 public void start() { 58 super.start(); 59 60 int useCertificate = DigitalCertificate.KEYSTORE_NOT_DETECTED; 61 boolean tryAgain = true; 62 63 do 64 { 65 66 // Cria uma instância de DigitalCertificate e a inicializa 67 this.dc = new DigitalCertificate(this.getDocumentBase(), setup); 68 useCertificate = dc.init(); 69 String[] returnCode = null; 70 71 try { 72 switch (useCertificate){ 73 case DigitalCertificate.KEYSTORE_DETECTED: 74 // Mostra PinNeedeDialog. 75 //tryAgain = false; 76 String pin = DialogBuilder.showPinDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), this.setup); 77 if (pin != null) { 78 dc.openKeyStore(pin.toCharArray()); 79 returnCode = dc.getCredentials(pin); 80 81 // se chegou aqui, keystore foi acessada e as credenciais do usuário foram recuperadas 82 //tryAgain = false; 83 assert (returnCode != null): "Valor de returnCode não pode ser nulo"; 84 85 //this.dc.destroy(); 86 87 // Faz o login 88 44 } 45 46 /* (non-Javadoc) 47 * @see java.applet.Applet#start() 48 */ 49 @Override 50 public void start() { 51 super.start(); 52 53 int useCertificate = DigitalCertificate.KEYSTORE_NOT_DETECTED; 54 boolean tryAgain = true; 55 56 do { 57 58 // Cria uma instância de DigitalCertificate e a inicializa 59 this.dc = new DigitalCertificate(this.getDocumentBase(), setup); 60 useCertificate = dc.init(); 61 String[] returnCode = null; 62 63 try { 64 switch (useCertificate) { 65 case DigitalCertificate.KEYSTORE_DETECTED: 66 // Mostra PinNeedeDialog. 67 String pin = DialogBuilder.showPinDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), this.setup); 68 if (pin != null) { 69 dc.openKeyStore(pin.toCharArray()); 70 returnCode = dc.getCredentials(pin); 71 72 // Faz o login 89 73 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 90 74 System.out.println("Código de retorno: " + returnCode[0].trim()); 91 75 } 92 76 93 if (Integer.parseInt(returnCode[0].trim()) == 0){ 94 95 tryAgain = false; 96 // Pega usuário e senha de credentials[1] e credentials[2], respectivamente 97 // adiciona na página e faz o submit. 98 JSObject document = (JSObject) JSObject.getWindow( this ).getMember("document"); 99 JSObject loginForm = (JSObject) document.getMember("flogin"); 100 JSObject loginField = (JSObject) loginForm.getMember("user"); 101 loginField.setMember("value", returnCode[1].trim()); 102 103 JSObject passwdField = (JSObject) loginForm.getMember("passwd"); 104 passwdField.setMember("value", returnCode[2].trim()); 105 106 loginForm.call("submit", null); 107 Thread.yield(); 108 109 } 110 else if (Integer.parseInt(returnCode[0].trim()) == 6){ 111 112 tryAgain = false; 113 114 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 115 System.out.println("Mensagem de retorno: " + returnCode[1].trim()); 116 } 117 118 //JOptionPane.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), credentials[1]); 119 DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), returnCode[1].trim(), this.setup); 120 121 122 123 String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() + "/login.php?cd=98&ts=202"; 124 try { 125 this.getAppletContext().showDocument(new URL(redirect)); 126 } catch (MalformedURLException e) { 127 // TODO Bloco catch gerado automaticamente 128 if (this.setup.getParameter("debug").equalsIgnoreCase("true")){ 77 if (returnCode == null){ // Ação cancelada 78 tryAgain = false; 79 String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() + "/login.php"; 80 try { 81 this.getAppletContext().showDocument(new URL(redirect)); 82 } catch (MalformedURLException e) { 83 // TODO Bloco catch gerado automaticamente 84 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 129 85 e.printStackTrace(); 130 86 } 131 } 132 } 133 else { 134 tryAgain = true; 135 dc.destroy(); 136 System.gc(); 87 } 88 } 89 else if (Integer.parseInt(returnCode[0].trim()) == 0) { 90 91 tryAgain = false; 92 // Pega usuário e senha de credentials[1] e credentials[2], respectivamente 93 // adiciona na página e faz o submit. 94 JSObject document = (JSObject) JSObject.getWindow(this).getMember("document"); 95 JSObject loginForm = (JSObject) document.getMember("flogin"); 96 JSObject loginField = (JSObject) loginForm.getMember("user"); 97 loginField.setMember("value", returnCode[1].trim()); 98 99 JSObject passwdField = (JSObject) loginForm.getMember("passwd"); 100 passwdField.setMember("value", returnCode[2].trim()); 101 102 loginForm.call("submit", null); 103 Thread.yield(); 104 105 } else if (Integer.parseInt(returnCode[0].trim()) == 6) { 106 107 tryAgain = false; 137 108 138 109 if (setup.getParameter("debug").equalsIgnoreCase("true")) { … … 140 111 } 141 112 142 // Mostra mensagem de erro para o usuário 143 //JOptionPane.showMessageDialog(this, credentials[1]); 144 DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), returnCode[1].trim(), this.setup); 145 Thread.yield(); 146 } 147 148 } 149 else { 150 151 tryAgain = false; 152 String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() + "/login.php"; 153 try { 154 this.getAppletContext().showDocument(new URL(redirect)); 155 } catch (MalformedURLException e) { 156 // TODO Bloco catch gerado automaticamente 113 DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), returnCode[1].trim(), this.setup); 114 115 116 117 String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() + "/login.php?cd=98&ts=202"; 118 try { 119 this.getAppletContext().showDocument(new URL(redirect)); 120 } catch (MalformedURLException e) { 121 // TODO Bloco catch gerado automaticamente 122 if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 123 e.printStackTrace(); 124 } 125 } 126 } else { 127 tryAgain = true; 128 dc.destroy(); 129 System.gc(); 130 131 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 132 System.out.println("Mensagem de retorno: " + returnCode[1].trim()); 133 } 134 135 // Mostra mensagem de erro para o usuário 136 DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), returnCode[1].trim(), this.setup); 137 Thread.yield(); 138 } 139 140 } else { 141 142 tryAgain = false; 143 String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() + "/login.php"; 144 try { 145 this.getAppletContext().showDocument(new URL(redirect)); 146 } catch (MalformedURLException e) { 147 // TODO Bloco catch gerado automaticamente 157 148 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 158 149 e.printStackTrace(); 159 150 } 160 } 161 } 162 163 break; 164 /* 165 case DigitalCertificate.KEYSTORE_ALREADY_LOADED: 166 // Mostra PinNotNeededDialog 167 tryAgain = false; 168 169 //Verifica na página se operação anterior foi um logout 170 JSObject document = (JSObject) JSObject.getWindow( this ).getMember("document"); 171 JSObject loginForm = (JSObject) document.getMember("flogin"); 172 JSObject loginField = (JSObject) loginForm.getMember("cd"); 173 String cdValue = (String) loginField.getMember("value"); 174 175 int cd = 0; 176 if (cdValue.length() != 0){ 177 cd = Integer.parseInt(cdValue); 178 } 179 180 // Se não foi logout prossegue com o login, senão pára tudo 181 if (cd != 1 && cd != 5){ 182 183 DialogBuilder.showPinNotNeededDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this)); 184 dc.openKeyStore(null); 185 returnCode = dc.getCredentials(""); 186 187 // se chegou aqui, keystore foi acessada e as credenciais do usuário foram recuperadas 188 assert (returnCode != null): "Valor de returnCode não pode ser nulo"; 189 190 // Faz o login 191 doLogin(returnCode); 192 } 193 else if (cd == 5){ 194 JOptionPane.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 195 "Não foi possível realizar o Logon com certificado!"); 196 // Redireciona para a tela de login 197 String redirect = this.getCodeBase().toExternalForm() + "login.php"; 198 try { 199 this.getAppletContext().showDocument(new URL(redirect)); 200 } catch (MalformedURLException e) { 201 // TODO Bloco catch gerado automaticamente 202 e.printStackTrace(); 203 } 204 205 } 206 207 //DialogBuilder.showPinNotNeededDialog(findParentframe()); 208 209 break; 210 */ 211 default: 212 213 // Mostra Diálogo dizendo que token não foi encontrado 214 // ou repositório de chaves públicas não foi configurado. 215 // Tentar carregar token/keystore novamente? / Logon sem certificado digital? 216 217 tryAgain = false; 151 } 152 } 153 154 break; 155 default: 156 157 // Mostra Diálogo dizendo que token não foi encontrado 158 // ou repositório de chaves públicas não foi configurado. 159 // Tentar carregar token/keystore novamente? / Logon sem certificado digital? 160 161 tryAgain = false; 218 162 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 219 163 System.out.println("não achou token"); 220 164 } 221 222 223 224 225 226 227 228 229 165 166 dc.destroy(); 167 System.gc(); 168 169 String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() + "/login.php"; 170 try { 171 this.getAppletContext().showDocument(new URL(redirect)); 172 } catch (MalformedURLException e) { 173 // TODO Bloco catch gerado automaticamente 230 174 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 231 175 e.printStackTrace(); 232 176 } 233 } 234 235 //int resultado = JOptionPane.showConfirmDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 236 // "Deseja tentar novamente?", 237 // "Token não foi encontrado!", 238 // JOptionPane.OK_CANCEL_OPTION, 239 // JOptionPane.QUESTION_MESSAGE); 240 241 //if (resultado == JOptionPane.OK_OPTION){ 242 // tryAgain = true; 243 //} 244 //else { 245 246 //} 247 248 // if () { 249 // tryAgain = true; 250 //} 251 } 252 253 } 254 catch (SSLHandshakeException e){ 255 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 256 e.printStackTrace(); 257 } 258 dc.destroy(); 259 System.gc(); 260 //JOptionPane.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), "Não foi possível validar o certificado do servidor!"); 261 //DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 262 // "Não foi possível validar o certificado do servidor!", this.setup); 177 } 178 } 179 180 } catch (SSLHandshakeException e) { 181 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 182 e.printStackTrace(); 183 } 184 dc.destroy(); 185 System.gc(); 263 186 DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 264 this.setup.getLang("ExpressoCertLoginMessages", "LoginApplet001"), this.setup); 265 266 Thread.yield(); 267 268 tryAgain = true; 269 } 270 catch (HttpException e) { 271 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 272 e.printStackTrace(); 273 } 274 275 tryAgain = true; 276 Thread.yield(); 277 } 278 catch (GeneralSecurityException e){ 279 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 280 e.printStackTrace(); 281 } 282 283 //DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 284 // "Algum erro ocorreu ao realizar o logon!", this.setup); 187 this.setup.getLang("ExpressoCertLoginMessages", "LoginApplet001"), this.setup); 188 189 Thread.yield(); 190 191 tryAgain = true; 192 } catch (HttpException e) { 193 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 194 e.printStackTrace(); 195 } 196 197 tryAgain = true; 198 Thread.yield(); 199 } catch (GeneralSecurityException e) { 200 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 201 e.printStackTrace(); 202 } 203 285 204 DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 286 this.setup.getLang("ExpressoCertLoginMessages", "LoginApplet002"), this.setup); 287 288 Thread.yield(); 289 tryAgain = true; 290 } 291 catch (IOException e) { 292 dc.destroy(); 293 System.gc(); 294 295 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 296 e.printStackTrace(); 297 } 298 //System.out.println("Classe que originou o erro de IO: " + e.getClass().getCanonicalName());; 205 this.setup.getLang("ExpressoCertLoginMessages", "LoginApplet002"), this.setup); 206 207 Thread.yield(); 208 tryAgain = true; 209 } catch (IOException e) { 210 dc.destroy(); 211 System.gc(); 212 213 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 214 e.printStackTrace(); 215 } 299 216 300 217 Throwable cause = null; 301 if ((cause = e.getCause()) != null){ 302 if (cause instanceof javax.security.auth.login.LoginException){ 303 //DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), "PIN incorreto!", this.setup); 218 if ((cause = e.getCause()) != null) { 219 if (cause instanceof javax.security.auth.login.LoginException) { 304 220 DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), this.setup.getLang("ExpressoCertLoginMessages", "LoginApplet003"), this.setup); 305 221 } else { … … 308 224 } 309 225 } 310 } 311 else { 312 if (e instanceof java.net.ConnectException){ 313 //DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 314 // "Não foi possível fazer a conexão com o servidor do Expresso.\n" + 315 // "Verifique suas configurações de rede/proxy.", this.setup); 226 } else { 227 if (e instanceof java.net.ConnectException) { 316 228 DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 317 229 this.setup.getLang("ExpressoCertLoginMessages", "LoginApplet004"), this.setup); … … 323 235 } 324 236 325 Thread.yield(); 326 tryAgain = true; 327 } 328 catch (ProviderException e) { 329 // Tentar novamente / cancel 330 //JOptionPane.showMessageDialog(this, "Token foi removido! Favor inserir seu token"); 331 332 dc.destroy(); 333 System.gc(); 334 335 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 336 e.printStackTrace(); 337 } 338 339 /* 340 JOptionPane optionPane = new JOptionPane("Token foi removido\nDeseja tentar carregá-lo novamente?", 341 JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION); 342 JDialog dialog = new JDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), true); 343 dialog.setContentPane(optionPane); 344 //Posicionando no centro da tela. 345 346 Dimension mySize = dialog.getSize(); 347 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 348 dialog.setLocation(screenSize.width/2 - (mySize.width/2), screenSize.height/2 - (mySize.height/2)); 349 dialog.setVisible(true); 350 351 Object selectedValue = optionPane.getValue(); 352 353 if (selectedValue == null){ 354 355 } 356 else { 357 if (selectedValue instanceof Integer){ 358 Integer 359 } 360 } 361 */ 362 363 int resultado = DialogBuilder.showConfirmDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 364 //"Deseja tentar carregá-lo novamente?", 237 Thread.yield(); 238 tryAgain = true; 239 } catch (ProviderException e) { 240 241 dc.destroy(); 242 System.gc(); 243 244 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 245 e.printStackTrace(); 246 } 247 248 int resultado = DialogBuilder.showConfirmDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 249 //"Deseja tentar carregá-lo novamente?", 365 250 this.setup.getLang("ExpressoCertLoginMessages", "LoginApplet005"), 366 JOptionPane.QUESTION_MESSAGE, 367 JOptionPane.OK_CANCEL_OPTION, this.setup); 368 369 /* int resultado = JOptionPane.showConfirmDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), 370 "Deseja tentar carregá-lo novamente?", 371 "Token foi removido!", 372 JOptionPane.OK_CANCEL_OPTION, 373 JOptionPane.QUESTION_MESSAGE); 374 */ 375 376 if (resultado == JOptionPane.OK_OPTION){ 377 tryAgain = true; 378 } 379 else { 380 tryAgain = false; 381 } 382 383 Thread.yield(); 384 } 385 386 } 387 while (tryAgain); 388 389 // chama o método que cria a interface na thread de lançamento de eventos (Event Dispatching Thread). 390 //try 391 //{ 392 // SwingUtilities.invokeAndWait(new Runnable(){ 393 394 /* (non-Javadoc) 395 * @see java.lang.Runnable#run() 396 */ 397 // public void run() { 398 // createGUI(); 399 // } 400 401 // }); 402 //} catch (Exception e){ 403 // System.out.println("Método createGUI não pôde ser carregado: " + e.getMessage()); 404 //} 405 406 } 407 408 /* 409 410 public void doLogin(String[] credentials){ 411 412 if (Integer.valueOf(credentials[0]) == 0){ 413 414 // Pega usuário e senha de credentials[1] e credentials[2], respectivamente 415 // adiciona na página e faz o submit. 416 JSObject document = (JSObject) JSObject.getWindow( this ).getMember("document"); 417 JSObject loginForm = (JSObject) document.getMember("flogin"); 418 JSObject loginField = (JSObject) loginForm.getMember("user"); 419 loginField.setMember("value", credentials[1]); 420 421 JSObject passwdField = (JSObject) loginForm.getMember("passwd"); 422 passwdField.setMember("value", credentials[2]); 423 424 loginForm.call("submit", null); 425 426 } 427 else if (Integer.valueOf(credentials[0]) == 6){ 428 429 //JOptionPane.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), credentials[1]); 430 DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), credentials[1]); 431 String redirect = this.getCodeBase().toExternalForm() + "login.php?cd=98&ts=202"; 432 try { 433 this.getAppletContext().showDocument(new URL(redirect)); 434 } catch (MalformedURLException e) { 435 // TODO Bloco catch gerado automaticamente 436 e.printStackTrace(); 437 } 438 } 439 else { 440 // Mostra mensagem de erro para o usuário 441 //JOptionPane.showMessageDialog(this, credentials[1]); 442 DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), credentials[1]); 443 } 444 445 } 446 447 */ 448 449 /** 450 * Destrói a Applet, executando códigos para desregistrar tokens, keystores, etc. 451 */ 452 @Override 453 public void stop() { 454 //super.destroy(); 251 JOptionPane.QUESTION_MESSAGE, 252 JOptionPane.OK_CANCEL_OPTION, this.setup); 253 254 if (resultado == JOptionPane.OK_OPTION) { 255 tryAgain = true; 256 } else { 257 tryAgain = false; 258 } 259 260 Thread.yield(); 261 } 262 263 } while (tryAgain); 264 265 } 266 267 /** 268 * Destrói a Applet, executando códigos para desregistrar tokens, keystores, etc. 269 */ 270 @Override 271 public void stop() { 272 //super.destroy(); 455 273 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 456 274 System.out.println("Finalizando Applet de Login!"); 457 275 } 458 459 this.dc.destroy(); 460 this.dc = null; 461 //Component[] components = this.getComponents(); 462 //for (Component component : components){ 463 // this.remove(component); 464 // component = null; 465 //} 466 System.gc(); 467 } 468 469 /** 470 * Cria a interface e seleciona o Painel que será exibido de acordo com o parâmetro useCertificate 471 */ 472 /* 473 private void createGUI(){ 474 475 this.setLayout(new FlowLayout()); 476 this.getContentPane().setBackground(Color.WHITE); 477 478 JSObject document = (JSObject) JSObject.getWindow( this ).getMember("document"); 479 JSObject loginForm = (JSObject) document.getMember("flogin"); 480 JSObject loginField = (JSObject) loginForm.getMember("user"); 481 482 uid = loginField.getMember("value").toString(); 483 484 pinPanel = new PinCodePanel(uid, true); // mostra pinCodeField 485 alreadyLoadedPanel = new PinCodePanel(uid, false); // não mostra pinCodeField 486 loginPanel = new LoginPanel(uid); 487 488 switch (useCertificate){ 489 case DigitalCertificate.KEYSTORE_NOT_DETECTED: 490 // Mostra interface de login com usuário e senha 491 this.getContentPane().add(loginPanel); 492 break; 493 case DigitalCertificate.KEYSTORE_ALREADY_LOADED: 494 // Mostra interface de login sem pedir o pin 495 this.getContentPane().add(alreadyLoadedPanel); 496 break; 497 default: 498 // Mostra interface de login pedindo o pin 499 this.getContentPane().add(pinPanel); 500 501 } 502 503 this.setVisible(true); 504 505 } 506 */ 507 508 /** 509 * Ação executada quando o Botão cancel de PinPanel for pressionado 510 * 511 */ 512 /* 513 private void cancelButtonActionPerformed(){ 514 515 pinPanel.setVisible(false); 516 this.remove(pinPanel); 517 this.add(loginPanel); 518 loginPanel.setVisible(true); 519 this.setVisible(true); 520 pinPanel.clearPasswordField(); 521 522 } 523 */ 524 525 /** 526 * Ação realizada quando o usuário pressiona o botão Ok ou Prossegir 527 * nas telas de login com pin ou sem o pin, respectivamente 528 * 529 */ 530 /* 531 private void okButtonActionPerformed(){ 532 // atribui o valor da senha para o atributo Pin 533 char[] pin = pinPanel.getPin(); 534 String[] returnCode = null; 535 536 // abre a keystore com o pin e recupera as credenciais do usuário 537 try { 538 dc.openKeyStore(pin); 539 540 returnCode = dc.getCredentials(new String(pin)); 541 542 assert (returnCode != null): "Valor de returnCode não pode ser nulo"; 543 544 if (Integer.valueOf(returnCode[0]) == 0){ 545 546 // Pega usuário e senha de returnCode[1] e returnCode[2], respectivamente 547 // adiciona na página e faz o submit. 548 JSObject document = (JSObject) JSObject.getWindow( this ).getMember("document"); 549 JSObject loginForm = (JSObject) document.getMember("flogin"); 550 JSObject loginField = (JSObject) loginForm.getMember("user"); 551 loginField.setMember("value", returnCode[1]); 552 553 JSObject passwdField = (JSObject) loginForm.getMember("passwd"); 554 passwdField.setMember("value", returnCode[2]); 555 556 this.pinPanel.clearPasswordField(); 557 loginForm.call("submit", null); 558 559 } 560 else { 561 // Mostra mensagem de erro para o usuário 562 showGetCredentialsError(returnCode[1]); 563 } 564 565 } catch (SSLHandshakeException e){ 566 e.printStackTrace(); 567 JOptionPane.showMessageDialog(this, "Não foi possível validar o certificado do servidor!"); 568 } catch (HttpException e) { 569 e.printStackTrace(); 570 } catch (GeneralSecurityException e){ 571 e.printStackTrace(); 572 } catch (IOException e) { 573 JOptionPane.showMessageDialog(this, "Senha não confere!"); 574 } catch (ProviderException e) { 575 JOptionPane.showMessageDialog(this, "Token foi removido!"); 576 } finally { 577 this.pinPanel.clearPasswordField(); 578 } 579 580 } 581 */ 582 583 /** 584 * Ação realizada quando o usuário pressiona o botão acessar na 585 * tela de login com usuário e senha 586 * 587 */ 588 /* 589 private void acessarButtonActionPerformed(){ 590 591 // Pega usuário e senha dos campos tfUsername e pfPasswd, respectivamente, 592 // adiciona na página e faz o submit. 593 String username = this.loginPanel.tfUsername.getText(); 594 String passwd = String.valueOf(this.loginPanel.pfPasswd.getPassword()); 595 596 JSObject document = (JSObject) JSObject.getWindow( this ).getMember("document"); 597 JSObject loginForm = (JSObject) document.getMember("flogin"); 598 JSObject loginField = (JSObject) loginForm.getMember("user"); 599 loginField.setMember("value", username); 600 601 JSObject passwdField = (JSObject) loginForm.getMember("passwd"); 602 passwdField.setMember("value", passwd); 603 604 this.loginPanel.clearPasswordField(); 605 loginForm.call("submit", null); 606 607 } 608 */ 609 610 /** 611 * Mostra mensagem "Campo PIN não foi preenchido!" quando o botão Ok for pressionado 612 * e o campo pin estiver vazio 613 * 614 */ 615 /* 616 private void okButtonPinEmpty(){ 617 JOptionPane.showMessageDialog(this, "Campo PIN não foi preenchido!"); 618 } 619 */ 620 621 /** 622 * Mostra mensagem de erro recebida de dc.getCredentials(); 623 * TODO: Mudar este método para ser mais genérico... Todas as mensagens de erro devem ser passadas para este 624 * método para serem exibidas. 625 * @param errorMsg Mensagem de erro que deve ser exibida 626 */ 627 /* 628 private void showGetCredentialsError(String errorMsg){ 629 JOptionPane.showMessageDialog(this, errorMsg); 630 } 631 632 private final class PinCodePanel extends JPanel implements ActionListener{ 633 */ 634 /** 635 * Gerado automaticamente 636 */ 637 /* 638 private static final long serialVersionUID = 1003857725229120014L; 639 640 JPanel pNorte, pCentro, pSul; 641 JButton btOk, btCancel; 642 JLabel lTitle, lPin; 643 JPasswordField pfPin; 644 645 // TODO: Implementar um construtor default (sem parâmetros); 646 public PinCodePanel(String uid, boolean showPinField){ 647 648 this.setLayout(new BorderLayout()); 649 Dimension panelsDimension = new Dimension(300, 42); 650 Dimension fieldsDimension = new Dimension(80, 20); 651 652 pNorte = new JPanel(new FlowLayout(FlowLayout.CENTER)); 653 pNorte.setBackground(Color.WHITE); 654 pNorte.setPreferredSize(panelsDimension); 655 656 pCentro = new JPanel(new FlowLayout(FlowLayout.CENTER)); 657 pCentro.setBackground(Color.WHITE); 658 pCentro.setPreferredSize(panelsDimension); 659 660 pSul = new JPanel(new FlowLayout(FlowLayout.CENTER)); 661 pSul.setBackground(Color.WHITE); 662 pSul.setPreferredSize(panelsDimension); 663 664 JPanel pTitle = new JPanel(new GridLayout(2, 0)); 665 pTitle.setBackground(Color.WHITE); 666 JLabel lTitle2 = null; 667 668 669 if (showPinField){ 670 lTitle = new JLabel("Entre com o seu PIN:"); 671 lTitle.setHorizontalTextPosition(SwingConstants.CENTER); 672 673 pfPin = new JPasswordField(20); 674 pfPin.setPreferredSize(fieldsDimension); 675 pfPin.addActionListener(this); 676 pfPin.setActionCommand("ok"); 677 pCentro.add(pfPin); 678 btOk = new JButton("Ok"); 679 btCancel = new JButton("Cancel"); 680 } 681 else { 682 lTitle = new JLabel("Token inserido e desbloqueado"); 683 lTitle.setHorizontalTextPosition(SwingConstants.CENTER); 684 lTitle2 = new JLabel(" pelo usuário " + uid + " foi detectado:"); 685 lTitle2.setHorizontalTextPosition(SwingConstants.CENTER); 686 btOk = new JButton("Prossegir"); 687 } 688 689 JPanel pTitle1 = new JPanel(new FlowLayout(FlowLayout.CENTER)); 690 pTitle1.setPreferredSize(new Dimension(300, 20)); 691 pTitle1.setBackground(Color.WHITE); 692 pTitle1.add(lTitle); 693 pTitle.add(pTitle1); 694 if (lTitle2 != null) { 695 JPanel pTitle2 = new JPanel(new FlowLayout(FlowLayout.CENTER)); 696 pTitle2.setPreferredSize(new Dimension(300,20)); 697 pTitle2.setBackground(Color.WHITE); 698 pTitle.add(pTitle2); 699 pTitle2.add(lTitle2); 700 } 701 702 pNorte.add(pTitle); 703 704 btOk.setMnemonic(KeyEvent.VK_ENTER); 705 btOk.setActionCommand("ok"); 706 btOk.addActionListener(this); 707 pSul.add(btOk); 708 709 if (btCancel != null){ 710 btCancel.setActionCommand("cancel"); 711 btCancel.addActionListener(this); 712 pSul.add(btCancel); 713 } 714 715 this.add(pNorte, BorderLayout.NORTH); 716 this.add(pCentro, BorderLayout.CENTER); 717 this.add(pSul, BorderLayout.SOUTH); 718 } 719 720 // design ruim!!! azar :-S 721 public char[] getPin() { 722 if (pfPin == null){ 723 return null; 724 } 725 return pfPin.getPassword(); 726 } 727 728 void clearPasswordField(){ 729 if (pfPin != null){ 730 pfPin.setText(""); 731 } 732 } 733 734 public void actionPerformed(ActionEvent evt) { 735 736 String command = evt.getActionCommand(); 737 738 // Atribui o valor digitado para o campo 739 // senha e esconde a interface e assina o certificado 740 if (command.equals("ok")){ 741 742 if (pfPin != null && pfPin.getPassword().length <= 0){ 743 // Mostra um aviso de que o campo PIN não foi preenchido 744 okButtonPinEmpty(); 745 } 746 else { 747 okButtonActionPerformed(); 748 } 749 750 } 751 else if (command.equals("cancel")){ 752 cancelButtonActionPerformed(); 753 } 754 } 755 756 757 } 758 759 private final class LoginPanel extends JPanel implements ActionListener{ 760 */ 761 /** 762 * 763 */ 764 /* 765 private static final long serialVersionUID = -8604718192554937222L; 766 JButton btAcessar; 767 JTextField tfUsername; 768 JPasswordField pfPasswd; 769 770 public LoginPanel(String uid){ 771 772 this.setLayout(new BorderLayout()); 773 774 JPanel panelCredentials = new JPanel(new GridLayout(2, 0)); 775 panelCredentials.setBackground(Color.WHITE); 776 panelCredentials.setPreferredSize(new Dimension(280, 84)); 777 778 JPanel panelUsername = new JPanel(new FlowLayout(FlowLayout.CENTER)); 779 panelUsername.setBackground(Color.WHITE); 780 panelUsername.setPreferredSize(new Dimension(300, 42)); 781 782 JLabel labelUsername = new JLabel("Usuário"); 783 panelUsername.add(labelUsername); 784 labelUsername.setPreferredSize(new Dimension(100, 40)); 785 786 tfUsername = new JTextField(15); 787 tfUsername.setText(uid); 788 panelUsername.add(tfUsername); 789 790 JPanel panelPasswd = new JPanel(new FlowLayout(FlowLayout.CENTER)); 791 panelPasswd.setPreferredSize(new Dimension(300, 42)); 792 JLabel labelPasswd = new JLabel("Senha"); 793 panelPasswd.add(labelPasswd); 794 panelPasswd.setBackground(Color.WHITE); 795 labelPasswd.setPreferredSize(new Dimension(100, 20)); 796 797 pfPasswd = new JPasswordField(15); 798 panelPasswd.add(pfPasswd); 799 800 panelCredentials.add(panelUsername); 801 panelCredentials.add(panelPasswd); 802 this.add(panelCredentials, BorderLayout.CENTER); 803 804 btAcessar = new JButton("Acessar"); 805 btAcessar.setActionCommand("acessar"); 806 btAcessar.addActionListener(this); 807 JPanel panelBtAcessar = new JPanel(new FlowLayout(FlowLayout.CENTER)); 808 panelBtAcessar.setBackground(Color.WHITE); 809 panelBtAcessar.setPreferredSize(new Dimension(300, 42)); 810 panelBtAcessar.add(btAcessar); 811 812 this.add(panelBtAcessar, BorderLayout.SOUTH); 813 this.setVisible(true); 814 815 } 816 817 public void actionPerformed(ActionEvent e) { 818 if (e.getActionCommand().equals("acessar")){ 819 acessarButtonActionPerformed(); 820 } 821 822 } 823 824 void clearPasswordField(){ 825 pfPasswd.setText(""); 826 } 827 828 } 829 */ 830 276 277 this.dc.destroy(); 278 this.dc = null; 279 System.gc(); 280 } 831 281 }
Note: See TracChangeset
for help on using the changeset viewer.