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