Changeset 5898 for branches/2.3/security/ExpressoCert/src/br
- Timestamp:
- 04/09/12 15:21:57 (12 years ago)
- Location:
- branches/2.3/security/ExpressoCert/src/br/gov/serpro/cert
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/2.3/security/ExpressoCert/src/br/gov/serpro/cert/DigitalCertificate.java
r5386 r5898 65 65 import java.security.AlgorithmParameters; 66 66 import java.security.cert.CertificateEncodingException; 67 import java.text.DateFormat; 67 68 import java.util.HashMap; 69 import java.util.Locale; 68 70 import java.util.regex.Matcher; 69 71 import java.util.regex.Pattern; … … 109 111 // caso seja necessário. 110 112 private int keystoreStatus; 113 private static boolean useMSCapi = false; 111 114 public static final int KEYSTORE_DETECTED = 0; 112 115 public static final int KEYSTORE_NOT_DETECTED = 1; … … 133 136 HOME_SUBDIR = "\\dados de aplicativos\\sun\\java\\deployment\\security"; 134 137 EPASS_2000 = System.getenv("SystemRoot") + "\\system32\\ngp11v211.dll"; 135 //EPASS_2000 = System.getenv("ProgramFiles")+"\\Gemplus\\GemSafe Libraries\\BIN\\gclib.dll";138 DigitalCertificate.useMSCapi = true; 136 139 } 137 140 … … 201 204 } 202 205 206 public static boolean isUseMSCapi() { 207 return useMSCapi; 208 } 209 203 210 public KeyStore getKeyStore() { 204 211 return keyStore; … … 219 226 public void destroy() { 220 227 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; 245 251 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; 250 255 } 251 256 … … 262 267 public int init() { 263 268 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 } 266 272 267 273 Provider[] providers = Security.getProviders(); … … 272 278 } 273 279 274 int interfaceType = DigitalCertificate.KEYSTORE_ DETECTED;280 int interfaceType = DigitalCertificate.KEYSTORE_NOT_DETECTED; 275 281 276 282 try { … … 312 318 try { 313 319 // 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")) { 315 322 keyStore.load(null, null); 316 323 } else { … … 319 326 320 327 // 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 ; 322 329 323 330 } catch (ProviderException e) { … … 402 409 while (headers.hasMoreElements()){ 403 410 String header = (String) headers.nextElement(); 404 System.out.println("header: "+header);405 411 headersString += header+"\r\n"; 406 412 } … … 455 461 public String signMail(Map<String, String> data) throws IOException, GeneralSecurityException, SMIMEException, MessagingException { 456 462 457 463 Key privateKey = null; 458 464 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 { 463 472 return null; 464 473 } 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 469 494 } /* 470 495 else if (this.keystoreStatus == DigitalCertificate.KEYSTORE_ALREADY_LOADED){ … … 671 696 Key privateKey = null; 672 697 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 683 715 } /* 684 716 else if (this.keystoreStatus == DigitalCertificate.KEYSTORE_ALREADY_LOADED){ … … 847 879 if (Integer.parseInt(resposta[0].trim()) == 0) { 848 880 // Se código da resposta for zero, decripta a senha criptografada do usuário 849 resposta[2] = decr iptPassword(resposta[2].trim(), pin);881 resposta[2] = decryptPassword(resposta[2].trim(), pin); 850 882 } 851 883 } … … 875 907 * @throws GeneralSecurityException se algum problema ocorrer na decriptação da senha. 876 908 */ 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); 883 919 884 920 // 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); 887 925 888 926 // Decodifica a senha em base64 e a decripta 889 890 927 decodedPassword = new String(dcipher.doFinal(Base64Utils.base64Decode(encodedPassword))); 928 891 929 return decodedPassword.trim(); 892 930 … … 902 940 903 941 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 } 909 960 } 910 961 catch (GeneralSecurityException kex){ … … 921 972 } 922 973 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 923 1027 /** 924 1028 * Abre a keystore passando o pin 925 1029 * @param pin pin para acessar o Token 926 1030 */ 1031 @SuppressWarnings("empty-statement") 927 1032 public void openKeyStore(char[] pin) throws IOException { 928 1033 // TODO: Verify if object DigitalCertificate was initiated … … 931 1036 if (this.keyStore.getType().equals("PKCS11")) { 932 1037 this.keyStore.load(null, pin); 933 } else { 1038 } else if (this.keyStore.getType().equals("Windows-MY")) { 1039 this.keyStore.load(null, null); 1040 } else { 934 1041 this.keyStore.load(this.pkcs12Input, pin); 935 1042 } 936 1043 937 Map<String, String> aliases = new HashMap<String, String>();938 for (Token token : tokens.getRegisteredTokens()){939 aliases.putAll(token.getAliases());940 }941 942 1044 // 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()); 944 1047 if (this.selectedCertificateAlias != null){ 945 1048 this.cert = this.keyStore.getCertificate(this.selectedCertificateAlias); -
branches/2.3/security/ExpressoCert/src/br/gov/serpro/cert/Token.java
r5179 r5898 13 13 import java.security.ProviderException; 14 14 import java.security.Security; 15 import java.security.cert.CertificateFactory;16 import java.util.logging.Level;17 import java.util.logging.Logger;18 import java.security.cert.X509Certificate;19 import java.text.DateFormat;20 import java.util.HashMap;21 import java.util.Locale;22 import java.util.Map;23 import sun.security.pkcs11.wrapper.CK_ATTRIBUTE;24 import sun.security.pkcs11.wrapper.CK_C_INITIALIZE_ARGS;25 import sun.security.pkcs11.wrapper.Functions;26 import sun.security.pkcs11.wrapper.PKCS11;27 import sun.security.pkcs11.wrapper.PKCS11Exception;28 import static sun.security.pkcs11.wrapper.PKCS11Constants.*;29 15 30 16 //TODO: Deal with wildcards for environments variables. … … 111 97 } 112 98 113 Map<String, String> getAliases() throws IOException{114 115 if (setup.getParameter("debug").equalsIgnoreCase("true")) {116 System.out.println("Getting Aliases");117 }118 119 Map<String, String> aliases = new HashMap<String, String>();120 121 CK_C_INITIALIZE_ARGS initArgs = new CK_C_INITIALIZE_ARGS();122 String functionList = "C_GetFunctionList";123 124 initArgs.flags = CKF_OS_LOCKING_OK;125 126 PKCS11 tmpPKCS11 = null;127 try {128 try {129 tmpPKCS11 = PKCS11.getInstance(libraryPath, functionList, initArgs, false);130 } catch (IOException ex) {131 if (setup.getParameter("debug").equalsIgnoreCase("true")) {132 Logger.getLogger(TokenCollection.class.getName()).log(Level.SEVERE, null, ex);133 }134 throw ex;135 }136 } catch (PKCS11Exception e) {137 try {138 initArgs = null;139 tmpPKCS11 = PKCS11.getInstance(libraryPath, functionList, initArgs, true);140 } catch (IOException ex) {141 if (setup.getParameter("debug").equalsIgnoreCase("true")) {142 Logger.getLogger(TokenCollection.class.getName()).log(Level.SEVERE, null, ex);143 }144 } catch (PKCS11Exception ex) {145 if (setup.getParameter("debug").equalsIgnoreCase("true")) {146 Logger.getLogger(TokenCollection.class.getName()).log(Level.SEVERE, null, ex);147 }148 }149 }150 151 try {152 // cria sessão pública rw. com flag CKF_SERIAL_SESSION153 long session = tmpPKCS11.C_OpenSession(this.slot, CKF_SERIAL_SESSION, null, null);154 155 if (setup.getParameter("debug").equalsIgnoreCase("true")) {156 System.out.println("session number: "+session);157 }158 159 // TODO: Verifica se está logado, senão loga usuário. Pede pin? ou recebe pin?160 161 CK_ATTRIBUTE[] TEMPLATE_CERTIFICATE = {new CK_ATTRIBUTE(CKA_CLASS, CKO_CERTIFICATE)};162 CK_ATTRIBUTE[] TEMPLATE_PKEY = {new CK_ATTRIBUTE(CKA_CLASS, CKO_PRIVATE_KEY)};163 CK_ATTRIBUTE[] TEMPLATE_KEY_LABEL_ID = {new CK_ATTRIBUTE(CKA_LABEL), new CK_ATTRIBUTE(CKA_ID)};164 CK_ATTRIBUTE[] TEMPLATE_CERT_LABEL_ID = {165 new CK_ATTRIBUTE(CKA_LABEL),166 new CK_ATTRIBUTE(CKA_ID),167 new CK_ATTRIBUTE(CKA_VALUE)168 };169 170 tmpPKCS11.C_FindObjectsInit(session, TEMPLATE_CERTIFICATE);171 long[] certs = tmpPKCS11.C_FindObjects(session, 20);172 173 tmpPKCS11.C_FindObjectsFinal(session);174 175 tmpPKCS11.C_FindObjectsInit(session, TEMPLATE_PKEY);176 long[] keys = tmpPKCS11.C_FindObjects(session, 20);177 178 if (setup.getParameter("debug").equalsIgnoreCase("true")) {179 System.out.println("Private Keys: "+keys.length);180 }181 182 for (long key : keys){183 tmpPKCS11.C_GetAttributeValue(session, key, TEMPLATE_KEY_LABEL_ID);184 185 if (setup.getParameter("debug").equalsIgnoreCase("true")) {186 System.out.print("Private key ID: ");187 for (byte b : (byte [])TEMPLATE_KEY_LABEL_ID[1].pValue){188 System.out.print(b);189 }190 System.out.println();191 if (TEMPLATE_KEY_LABEL_ID[0].pValue != null)192 {193 System.out.println("Private key LABEL: "+new String((char [])TEMPLATE_KEY_LABEL_ID[0].pValue));194 }195 }196 197 if (setup.getParameter("debug").equalsIgnoreCase("true")) {198 System.out.println("Certs:");199 }200 201 for (long cert : certs){202 tmpPKCS11.C_GetAttributeValue(session, cert, TEMPLATE_CERT_LABEL_ID);203 204 if (Functions.equals((byte [])TEMPLATE_KEY_LABEL_ID[1].pValue,205 (byte [])TEMPLATE_CERT_LABEL_ID[1].pValue)){206 if (TEMPLATE_CERT_LABEL_ID[0].pValue != null)207 {208 if (setup.getParameter("debug").equalsIgnoreCase("true")) {209 System.out.println("Certificate LABEL: "+new String((char [])TEMPLATE_CERT_LABEL_ID[0].pValue));210 }211 ByteArrayInputStream in = new ByteArrayInputStream((byte [])TEMPLATE_CERT_LABEL_ID[2].pValue);212 CertificateFactory cf = CertificateFactory.getInstance("X.509");213 X509Certificate certObj = (X509Certificate)cf.generateCertificate(in);214 if (certObj.getBasicConstraints() == -1 ){215 216 StringBuilder selector = new StringBuilder();217 // get more info to generate the value218 // Subject's CN / Issuer's CN / Expiration Data219 String subject = certObj.getSubjectX500Principal().getName();220 int pInicial = subject.indexOf('=')+1;221 int pFinal = subject.indexOf(',', pInicial);222 selector.append(subject.substring(pInicial, pFinal)+" | ");223 224 String issuer = certObj.getIssuerX500Principal().getName();225 pInicial = issuer.indexOf('=')+1;226 pFinal = issuer.indexOf(',', pInicial);227 selector.append(issuer.substring(pInicial, pFinal)+" | ");228 229 Locale locale = new Locale("pt", "BR");230 DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);231 selector.append(df.format(certObj.getNotAfter())+" | ");232 233 selector.append("("+certObj.getSerialNumber()+")");234 235 aliases.put(new String((char [])TEMPLATE_CERT_LABEL_ID[0].pValue),236 selector.toString());237 }238 }239 }240 241 }242 if (setup.getParameter("debug").equalsIgnoreCase("true")) {243 System.out.println();244 }245 }246 247 tmpPKCS11.C_CloseSession(session);248 249 } catch (PKCS11Exception ex) {250 if (setup.getParameter("debug").equalsIgnoreCase("true")) {251 Logger.getLogger(TokenCollection.class.getName()).log(Level.SEVERE, null, ex);252 }253 } catch (Throwable t) {254 if (setup.getParameter("debug").equalsIgnoreCase("true")) {255 Logger.getLogger(TokenCollection.class.getName()).log(Level.SEVERE, null, t);256 }257 }258 259 return aliases;260 261 }262 263 99 public boolean libraryExists(){ 264 100
Note: See TracChangeset
for help on using the changeset viewer.