1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
|
package ClassesNFEAssinadorA3;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import javax.xml.crypto.dsig.CanonicalizationMethod;
import javax.xml.crypto.dsig.DigestMethod;
import javax.xml.crypto.dsig.Reference;
import javax.xml.crypto.dsig.SignatureMethod;
import javax.xml.crypto.dsig.SignedInfo;
import javax.xml.crypto.dsig.Transform;
import javax.xml.crypto.dsig.XMLSignature;
import javax.xml.crypto.dsig.XMLSignatureFactory;
import javax.xml.crypto.dsig.dom.DOMSignContext;
import javax.xml.crypto.dsig.dom.DOMValidateContext;
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
import javax.xml.crypto.dsig.keyinfo.X509Data;
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
import javax.xml.crypto.dsig.spec.TransformParameterSpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import TelasInicial.TelaInicial;
import ClassesComum.ArrumarNumero;
/**
*
* @author Albert Eije
*/
public class Assinador {
private static PrivateKey privateKey;
private static KeyInfo keyInfo;
private static final String C14N_TRANSFORM_METHOD = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
private static final String PROVIDER_CLASS_NAME = "org.jcp.xml.dsig.internal.dom.XMLDSigRI";
private static final String PROVIDER_NAME = "jsr105Provider";
private static void info(String info) {
System.out.println("| INFO: " + info);
}
private static void loadCertificates(String senha,
XMLSignatureFactory signatureFactory) throws Exception {
/**
* Para Certificados A3 Cartao usar: SmartCard.cfg;
* Para Certificados A3 Token usar: Token.cfg;
*/
Provider provider = new sun.security.pkcs11.SunPKCS11(ConfigService.leitorGemPC_Perto());
Security.addProvider(provider);
KeyStore ks = KeyStore.getInstance("pkcs11", provider);
try {
ks.load(null, senha.toCharArray());
} catch (IOException e) {
throw new Exception("Senha do Certificado Digital incorreta ou Certificado inválido.");
}
KeyStore.PrivateKeyEntry pkEntry = null;
Enumeration<String> aliasesEnum = ks.aliases();
while (aliasesEnum.hasMoreElements()) {
String alias = (String) aliasesEnum.nextElement();
if (ks.isKeyEntry(alias)) {
pkEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(alias,
new KeyStore.PasswordProtection(senha.toCharArray()));
privateKey = pkEntry.getPrivateKey();
break;
}
}
X509Certificate cert = (X509Certificate) pkEntry.getCertificate();
info("SubjectDN: " + cert.getSubjectDN().toString());
KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory();
List<X509Certificate> x509Content = new ArrayList<X509Certificate>();
x509Content.add(cert);
X509Data x509Data = keyInfoFactory.newX509Data(x509Content);
keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data));
}
public void assinar(String arquivoXML,
String password, String arquivoXMLNovo, String operacao) throws Exception {
/*
operacao
'1' - NFE
'2' - CANCELAMENTO
'3' - INUTILIZACAO
*/
String tag = "";
if (operacao.equals("1")) {
tag = "infNFe";
} else if (operacao.equals("2")) {
tag = "infCanc";
} else if (operacao.equals("3")) {
tag = "infInut";
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document docs = builder.parse(new File(arquivoXML));
NodeList elements = docs.getElementsByTagName(tag);
Element el = (Element) elements.item(0);
String id = el.getAttribute("Id");
// Cria um DOM do tipo XMLSignatureFactory que será utilizado
// para gerar a assinatura envelopada (enveloped signature)
String providerName = System.getProperty(PROVIDER_NAME,
PROVIDER_CLASS_NAME);
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM",
(Provider) Class.forName(providerName).newInstance());
// Define os algoritmos de transformação
ArrayList transformList = new ArrayList();
TransformParameterSpec tps = null;
Transform envelopedTransform = fac.newTransform(Transform.ENVELOPED,
tps);
Transform c14NTransform = fac.newTransform(C14N_TRANSFORM_METHOD, tps);
transformList.add(envelopedTransform);
transformList.add(c14NTransform);
// Cria o objeto Reference
Reference ref = fac.newReference("#" + id, fac.newDigestMethod(
DigestMethod.SHA1, null), transformList, null, null);
// Cria o elemento SignedInfo
SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(
CanonicalizationMethod.INCLUSIVE,
(C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
Collections.singletonList(ref));
// Carrega o KeyStore e obtem a chave do certificado
KeyStore ks = KeyStore.getInstance("PKCS11");
ks.load(ConfigService.leitorGemPC_Perto(), password.toCharArray());
Enumeration aliasesEnum = ks.aliases();
String alias = "";
while (aliasesEnum.hasMoreElements()) {
alias = (String) aliasesEnum.nextElement();
if (ks.isKeyEntry(alias)) {
break;
}
}
KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(alias, new KeyStore.PasswordProtection(password.toCharArray()));
// Instancia um certificado do tipo X509
X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
// Cria o elemente KeyInfo contendo a X509Data.
KeyInfoFactory kif = fac.getKeyInfoFactory();
List x509Content = new ArrayList();
x509Content.add(cert);
X509Data xd = kif.newX509Data(x509Content);
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
// Instancia o documento que será assinado
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().parse(
new FileInputStream(arquivoXML));
// Cria o DOMSignContext especificando a chave e o nó pai
DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement());
// Cria a XMLSignature, mas não assina ainda
XMLSignature signature = fac.newXMLSignature(si, ki);
// Empacota (marshal), gera e assina
signature.sign(dsc);
// Arquivo novo assinado
OutputStream os = new FileOutputStream(arquivoXMLNovo);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
trans.transform(new DOMSource(doc), new StreamResult(os));
// Encontra o elemente Signature
NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS,
"Signature");
if (nl.getLength() == 0) {
throw new Exception("Não foi possÃ*vel encontrar o elemente Signature");
}
// Cria um DOMValidateContext
DOMValidateContext valContext = new DOMValidateContext(
new X509KeySelector(ks), nl.item(0));
// Dsempacota (unmarshal) a XMLSignature
XMLSignature signatures = fac.unmarshalXMLSignature(valContext);
// Valida a XMLSignature.
boolean coreValidity = signatures.validate(valContext);
// Checa o status da validação
if (coreValidity == false) {
System.err.println("Falha na Assinatura!");
} else {
System.out.println("Assinatura Correta!");
}
}
static XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");
public static void main(String[] args) throws Exception {
/*if (args.length != 5) {
System.out.println("Passe os cinco parâmetros necessários");
return;
}*/
String caminhoXml = "C:/Users/Murilo/Desktop/MINHA.xml";
//String caminhoCertificado = "C:/Windows/System32/aetpkss1.dll";
String senha = TelaInicial.senhaCert;
String arquivoXmlNovo = "C:/Users/Murilo/Desktop/MINHA_21.xml";
String tipo = "1";
File file = new File(caminhoXml);
if (!file.exists()) {
System.out.println("Arquivo " + caminhoXml + " não encontrado!");
return;
}
// file = new File(caminhoCertificado);
// if (!file.exists()) {
// System.out.println("Arquivo " + caminhoCertificado + " não encontrado!");
// return;
// }
try {
Assinador t = new Assinador();
loadCertificates(senha, signatureFactory);
t.assinar(caminhoXml, senha, arquivoXmlNovo,
tipo);
System.out.println("Arquivo XML assinado com sucesso" + caminhoXml + "!");
} catch (Exception e) {
System.out.println("Erro ao tentar assinar arquivo XML! \n\n" + e.toString());
}
}
public void assinarXML(String nomeDoc, String chave){
/*if (args.length != 5) {
System.out.println("Passe os cinco parâmetros necessários");
return;
}*/
String caminhoXml = "C:/Software MHM/NFESAIDA/"+nomeDoc+".xml";
//String caminhoCertificado = "C:/Windows/System32/aetpkss1.dll";
String senha = TelaInicial.senhaCert;
String arquivoXmlNovo = "C:/Software MHM/NFESAIDA/"+nomeDoc+"ASSINADO.xml";
String tipo = "1";
File file = new File(caminhoXml);
if (!file.exists()) {
System.out.println("Arquivo " + caminhoXml + " não encontrado!");
return;
}
// file = new File(caminhoCertificado);
// if (!file.exists()) {
// System.out.println("Arquivo " + caminhoCertificado + " não encontrado!");
// return;
// }
try {
Assinador t = new Assinador();
loadCertificates(senha, signatureFactory);
t.assinar(caminhoXml, senha, arquivoXmlNovo,
tipo);
//System.out.println("Arquivo XML assinado com sucesso" + caminhoXml + "!");
} catch (Exception e) {
ArrumarNumero aN = new ArrumarNumero();
aN.jOptionPaneError("Erro ao tentar assinar arquivo XML "+nomeDoc+"! \n\n" + e.toString());
}
}
}
package ClassesNFEAssinadorA3;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
public class ConfigService {
private static InputStream defaultConfig(String name, String library)
throws UnsupportedEncodingException {
StringBuilder conf = new StringBuilder();
conf.append("name = ")
.append(name)
.append("\n\r")
.append("library = ")
.append(library)
.append("\n\r")
.append("showInfo = true");
return new ByteArrayInputStream(conf.toString().getBytes("UTF-8"));
}
/**
* Compatível com:
* Cartão SafeWeb - Serasa Experian
* Leitor SCR 3310;
* @return
* @throws UnsupportedEncodingException
*/
public static InputStream leitorSCR3310() throws UnsupportedEncodingException {
return defaultConfig("SafeWeb", "c:/windows/system32/cmp11.dll");
}
/**
* Compatível com:
* eToken Pro - Certisign
* Token Laranja e Azul;
* @return
* @throws UnsupportedEncodingException
*/
public static InputStream tokenAladdin() throws UnsupportedEncodingException {
return defaultConfig("eToken", "c:/windows/system32/eTpkcs11.dll");
}
/**
* Compatível com:
* Cartão Certisign - Leitor GemPC Twin;
* Cartão Serasa - Leitor Perto;
* @return
* @throws UnsupportedEncodingException
*/
public static InputStream leitorGemPC_Perto() throws UnsupportedEncodingException {
// return defaultConfig("SmartCard", "C:/Windows/SysWOW64/aetpkss1.dll");
return defaultConfig("SmartCard", "C:/Windows/System32/aetpkss1.dll");
// "C:/Windows/SysWOW64/aetpkss1.dll"
}
}
package ClassesNFEAssinadorA3;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import javax.xml.crypto.*;
import javax.xml.crypto.dsig.*;
import javax.xml.crypto.dsig.keyinfo.*;
public class X509KeySelector extends KeySelector {
private KeyStore ks;
public X509KeySelector(KeyStore keyStore) throws KeyStoreException {
if (keyStore == null) {
throw new NullPointerException("keyStore is null");
}
this.ks = keyStore;
this.ks.size();
}
public KeySelectorResult select(KeyInfo keyInfo,
KeySelector.Purpose purpose,
AlgorithmMethod method,
XMLCryptoContext context)
throws KeySelectorException {
Iterator ki = keyInfo.getContent().iterator();
while (ki.hasNext()) {
XMLStructure info = (XMLStructure) ki.next();
if (!(info instanceof X509Data)) {
continue;
}
X509Data x509Data = (X509Data) info;
Iterator xi = x509Data.getContent().iterator();
while (xi.hasNext()) {
Object o = xi.next();
if (!(o instanceof X509Certificate)) {
continue;
}
final PublicKey key = ((X509Certificate) o).getPublicKey();
if (algEquals(method.getAlgorithm(), key.getAlgorithm())) {
return new KeySelectorResult() {
public Key getKey() {
return key;
}
};
}
}
}
throw new KeySelectorException("No key found!");
}
static boolean algEquals(String algURI, String algName) {
if ((algName.equalsIgnoreCase("DSA") &&
algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) ||
(algName.equalsIgnoreCase("RSA") &&
algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1))) {
return true;
} else {
return false;
}
}
} |