File: BaltimoreEncTest.java

package info (click to toggle)
libxml-security-java 1.4.3-2%2Bdeb6u1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze-lts
  • size: 14,184 kB
  • ctags: 5,406
  • sloc: java: 41,126; xml: 22,042; sh: 196; makefile: 17
file content (706 lines) | stat: -rw-r--r-- 18,864 bytes parent folder | download | duplicates (4)
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
/*
 * Copyright  1999-2004 The Apache Software Foundation.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package org.apache.xml.security.test.encryption;

import java.io.File;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import junit.framework.Assert;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import org.apache.xml.security.algorithms.JCEMapper;
import org.apache.xml.security.encryption.EncryptedData;
import org.apache.xml.security.encryption.EncryptedKey;
import org.apache.xml.security.encryption.XMLCipher;
import org.apache.xml.security.keys.KeyInfo;
import org.apache.xml.security.keys.content.KeyName;
import org.apache.xml.security.keys.content.X509Data;
import org.apache.xml.security.keys.content.x509.XMLX509Certificate;
import org.apache.xml.security.keys.keyresolver.KeyResolver;
import org.apache.xml.security.test.TestUtils;
import org.apache.xml.security.utils.JavaUtils;
import org.apache.xpath.XPathAPI;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

/**
 * Interop test for XML Encryption
 *
 * @author Berin Lautenbach
 */

/*

Tests for merlin-xmlenc-five not currently done

bad-encrypt-content-aes128-cbc-kw-aes192.xml
decryption-transform-except.xml 
decryption-transform.xml        
encrypt-content-aes192-cbc-dh-sha512.xml
encrypt-data-tripledes-cbc-rsa-oaep-mgf1p-sha256.xml
encrypt-element-aes256-cbc-carried-kw-aes256.xml
encrypt-element-aes256-cbc-kw-aes256-dh-ripemd160.xml
encrypt-element-aes256-cbc-retrieved-kw-aes256.xml
encsig-hmac-sha256-dh.xml
encsig-hmac-sha256-kw-tripledes-dh.xml
encsig-hmac-sha256-rsa-1_5.xml
encsig-hmac-sha256-rsa-oaep-mgf1p.xml
encsig-ripemd160-hmac-ripemd160-kw-tripledes.xml
encsig-sha256-hmac-sha256-kw-aes128.xml
encsig-sha384-hmac-sha384-kw-aes192.xml
encsig-sha512-hmac-sha512-kw-aes256.xml

*/
public class BaltimoreEncTest extends TestCase {

	private static String cardNumber;
	private static String rsaCertSerialNumber;
	private static String testDecryptString;
	private static int nodeCount = 0;
	private static byte[] jebBytes;
	private static byte[] jobBytes;
	private static byte[] jedBytes;
	private static PrivateKey rsaKey;
	private boolean haveISOPadding;
	private boolean haveKeyWraps;

	/** {@link org.apache.commons.logging} logging facility */
    static org.apache.commons.logging.Log log = 
        org.apache.commons.logging.LogFactory.getLog(BaltimoreEncTest.class.getName());
	
	/**
	 * Method suite
	 *
	 *
	 */
	public static Test suite() throws Exception {
		return new TestSuite(BaltimoreEncTest.class);
	}

	/**
	 *  Constructor BaltimoreEncTest
	 *
	 *  @param Name_
	 */
	public BaltimoreEncTest(String Name_) {
		super(Name_);
	}
	
	/**
	 * Method setUp
	 */
	protected void setUp() throws Exception {
		// Create the comparison strings
	
		DocumentBuilderFactory dbf =
			DocumentBuilderFactory.newInstance();
		dbf.setNamespaceAware(true);
		dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE);
		
		String filename = 
			"data/ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml";
		String basedir = System.getProperty("basedir");
		if(basedir != null && !"".equals(basedir)) {
			filename = basedir + "/" + filename;
		}
		File f = new File(filename);
	
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = db.parse(new java.io.FileInputStream(f));
	
		cardNumber = retrieveCCNumber(doc);
	
		// Test decrypt
		testDecryptString = new String("top secret message\n");
	
		// Count the nodes in the document as a secondary test
		nodeCount = countNodes(doc);
	
		// Create the keys
		jebBytes =
			"abcdefghijklmnopqrstuvwx".getBytes("ASCII");
		jobBytes = 
			"abcdefghijklmnop".getBytes("ASCII");
		jedBytes = 
			"abcdefghijklmnopqrstuvwxyz012345".getBytes("ASCII");
	
		// Certificate information
		rsaCertSerialNumber = new String("1014918766910");
	
		// rsaKey
		filename = "data/ie/baltimore/merlin-examples/merlin-xmlenc-five/rsa.p8";
		if(basedir != null && !"".equals(basedir)) {
			filename = basedir + "/" + filename;
		}
		
		byte[] pkcs8Bytes = JavaUtils.getBytesFromFile(filename);
	
		PKCS8EncodedKeySpec pkcs8Spec = 
			new PKCS8EncodedKeySpec(pkcs8Bytes);
	
		// Create a key factory 
		KeyFactory keyFactory = 
			KeyFactory.getInstance("RSA");
		rsaKey = keyFactory.generatePrivate(pkcs8Spec);
	
		// Initialise the library
	
		org.apache.xml.security.Init.init();
	
		// Register our key resolver
		KeyResolver.register("org.apache.xml.security.test.encryption.BobKeyResolver");

		// Check what algorithms are available

		haveISOPadding = false;
		String algorithmId = 
			JCEMapper.translateURItoJCEID(org.apache.xml.security.utils.EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128);

		if (algorithmId != null) {
			try {
				if (Cipher.getInstance(algorithmId) != null)
					haveISOPadding = true;
			} catch (NoSuchAlgorithmException nsae) {
			} catch (NoSuchPaddingException nspe) {
			}
		}

		haveKeyWraps = (JCEMapper.translateURItoJCEID(org.apache.xml.security.utils.EncryptionConstants.ALGO_ID_KEYWRAP_AES128) != null);
	}

	/**
	 * Method retrieveCCNumber
	 *
	 * Retrieve the credit card number from the payment info document
	 *
	 * @param doc The document to retreive the card number from
	 * @return The retrieved credit card number
	 */

	public static String retrieveCCNumber (Document doc) 
		throws javax.xml.transform.TransformerException {

		Element nscontext =
			TestUtils.createDSctx(doc, "x",
                              "urn:example:po");
		Node ccnumElt = 
			XPathAPI.selectSingleNode(doc, "//x:Number/text()", nscontext);
		
		if (ccnumElt != null)
			return ccnumElt.getNodeValue();

		return null;

	}

	/*
	 * Check we have retrieved a Credit Card number and that it is OK
	 * Check that the document has the correct number of nodes
	 */

	private void checkDecryptedDoc(Document d, boolean doNodeCheck) throws Exception {

		String cc = retrieveCCNumber(d);
		log.debug("Retrieved Credit Card : " + cc);
		assertTrue(cc, ((cc!= null) && (cc.equals(cardNumber))));

		// Test cc numbers

		if (doNodeCheck) {
			int myNodeCount = countNodes(d);

			assertTrue("Node count mismatches", 
					   ((myNodeCount > 0) && myNodeCount == nodeCount));
		}
	}

	/**
	 * Check a decrypt of data was OK
	 */

	private void checkDecryptedData(byte [] data) throws Exception {

		String input = new String(data, "ASCII");
        Assert.assertEquals(testDecryptString, input);
	}

	/**
	 * Method test_five_content_3des_cbc
	 *
	 * Check the merlin-enc-five element content test for 3DES
	 *
	 */


	public void test_five_content_3des_cbc() throws Exception {

		if (haveISOPadding) {
			String filename = "data/ie/baltimore/merlin-examples/merlin-xmlenc-five/encrypt-content-tripledes-cbc.xml";

			Document dd = decryptElement(filename);
			checkDecryptedDoc(dd, true);
		}
		else {
			log.warn("Skipping test test_five_content_3des_cbs as necessary crypto algorithms are not available");
		}
    }

	/**
	 * Method test_five_content_aes256_cbc
	 *
	 * Check the merlin-enc-five element content test for AES256
	 *
	 */

	public void test_five_content_aes256_cbc() throws Exception {

		if (haveISOPadding) {
			String filename = "data/ie/baltimore/merlin-examples/merlin-xmlenc-five/encrypt-content-aes256-cbc-prop.xml";

			Document dd = decryptElement(filename);
			checkDecryptedDoc(dd, true);
		}
		else {
			log.warn("Skipping test test_five_content_aes256_cbc as necessary crypto algorithms are not available");
		}
    }

	/**
	 * Method test_five_content_aes128_cbc_kw_aes192
	 *
	 * Check the merlin-enc-five element content test for AES128 with
	 * AES 192 key wrap
	 *
	 */

	public void test_five_content_aes128_cbc_kw_aes192() throws Exception {

		if (haveISOPadding && haveKeyWraps) {
			String filename = "data/ie/baltimore/merlin-examples/merlin-xmlenc-five/encrypt-content-aes128-cbc-kw-aes192.xml";

			Document dd = decryptElement(filename);
			checkDecryptedDoc(dd, true);
		}
		else {
			log.warn("Skipping test test_five_content_aes128_cbc_kw_aes192 as necessary crypto algorithms are not available");
		}
    }

	/**
	 * Method test_five_content_3des_cbc_kw_aes128
	 *
	 * Check the merlin-enc-five element content test for 3DES with
	 * AES 128 key wrap
	 *
	 */

	public void test_five_content_3des_cbc_kw_aes128() throws Exception {

		if (haveISOPadding && haveKeyWraps) {
			String filename = "data/ie/baltimore/merlin-examples/merlin-xmlenc-five/encrypt-element-tripledes-cbc-kw-aes128.xml";

			Document dd = decryptElement(filename);
			checkDecryptedDoc(dd, true);
		}
		else {
			log.warn("Skipping test test_five_content_3des_cbc_kw_aes128 as necessary crypto algorithms are not available");
		}

    }

	/**
	 * Method test_five_content_aes128_cbc_kw_rsa_15
	 *
	 * Check the merlin-enc-five element content test for AES128 with
	 * RSA key wrap (PKCS 1.5 padding)
	 *
	 */

	public void test_five_content_aes128_cbc_rsa_15() throws Exception {

		if (haveISOPadding) {
			String filename = "data/ie/baltimore/merlin-examples/merlin-xmlenc-five/encrypt-element-aes128-cbc-rsa-1_5.xml";

			Document dd = decryptElement(filename);
			checkDecryptedDoc(dd, true);
		}
		else {
			log.warn("Skipping test test_five_content_aes128_cbc_rsa_15 as necessary crypto algorithms are not available");
		}
    }

	/**
	 * Method test_five_element_aes192_cbc_ref
	 *
	 * Check the merlin-enc-five element data test for AES192 with
	 * a CipherReference element
	 *
	 */

	public void test_five_element_aes192_cbc_ref() throws Exception {

		if (haveISOPadding) {
			String filename = "data/ie/baltimore/merlin-examples/merlin-xmlenc-five/encrypt-element-aes192-cbc-ref.xml";

			Document dd = decryptElement(filename);
			// Note - we don't check the node count, as it will be different
			// due to the encrypted text remainin in the reference nodes
			checkDecryptedDoc(dd, false);
		}
		else {
			log.warn("Skipping test test_five_element_aes192_cbc_ref as necessary crypto algorithms are not available");
		}
    }

	/**
	 * Method test_five_data_aes128_cbc
	 *
	 * Check the merlin-enc-five element data test for AES128 with no
	 * key wrap
	 *
	 */

	public void test_five_data_aes128_cbc() throws Exception {

		if (haveISOPadding) {
			String filename = "data/ie/baltimore/merlin-examples/merlin-xmlenc-five/encrypt-data-aes128-cbc.xml";

			byte[] decrypt = decryptData(filename);
			checkDecryptedData(decrypt);
		}
		else {
			log.warn("Skipping test test_five_data_aes128_cbc as necessary crypto algorithms are not available");
		}
    }

	/**
	 * Method test_five_data_aes256_cbc_3des
	 *
	 * Check the merlin-enc-five element data test for AES256 with 3DES
	 * key wrap
	 *
	 */

	public void test_five_data_aes256_cbc_3des() throws Exception {

		if (haveISOPadding && haveKeyWraps) {
			String filename = "data/ie/baltimore/merlin-examples/merlin-xmlenc-five/encrypt-data-aes256-cbc-kw-tripledes.xml";

			byte[] decrypt = decryptData(filename);
			checkDecryptedData(decrypt);
		}
		else {
			log.warn("Skipping test test_five_data_aes256_cbc_3des as necessary crypto algorithms are not available");
		}
    }

	/**
	 * Method test_five_data_aes192_cbc_aes256
	 *
	 * Check the merlin-enc-five element data test for AES192 with AES256
	 * key wrap
	 *
	 */

	public void test_five_data_aes192_cbc_aes256() throws Exception {

		if (haveISOPadding && haveKeyWraps) {
			String filename = "data/ie/baltimore/merlin-examples/merlin-xmlenc-five/encrypt-data-aes192-cbc-kw-aes256.xml";

			byte[] decrypt = decryptData(filename);
			checkDecryptedData(decrypt);
		}
		else {
			log.warn("Skipping test test_five_data_aes192_cbc_aes256 as necessary crypto algorithms are not available");
		}
    }

	/**
	 * Method test_five_data_3des_cbc_rsa_oaep
	 *
	 * Check the merlin-enc-five element data test for 3DES with
	 * RSA key wrap (OAEP and no parameters)
	 *
	 */

	public void test_five_data_3des_cbc_rsa_oaep() throws Exception {

                // Work-around for the fact that BC currently doesn't support
                // the standard JCE name for oaep padding
                java.security.Provider bc = java.security.Security.getProvider("BC");
                if (bc != null)
                    bc.put("Alg.Alias.Cipher.RSA/ECB/OAEPWithSHA1AndMGF1Padding","RSA/OAEP");

		if (haveISOPadding) {
			String filename = "data/ie/baltimore/merlin-examples/merlin-xmlenc-five/encrypt-data-tripledes-cbc-rsa-oaep-mgf1p.xml";

			byte[] decrypt = decryptData(filename);
			checkDecryptedData(decrypt);
		}
		else {
			log.warn("Skipping test test_five_data_3des_cbc_rsa_oaep as necessary crypto algorithms are not available");
		}
    }

	/**
	 * Method decryptElement
	 *
	 * Take a key, encryption type and a file, find an encrypted element
	 * decrypt it and return the resulting document
	 *
	 * @param filename File to decrypt from
	 */

	public Document decryptElement (String filename) 
		throws Exception {

		XMLCipher cipher;
		
		// Parse the document in question

		javax.xml.parsers.DocumentBuilderFactory dbf =
			javax.xml.parsers.DocumentBuilderFactory.newInstance();
		dbf.setNamespaceAware(true);
		dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE);
		String basedir = System.getProperty("basedir");
		if(basedir != null && !"".equals(basedir)) {
			filename = basedir + "/" + filename;
		}
		File f = new File(filename);

		DocumentBuilder db = dbf.newDocumentBuilder();
		
		Document doc = db.parse(new java.io.FileInputStream(f));
		
		// Now we have the document, lets build the XMLCipher element

		Element ee = null;
		
		// Create the XMLCipher element
		
		cipher = XMLCipher.getInstance();

		// Need to pre-load the Encrypted Data so we can get the key info

		ee = (Element) doc.getElementsByTagName("EncryptedData").item(0);
		cipher.init(XMLCipher.DECRYPT_MODE, null);
		EncryptedData encryptedData = cipher.loadEncryptedData(doc, ee);
   
		Key key = findKey(encryptedData);
		cipher.init(XMLCipher.DECRYPT_MODE, key);
		Document dd = cipher.doFinal(doc, ee);

		return dd;
			
    }

	/**
	 * Method decryptData
	 *
	 * Take a file, find an encrypted element decrypt it and return the 
	 * resulting byte array
	 *
	 * @param filename File to decrypt from
	 */

	public byte[] decryptData (String filename) 
		throws Exception {

		XMLCipher cipher;
		
		// Parse the document in question

		javax.xml.parsers.DocumentBuilderFactory dbf =
			javax.xml.parsers.DocumentBuilderFactory.newInstance();
		dbf.setNamespaceAware(true);
		dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE);
		String basedir = System.getProperty("basedir");
		if(basedir != null && !"".equals(basedir)) {
			filename = basedir + "/" + filename;
		}
		File f = new File(filename);

		DocumentBuilder db = dbf.newDocumentBuilder();
		
		Document doc = db.parse(new java.io.FileInputStream(f));
		
		// Now we have the document, lets build the XMLCipher element

		Element ee = null;
		
		// Create the XMLCipher element
		
		cipher = XMLCipher.getInstance();

		// Need to pre-load the Encrypted Data so we can get the key info

		ee = (Element) doc.getElementsByTagName("EncryptedData").item(0);
		cipher.init(XMLCipher.DECRYPT_MODE, null);
		EncryptedData encryptedData = cipher.loadEncryptedData(doc, ee);

		Key key = findKey(encryptedData);
		
		cipher.init(XMLCipher.DECRYPT_MODE, key);
               
		byte[] dd = cipher.decryptToByteArray(ee);

		return dd;
			
    }

	/** 
	 * Method mapKeyName
	 *
	 * Create a secret key from a key name for merlin-five
	 *
	 * @param name Name to map a key from
	 */

	public SecretKey mapKeyName(String name) throws Exception {

        if (name.equals("job")) {

			// Jeb is a AES-128 key
	        SecretKey key = new SecretKeySpec(jobBytes, "AES");
			return key;
		}
		if (name.equals("jeb")) {

			// Jeb is a AES-192 key
	        SecretKey key = new SecretKeySpec(jebBytes, "AES");
			return key;
		}
		if (name.equals("jed")) {

			// Jeb is a AES-256 key
	        SecretKey key = new SecretKeySpec(jedBytes, "AES");
			return key;
		}

		return null;

	}

	/**
	 * Method findKey
	 *
	 * Given an encryptedData structure, return the key that will decrypt
	 * it
	 *
	 * @param encryptedData EncryptedData to get key for
	 */

	public Key findKey(EncryptedData encryptedData) throws Exception {

		KeyInfo ki = encryptedData.getKeyInfo();
   
		Key key = null;
		Key kek = null;

		if (ki == null)
			return null;
		

		// First check for a known key name
		KeyName keyName = ki.itemKeyName(0);
		if (keyName != null) {
			return (mapKeyName(keyName.getKeyName()));
		}

		// Decrypt any encryptedKey structures
		EncryptedKey encryptedKey = ki.itemEncryptedKey(0);
		
		if (encryptedKey == null)
			return null;
	 
		KeyInfo kiek = encryptedKey.getKeyInfo();
		if (kiek == null) {
			return null;
		}

		KeyName kekKeyName = kiek.itemKeyName(0);
		if (kekKeyName != null) {
			kek = mapKeyName(kekKeyName.getKeyName());
		}
		else {

			X509Data certData = kiek.itemX509Data(0);
			XMLX509Certificate xcert = certData.itemCertificate(0);
			X509Certificate cert = xcert.getX509Certificate();

			if (cert != null) {

				if (cert.getSerialNumber().toString().equals(rsaCertSerialNumber)) {

					kek = rsaKey;
					
				}
			}
		}
		if (kek != null) {
			XMLCipher cipher = XMLCipher.getInstance();
			cipher.init(XMLCipher.UNWRAP_MODE, kek);
			key = cipher.decryptKey(encryptedKey,
									encryptedData.
									getEncryptionMethod().
									getAlgorithm());
		}
		
		return key;
	}
	/**
	 * Method countNodes
	 *
	 * Recursively count the number of nodes in the document
	 *
	 * @param n Node to count beneath
	 */

	private static int countNodes(Node n) {

		if (n == null)
			return 0;  // Paranoia

		int count = 1;  // Always count myself
		Node c = n.getFirstChild();

		while (c != null) {

			count += countNodes(c);
			c = c.getNextSibling();

		}

		return count;

	}
}