简体   繁体   中英

Digital signature in java

I'm trying signature a xml, but have some problems.

The digital signature always appear in the end of file, I need add it to node father:

X509Certificate cert= (X509Certificate)keyEntry.getCertificate();        
KeyInfoFactory kif = fac.getKeyInfoFactory();
List x509Content = new ArrayList();
x509Content.add(cert.getSubjectX500Principal().getName());
x509Content.add(cert);
X509Data xd = kif.newX509Data(x509Content);
KeyInfo Ki = kif.newKeyInfo(Collections.singletonList(xd));

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);            
Document doc;
doc = dbf.newDocumentBuilder().parse(new FileInputStream("E:\\HFACHO\\JAVA\\Netbean\\filejavaws.xml"));
DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(),doc.getDocumentElement());
// ad namespace
dsc.setDefaultNamespacePrefix("ds");          
XMLSignature signature = fac.newXMLSignature(si, Ki);        
signature.sign(dsc);                         


//create output file
OutputStream os = new FileOutputStream("E:\\HFACHO\\JAVA\\Netbean\\filejavaws_Firmado.xml");
TransformerFactory tf=  TransformerFactory.newInstance();
javax.xml.transform.Transformer trans = tf.newTransformer();
trans.transform(new DOMSource(doc), new StreamResult(os)); 

Well my approach, may not be very conventional, but it would be to take the signature node from the result and build a new xml with the signature node at the top

UPDATE based on your comment:

Well you have to decide if you are going to keep the signature where its generated and expected or if you want in at the beginning of the document.

The later approach could work if you are also responsible of the code that verifies your customs-process signature

http://www.w3.org/TR/xmldsig-core/#sec-o-Simple

解决方案很简单:

dsc.setParent();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM