source: branches/2.2.0.1/security/ExpressoCert/src/br/gov/serpro/cert/DigitalCertificate.java @ 4123

Revision 4123, 29.4 KB checked in by rafaelraymundo, 13 years ago (diff)

Ticket #1739 - Login com certificado em atributo customizável.

Line 
1package br.gov.serpro.cert;
2
3import br.gov.serpro.setup.Setup;
4import java.awt.Frame;
5import java.io.ByteArrayInputStream;
6import java.io.ByteArrayOutputStream;
7import java.io.File;
8import java.io.FileInputStream;
9import java.io.IOException;
10import java.io.InputStream;
11import java.net.MalformedURLException;
12import java.net.URL;
13import java.security.AuthProvider;
14import java.security.GeneralSecurityException;
15import java.security.Key;
16import java.security.KeyPair;
17import java.security.KeyStore;
18import java.security.KeyStoreException;
19import java.security.PrivateKey;
20import java.security.Provider;
21import java.security.ProviderException;
22import java.security.Security;
23import java.security.cert.CertStore;
24import java.security.cert.Certificate;
25import java.security.cert.CollectionCertStoreParameters;
26import java.security.cert.X509Certificate;
27import java.util.ArrayList;
28import java.util.Enumeration;
29import java.util.List;
30import java.util.Map;
31import java.util.Properties;
32
33import javax.crypto.Cipher;
34import javax.mail.Message;
35import javax.mail.MessagingException;
36import javax.mail.Session;
37import javax.mail.internet.MimeBodyPart;
38import javax.mail.internet.MimeMessage;
39import javax.mail.internet.MimeMultipart;
40import javax.net.ssl.SSLHandshakeException;
41import javax.security.auth.login.LoginException;
42
43import org.apache.commons.httpclient.HttpClient;
44import org.apache.commons.httpclient.HttpException;
45import org.apache.commons.httpclient.methods.PostMethod;
46import org.apache.commons.httpclient.protocol.Protocol;
47import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
48import org.bouncycastle.asn1.ASN1EncodableVector;
49import org.bouncycastle.asn1.cms.AttributeTable;
50import org.bouncycastle.asn1.smime.SMIMECapability;
51import org.bouncycastle.asn1.smime.SMIMECapabilityVector;
52import org.bouncycastle.mail.smime.SMIMEException;
53import org.bouncycastle.mail.smime.SMIMESignedGenerator;
54
55import br.gov.serpro.ui.DialogBuilder;
56import br.gov.serpro.util.Base64Utils;
57import java.io.OutputStream;
58import java.io.OutputStreamWriter;
59import java.security.AlgorithmParameters;
60import java.security.cert.CertificateEncodingException;
61import java.util.regex.Matcher;
62import java.util.regex.Pattern;
63import javax.activation.CommandMap;
64import javax.activation.MailcapCommandMap;
65import javax.mail.internet.ContentType;
66import javax.mail.internet.MimeUtility;
67import javax.mail.internet.PreencodedMimeBodyPart;
68import org.bouncycastle.cms.CMSException;
69import org.bouncycastle.cms.RecipientId;
70import org.bouncycastle.cms.RecipientInformation;
71import org.bouncycastle.cms.RecipientInformationStore;
72import org.bouncycastle.mail.smime.SMIMEEnvelopedParser;
73import org.bouncycastle.mail.smime.SMIMEUtil;
74
75/**
76 * Classe que realiza todo o trabalho realizado com o certificado
77 * @author Mário César Kolling - mario.kolling@serpro.gov.br
78 */
79//TODO: Criar exceções para serem lançadas, entre elas DigitalCertificateNotLoaded
80//TODO: Adicionar setup
81public class DigitalCertificate {
82
83    private TokenCollection tokens;
84    private String selectedCertificateAlias;
85    private Certificate cert; // Certificado extraído da KeyStore. Pode ser nulo.
86    private KeyStore keyStore; // KeyStore que guarda o certificado do usuário. Pode ser nulo.
87    private Frame parentFrame;
88    private Setup setup;
89    // TODO: Transformar pkcs12Input em uma string ou URL com o caminho para a KeyStore pkcs12
90    private FileInputStream pkcs12Input; // stream da KeyStore pkcs12. Pode ser nulo.
91    private String providerName; // Nome do SecurityProvider pkcs11 carregado. Pode ser nulo.
92    private URL pageAddress; // Endereço do host, onde a página principal do
93    private static final String HOME_SUBDIR; // Subdiretório dentro do diretório home do usuário. Dependente de SO.
94    private static final String EPASS_2000; // Caminho da biblioteca do token ePass2000. Dependente de SO.
95    private static final String CRLF = "\r\n"; // Separa campos na resposta do serviço de verificação de certificados
96    private static final String SUBJECT_ALTERNATIVE_NAME = "2.5.29.17"; // Não é mais utilizado.
97    private static final URL[] TRUST_STORES_URLS = new URL[3]; // URLs (file:/) das TrustStores, cacerts (jre),
98    // trusted.certs e trusted.jssecerts (home do usuário)
99    // Utilizadas para validação do certificado do servidor.
100    private static final String[] TRUST_STORES_PASSWORDS = null; // Senhas para cada uma das TrustStores,
101    // caso seja necessário.
102    private int keystoreStatus;
103    public static final int KEYSTORE_DETECTED = 0;
104    public static final int KEYSTORE_NOT_DETECTED = 1;
105    public static final int KEYSTORE_ALREADY_LOADED = 2;
106
107    /*
108     * Bloco estático que define os caminhos padrões da instalação da jre,
109     * do diretório home do usuário, e da biblioteca de sistema do token ePass2000,
110     * de acordo com o sistema operacional.
111     */
112    static {
113
114        Properties systemProperties = System.getProperties();
115        Map<String, String> env = System.getenv();
116
117        /* TODO: Testar a existência de vários drivers de dispositivos. Determinar qual deve ser utilizado
118         * e guardar em uma property no subdiretório home do usuário.
119         */
120
121        if (systemProperties.getProperty("os.name").equalsIgnoreCase("linux")) {
122            HOME_SUBDIR = "/.java/deployment/security";
123            EPASS_2000 = "/usr/lib/libepsng_p11.so";
124        } else {
125            HOME_SUBDIR = "\\dados de aplicativos\\sun\\java\\deployment\\security";
126            EPASS_2000 = System.getenv("SystemRoot") + "\\system32\\ngp11v211.dll";
127            //EPASS_2000 = System.getenv("ProgramFiles")+"\\Gemplus\\GemSafe Libraries\\BIN\\gclib.dll";
128        }
129
130        try {
131            if (systemProperties.getProperty("os.name").equalsIgnoreCase("linux")) {
132                TRUST_STORES_URLS[0] = new File(systemProperties.getProperty("java.home") + "/lib/security/cacerts").toURI().toURL();
133                TRUST_STORES_URLS[1] = new File(systemProperties.getProperty("user.home") + HOME_SUBDIR + "/trusted.certs").toURI().toURL();
134                TRUST_STORES_URLS[2] = new File(systemProperties.getProperty("user.home") + HOME_SUBDIR + "/trusted.jssecerts").toURI().toURL();
135            } else {
136
137                TRUST_STORES_URLS[0] = new File(systemProperties.getProperty("java.home") +
138                        "\\lib\\security\\cacerts").toURI().toURL();
139                TRUST_STORES_URLS[1] = new File(systemProperties.getProperty("user.home") +
140                        HOME_SUBDIR + "\\trusted.certs").toURI().toURL();
141                TRUST_STORES_URLS[2] = new File(systemProperties.getProperty("user.home") +
142                        HOME_SUBDIR + "\\trusted.jssecerts").toURI().toURL();
143            }
144
145            // Define os tipos smime no mailcap
146            MailcapCommandMap mailcap = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
147
148            mailcap.addMailcap("application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature");
149            mailcap.addMailcap("application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime");
150            mailcap.addMailcap("application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature");
151            mailcap.addMailcap("application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime");
152            mailcap.addMailcap("multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed");
153
154            CommandMap.setDefaultCommandMap(mailcap);
155
156
157
158        } catch (MalformedURLException e) {
159            e.printStackTrace();
160        }
161    }
162
163    /**
164     *
165     */
166    public DigitalCertificate() {
167        this.pageAddress = null;
168        this.parentFrame = null;
169    }
170
171    /**
172     * Construtor da classe. Recebe a {@link URL} da página em que a Applet está incluída.
173     * @param pageAddress URL da página em que a Applet está incluída
174     */
175    private DigitalCertificate(URL pageAddress) {
176        this.pageAddress = pageAddress;
177        this.parentFrame = null;
178    }
179
180    private DigitalCertificate(Frame parent) {
181        this.pageAddress = null;
182        this.parentFrame = parent;
183    }
184
185    public DigitalCertificate(Frame parent, Setup setup) {
186        this(parent);
187        this.setup = setup;
188    }
189
190    public DigitalCertificate(URL pageAddress, Setup setup) {
191        this(pageAddress);
192        this.setup = setup;
193    }
194
195    public KeyStore getKeyStore() {
196        return keyStore;
197    }
198
199    public int getKeystoreStatus() {
200        return keystoreStatus;
201    }
202
203    public String getProviderName() {
204        return providerName;
205    }
206
207    /**
208     * Destrói a Applet, removendo o security provider inicializado se o atributo providerName
209     * for diferente de nulo.
210     */
211    public void destroy() {
212
213        AuthProvider ap = null;
214
215        if (this.setup.getParameter("debug").equalsIgnoreCase("true")) {
216            System.out.println("logout no provider");
217        }
218        if (keyStore != null) {
219            ap = (AuthProvider) this.keyStore.getProvider();
220        }
221
222        if (ap != null) {
223            try {
224                ap.logout();
225            } catch (LoginException e) {
226                if (this.setup.getParameter("debug").equalsIgnoreCase("true")) {
227                    e.printStackTrace();
228                }
229            }
230        }
231
232        if (providerName != null) {
233            Security.removeProvider(providerName);
234        }
235
236        this.cert = null;
237        this.selectedCertificateAlias = null;
238        this.keyStore = null;
239        this.pkcs12Input = null;
240        this.providerName = null;
241
242    }
243
244    /**
245     * Procura pelo token nos locais padrões (Por enquanto só suporta o token ePass200),
246     * senão procura por um certificado A1 em System.getProperties().getProperty("user.home") +
247     * HOME_SUBDIR  + "/trusted.clientcerts" e retorna um inteiro de acordo com resultado desta procura.
248     *
249     * @author  Mário César Kolling
250     * @return  Retorna um destes valores inteiros DigitalCertificate.KEYSTORE_DETECTED,
251     *          DigitalCertificate.KEYSTORE_ALREADY_LOADED ou DigitalCertificate.KEYSTORE_NOT_DETECTED
252     * @see     DigitalCertificate
253     */
254    public int init() {
255
256        // TODO: Usar dentro de um "loop" para testar outros modelos de tokens.
257        this.tokens = new TokenCollection(setup);
258        int interfaceType = DigitalCertificate.KEYSTORE_DETECTED;
259
260        try {
261            // Tenta abrir o Token padrï¿œo (ePass2000).
262            loadKeyStore();
263
264        } catch (Exception e1) {
265
266            Provider[] providers = Security.getProviders();
267            if (this.setup.getParameter("debug").equalsIgnoreCase("true")) {
268                for (Provider provider : providers) {
269                    System.out.println(provider.getInfo());
270                }
271
272                // Não conseguiu abrir o token (ePass2000).
273                System.out.println("Erro ao ler o token: " + e1.getMessage());
274            }
275
276            try {
277                // Tenta abrir a keyStore padrão
278                // USER_HOME/deployment/security/trusted.clientcerts
279
280                Properties props = System.getProperties();
281                pkcs12Input = new FileInputStream(props.getProperty("user.home") + HOME_SUBDIR + "/trusted.clientcerts");
282
283                // Se chegar aqui significa que arquivo de KeyStore existe.
284                keyStore = KeyStore.getInstance("JKS");
285
286            } catch (Exception ioe) {
287                // Não conseguiu abrir a KeyStore pkcs12
288                if (this.setup.getParameter("debug").equalsIgnoreCase("true")) {
289                    System.out.println(ioe.getMessage());
290                }
291            }
292        }
293
294
295        if (keyStore == null) {
296            // Não conseguiu inicializar a KeyStore. Mostra tela de login com usuário e senha.
297            this.keystoreStatus = DigitalCertificate.KEYSTORE_NOT_DETECTED;
298            //} else if (keyStore.getType().equalsIgnoreCase("pkcs11")){
299        } else {
300            // Usa certificado digital.
301            try {
302                // Testa se uma keystore já foi carregada previamente
303                if (keyStore.getType().equalsIgnoreCase("pkcs11")) {
304                    keyStore.load(null, null);
305                } else {
306                    keyStore.load(pkcs12Input, null);
307                }
308
309                // Se chegou aqui KeyStore está liberada, mostrar tela de login sem pedir o pin.
310                this.keystoreStatus = DigitalCertificate.KEYSTORE_ALREADY_LOADED;
311
312            } catch (ProviderException e) {
313                // Algum erro ocorreu, mostra  tela de login com usuário e senha.
314                this.keystoreStatus = DigitalCertificate.KEYSTORE_NOT_DETECTED;
315                if (this.setup.getParameter("debug").equalsIgnoreCase("true")) {
316                    e.printStackTrace();
317                }
318            } catch (IOException e) {
319                // KeyStore não está liberada, mostra tela de login com o pin.
320                if (this.setup.getParameter("debug").equalsIgnoreCase("true")) {
321                    System.out.println(e.getMessage());
322                }
323                this.keystoreStatus = DigitalCertificate.KEYSTORE_DETECTED;
324            } catch (GeneralSecurityException e) {
325                if (this.setup.getParameter("debug").equalsIgnoreCase("true")) {
326                    e.printStackTrace();
327                }
328            }
329        }
330
331        return keystoreStatus;
332
333    }
334
335    /**
336     * Usado para assinar digitalmente um e-mail.
337     * @param mime
338     * @return String vazia
339     */
340    public String signMail(Map<String, String> data) throws IOException, GeneralSecurityException, SMIMEException, MessagingException {
341
342        Key privateKey = null;
343        if (this.keystoreStatus == DigitalCertificate.KEYSTORE_DETECTED) {
344            String pin = DialogBuilder.showPinDialog(this.parentFrame, this.setup);
345            if (pin != null) {
346                openKeyStore(pin.toCharArray());
347                if (this.selectedCertificateAlias == null){
348                    return null;
349                }
350                privateKey = this.keyStore.getKey(this.selectedCertificateAlias, pin.toCharArray());
351            } else {
352                return null;
353            }
354        } /*
355        else if (this.keystoreStatus == DigitalCertificate.KEYSTORE_ALREADY_LOADED){
356        if (DialogBuilder.showPinNotNeededDialog(this.parentFrame)){
357        openKeyStore(null);
358        privateKey = this.keyStore.getKey(keyStore.aliases().nextElement(), null);
359        }
360        else {
361        return null;
362        }
363        }
364         */ else {
365
366            //DialogBuilder.showMessageDialog(this.parentFrame, "Nenhum token/smartcard foi detectado.\nOperação não pôde ser realizada!");
367            DialogBuilder.showMessageDialog(this.parentFrame, setup.getLang("ExpressoCertMessages", "DigitalCertificate001"), this.setup);
368            return null;
369        }
370
371        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
372
373        Certificate certificate = getCert();
374
375        KeyPair keypair = new KeyPair(certificate.getPublicKey(), (PrivateKey) privateKey);
376
377        // Cria a cadeia de certificados que a gente vai enviar
378        List certList = new ArrayList();
379
380        certList.add(certificate);
381
382        //
383        // create the base for our message
384        //
385        String fullMsg = data.get("body");
386
387        if (this.setup.getParameter("debug").equalsIgnoreCase("true")) {
388            System.out.println("Corpo do e-mail:\n" + fullMsg + "\n");
389        }
390
391        //
392        // Get a Session object and create the mail message
393        //
394        Properties props = System.getProperties();
395        Session session = Session.getDefaultInstance(props, null);
396
397        InputStream is = new ByteArrayInputStream(fullMsg.getBytes("iso-8859-1"));
398        MimeMessage unsignedMessage = new MimeMessage(session, is);
399
400        //
401        // create a CertStore containing the certificates we want carried
402        // in the signature
403        //
404        if (this.setup.getParameter("debug").equalsIgnoreCase("true")) {
405            System.out.println("Provider: " + providerName);
406        }
407        CertStore certsAndcrls = CertStore.getInstance(
408                "Collection",
409                new CollectionCertStoreParameters(certList), "BC");
410
411        //
412        // create some smime capabilities in case someone wants to respond
413        //
414        ASN1EncodableVector signedAttrs = new ASN1EncodableVector();
415
416        SMIMECapabilityVector caps = new SMIMECapabilityVector();
417
418        caps.addCapability(SMIMECapability.dES_EDE3_CBC);
419        caps.addCapability(SMIMECapability.rC2_CBC, 128);
420        caps.addCapability(SMIMECapability.dES_CBC);
421
422        SMIMESignedGenerator gen = new SMIMESignedGenerator(unsignedMessage.getEncoding());
423
424        //SMIMESignedGenerator gen = new SMIMESignedGenerator();
425
426        gen.addSigner(keypair.getPrivate(), (X509Certificate) certificate, SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(signedAttrs), null);
427
428        gen.addCertificatesAndCRLs(certsAndcrls);
429
430        //TODO: Extrair todos os headers de unsignedMessage
431
432        // Gera a assinatura
433        Object content = unsignedMessage.getContent();
434
435        //TODO: igualar unsignedMessage a null
436        //TODO: Pegar os headers do objeto que guardarï¿œ esses headers quando necessï¿œrio.
437
438        MimeMultipart mimeMultipartContent = null;
439        PreencodedMimeBodyPart mimeBodyPartContent = null;
440
441        if (content.getClass().getName().contains("MimeMultipart")) {
442            mimeMultipartContent = (MimeMultipart) content;
443        } else {
444            String encoding = MimeUtility.getEncoding(unsignedMessage.getDataHandler());
445            mimeBodyPartContent = new PreencodedMimeBodyPart(encoding);
446            if (encoding.equalsIgnoreCase("quoted-printable")) {
447                ByteArrayOutputStream os = new ByteArrayOutputStream();
448                OutputStream encode = MimeUtility.encode(os, encoding);
449                OutputStreamWriter writer = new OutputStreamWriter(encode, "iso-8859-1");
450                writer.write(content.toString());
451                writer.flush();
452                mimeBodyPartContent.setText(os.toString(), "iso-8859-1");
453                os = null;
454                encode = null;
455                writer = null;
456            } else {
457                mimeBodyPartContent.setText(content.toString(), "iso-8859-1");
458            }
459            mimeBodyPartContent.setHeader("Content-Type", unsignedMessage.getHeader("Content-Type", null));
460        }
461        content = null;
462
463        //
464        // extract the multipart object from the SMIMESigned object.
465        //
466        MimeMultipart mm = null;
467        if (mimeMultipartContent == null) {
468            mm = gen.generate(mimeBodyPartContent, providerName);
469            mimeBodyPartContent = null;
470        } else {
471            MimeBodyPart multipartMsg = new MimeBodyPart();
472            multipartMsg.setContent(mimeMultipartContent);
473            mm = gen.generate(multipartMsg, providerName);
474            multipartMsg = null;
475            mimeMultipartContent = null;
476        }
477
478        gen = null;
479
480        MimeMessage body = new MimeMessage(session);
481        body.setFrom(unsignedMessage.getFrom()[0]);
482        body.setRecipients(Message.RecipientType.TO, unsignedMessage.getRecipients(Message.RecipientType.TO));
483        body.setRecipients(Message.RecipientType.CC, unsignedMessage.getRecipients(Message.RecipientType.CC));
484        body.setRecipients(Message.RecipientType.BCC, unsignedMessage.getRecipients(Message.RecipientType.BCC));
485        body.setSubject(unsignedMessage.getSubject(), "iso-8859-1");
486
487        // Atrafuia o resto dos headers
488        body.setHeader("Return-Path", unsignedMessage.getHeader("Return-Path", null));
489        body.setHeader("Message-ID", unsignedMessage.getHeader("Message-ID", null));
490        body.setHeader("X-Priority", unsignedMessage.getHeader("X-Priority", null));
491        body.setHeader("X-Mailer", unsignedMessage.getHeader("X-Mailer", null));
492        body.setHeader("Importance", unsignedMessage.getHeader("Importance", null));
493        body.setHeader("Disposition-Notification-To", unsignedMessage.getHeader("Disposition-Notification-To", null));
494        body.setHeader("Date", unsignedMessage.getHeader("Date", null));
495        body.setContent(mm, mm.getContentType());
496        mm = null;
497
498        if (setup.getParameter("debug").equalsIgnoreCase("true")) {
499            System.out.println("\nHeaders do e-mail original:\n");
500        }
501
502        body.saveChanges();
503
504        ByteArrayOutputStream oStream = new ByteArrayOutputStream();
505
506        oStream = new ByteArrayOutputStream();
507        body.writeTo(oStream);
508
509        body = null;
510        return oStream.toString("iso-8859-1");
511
512    }
513
514    /**
515     * Método utilizado para criptografar um e-mail
516     * @param source
517     * @return
518     */
519    public String cipherMail(Map<String, String> data) throws IOException, GeneralSecurityException, MessagingException, CMSException, SMIMEException {
520
521        //Pega certificado do usuário.
522
523        Key privateKey = null;
524        if (this.keystoreStatus == DigitalCertificate.KEYSTORE_DETECTED) {
525            String pin = DialogBuilder.showPinDialog(this.parentFrame, this.setup);
526            if (pin != null) {
527                openKeyStore(pin.toCharArray());
528                if (this.selectedCertificateAlias == null){
529                    return null;
530                }
531                privateKey = this.keyStore.getKey(this.selectedCertificateAlias, pin.toCharArray());
532            } else {
533                return null;
534            }
535        } /*
536        else if (this.keystoreStatus == DigitalCertificate.KEYSTORE_ALREADY_LOADED){
537        if (DialogBuilder.showPinNotNeededDialog(this.parentFrame)){
538        openKeyStore(null);
539        privateKey = this.keyStore.getKey(keyStore.aliases().nextElement(), null);
540        }
541        else {
542        return null;
543        }
544        }
545         */ else {
546
547            //DialogBuilder.showMessageDialog(this.parentFrame, "Nenhum token/smartcard foi detectado.\nOperação não pôde ser realizada!");
548            DialogBuilder.showMessageDialog(this.parentFrame, setup.getLang("ExpressoCertMessages", "DigitalCertificate001"), this.setup);
549            return null;
550        }
551
552        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
553
554        X509Certificate cert = (X509Certificate) getCert();
555
556        RecipientId recId = new RecipientId();
557        recId.setSerialNumber(cert.getSerialNumber());
558        recId.setIssuer(cert.getIssuerX500Principal());
559
560        Properties props = System.getProperties();
561        Session session = Session.getDefaultInstance(props, null);
562
563        String fullMsg = data.get("body");
564        InputStream is = new ByteArrayInputStream(fullMsg.getBytes("iso-8859-1"));
565        MimeMessage encriptedMsg = new MimeMessage(session, is);
566
567        Provider prov = Security.getProvider(providerName);
568        if (this.setup.getParameter("debug").equalsIgnoreCase("true")) {
569            System.out.println("Serviços do provider " + providerName + ":\n" + prov.getInfo());
570            for (Provider.Service service : prov.getServices()) {
571                System.out.println(service.toString() + ": " + service.getAlgorithm());
572            }
573        }
574
575        if (setup.getParameter("debug").equalsIgnoreCase("true")) {
576            System.out.println("Email criptografado:\n" + fullMsg);
577        }
578
579        SMIMEEnvelopedParser m = new SMIMEEnvelopedParser(encriptedMsg);
580        if (setup.getParameter("debug").equalsIgnoreCase("true")) {
581            System.out.println("Algoritmo de encriptação: " + m.getEncryptionAlgOID());
582        }
583
584        AlgorithmParameters algParams = m.getEncryptionAlgorithmParameters("BC");
585        if (this.setup.getParameter("debug").equalsIgnoreCase("true")) {
586            System.out.println("Parâmetros do algoritmo: " + algParams.toString());
587        }
588
589        RecipientInformationStore recipients = m.getRecipientInfos();
590        RecipientInformation recipient = recipients.get(recId);
591
592        if (recipient != null) {
593            String retorno;
594
595            MimeBodyPart decriptedBodyPart = SMIMEUtil.toMimeBodyPart(recipient.getContent(privateKey, getProviderName()));
596
597            if ((new ContentType(decriptedBodyPart.getContentType())).getSubType().equalsIgnoreCase("x-pkcs7-mime")) {
598                StringBuffer sb = new StringBuffer(encriptedMsg.getSize());
599
600                for (Enumeration e = encriptedMsg.getAllHeaderLines(); e.hasMoreElements();) {
601                    String header = (String) e.nextElement();
602                    if (!header.contains("Content-Type") &&
603                            !header.contains("Content-Transfer-Encoding") &&
604                            !header.contains("Content-Disposition")) {
605                        sb.append(header);
606                        sb.append("\r\n");
607                    }
608                }
609                ByteArrayOutputStream oStream = new ByteArrayOutputStream();
610                decriptedBodyPart.writeTo(oStream);
611
612                decriptedBodyPart = null;
613                encriptedMsg = null;
614
615                sb.append(oStream.toString("iso-8859-1"));
616
617                retorno = sb.toString();
618
619            } else {
620               
621                encriptedMsg.setContent(decriptedBodyPart.getContent(), decriptedBodyPart.getContentType());
622                encriptedMsg.saveChanges();
623
624                ByteArrayOutputStream oStream = new ByteArrayOutputStream();
625                encriptedMsg.writeTo(oStream);
626                encriptedMsg = null;
627
628                retorno = oStream.toString("iso-8859-1");
629            }
630
631            // Corrige problemas com e-mails vindos do Outlook
632            // Corrige linhas que são terminadas por \n (\x0A) e deveriam ser terminadas por \r\n (\x0D\x0A)
633            Pattern p = Pattern.compile("(?<!\\r)\\n");
634            Matcher matcher = p.matcher(retorno);
635            retorno = matcher.replaceAll(CRLF);
636
637            return retorno;
638        } else {
639            //DialogBuilder.showMessageDialog(this.parentFrame, "Não é possível ler este e-mail com o Certificado Digital apresentado!\n" +
640            //        "Motivo: Este e-mail não foi cifrado com a chave pública deste Certificado Digital.");
641            DialogBuilder.showMessageDialog(this.parentFrame, setup.getLang("ExpressoCertMessages", "DigitalCertificate002"), this.setup);
642            return null;
643        }
644    }
645
646    /**
647     * Pega as credenciais de login do dono do certificado do serviço de verificação de certificados
648     * @param   pin                     pin para acessar o token
649     * @param   where                   URL que será acessada para recuperar as credenciais
650     * @return  resposta        Array de Strings em que:
651     *                                          Indice 0: código de retorno;
652     *                                          Indice 1: username se código de retorno for 0, senão mensagem de erro;
653     *                                          Indice 2: senha decriptada se código de retorno for 0, senão não existe;
654     * @throws SSLHandshakeException
655     * @throws HttpException
656     * @throws IOException
657     * @throws GeneralSecurityException
658     */
659
660    public String[] getCredentials(String pin, URL where) throws SSLHandshakeException, HttpException, IOException, GeneralSecurityException {
661
662        String[] resposta = null;
663
664        if (this.selectedCertificateAlias == null){
665            return resposta;
666        }
667
668        if (this.setup.getParameter("debug").equalsIgnoreCase("true")) {
669            System.out.println("Proxy Configurado no browser: " + System.getProperty("http.proxyHost") + ":" + System.getProperty("http.proxyPort"));
670        }
671
672        // Registra novo protocolo https, utilizando nova implementação de AuthSSLProtocolSocketFactory
673        Protocol.registerProtocol("https", new Protocol("https",
674                (ProtocolSocketFactory) new AuthSSLProtocolSocketFactory(TRUST_STORES_URLS, TRUST_STORES_PASSWORDS, this.setup),
675                443));
676
677        HttpClient httpclient = new HttpClient();
678        // Define um método post para o link do serviço de verificação de certificados
679        if (System.getProperty("http.proxyHost") != null && System.getProperty("http.proxyPort") != null) {
680            httpclient.getHostConfiguration().setProxy(System.getProperty("http.proxyHost"),
681                    Integer.parseInt(System.getProperty("http.proxyPort")));
682        }
683
684        PostMethod httppost = new PostMethod(where.toExternalForm());
685       
686        try {
687            // Adiciona parâmetro certificado no método post, executa o método, pega a resposta do servidor
688            // como uma string com CRLF de separador entre os campos e gera um array de Strings
689            httppost.addParameter("certificado", Base64Utils.der2pem(cert.getEncoded()));
690            httpclient.executeMethod(httppost);
691            resposta = httppost.getResponseBodyAsString().split(CRLF);
692
693            if (resposta.length > 2) {
694                if (Integer.parseInt(resposta[0].trim()) == 0) {
695                    // Se código da resposta for zero, decripta a senha criptografada do usuário
696                    resposta[2] = decriptPassword(resposta[2].trim(), pin);
697                }
698            }
699
700        } catch (IOException e) {
701            // Se for instância de SSLHandshakeException faz um cast para este tipo e lança a exceção novamente
702            // Isto é usado para diferenciar o tipo de falha, para que a mensagem para o usuário seja mostrada de
703            // acordo.
704            if (e instanceof SSLHandshakeException) {
705                throw (SSLHandshakeException) e;
706            }
707            // senão lança novamente a exceção do tipo IOException
708            throw e;
709        } finally {
710            // fecha a conexão
711            httppost.releaseConnection();
712        }
713
714        return resposta;
715    }
716
717    /**
718     * Decripta a senha criptografada
719     * @param encodedPassword senha criptografada e codificada em base64 para ser decriptada
720     * @param pin pin para acessar a KeyStore
721     * @return decodedPassword
722     * @throws GeneralSecurityException se algum problema ocorrer na decriptação da senha.
723     */
724    public String decriptPassword(String encodedPassword, String pin) throws GeneralSecurityException {
725
726        String decodedPassword = new String();
727
728        // Pega a chave privada do primeiro certificado armazenado na KeyStore
729        Key privateKey = this.keyStore.getKey(selectedCertificateAlias, pin.toCharArray());
730
731        // Inicializa os cipher com os parâmetros corretos para realizar a decriptação
732        Cipher dcipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
733        dcipher.init(Cipher.DECRYPT_MODE, privateKey);
734
735        // Decodifica a senha em base64 e a decripta
736        decodedPassword = new String(dcipher.doFinal(Base64Utils.base64Decode(encodedPassword)));
737
738        return decodedPassword.trim();
739
740    }
741
742    /**
743     * Carrega um novo SecurityProvider
744     * @param pkcs11Config Linha de configuração do SmartCard ou Token
745     * @throws KeyStoreException Quando não conseguir iniciar a KeyStore, ou a lib do Token
746     *                                                   ou Smartcard não foi encontrada, ou o usuário não inseriu o Token.
747     */
748    private void loadKeyStore() throws KeyStoreException {
749
750        //Provider pkcs11Provider = new sun.security.pkcs11.SunPKCS11(new ByteArrayInputStream(pkcs11Config.getBytes()));
751        //Security.addProvider(pkcs11Provider);
752        this.keyStore = KeyStore.getInstance("PKCS11");
753        this.providerName = keyStore.getProvider().getName();
754
755    }
756
757    /**
758     *  Abre a keystore passando o pin
759     *  @param pin pin para acessar o Token
760     */
761    public void openKeyStore(char[] pin) throws IOException {
762        // TODO:  Verify if object DigitalCertificate was initiated
763        try {
764
765            if (this.keyStore.getType().equals("PKCS11")) {
766                this.keyStore.load(null, pin);
767            } else {
768                this.keyStore.load(this.pkcs12Input, pin);
769            }
770
771            List<String> aliases = new ArrayList<String>();
772            for (Enumeration<String> certificateList = keyStore.aliases(); certificateList.hasMoreElements();){
773                aliases.add(certificateList.nextElement());
774            }
775
776            // selecionador de certificado
777            this.selectedCertificateAlias = DialogBuilder.showCertificateSelector(this.parentFrame, this.setup, aliases);
778            if (this.selectedCertificateAlias != null){
779                this.cert = this.keyStore.getCertificate(this.selectedCertificateAlias);
780           
781                System.out.println("Aliases (" + this.keyStore.size() + "): ");
782                if (this.setup.getParameter("debug").equalsIgnoreCase("true")) {
783                    for (Enumeration alias = this.keyStore.aliases(); alias.hasMoreElements();) {
784                        System.out.println(alias.nextElement());
785                    }
786                }
787            }
788
789        } catch (GeneralSecurityException e) {
790            if (this.setup.getParameter("debug").equalsIgnoreCase("true")) {
791                e.printStackTrace();
792            }
793        }
794
795    }
796
797    /**
798     * @return the cert
799     */
800    Certificate getCert() {
801        return this.cert;
802    }
803
804    /**
805     * Get a PEM encoded instance of the user certificate
806     * @return PEM encoded Certificate
807     * @throws CertificateEncodingException
808     */
809    public String getPEMCertificate() throws CertificateEncodingException {
810        return Base64Utils.der2pem(this.cert.getEncoded());
811    }
812
813    /**
814     * @param cert the cert to set
815     */
816    void setCert(Certificate cert) {
817        this.cert = cert;
818    }
819}
Note: See TracBrowser for help on using the repository browser.