Bonjour,
j'ai trouvé ce code qui signe la totalité d'un fichier xml,
je vais savoir comment peut'on procéder pour signer une portion de cet fichier?, c'est à dire des champs exactes. (pas la totalité du fichier).


et merci d'avance.





Code : Sélectionner tout - Visualiser dans une fenêtre à part
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
 
 
//les APIs necessaire
import java.io.*;
import java.util.*;
 
import java.security.*;
import java.security.cert.*;
 
import org.w3c.dom.*;
import org.xml.sax.*;
 
import javax.xml.crypto.*;
import javax.xml.crypto.dsig.*;
import javax.xml.crypto.dsig.dom.*;
import javax.xml.crypto.dsig.keyinfo.*;
import javax.xml.crypto.dsig.spec.*;
import javax.xml.crypto.dsig.*;
 
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
 
 
public class Main3{
 
    public static void main(String args[]) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyStoreException, SAXException, GeneralSecurityException, TransformerException
    {
        Object dom;
        //initiliser les parametres
    XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM");
    DigestMethod sha1 = factory.newDigestMethod(DigestMethod.SHA1, null);
    CanonicalizationMethod inclusive = factory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null);
    SignatureMethod rsasha1 = factory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
    Transform enveloped = factory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
    List transforms = Collections.singletonList(enveloped);
    Reference ref = factory.newReference("",sha1);
    List references = Collections.singletonList(ref);
    SignedInfo signer = factory.newSignedInfo(inclusive, rsasha1, references);
    char[] password = "2[$0wUOS".toCharArray();
    KeyStore store = KeyStore.getInstance("PKCS12");
        try {
            //lire le fichier de certificat
            InputStream keys = new FileInputStream("personnal_nyal.p12");
            try {
                //charger la boutique 
                store.load(keys, password);
                System.out.println("Certificat chargé avec succés");
 
            } catch (NoSuchAlgorithmException ex) {
                //ex.printStackTrace();
                 System.out.println("Pas d'algorthme ds le certificat");
            } catch (CertificateException ex) {
                //ex.printStackTrace();
                System.out.println("Mot de passe incorrect du certificat");
            } catch (IOException ex) {
               // ex.printStackTrace();
                 System.out.println("Erreur ds la lecture du certificat");
            }
        } catch (FileNotFoundException ex) {
           // ex.printStackTrace();
                System.out.println("fichier spécifié est introuvable");
        }
 
        try {
               List certs = new ArrayList(); 
               String alias=getCertificateAliases(store);
               KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry)store.getEntry(alias, new KeyStore.PasswordProtection(password));
               X509Certificate cert = (X509Certificate) entry.getCertificate();
               certs.add(cert.getSubjectX500Principal().getName());
               certs.add(cert);  
               System.out.println("Clé privée recupérée avc succès"); 
               System.out.println("X509 opération terminée");
               KeyInfoFactory keyFactory = factory.getKeyInfoFactory();    
               //cahrger les donnees du certificat
               X509Data data = keyFactory.newX509Data(certs);
               List dataList = Collections.singletonList(data);
               KeyInfo key = keyFactory.newKeyInfo(dataList);
               ////////charger le fichier Xml
               DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
               DocumentBuilder db;
 
            try {
                db = dbf.newDocumentBuilder();
                try {
                    //charger le fichier xml à signer
                    Document doc=db.parse("personnes.xml");
                    Node node=doc.getFirstChild();
                    Object nabil =db.getSchema() ;
                   // Node node2=doc.appendChild(doc);
                    //creer le context de la signature
                    DOMSignContext context = new DOMSignContext(entry.getPrivateKey(),node);
                    XMLSignature signature = factory.newXMLSignature(signer, key);
                    try {
                        signature.sign(context);  
                         TransformerFactory tf = TransformerFactory.newInstance();
                         Transformer trans = tf.newTransformer();
                         trans.transform(new DOMSource(doc),new StreamResult(new FileOutputStream("mySignedFile.xml")));
                         System.out.println(""+doc.getDocumentURI()+ "           bien signé");
 
                    } catch (MarshalException ex) {                      
                        System.out.println("Erreur ds la signature (Marshal)");
                    } catch (XMLSignatureException ex) {   
                        System.out.println("Erreur ds la signature");
 
                    }  
                    try {
                        signature.sign(context);
                    } catch (XMLSignatureException ex) {
                        ex.printStackTrace();
                    } catch (MarshalException ex) {
                        ex.printStackTrace();
                    }
                } catch (IOException ex) {
                    //ex.printStackTrace();
                    System.out.println("Fichier XMl pas trouvée");
                } catch (SAXException ex) {
                    //ex.printStackTrace();
                    System.out.println("Erreur ds le parseur XML");
                }
            } catch (ParserConfigurationException ex) {
                ex.printStackTrace();
            }                     
        } catch (UnrecoverableEntryException ex) {
            ex.printStackTrace();
        } catch (KeyStoreException ex) {
            ex.printStackTrace();
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        } 
    }
 
    public static String getCertificateAliases(KeyStore akeyStore) throws GeneralSecurityException
    {
          Enumeration aliasesEnum = akeyStore.aliases();
             List certs = new ArrayList();
            while(aliasesEnum.hasMoreElements())
            {
               String alias = (String)aliasesEnum.nextElement(); 
              return alias;
            }
             return null;//retourne null si aucun aléas n'a été trouvé
    }    
}