Ignore:
Timestamp:
04/09/12 15:21:57 (12 years ago)
Author:
rafaelraymundo
Message:

Ticket #2256 - Problemas com o token iKey 2032 / 4000.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • branches/2.3/security/ExpressoCert/src/br/gov/serpro/cert/DigitalCertificate.java

    r5386 r5898  
    6565import java.security.AlgorithmParameters; 
    6666import java.security.cert.CertificateEncodingException; 
     67import java.text.DateFormat; 
    6768import java.util.HashMap; 
     69import java.util.Locale; 
    6870import java.util.regex.Matcher; 
    6971import java.util.regex.Pattern; 
     
    109111    // caso seja necessário. 
    110112    private int keystoreStatus; 
     113    private static boolean useMSCapi = false; 
    111114    public static final int KEYSTORE_DETECTED = 0; 
    112115    public static final int KEYSTORE_NOT_DETECTED = 1; 
     
    133136            HOME_SUBDIR = "\\dados de aplicativos\\sun\\java\\deployment\\security"; 
    134137            EPASS_2000 = System.getenv("SystemRoot") + "\\system32\\ngp11v211.dll"; 
    135             //EPASS_2000 = System.getenv("ProgramFiles")+"\\Gemplus\\GemSafe Libraries\\BIN\\gclib.dll"; 
     138            DigitalCertificate.useMSCapi = true; 
    136139        } 
    137140 
     
    201204    } 
    202205 
     206    public static boolean isUseMSCapi() { 
     207        return useMSCapi; 
     208    } 
     209 
    203210    public KeyStore getKeyStore() { 
    204211        return keyStore; 
     
    219226    public void destroy() { 
    220227 
    221         AuthProvider ap = null; 
    222  
    223         if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 
    224             System.out.println("logout no provider"); 
    225         } 
    226         if (keyStore != null) { 
    227             ap = (AuthProvider) this.keyStore.getProvider(); 
    228         } 
    229  
    230         if (ap != null) { 
    231             try { 
    232                 ap.logout(); 
    233             } catch (LoginException e) { 
    234                 if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 
    235                     e.printStackTrace(); 
    236                 } 
    237             } 
    238         } 
    239  
    240         if (providerName != null) { 
    241             Security.removeProvider(providerName); 
    242         } 
    243  
    244         this.cert = null; 
     228        AuthProvider ap = null; 
     229 
     230        if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 
     231            System.out.println("logout no provider"); 
     232        } 
     233         
     234        if (this.keyStore != null && this.keyStore.getProvider() instanceof AuthProvider) { 
     235            ap = (AuthProvider) this.keyStore.getProvider(); 
     236         
     237            try { 
     238                ap.logout(); 
     239            } catch (LoginException e) { 
     240                if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 
     241                    e.printStackTrace(); 
     242                } 
     243            } 
     244 
     245            if (this.providerName != null) { 
     246                Security.removeProvider(providerName); 
     247            } 
     248        } 
     249         
     250        this.cert = null; 
    245251        this.selectedCertificateAlias = null; 
    246         this.keyStore = null; 
    247         this.pkcs12Input = null; 
    248         this.providerName = null; 
    249  
     252        this.keyStore = null; 
     253        this.pkcs12Input = null; 
     254        this.providerName = null; 
    250255    } 
    251256 
     
    262267    public int init() { 
    263268 
    264         // TODO: Usar dentro de um "loop" para testar outros modelos de tokens. 
    265         this.tokens = new TokenCollection(setup); 
     269        if (!DigitalCertificate.useMSCapi){ 
     270            this.tokens = new TokenCollection(setup); 
     271        } 
    266272 
    267273        Provider[] providers = Security.getProviders(); 
     
    272278        } 
    273279 
    274         int interfaceType = DigitalCertificate.KEYSTORE_DETECTED; 
     280        int interfaceType = DigitalCertificate.KEYSTORE_NOT_DETECTED; 
    275281 
    276282        try { 
     
    312318            try { 
    313319                // Testa se uma keystore já foi carregada previamente 
    314                 if (keyStore.getType().equalsIgnoreCase("pkcs11")) { 
     320                if (keyStore.getType().equalsIgnoreCase("pkcs11")  
     321                        || keyStore.getType().equalsIgnoreCase("windows-my")) { 
    315322                    keyStore.load(null, null); 
    316323                } else { 
     
    319326 
    320327                // Se chegou aqui KeyStore está liberada, mostrar tela de login sem pedir o pin. 
    321                 this.keystoreStatus = DigitalCertificate.KEYSTORE_ALREADY_LOADED; 
     328                this.keystoreStatus = DigitalCertificate.useMSCapi ? DigitalCertificate.KEYSTORE_DETECTED : DigitalCertificate.KEYSTORE_ALREADY_LOADED ; 
    322329 
    323330            } catch (ProviderException e) { 
     
    402409                        while (headers.hasMoreElements()){ 
    403410                            String header = (String) headers.nextElement(); 
    404                             System.out.println("header: "+header); 
    405411                            headersString += header+"\r\n"; 
    406412                        } 
     
    455461    public String signMail(Map<String, String> data) throws IOException, GeneralSecurityException, SMIMEException, MessagingException { 
    456462 
    457         Key privateKey = null; 
     463        Key privateKey = null; 
    458464        if (this.keystoreStatus == DigitalCertificate.KEYSTORE_DETECTED) { 
    459             String pin = DialogBuilder.showPinDialog(this.parentFrame, this.setup); 
    460             if (pin != null) { 
    461                 openKeyStore(pin.toCharArray()); 
    462                 if (this.selectedCertificateAlias == null){ 
     465            char[] pin = null; 
     466            if (!DigitalCertificate.useMSCapi) { 
     467                String sPin = DialogBuilder.showPinDialog(this.parentFrame, this.setup); 
     468                if (sPin != null) { 
     469                    pin = sPin.toCharArray(); 
     470                } 
     471                else { 
    463472                    return null; 
    464473                } 
    465                 privateKey = this.keyStore.getKey(this.selectedCertificateAlias, pin.toCharArray()); 
    466             } else { 
    467                 return null; 
    468             } 
     474            } 
     475 
     476            try { 
     477                openKeyStore(pin); 
     478            } 
     479            catch (Exception e) 
     480            { 
     481                if (e instanceof IOException){ 
     482                    throw new IOException(e); 
     483                } 
     484                else if (e instanceof GeneralSecurityException){ 
     485                    throw new GeneralSecurityException(e); 
     486                } 
     487            } 
     488             
     489            if (this.selectedCertificateAlias == null){ 
     490                return null; 
     491            } 
     492            privateKey = this.keyStore.getKey(this.selectedCertificateAlias, pin); 
     493             
    469494        } /* 
    470495        else if (this.keystoreStatus == DigitalCertificate.KEYSTORE_ALREADY_LOADED){ 
     
    671696        Key privateKey = null; 
    672697        if (this.keystoreStatus == DigitalCertificate.KEYSTORE_DETECTED) { 
    673             String pin = DialogBuilder.showPinDialog(this.parentFrame, this.setup); 
    674             if (pin != null) { 
    675                 openKeyStore(pin.toCharArray()); 
    676                 if (this.selectedCertificateAlias == null){ 
    677                     return null; 
    678                 } 
    679                 privateKey = this.keyStore.getKey(this.selectedCertificateAlias, pin.toCharArray()); 
    680             } else { 
    681                 return null; 
    682             } 
     698            char[] pin = null; 
     699            if (!DigitalCertificate.useMSCapi) { 
     700               String sPin = DialogBuilder.showPinDialog(this.parentFrame, this.setup); 
     701               if (sPin != null) { 
     702                   pin = sPin.toCharArray(); 
     703               } 
     704               else { 
     705                   return null; 
     706               } 
     707            } 
     708 
     709            openKeyStore(pin); 
     710            if (this.selectedCertificateAlias == null){ 
     711                return null; 
     712            } 
     713            privateKey = this.keyStore.getKey(this.selectedCertificateAlias, pin); 
     714             
    683715        } /* 
    684716        else if (this.keystoreStatus == DigitalCertificate.KEYSTORE_ALREADY_LOADED){ 
     
    847879                if (Integer.parseInt(resposta[0].trim()) == 0) { 
    848880                    // Se código da resposta for zero, decripta a senha criptografada do usuário 
    849                     resposta[2] = decriptPassword(resposta[2].trim(), pin); 
     881                    resposta[2] = decryptPassword(resposta[2].trim(), pin); 
    850882                } 
    851883            } 
     
    875907     * @throws GeneralSecurityException se algum problema ocorrer na decriptação da senha. 
    876908     */ 
    877     public String decriptPassword(String encodedPassword, String pin) throws GeneralSecurityException { 
    878  
    879         String decodedPassword = new String(); 
    880  
    881         // Pega a chave privada do primeiro certificado armazenado na KeyStore 
    882         Key privateKey = this.keyStore.getKey(selectedCertificateAlias, pin.toCharArray()); 
     909    public String decryptPassword(String encodedPassword, String pin) throws GeneralSecurityException, IOException { 
     910 
     911        String decodedPassword = new String(); 
     912 
     913        // Pega a chave privada do primeiro certificado armazenado na KeyStore 
     914        Key privateKey = pin == null ? this.keyStore.getKey(selectedCertificateAlias, null) : 
     915            this.keyStore.getKey(selectedCertificateAlias, pin.toCharArray()); 
     916 
     917        Cipher dcipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); 
     918        dcipher.init(Cipher.DECRYPT_MODE, privateKey); 
    883919 
    884920        // Inicializa os cipher com os parâmetros corretos para realizar a decriptação 
    885         Cipher dcipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); 
    886         dcipher.init(Cipher.DECRYPT_MODE, privateKey); 
     921//      Cipher dcipher = DigitalCertificate.useMSCapi ? 
     922//            Cipher.getInstance("RSA/ECB/PKCS1Padding", Security.getProvider(this.providerName)) 
     923//            : Cipher.getInstance("RSA/ECB/PKCS1Padding"); 
     924//      dcipher.init(Cipher.DECRYPT_MODE, privateKey); 
    887925 
    888926        // Decodifica a senha em base64 e a decripta 
    889         decodedPassword = new String(dcipher.doFinal(Base64Utils.base64Decode(encodedPassword))); 
    890  
     927        decodedPassword = new String(dcipher.doFinal(Base64Utils.base64Decode(encodedPassword))); 
     928        
    891929        return decodedPassword.trim(); 
    892930 
     
    902940 
    903941        try{ 
    904             if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 
    905                 System.out.println("Carregando provider: PKCS11"); 
    906             } 
    907             this.keyStore = KeyStore.getInstance("PKCS11"); 
    908             this.providerName = keyStore.getProvider().getName(); 
     942            if (!DigitalCertificate.useMSCapi) { 
     943                if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 
     944                    System.out.println("Carregando provider: PKCS11"); 
     945                } 
     946                this.keyStore = KeyStore.getInstance("PKCS11"); 
     947                this.providerName = keyStore.getProvider().getName(); 
     948            } 
     949            else { 
     950                if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 
     951                    System.out.println("Carregando provider: SunMSCAPI"); 
     952                } 
     953                this.keyStore = KeyStore.getInstance("Windows-MY", "SunMSCAPI"); 
     954                this.providerName = this.keyStore.getProvider().getName(); 
     955 
     956                if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 
     957                    System.out.println(keyStore.getProvider().getName() +" carregado!"); 
     958                } 
     959            } 
    909960        } 
    910961        catch (GeneralSecurityException kex){ 
     
    921972    } 
    922973 
     974    Map<String, String> getAliasesList() throws IOException, KeyStoreException{ 
     975 
     976        if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
     977            System.out.println("Getting Aliases"); 
     978        } 
     979 
     980        Map<String, String> aliases = new HashMap<String, String>(); 
     981       
     982        for (Enumeration<String> al = this.keyStore.aliases(); al.hasMoreElements();){ 
     983            String alias = al.nextElement(); 
     984            X509Certificate certObj = (X509Certificate) this.keyStore.getCertificate(alias); 
     985             
     986            StringBuilder selector = new StringBuilder(); 
     987            // get more info to generate the value 
     988            // Subject's CN / Issuer's CN / Expiration Data 
     989            String subject = certObj.getSubjectX500Principal().getName(); 
     990            int pInicial = subject.indexOf('=')+1; 
     991            int pFinal = subject.indexOf(',', pInicial); 
     992            selector.append(subject.substring(pInicial, pFinal)+" | "); 
     993 
     994            String issuer = certObj.getIssuerX500Principal().getName(); 
     995            pInicial = issuer.indexOf('=')+1; 
     996            pFinal = issuer.indexOf(',', pInicial); 
     997            selector.append(issuer.substring(pInicial, pFinal)+" | "); 
     998 
     999            // TODO: get the system locale 
     1000            Locale locale = new Locale("pt", "BR"); 
     1001            DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale); 
     1002            selector.append(df.format(certObj.getNotAfter())+" | "); 
     1003 
     1004            selector.append("("+certObj.getSerialNumber()+")"); 
     1005 
     1006            aliases.put(alias, selector.toString()); 
     1007             
     1008        } 
     1009 
     1010        return aliases; 
     1011    } 
     1012 
     1013//    public void removeCertificate() throws IOException { 
     1014//        Token token = tokens.getRegisteredTokens().iterator().next(); 
     1015//        token.removeCertificate(); 
     1016//    } 
     1017// 
     1018//    public void writeCerts(char[] pin, LinkedHashMap<char[], Certificate> certs) throws IOException{ 
     1019//        Token token = tokens.getRegisteredTokens().iterator().next(); 
     1020//        token.getAliases(); 
     1021// 
     1022//        for (Map.Entry<char[], Certificate> entry : certs.entrySet()) { 
     1023//            token.writeCert(pin, entry.getKey(), entry.getValue()); 
     1024//        } 
     1025//    } 
     1026 
    9231027    /** 
    9241028     *  Abre a keystore passando o pin 
    9251029     *  @param pin pin para acessar o Token 
    9261030     */ 
     1031    @SuppressWarnings("empty-statement") 
    9271032    public void openKeyStore(char[] pin) throws IOException { 
    9281033        // TODO:  Verify if object DigitalCertificate was initiated 
     
    9311036            if (this.keyStore.getType().equals("PKCS11")) { 
    9321037                this.keyStore.load(null, pin); 
    933             } else { 
     1038            } else if (this.keyStore.getType().equals("Windows-MY")) { 
     1039                this.keyStore.load(null, null); 
     1040            } else { 
    9341041                this.keyStore.load(this.pkcs12Input, pin); 
    9351042            } 
    9361043 
    937             Map<String, String> aliases = new HashMap<String, String>(); 
    938             for (Token token : tokens.getRegisteredTokens()){ 
    939                 aliases.putAll(token.getAliases()); 
    940             } 
    941  
    9421044            // selecionador de certificado 
    943             this.selectedCertificateAlias = DialogBuilder.showCertificateSelector(this.parentFrame, this.setup, aliases); 
     1045            this.selectedCertificateAlias = DialogBuilder.showCertificateSelector(this.parentFrame, 
     1046                    this.setup, this.getAliasesList()); 
    9441047            if (this.selectedCertificateAlias != null){ 
    9451048                this.cert = this.keyStore.getCertificate(this.selectedCertificateAlias); 
Note: See TracChangeset for help on using the changeset viewer.