1/*
2 * reserved comment block
3 * DO NOT REMOVE OR ALTER!
4 */
5/**
6 * Licensed to the Apache Software Foundation (ASF) under one
7 * or more contributor license agreements. See the NOTICE file
8 * distributed with this work for additional information
9 * regarding copyright ownership. The ASF licenses this file
10 * to you under the Apache License, Version 2.0 (the
11 * "License"); you may not use this file except in compliance
12 * with the License. You may obtain a copy of the License at
13 *
14 * http://www.apache.org/licenses/LICENSE-2.0
15 *
16 * Unless required by applicable law or agreed to in writing,
17 * software distributed under the License is distributed on an
18 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
19 * KIND, either express or implied. See the License for the
20 * specific language governing permissions and limitations
21 * under the License.
22 */
23/*
24 * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
25 */
26/*
27 * $Id: DOMX509Data.java 1333415 2012-05-03 12:03:51Z coheigea $
28 */
29package org.jcp.xml.dsig.internal.dom;
30
31import java.io.ByteArrayInputStream;
32import java.security.cert.*;
33import java.util.*;
34import javax.xml.crypto.*;
35import javax.xml.crypto.dom.DOMCryptoContext;
36import javax.xml.crypto.dsig.*;
37import javax.xml.crypto.dsig.keyinfo.X509IssuerSerial;
38import javax.xml.crypto.dsig.keyinfo.X509Data;
39import javax.security.auth.x500.X500Principal;
40import org.w3c.dom.Document;
41import org.w3c.dom.Element;
42import org.w3c.dom.Node;
43import org.w3c.dom.NodeList;
44
45import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
46import com.sun.org.apache.xml.internal.security.utils.Base64;
47
48/**
49 * DOM-based implementation of X509Data.
50 *
51 * @author Sean Mullan
52 */
53//@@@ check for illegal combinations of data violating MUSTs in W3c spec
54public final class DOMX509Data extends DOMStructure implements X509Data {
55
56    private final List<Object> content;
57    private CertificateFactory cf;
58
59    /**
60     * Creates a DOMX509Data.
61     *
62     * @param content a list of one or more X.509 data types. Valid types are
63     *    {@link String} (subject names), <code>byte[]</code> (subject key ids),
64     *    {@link java.security.cert.X509Certificate}, {@link X509CRL},
65     *    or {@link javax.xml.dsig.XMLStructure} ({@link X509IssuerSerial}
66     *    objects or elements from an external namespace). The list is
67     *    defensively copied to protect against subsequent modification.
68     * @throws NullPointerException if <code>content</code> is <code>null</code>
69     * @throws IllegalArgumentException if <code>content</code> is empty
70     * @throws ClassCastException if <code>content</code> contains any entries
71     *    that are not of one of the valid types mentioned above
72     */
73    public DOMX509Data(List<?> content) {
74        if (content == null) {
75            throw new NullPointerException("content cannot be null");
76        }
77        List<Object> contentCopy = new ArrayList<Object>(content);
78        if (contentCopy.isEmpty()) {
79            throw new IllegalArgumentException("content cannot be empty");
80        }
81        for (int i = 0, size = contentCopy.size(); i < size; i++) {
82            Object x509Type = contentCopy.get(i);
83            if (x509Type instanceof String) {
84                new X500Principal((String)x509Type);
85            } else if (!(x509Type instanceof byte[]) &&
86                !(x509Type instanceof X509Certificate) &&
87                !(x509Type instanceof X509CRL) &&
88                !(x509Type instanceof XMLStructure)) {
89                throw new ClassCastException
90                    ("content["+i+"] is not a valid X509Data type");
91            }
92        }
93        this.content = Collections.unmodifiableList(contentCopy);
94    }
95
96    /**
97     * Creates a <code>DOMX509Data</code> from an element.
98     *
99     * @param xdElem an X509Data element
100     * @throws MarshalException if there is an error while unmarshalling
101     */
102    public DOMX509Data(Element xdElem) throws MarshalException {
103        // get all children nodes
104        NodeList nl = xdElem.getChildNodes();
105        int length = nl.getLength();
106        List<Object> content = new ArrayList<Object>(length);
107        for (int i = 0; i < length; i++) {
108            Node child = nl.item(i);
109            // ignore all non-Element nodes
110            if (child.getNodeType() != Node.ELEMENT_NODE) {
111                continue;
112            }
113
114            Element childElem = (Element)child;
115            String localName = childElem.getLocalName();
116            if (localName.equals("X509Certificate")) {
117                content.add(unmarshalX509Certificate(childElem));
118            } else if (localName.equals("X509IssuerSerial")) {
119                content.add(new DOMX509IssuerSerial(childElem));
120            } else if (localName.equals("X509SubjectName")) {
121                content.add(childElem.getFirstChild().getNodeValue());
122            } else if (localName.equals("X509SKI")) {
123                try {
124                    content.add(Base64.decode(childElem));
125                } catch (Base64DecodingException bde) {
126                    throw new MarshalException("cannot decode X509SKI", bde);
127                }
128            } else if (localName.equals("X509CRL")) {
129                content.add(unmarshalX509CRL(childElem));
130            } else {
131                content.add(new javax.xml.crypto.dom.DOMStructure(childElem));
132            }
133        }
134        this.content = Collections.unmodifiableList(content);
135    }
136
137    public List<?> getContent() {
138        return content;
139    }
140
141    public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
142        throws MarshalException
143    {
144        Document ownerDoc = DOMUtils.getOwnerDocument(parent);
145        Element xdElem = DOMUtils.createElement(ownerDoc, "X509Data",
146                                                XMLSignature.XMLNS, dsPrefix);
147
148        // append children and preserve order
149        for (int i = 0, size = content.size(); i < size; i++) {
150            Object object = content.get(i);
151            if (object instanceof X509Certificate) {
152                marshalCert((X509Certificate)object,xdElem,ownerDoc,dsPrefix);
153            } else if (object instanceof XMLStructure) {
154                if (object instanceof X509IssuerSerial) {
155                    ((DOMX509IssuerSerial)object).marshal
156                        (xdElem, dsPrefix, context);
157                } else {
158                    javax.xml.crypto.dom.DOMStructure domContent =
159                        (javax.xml.crypto.dom.DOMStructure)object;
160                    DOMUtils.appendChild(xdElem, domContent.getNode());
161                }
162            } else if (object instanceof byte[]) {
163                marshalSKI((byte[])object, xdElem, ownerDoc, dsPrefix);
164            } else if (object instanceof String) {
165                marshalSubjectName((String)object, xdElem, ownerDoc,dsPrefix);
166            } else if (object instanceof X509CRL) {
167                marshalCRL((X509CRL)object, xdElem, ownerDoc, dsPrefix);
168            }
169        }
170
171        parent.appendChild(xdElem);
172    }
173
174    private void marshalSKI(byte[] skid, Node parent, Document doc,
175                            String dsPrefix)
176    {
177        Element skidElem = DOMUtils.createElement(doc, "X509SKI",
178                                                  XMLSignature.XMLNS, dsPrefix);
179        skidElem.appendChild(doc.createTextNode(Base64.encode(skid)));
180        parent.appendChild(skidElem);
181    }
182
183    private void marshalSubjectName(String name, Node parent, Document doc,
184                                    String dsPrefix)
185    {
186        Element snElem = DOMUtils.createElement(doc, "X509SubjectName",
187                                                XMLSignature.XMLNS, dsPrefix);
188        snElem.appendChild(doc.createTextNode(name));
189        parent.appendChild(snElem);
190    }
191
192    private void marshalCert(X509Certificate cert, Node parent, Document doc,
193                             String dsPrefix)
194        throws MarshalException
195    {
196        Element certElem = DOMUtils.createElement(doc, "X509Certificate",
197                                                  XMLSignature.XMLNS, dsPrefix);
198        try {
199            certElem.appendChild(doc.createTextNode
200                                 (Base64.encode(cert.getEncoded())));
201        } catch (CertificateEncodingException e) {
202            throw new MarshalException("Error encoding X509Certificate", e);
203        }
204        parent.appendChild(certElem);
205    }
206
207    private void marshalCRL(X509CRL crl, Node parent, Document doc,
208                            String dsPrefix)
209        throws MarshalException
210    {
211        Element crlElem = DOMUtils.createElement(doc, "X509CRL",
212                                                 XMLSignature.XMLNS, dsPrefix);
213        try {
214            crlElem.appendChild(doc.createTextNode
215                                (Base64.encode(crl.getEncoded())));
216        } catch (CRLException e) {
217            throw new MarshalException("Error encoding X509CRL", e);
218        }
219        parent.appendChild(crlElem);
220    }
221
222    private X509Certificate unmarshalX509Certificate(Element elem)
223        throws MarshalException
224    {
225        try {
226            ByteArrayInputStream bs = unmarshalBase64Binary(elem);
227            return (X509Certificate)cf.generateCertificate(bs);
228        } catch (CertificateException e) {
229            throw new MarshalException("Cannot create X509Certificate", e);
230        }
231    }
232
233    private X509CRL unmarshalX509CRL(Element elem) throws MarshalException {
234        try {
235            ByteArrayInputStream bs = unmarshalBase64Binary(elem);
236            return (X509CRL)cf.generateCRL(bs);
237        } catch (CRLException e) {
238            throw new MarshalException("Cannot create X509CRL", e);
239        }
240    }
241
242    private ByteArrayInputStream unmarshalBase64Binary(Element elem)
243        throws MarshalException {
244        try {
245            if (cf == null) {
246                cf = CertificateFactory.getInstance("X.509");
247            }
248            return new ByteArrayInputStream(Base64.decode(elem));
249        } catch (CertificateException e) {
250            throw new MarshalException("Cannot create CertificateFactory", e);
251        } catch (Base64DecodingException bde) {
252            throw new MarshalException("Cannot decode Base64-encoded val", bde);
253        }
254    }
255
256    @Override
257    public boolean equals(Object o) {
258        if (this == o) {
259            return true;
260        }
261
262        if (!(o instanceof X509Data)) {
263            return false;
264        }
265        X509Data oxd = (X509Data)o;
266
267        List<?> ocontent = oxd.getContent();
268        int size = content.size();
269        if (size != ocontent.size()) {
270            return false;
271        }
272
273        for (int i = 0; i < size; i++) {
274            Object x = content.get(i);
275            Object ox = ocontent.get(i);
276            if (x instanceof byte[]) {
277                if (!(ox instanceof byte[]) ||
278                    !Arrays.equals((byte[])x, (byte[])ox)) {
279                    return false;
280                }
281            } else {
282                if (!(x.equals(ox))) {
283                    return false;
284                }
285            }
286        }
287
288        return true;
289    }
290
291    @Override
292    public int hashCode() {
293        int result = 17;
294        result = 31 * result + content.hashCode();
295
296        return result;
297    }
298}
299