diff --git a/.hgtags-top-repo b/.hgtags-top-repo index f02d32f4820..2aef17b1cf2 100644 --- a/.hgtags-top-repo +++ b/.hgtags-top-repo @@ -220,3 +220,4 @@ cb51fb4789ac0b8be4056482077ddfb8f3bd3805 jdk8-b91 c156084add486f941c12d886a0b1b2854795d557 jdk8-b96 a1c1e8bf71f354f3aec0214cf13d6668811e021d jdk8-b97 0d0c983a817bbe8518a5ff201306334a8de267f2 jdk8-b98 +59dc9da813794c924a0383c2a6241af94defdfed jdk8-b99 diff --git a/corba/.hgtags b/corba/.hgtags index 22add8d745b..6c4fabef021 100644 --- a/corba/.hgtags +++ b/corba/.hgtags @@ -220,3 +220,4 @@ c8286839d0df04aba819ec4bef12b86babccf30e jdk8-b90 3357c2776431d51a8de326a85e0f41420e40774f jdk8-b96 469995a8e97424f450c880606d689bf345277b19 jdk8-b97 3370fb6146e47a6cc05a213fc213e12fc0a38d07 jdk8-b98 +3f67804ab61303782df57e54989ef5e0e4629beb jdk8-b99 diff --git a/hotspot/.hgtags b/hotspot/.hgtags index b9bba1537d2..edfa2aa21bf 100644 --- a/hotspot/.hgtags +++ b/hotspot/.hgtags @@ -359,3 +359,5 @@ d197d377ab2e016d024e8c86cb06a57bd7eae590 jdk8-b97 c9dd82da51ed34a28f7c6b3245163ee962e94572 hs25-b40 30b5b75c42ac5174b640fbef8aa87527668e8400 jdk8-b98 2b9946e10587f74ef75ae8145bea484df4a2738b hs25-b41 +81b6cb70717c66375846b78bb174594ec3aa998e jdk8-b99 +9f71e36a471ae4a668e08827d33035963ed10c08 hs25-b42 diff --git a/hotspot/make/hotspot_version b/hotspot/make/hotspot_version index 8d98d13fbaf..86018ca9e0c 100644 --- a/hotspot/make/hotspot_version +++ b/hotspot/make/hotspot_version @@ -35,7 +35,7 @@ HOTSPOT_VM_COPYRIGHT=Copyright 2013 HS_MAJOR_VER=25 HS_MINOR_VER=0 -HS_BUILD_NUMBER=41 +HS_BUILD_NUMBER=42 JDK_MAJOR_VER=1 JDK_MINOR_VER=8 diff --git a/hotspot/make/linux/makefiles/vm.make b/hotspot/make/linux/makefiles/vm.make index 3c3bd2e2d16..4c984be2cd6 100644 --- a/hotspot/make/linux/makefiles/vm.make +++ b/hotspot/make/linux/makefiles/vm.make @@ -46,6 +46,7 @@ ifeq ($(findstring true, $(JVM_VARIANT_ZERO) $(JVM_VARIANT_ZEROSHARK)), true) include $(MAKEFILES_DIR)/zeroshark.make else include $(MAKEFILES_DIR)/$(BUILDARCH).make + -include $(HS_ALT_MAKE)/$(Platform_os_family)/makefiles/$(BUILDARCH).make endif # set VPATH so make knows where to look for source files @@ -380,4 +381,4 @@ build: $(LIBJVM) $(LAUNCHER) $(LIBJSIG) $(LIBJVM_DB) $(BUILDLIBSAPROC) dtraceChe install: install_jvm install_jsig install_saproc -.PHONY: default build install install_jvm +.PHONY: default build install install_jvm $(HS_ALT_MAKE)/$(Platform_os_family)/makefiles/$(BUILDARCH).make diff --git a/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp b/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp index 494c1bc405a..214940cdbfb 100644 --- a/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp @@ -410,6 +410,51 @@ class StubGenerator: public StubCodeGenerator { return start; } + // Safefetch stubs. + void generate_safefetch(const char* name, int size, address* entry, + address* fault_pc, address* continuation_pc) { + // safefetch signatures: + // int SafeFetch32(int* adr, int errValue); + // intptr_t SafeFetchN (intptr_t* adr, intptr_t errValue); + // + // arguments: + // o0 = adr + // o1 = errValue + // + // result: + // o0 = *adr or errValue + + StubCodeMark mark(this, "StubRoutines", name); + + // Entry point, pc or function descriptor. + __ align(CodeEntryAlignment); + *entry = __ pc(); + + __ mov(O0, G1); // g1 = o0 + __ mov(O1, O0); // o0 = o1 + // Load *adr into c_rarg1, may fault. + *fault_pc = __ pc(); + switch (size) { + case 4: + // int32_t + __ ldsw(G1, 0, O0); // o0 = [g1] + break; + case 8: + // int64_t + __ ldx(G1, 0, O0); // o0 = [g1] + break; + default: + ShouldNotReachHere(); + } + + // return errValue or *adr + *continuation_pc = __ pc(); + // By convention with the trap handler we ensure there is a non-CTI + // instruction in the trap shadow. + __ nop(); + __ retl(); + __ delayed()->nop(); + } //------------------------------------------------------------------------------------------------------------------------ // Continuation point for throwing of implicit exceptions that are not handled in @@ -3315,6 +3360,14 @@ class StubGenerator: public StubCodeGenerator { // Don't initialize the platform math functions since sparc // doesn't have intrinsics for these operations. + + // Safefetch stubs. + generate_safefetch("SafeFetch32", sizeof(int), &StubRoutines::_safefetch32_entry, + &StubRoutines::_safefetch32_fault_pc, + &StubRoutines::_safefetch32_continuation_pc); + generate_safefetch("SafeFetchN", sizeof(intptr_t), &StubRoutines::_safefetchN_entry, + &StubRoutines::_safefetchN_fault_pc, + &StubRoutines::_safefetchN_continuation_pc); } diff --git a/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp b/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp index 82e4183ef47..a8abfea6bcd 100644 --- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp +++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp @@ -2766,6 +2766,39 @@ class StubGenerator: public StubCodeGenerator { return start; } + // Safefetch stubs. + void generate_safefetch(const char* name, int size, address* entry, + address* fault_pc, address* continuation_pc) { + // safefetch signatures: + // int SafeFetch32(int* adr, int errValue); + // intptr_t SafeFetchN (intptr_t* adr, intptr_t errValue); + + StubCodeMark mark(this, "StubRoutines", name); + + // Entry point, pc or function descriptor. + *entry = __ pc(); + + __ movl(rax, Address(rsp, 0x8)); + __ movl(rcx, Address(rsp, 0x4)); + // Load *adr into eax, may fault. + *fault_pc = __ pc(); + switch (size) { + case 4: + // int32_t + __ movl(rax, Address(rcx, 0)); + break; + case 8: + // int64_t + Unimplemented(); + break; + default: + ShouldNotReachHere(); + } + + // Return errValue or *adr. + *continuation_pc = __ pc(); + __ ret(0); + } public: // Information about frame layout at time of blocking runtime call. @@ -2978,6 +3011,14 @@ class StubGenerator: public StubCodeGenerator { StubRoutines::_cipherBlockChaining_encryptAESCrypt = generate_cipherBlockChaining_encryptAESCrypt(); StubRoutines::_cipherBlockChaining_decryptAESCrypt = generate_cipherBlockChaining_decryptAESCrypt(); } + + // Safefetch stubs. + generate_safefetch("SafeFetch32", sizeof(int), &StubRoutines::_safefetch32_entry, + &StubRoutines::_safefetch32_fault_pc, + &StubRoutines::_safefetch32_continuation_pc); + StubRoutines::_safefetchN_entry = StubRoutines::_safefetch32_entry; + StubRoutines::_safefetchN_fault_pc = StubRoutines::_safefetch32_fault_pc; + StubRoutines::_safefetchN_continuation_pc = StubRoutines::_safefetch32_continuation_pc; } diff --git a/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp b/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp index 2d94642f828..c80f1807936 100644 --- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp +++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp @@ -3357,7 +3357,45 @@ class StubGenerator: public StubCodeGenerator { return start; } + // Safefetch stubs. + void generate_safefetch(const char* name, int size, address* entry, + address* fault_pc, address* continuation_pc) { + // safefetch signatures: + // int SafeFetch32(int* adr, int errValue); + // intptr_t SafeFetchN (intptr_t* adr, intptr_t errValue); + // + // arguments: + // c_rarg0 = adr + // c_rarg1 = errValue + // + // result: + // PPC_RET = *adr or errValue + StubCodeMark mark(this, "StubRoutines", name); + + // Entry point, pc or function descriptor. + *entry = __ pc(); + + // Load *adr into c_rarg1, may fault. + *fault_pc = __ pc(); + switch (size) { + case 4: + // int32_t + __ movl(c_rarg1, Address(c_rarg0, 0)); + break; + case 8: + // int64_t + __ movq(c_rarg1, Address(c_rarg0, 0)); + break; + default: + ShouldNotReachHere(); + } + + // return errValue or *adr + *continuation_pc = __ pc(); + __ movq(rax, c_rarg1); + __ ret(0); + } // This is a version of CBC/AES Decrypt which does 4 blocks in a loop at a time // to hide instruction latency @@ -3833,6 +3871,14 @@ class StubGenerator: public StubCodeGenerator { StubRoutines::_cipherBlockChaining_encryptAESCrypt = generate_cipherBlockChaining_encryptAESCrypt(); StubRoutines::_cipherBlockChaining_decryptAESCrypt = generate_cipherBlockChaining_decryptAESCrypt_Parallel(); } + + // Safefetch stubs. + generate_safefetch("SafeFetch32", sizeof(int), &StubRoutines::_safefetch32_entry, + &StubRoutines::_safefetch32_fault_pc, + &StubRoutines::_safefetch32_continuation_pc); + generate_safefetch("SafeFetchN", sizeof(intptr_t), &StubRoutines::_safefetchN_entry, + &StubRoutines::_safefetchN_fault_pc, + &StubRoutines::_safefetchN_continuation_pc); } public: diff --git a/hotspot/src/os/windows/vm/os_windows.cpp b/hotspot/src/os/windows/vm/os_windows.cpp index 23d2efb3692..3b00e86a2c7 100644 --- a/hotspot/src/os/windows/vm/os_windows.cpp +++ b/hotspot/src/os/windows/vm/os_windows.cpp @@ -2323,6 +2323,11 @@ LONG WINAPI topLevelExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo) { #endif Thread* t = ThreadLocalStorage::get_thread_slow(); // slow & steady + // Handle SafeFetch32 and SafeFetchN exceptions. + if (StubRoutines::is_safefetch_fault(pc)) { + return Handle_Exception(exceptionInfo, StubRoutines::continuation_for_safefetch_fault(pc)); + } + #ifndef _WIN64 // Execution protection violation - win32 running on AMD64 only // Handled first to avoid misdiagnosis as a "normal" access violation; diff --git a/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_32.s b/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_32.s index 402c8da11a6..3275996f0c7 100644 --- a/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_32.s +++ b/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_32.s @@ -63,24 +63,6 @@ SYMBOL(fixcw): popl %eax ret - .globl SYMBOL(SafeFetch32), SYMBOL(Fetch32PFI), SYMBOL(Fetch32Resume) - .globl SYMBOL(SafeFetchN) - ## TODO: avoid exposing Fetch32PFI and Fetch32Resume. - ## Instead, the signal handler would call a new SafeFetchTriage(FaultingEIP) - ## routine to vet the address. If the address is the faulting LD then - ## SafeFetchTriage() would return the resume-at EIP, otherwise null. - ELF_TYPE(SafeFetch32,@function) - .p2align 4,,15 -SYMBOL(SafeFetch32): -SYMBOL(SafeFetchN): - movl 0x8(%esp), %eax - movl 0x4(%esp), %ecx -SYMBOL(Fetch32PFI): - movl (%ecx), %eax -SYMBOL(Fetch32Resume): - ret - - .globl SYMBOL(SpinPause) ELF_TYPE(SpinPause,@function) .p2align 4,,15 diff --git a/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_64.s b/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_64.s index 65d2db45f70..2f70fce77a3 100644 --- a/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_64.s +++ b/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_64.s @@ -46,28 +46,6 @@ .text - .globl SYMBOL(SafeFetch32), SYMBOL(Fetch32PFI), SYMBOL(Fetch32Resume) - .p2align 4,,15 - ELF_TYPE(SafeFetch32,@function) - // Prototype: int SafeFetch32 (int * Adr, int ErrValue) -SYMBOL(SafeFetch32): - movl %esi, %eax -SYMBOL(Fetch32PFI): - movl (%rdi), %eax -SYMBOL(Fetch32Resume): - ret - - .globl SYMBOL(SafeFetchN), SYMBOL(FetchNPFI), SYMBOL(FetchNResume) - .p2align 4,,15 - ELF_TYPE(SafeFetchN,@function) - // Prototype: intptr_t SafeFetchN (intptr_t * Adr, intptr_t ErrValue) -SYMBOL(SafeFetchN): - movq %rsi, %rax -SYMBOL(FetchNPFI): - movq (%rdi), %rax -SYMBOL(FetchNResume): - ret - .globl SYMBOL(SpinPause) .p2align 4,,15 ELF_TYPE(SpinPause,@function) diff --git a/hotspot/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp b/hotspot/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp index aa36599ea2a..55ef24b899d 100644 --- a/hotspot/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp +++ b/hotspot/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp @@ -385,13 +385,6 @@ enum { trap_page_fault = 0xE }; -extern "C" void Fetch32PFI () ; -extern "C" void Fetch32Resume () ; -#ifdef AMD64 -extern "C" void FetchNPFI () ; -extern "C" void FetchNResume () ; -#endif // AMD64 - extern "C" JNIEXPORT int JVM_handle_bsd_signal(int sig, siginfo_t* info, @@ -454,16 +447,10 @@ JVM_handle_bsd_signal(int sig, if (info != NULL && uc != NULL && thread != NULL) { pc = (address) os::Bsd::ucontext_get_pc(uc); - if (pc == (address) Fetch32PFI) { - uc->context_pc = intptr_t(Fetch32Resume) ; - return 1 ; + if (StubRoutines::is_safefetch_fault(pc)) { + uc->context_pc = intptr_t(StubRoutines::continuation_for_safefetch_fault(pc)); + return 1; } -#ifdef AMD64 - if (pc == (address) FetchNPFI) { - uc->context_pc = intptr_t (FetchNResume) ; - return 1 ; - } -#endif // AMD64 // Handle ALL stack overflow variations here if (sig == SIGSEGV || sig == SIGBUS) { diff --git a/hotspot/src/os_cpu/linux_sparc/vm/linux_sparc.s b/hotspot/src/os_cpu/linux_sparc/vm/linux_sparc.s index e04f871f49e..d7c2ce87414 100644 --- a/hotspot/src/os_cpu/linux_sparc/vm/linux_sparc.s +++ b/hotspot/src/os_cpu/linux_sparc/vm/linux_sparc.s @@ -21,42 +21,6 @@ # questions. # - # Prototype: int SafeFetch32 (int * adr, int ErrValue) - # The "ld" at Fetch32 is potentially faulting instruction. - # If the instruction traps the trap handler will arrange - # for control to resume at Fetch32Resume. - # By convention with the trap handler we ensure there is a non-CTI - # instruction in the trap shadow. - - - .globl SafeFetch32, Fetch32PFI, Fetch32Resume - .globl SafeFetchN - .align 32 - .type SafeFetch32,@function -SafeFetch32: - mov %o0, %g1 - mov %o1, %o0 -Fetch32PFI: - # <-- Potentially faulting instruction - ld [%g1], %o0 -Fetch32Resume: - nop - retl - nop - - .globl SafeFetchN, FetchNPFI, FetchNResume - .type SafeFetchN,@function - .align 32 -SafeFetchN: - mov %o0, %g1 - mov %o1, %o0 -FetchNPFI: - ldn [%g1], %o0 -FetchNResume: - nop - retl - nop - # Possibilities: # -- membar # -- CAS (SP + BIAS, G0, G0) diff --git a/hotspot/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp b/hotspot/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp index d97f0e041bf..2367e2a0604 100644 --- a/hotspot/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp +++ b/hotspot/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp @@ -366,18 +366,9 @@ intptr_t* os::Linux::ucontext_get_fp(ucontext_t *uc) { // Utility functions -extern "C" void Fetch32PFI(); -extern "C" void Fetch32Resume(); -extern "C" void FetchNPFI(); -extern "C" void FetchNResume(); - inline static bool checkPrefetch(sigcontext* uc, address pc) { - if (pc == (address) Fetch32PFI) { - set_cont_address(uc, address(Fetch32Resume)); - return true; - } - if (pc == (address) FetchNPFI) { - set_cont_address(uc, address(FetchNResume)); + if (StubRoutines::is_safefetch_fault(pc)) { + set_cont_address(uc, address(StubRoutines::continuation_for_safefetch_fault(pc))); return true; } return false; diff --git a/hotspot/src/os_cpu/linux_x86/vm/linux_x86_32.s b/hotspot/src/os_cpu/linux_x86/vm/linux_x86_32.s index d29d31df464..7936cbf52bd 100644 --- a/hotspot/src/os_cpu/linux_x86/vm/linux_x86_32.s +++ b/hotspot/src/os_cpu/linux_x86/vm/linux_x86_32.s @@ -42,24 +42,6 @@ .text - .globl SafeFetch32, Fetch32PFI, Fetch32Resume - .globl SafeFetchN - ## TODO: avoid exposing Fetch32PFI and Fetch32Resume. - ## Instead, the signal handler would call a new SafeFetchTriage(FaultingEIP) - ## routine to vet the address. If the address is the faulting LD then - ## SafeFetchTriage() would return the resume-at EIP, otherwise null. - .type SafeFetch32,@function - .p2align 4,,15 -SafeFetch32: -SafeFetchN: - movl 0x8(%esp), %eax - movl 0x4(%esp), %ecx -Fetch32PFI: - movl (%ecx), %eax -Fetch32Resume: - ret - - .globl SpinPause .type SpinPause,@function .p2align 4,,15 diff --git a/hotspot/src/os_cpu/linux_x86/vm/linux_x86_64.s b/hotspot/src/os_cpu/linux_x86/vm/linux_x86_64.s index 8be68610e80..fb688e7a7b6 100644 --- a/hotspot/src/os_cpu/linux_x86/vm/linux_x86_64.s +++ b/hotspot/src/os_cpu/linux_x86/vm/linux_x86_64.s @@ -38,28 +38,6 @@ .text - .globl SafeFetch32, Fetch32PFI, Fetch32Resume - .align 16 - .type SafeFetch32,@function - // Prototype: int SafeFetch32 (int * Adr, int ErrValue) -SafeFetch32: - movl %esi, %eax -Fetch32PFI: - movl (%rdi), %eax -Fetch32Resume: - ret - - .globl SafeFetchN, FetchNPFI, FetchNResume - .align 16 - .type SafeFetchN,@function - // Prototype: intptr_t SafeFetchN (intptr_t * Adr, intptr_t ErrValue) -SafeFetchN: - movq %rsi, %rax -FetchNPFI: - movq (%rdi), %rax -FetchNResume: - ret - .globl SpinPause .align 16 .type SpinPause,@function diff --git a/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp b/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp index 4fc3b76d228..f7a57773fe9 100644 --- a/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp +++ b/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp @@ -209,13 +209,6 @@ enum { trap_page_fault = 0xE }; -extern "C" void Fetch32PFI () ; -extern "C" void Fetch32Resume () ; -#ifdef AMD64 -extern "C" void FetchNPFI () ; -extern "C" void FetchNResume () ; -#endif // AMD64 - extern "C" JNIEXPORT int JVM_handle_linux_signal(int sig, siginfo_t* info, @@ -278,16 +271,10 @@ JVM_handle_linux_signal(int sig, if (info != NULL && uc != NULL && thread != NULL) { pc = (address) os::Linux::ucontext_get_pc(uc); - if (pc == (address) Fetch32PFI) { - uc->uc_mcontext.gregs[REG_PC] = intptr_t(Fetch32Resume) ; - return 1 ; + if (StubRoutines::is_safefetch_fault(pc)) { + uc->uc_mcontext.gregs[REG_PC] = intptr_t(StubRoutines::continuation_for_safefetch_fault(pc)); + return 1; } -#ifdef AMD64 - if (pc == (address) FetchNPFI) { - uc->uc_mcontext.gregs[REG_PC] = intptr_t (FetchNResume) ; - return 1 ; - } -#endif // AMD64 #ifndef AMD64 // Halt if SI_KERNEL before more crashes get misdiagnosed as Java bugs diff --git a/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp b/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp index 939def32fec..4257f4e460b 100644 --- a/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp +++ b/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp @@ -303,11 +303,6 @@ bool os::is_allocatable(size_t bytes) { #endif } -extern "C" void Fetch32PFI () ; -extern "C" void Fetch32Resume () ; -extern "C" void FetchNPFI () ; -extern "C" void FetchNResume () ; - extern "C" JNIEXPORT int JVM_handle_solaris_signal(int sig, siginfo_t* info, void* ucVoid, int abort_if_unrecognized) { @@ -379,17 +374,10 @@ JVM_handle_solaris_signal(int sig, siginfo_t* info, void* ucVoid, npc = (address) uc->uc_mcontext.gregs[REG_nPC]; // SafeFetch() support - // Implemented with either a fixed set of addresses such - // as Fetch32*, or with Thread._OnTrap. - if (uc->uc_mcontext.gregs[REG_PC] == intptr_t(Fetch32PFI)) { - uc->uc_mcontext.gregs [REG_PC] = intptr_t(Fetch32Resume) ; - uc->uc_mcontext.gregs [REG_nPC] = intptr_t(Fetch32Resume) + 4 ; - return true ; - } - if (uc->uc_mcontext.gregs[REG_PC] == intptr_t(FetchNPFI)) { - uc->uc_mcontext.gregs [REG_PC] = intptr_t(FetchNResume) ; - uc->uc_mcontext.gregs [REG_nPC] = intptr_t(FetchNResume) + 4 ; - return true ; + if (StubRoutines::is_safefetch_fault(pc)) { + uc->uc_mcontext.gregs[REG_PC] = intptr_t(StubRoutines::continuation_for_safefetch_fault(pc)); + uc->uc_mcontext.gregs[REG_nPC] = uc->uc_mcontext.gregs[REG_PC] + 4; + return 1; } // Handle ALL stack overflow variations here diff --git a/hotspot/src/os_cpu/solaris_sparc/vm/solaris_sparc.s b/hotspot/src/os_cpu/solaris_sparc/vm/solaris_sparc.s index aa526a09d08..39aaa77f664 100644 --- a/hotspot/src/os_cpu/solaris_sparc/vm/solaris_sparc.s +++ b/hotspot/src/os_cpu/solaris_sparc/vm/solaris_sparc.s @@ -21,47 +21,6 @@ !! questions. !! - !! Prototype: int SafeFetch32 (int * adr, int ErrValue) - !! The "ld" at Fetch32 is potentially faulting instruction. - !! If the instruction traps the trap handler will arrange - !! for control to resume at Fetch32Resume. - !! By convention with the trap handler we ensure there is a non-CTI - !! instruction in the trap shadow. - !! - !! The reader might be tempted to move this service to .il. - !! Don't. Sun's CC back-end reads and optimize code emitted - !! by the .il "call", in some cases optimizing the code, completely eliding it, - !! or by moving the code from the "call site". - - !! ASM better know we may use G6 for our own purposes - .register %g6, #ignore - - .globl SafeFetch32 - .align 32 - .global Fetch32PFI, Fetch32Resume -SafeFetch32: - mov %o0, %g1 - mov %o1, %o0 -Fetch32PFI: - ld [%g1], %o0 !! <-- Potentially faulting instruction -Fetch32Resume: - nop - retl - nop - - .globl SafeFetchN - .align 32 - .globl FetchNPFI, FetchNResume -SafeFetchN: - mov %o0, %g1 - mov %o1, %o0 -FetchNPFI: - ldn [%g1], %o0 -FetchNResume: - nop - retl - nop - !! Possibilities: !! -- membar !! -- CAS (SP + BIAS, G0, G0) diff --git a/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp b/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp index 4ed094db734..f479ffbb193 100644 --- a/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp +++ b/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp @@ -352,13 +352,6 @@ bool os::is_allocatable(size_t bytes) { } -extern "C" void Fetch32PFI () ; -extern "C" void Fetch32Resume () ; -#ifdef AMD64 -extern "C" void FetchNPFI () ; -extern "C" void FetchNResume () ; -#endif // AMD64 - extern "C" JNIEXPORT int JVM_handle_solaris_signal(int sig, siginfo_t* info, void* ucVoid, int abort_if_unrecognized) { @@ -436,17 +429,10 @@ JVM_handle_solaris_signal(int sig, siginfo_t* info, void* ucVoid, // factor me: getPCfromContext pc = (address) uc->uc_mcontext.gregs[REG_PC]; - // SafeFetch32() support - if (pc == (address) Fetch32PFI) { - uc->uc_mcontext.gregs[REG_PC] = intptr_t(Fetch32Resume) ; - return true ; + if (StubRoutines::is_safefetch_fault(pc)) { + uc->uc_mcontext.gregs[REG_PC] = intptr_t(StubRoutines::continuation_for_safefetch_fault(pc)); + return true; } -#ifdef AMD64 - if (pc == (address) FetchNPFI) { - uc->uc_mcontext.gregs [REG_PC] = intptr_t(FetchNResume) ; - return true ; - } -#endif // AMD64 // Handle ALL stack overflow variations here if (sig == SIGSEGV && info->si_code == SEGV_ACCERR) { diff --git a/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_32.s b/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_32.s index 1fac3b25f11..19e790b6013 100644 --- a/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_32.s +++ b/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_32.s @@ -54,20 +54,6 @@ fixcw: popl %eax ret - .align 16 - .globl SafeFetch32 - .globl SafeFetchN - .globl Fetch32PFI, Fetch32Resume -SafeFetch32: -SafeFetchN: - movl 0x8(%esp), %eax - movl 0x4(%esp), %ecx -Fetch32PFI: - movl (%ecx), %eax -Fetch32Resume: - ret - - .align 16 .globl SpinPause SpinPause: diff --git a/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_64.s b/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_64.s index 95050af24f0..487b569e58c 100644 --- a/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_64.s +++ b/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_64.s @@ -21,54 +21,34 @@ / questions. / - .globl fs_load - .globl fs_thread + .globl fs_load + .globl fs_thread // NOTE WELL! The _Copy functions are called directly - // from server-compiler-generated code via CallLeafNoFP, - // which means that they *must* either not use floating - // point or use it in the same manner as does the server - // compiler. + // from server-compiler-generated code via CallLeafNoFP, + // which means that they *must* either not use floating + // point or use it in the same manner as does the server + // compiler. .globl _Copy_arrayof_conjoint_bytes .globl _Copy_conjoint_jshorts_atomic - .globl _Copy_arrayof_conjoint_jshorts + .globl _Copy_arrayof_conjoint_jshorts .globl _Copy_conjoint_jints_atomic .globl _Copy_arrayof_conjoint_jints - .globl _Copy_conjoint_jlongs_atomic + .globl _Copy_conjoint_jlongs_atomic .globl _Copy_arrayof_conjoint_jlongs - .section .text,"ax" + .section .text,"ax" / Fast thread accessors, used by threadLS_solaris_amd64.cpp - .align 16 + .align 16 fs_load: - movq %fs:(%rdi),%rax - ret - - .align 16 -fs_thread: - movq %fs:0x0,%rax - ret - - .globl SafeFetch32, Fetch32PFI, Fetch32Resume - .align 16 - // Prototype: int SafeFetch32 (int * Adr, int ErrValue) -SafeFetch32: - movl %esi, %eax -Fetch32PFI: - movl (%rdi), %eax -Fetch32Resume: + movq %fs:(%rdi),%rax ret - .globl SafeFetchN, FetchNPFI, FetchNResume - .align 16 - // Prototype: intptr_t SafeFetchN (intptr_t * Adr, intptr_t ErrValue) -SafeFetchN: - movq %rsi, %rax -FetchNPFI: - movq (%rdi), %rax -FetchNResume: + .align 16 +fs_thread: + movq %fs:0x0,%rax ret .globl SpinPause @@ -78,7 +58,7 @@ SpinPause: nop movq $1, %rax ret - + / Support for void Copy::arrayof_conjoint_bytes(void* from, / void* to, @@ -340,7 +320,7 @@ aci_CopyLeft: addq $4,%rdx jg 1b ret - + / Support for void Copy::arrayof_conjoint_jlongs(jlong* from, / jlong* to, / size_t count) diff --git a/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp b/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp index 1ef29f99a55..a0f2a7680be 100644 --- a/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp +++ b/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp @@ -518,24 +518,6 @@ void os::print_register_info(outputStream *st, void *context) { st->cr(); } -extern "C" int SafeFetch32 (int * adr, int Err) { - int rv = Err ; - _try { - rv = *((volatile int *) adr) ; - } __except(EXCEPTION_EXECUTE_HANDLER) { - } - return rv ; -} - -extern "C" intptr_t SafeFetchN (intptr_t * adr, intptr_t Err) { - intptr_t rv = Err ; - _try { - rv = *((volatile intptr_t *) adr) ; - } __except(EXCEPTION_EXECUTE_HANDLER) { - } - return rv ; -} - extern "C" int SpinPause () { #ifdef AMD64 return 0 ; diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp index 3bd04281955..4c6d2bbf877 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp +++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp @@ -873,7 +873,7 @@ bool G1CollectorPolicy::need_to_start_conc_mark(const char* source, size_t alloc size_t alloc_byte_size = alloc_word_size * HeapWordSize; if ((cur_used_bytes + alloc_byte_size) > marking_initiating_used_threshold) { - if (gcs_are_young()) { + if (gcs_are_young() && !_last_young_gc) { ergo_verbose5(ErgoConcCycles, "request concurrent cycle initiation", ergo_format_reason("occupancy higher than threshold") @@ -931,7 +931,7 @@ void G1CollectorPolicy::record_collection_pause_end(double pause_time_ms, Evacua last_pause_included_initial_mark = during_initial_mark_pause(); if (last_pause_included_initial_mark) { record_concurrent_mark_init_end(0.0); - } else if (!_last_young_gc && need_to_start_conc_mark("end of GC")) { + } else if (need_to_start_conc_mark("end of GC")) { // Note: this might have already been set, if during the last // pause we decided to start a cycle but at the beginning of // this pause we decided to postpone it. That's OK. diff --git a/hotspot/src/share/vm/runtime/os.hpp b/hotspot/src/share/vm/runtime/os.hpp index 0d0e59efa4b..6078a21181c 100644 --- a/hotspot/src/share/vm/runtime/os.hpp +++ b/hotspot/src/share/vm/runtime/os.hpp @@ -915,8 +915,6 @@ class os: AllStatic { // of the global SpinPause() with C linkage. // It'd also be eligible for inlining on many platforms. -extern "C" int SpinPause () ; -extern "C" int SafeFetch32 (int * adr, int errValue) ; -extern "C" intptr_t SafeFetchN (intptr_t * adr, intptr_t errValue) ; +extern "C" int SpinPause(); #endif // SHARE_VM_RUNTIME_OS_HPP diff --git a/hotspot/src/share/vm/runtime/stubRoutines.cpp b/hotspot/src/share/vm/runtime/stubRoutines.cpp index a1179acd543..ff12ca65163 100644 --- a/hotspot/src/share/vm/runtime/stubRoutines.cpp +++ b/hotspot/src/share/vm/runtime/stubRoutines.cpp @@ -136,6 +136,13 @@ double (* StubRoutines::_intrinsic_sin )(double) = NULL; double (* StubRoutines::_intrinsic_cos )(double) = NULL; double (* StubRoutines::_intrinsic_tan )(double) = NULL; +address StubRoutines::_safefetch32_entry = NULL; +address StubRoutines::_safefetch32_fault_pc = NULL; +address StubRoutines::_safefetch32_continuation_pc = NULL; +address StubRoutines::_safefetchN_entry = NULL; +address StubRoutines::_safefetchN_fault_pc = NULL; +address StubRoutines::_safefetchN_continuation_pc = NULL; + // Initialization // // Note: to break cycle with universe initialization, stubs are generated in two phases. diff --git a/hotspot/src/share/vm/runtime/stubRoutines.hpp b/hotspot/src/share/vm/runtime/stubRoutines.hpp index b8d61ea0cbf..e43e3ab0e7b 100644 --- a/hotspot/src/share/vm/runtime/stubRoutines.hpp +++ b/hotspot/src/share/vm/runtime/stubRoutines.hpp @@ -221,6 +221,14 @@ class StubRoutines: AllStatic { static double (*_intrinsic_cos)(double); static double (*_intrinsic_tan)(double); + // Safefetch stubs. + static address _safefetch32_entry; + static address _safefetch32_fault_pc; + static address _safefetch32_continuation_pc; + static address _safefetchN_entry; + static address _safefetchN_fault_pc; + static address _safefetchN_continuation_pc; + public: // Initialization/Testing static void initialize1(); // must happen before universe::genesis @@ -381,6 +389,34 @@ class StubRoutines: AllStatic { return _intrinsic_tan(d); } + // + // Safefetch stub support + // + + typedef int (*SafeFetch32Stub)(int* adr, int errValue); + typedef intptr_t (*SafeFetchNStub) (intptr_t* adr, intptr_t errValue); + + static SafeFetch32Stub SafeFetch32_stub() { return CAST_TO_FN_PTR(SafeFetch32Stub, _safefetch32_entry); } + static SafeFetchNStub SafeFetchN_stub() { return CAST_TO_FN_PTR(SafeFetchNStub, _safefetchN_entry); } + + static bool is_safefetch_fault(address pc) { + return pc != NULL && + (pc == _safefetch32_fault_pc || + pc == _safefetchN_fault_pc); + } + + static address continuation_for_safefetch_fault(address pc) { + assert(_safefetch32_continuation_pc != NULL && + _safefetchN_continuation_pc != NULL, + "not initialized"); + + if (pc == _safefetch32_fault_pc) return _safefetch32_continuation_pc; + if (pc == _safefetchN_fault_pc) return _safefetchN_continuation_pc; + + ShouldNotReachHere(); + return NULL; + } + // // Default versions of the above arraycopy functions for platforms which do // not have specialized versions @@ -400,4 +436,15 @@ class StubRoutines: AllStatic { static void arrayof_oop_copy_uninit(HeapWord* src, HeapWord* dest, size_t count); }; +// Safefetch allows to load a value from a location that's not known +// to be valid. If the load causes a fault, the error value is returned. +inline int SafeFetch32(int* adr, int errValue) { + assert(StubRoutines::SafeFetch32_stub(), "stub not yet generated"); + return StubRoutines::SafeFetch32_stub()(adr, errValue); +} +inline intptr_t SafeFetchN(intptr_t* adr, intptr_t errValue) { + assert(StubRoutines::SafeFetchN_stub(), "stub not yet generated"); + return StubRoutines::SafeFetchN_stub()(adr, errValue); +} + #endif // SHARE_VM_RUNTIME_STUBROUTINES_HPP diff --git a/hotspot/src/share/vm/services/memTracker.cpp b/hotspot/src/share/vm/services/memTracker.cpp index e0a1b29a8e9..353e6a17fa4 100644 --- a/hotspot/src/share/vm/services/memTracker.cpp +++ b/hotspot/src/share/vm/services/memTracker.cpp @@ -81,13 +81,13 @@ void MemTracker::init_tracking_options(const char* option_line) { } else if (strcmp(option_line, "=detail") == 0) { // detail relies on a stack-walking ability that may not // be available depending on platform and/or compiler flags - if (PLATFORM_NMT_DETAIL_SUPPORTED) { +#if PLATFORM_NATIVE_STACK_WALKING_SUPPORTED _tracking_level = NMT_detail; - } else { +#else jio_fprintf(defaultStream::error_stream(), - "NMT detail is not supported on this platform. Using NMT summary instead."); + "NMT detail is not supported on this platform. Using NMT summary instead.\n"); _tracking_level = NMT_summary; - } +#endif } else if (strcmp(option_line, "=off") != 0) { vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL); } diff --git a/hotspot/src/share/vm/utilities/globalDefinitions.hpp b/hotspot/src/share/vm/utilities/globalDefinitions.hpp index e7f3f3f7080..181e80a0823 100644 --- a/hotspot/src/share/vm/utilities/globalDefinitions.hpp +++ b/hotspot/src/share/vm/utilities/globalDefinitions.hpp @@ -381,12 +381,12 @@ const uint64_t KlassEncodingMetaspaceMax = (uint64_t(max_juint) + 1) << LogKlass #endif /* - * If a platform does not support NMT_detail + * If a platform does not support native stack walking * the platform specific globalDefinitions (above) - * can set PLATFORM_NMT_DETAIL_SUPPORTED to false + * can set PLATFORM_NATIVE_STACK_WALKING_SUPPORTED to 0 */ -#ifndef PLATFORM_NMT_DETAIL_SUPPORTED -#define PLATFORM_NMT_DETAIL_SUPPORTED true +#ifndef PLATFORM_NATIVE_STACK_WALKING_SUPPORTED +#define PLATFORM_NATIVE_STACK_WALKING_SUPPORTED 1 #endif // The byte alignment to be used by Arena::Amalloc. See bugid 4169348. diff --git a/jdk/.hgtags b/jdk/.hgtags index 45fbf746c13..3bdc713a8d4 100644 --- a/jdk/.hgtags +++ b/jdk/.hgtags @@ -220,3 +220,4 @@ a2a2a91075ad85becbe10a39d7fd04ef9bea8df5 jdk8-b92 4a5d3cf2b3af1660db0237e8da324c140e534fa4 jdk8-b96 978a95239044f26dcc8a6d59246be07ad6ca6be2 jdk8-b97 c4908732fef5235f1b98cafe0ce507771ef7892c jdk8-b98 +6a099a36589bd933957272ba63e5263bede29971 jdk8-b99 diff --git a/jdk/make/sun/security/pkcs11/mapfile-vers b/jdk/make/sun/security/pkcs11/mapfile-vers index 7301c11417d..dfd2e34e74a 100644 --- a/jdk/make/sun/security/pkcs11/mapfile-vers +++ b/jdk/make/sun/security/pkcs11/mapfile-vers @@ -102,7 +102,7 @@ SUNWprivate_1.1 { Java_sun_security_pkcs11_Secmod_nssGetLibraryHandle; Java_sun_security_pkcs11_Secmod_nssLoadLibrary; Java_sun_security_pkcs11_Secmod_nssVersionCheck; - Java_sun_security_pkcs11_Secmod_nssInit; + Java_sun_security_pkcs11_Secmod_nssInitialize; Java_sun_security_pkcs11_Secmod_nssGetModuleList; local: diff --git a/jdk/makefiles/mapfiles/libj2pkcs11/mapfile-vers b/jdk/makefiles/mapfiles/libj2pkcs11/mapfile-vers index 7301c11417d..6ca76c07047 100644 --- a/jdk/makefiles/mapfiles/libj2pkcs11/mapfile-vers +++ b/jdk/makefiles/mapfiles/libj2pkcs11/mapfile-vers @@ -1,5 +1,5 @@ # -# Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -102,7 +102,7 @@ SUNWprivate_1.1 { Java_sun_security_pkcs11_Secmod_nssGetLibraryHandle; Java_sun_security_pkcs11_Secmod_nssLoadLibrary; Java_sun_security_pkcs11_Secmod_nssVersionCheck; - Java_sun_security_pkcs11_Secmod_nssInit; + Java_sun_security_pkcs11_Secmod_nssInitialize; Java_sun_security_pkcs11_Secmod_nssGetModuleList; local: diff --git a/jdk/src/macosx/classes/com/apple/eawt/FullScreenHandler.java b/jdk/src/macosx/classes/com/apple/eawt/FullScreenHandler.java index f5a843bcdbf..64e81b08a00 100644 --- a/jdk/src/macosx/classes/com/apple/eawt/FullScreenHandler.java +++ b/jdk/src/macosx/classes/com/apple/eawt/FullScreenHandler.java @@ -32,6 +32,7 @@ import java.util.List; import javax.swing.RootPaneContainer; import com.apple.eawt.AppEvent.FullScreenEvent; +import sun.awt.SunToolkit; import java.lang.annotation.Native; @@ -75,7 +76,7 @@ final class FullScreenHandler { static void handleFullScreenEventFromNative(final Window window, final int type) { if (!(window instanceof RootPaneContainer)) return; // handles null - EventQueue.invokeLater(new Runnable() { + SunToolkit.executeOnEventHandlerThread(window, new Runnable() { public void run() { final FullScreenHandler handler = getHandlerFor((RootPaneContainer)window); if (handler != null) handler.notifyListener(new FullScreenEvent(window), type); diff --git a/jdk/src/macosx/classes/com/apple/eawt/_AppEventHandler.java b/jdk/src/macosx/classes/com/apple/eawt/_AppEventHandler.java index a380e8412fd..b98d5739510 100644 --- a/jdk/src/macosx/classes/com/apple/eawt/_AppEventHandler.java +++ b/jdk/src/macosx/classes/com/apple/eawt/_AppEventHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,6 +31,8 @@ import java.io.File; import java.net.*; import java.util.*; import java.util.List; +import sun.awt.AppContext; +import sun.awt.SunToolkit; import com.apple.eawt.AppEvent.*; @@ -269,11 +271,9 @@ class _AppEventHandler { } class _AppReOpenedDispatcher extends _AppEventMultiplexor { - void performOnListeners(final List listeners, final _NativeEvent event) { + void performOnListener(AppReOpenedListener listener, final _NativeEvent event) { final AppReOpenedEvent e = new AppReOpenedEvent(); - for (final AppReOpenedListener listener : listeners) { - listener.appReOpened(e); - } + listener.appReOpened(e); } } @@ -415,50 +415,67 @@ class _AppEventHandler { } abstract class _AppEventMultiplexor { - final List _listeners = new ArrayList(0); + private final Map listenerToAppContext = + new IdentityHashMap(); boolean nativeListenerRegistered; // called from AppKit Thread-0 void dispatch(final _NativeEvent event, final Object... args) { - // grab a local ref to the listeners - final List localListeners; + // grab a local ref to the listeners and its contexts as an array of the map's entries + final ArrayList> localEntries; synchronized (this) { - if (_listeners.size() == 0) return; - localListeners = new ArrayList(_listeners); + if (listenerToAppContext.size() == 0) { + return; + } + localEntries = new ArrayList>(listenerToAppContext.size()); + localEntries.addAll(listenerToAppContext.entrySet()); } - EventQueue.invokeLater(new Runnable() { - public void run() { - performOnListeners(localListeners, event); - } - }); + for (final Map.Entry e : localEntries) { + final L listener = e.getKey(); + final AppContext listenerContext = e.getValue(); + SunToolkit.invokeLaterOnAppContext(listenerContext, new Runnable() { + public void run() { + performOnListener(listener, event); + } + }); + } } synchronized void addListener(final L listener) { + setListenerContext(listener, AppContext.getAppContext()); + if (!nativeListenerRegistered) { registerNativeListener(); nativeListenerRegistered = true; } - _listeners.add(listener); } synchronized void removeListener(final L listener) { - _listeners.remove(listener); + listenerToAppContext.remove(listener); } - abstract void performOnListeners(final List listeners, final _NativeEvent event); + abstract void performOnListener(L listener, final _NativeEvent event); void registerNativeListener() { } + + private void setListenerContext(L listener, AppContext listenerContext) { + if (listenerContext == null) { + throw new RuntimeException( + "Attempting to add a listener from a thread group without AppContext"); + } + listenerToAppContext.put(listener, AppContext.getAppContext()); + } } abstract class _BooleanAppEventMultiplexor extends _AppEventMultiplexor { @Override - void performOnListeners(final List listeners, final _NativeEvent event) { + void performOnListener(L listener, final _NativeEvent event) { final boolean isTrue = Boolean.TRUE.equals(event.get(0)); final E e = createEvent(isTrue); if (isTrue) { - for (final L listener : listeners) performTrueEventOn(listener, e); + performTrueEventOn(listener, e); } else { - for (final L listener : listeners) performFalseEventOn(listener, e); + performFalseEventOn(listener, e); } } @@ -479,30 +496,34 @@ class _AppEventHandler { */ abstract class _AppEventDispatcher { H _handler; + AppContext handlerContext; // called from AppKit Thread-0 void dispatch(final _NativeEvent event) { - EventQueue.invokeLater(new Runnable() { - public void run() { - // grab a local ref to the handler - final H localHandler; - synchronized (_AppEventDispatcher.this) { - localHandler = _handler; - } + // grab a local ref to the handler + final H localHandler; + final AppContext localHandlerContext; + synchronized (_AppEventDispatcher.this) { + localHandler = _handler; + localHandlerContext = handlerContext; + } - // invoke the handler outside of the synchronized block - if (localHandler == null) { - performDefaultAction(event); - } else { + if (localHandler == null) { + performDefaultAction(event); + } else { + SunToolkit.invokeLaterOnAppContext(localHandlerContext, new Runnable() { + public void run() { performUsing(localHandler, event); } - } - }); + }); + } } synchronized void setHandler(final H handler) { this._handler = handler; + setHandlerContext(AppContext.getAppContext()); + // if a new handler is installed, block addition of legacy ApplicationListeners if (handler == legacyHandler) return; legacyHandler.blockLegacyAPI(); @@ -510,6 +531,15 @@ class _AppEventHandler { void performDefaultAction(final _NativeEvent event) { } // by default, do nothing abstract void performUsing(final H handler, final _NativeEvent event); + + protected void setHandlerContext(AppContext ctx) { + if (ctx == null) { + throw new RuntimeException( + "Attempting to set a handler from a thread group without AppContext"); + } + + handlerContext = ctx; + } } abstract class _QueuingAppEventDispatcher extends _AppEventDispatcher { @@ -531,6 +561,8 @@ class _AppEventHandler { synchronized void setHandler(final H handler) { this._handler = handler; + setHandlerContext(AppContext.getAppContext()); + // dispatch any events in the queue if (queuedEvents != null) { // grab a local ref to the queue, so the real one can be nulled out diff --git a/jdk/src/macosx/classes/com/apple/eawt/event/GestureHandler.java b/jdk/src/macosx/classes/com/apple/eawt/event/GestureHandler.java index 1378a2c808e..4514da90ca9 100644 --- a/jdk/src/macosx/classes/com/apple/eawt/event/GestureHandler.java +++ b/jdk/src/macosx/classes/com/apple/eawt/event/GestureHandler.java @@ -25,6 +25,8 @@ package com.apple.eawt.event; +import sun.awt.SunToolkit; + import java.awt.*; import java.util.*; import java.util.List; @@ -70,7 +72,7 @@ final class GestureHandler { static void handleGestureFromNative(final Window window, final int type, final double x, final double y, final double a, final double b) { if (window == null) return; // should never happen... - EventQueue.invokeLater(new Runnable() { + SunToolkit.executeOnEventHandlerThread(window, new Runnable() { public void run() { final Component component = SwingUtilities.getDeepestComponentAt(window, (int)x, (int)y); diff --git a/jdk/src/macosx/classes/com/apple/laf/ScreenMenu.java b/jdk/src/macosx/classes/com/apple/laf/ScreenMenu.java index 23c55c8d2a1..5f78ff6e061 100644 --- a/jdk/src/macosx/classes/com/apple/laf/ScreenMenu.java +++ b/jdk/src/macosx/classes/com/apple/laf/ScreenMenu.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,6 +32,7 @@ import java.util.Hashtable; import javax.swing.*; +import sun.awt.SunToolkit; import sun.lwawt.LWToolkit; import sun.lwawt.macosx.*; @@ -144,7 +145,7 @@ class ScreenMenu extends Menu implements ContainerListener, ComponentListener, S updateItems(); fItemBounds = new Rectangle[invoker.getMenuComponentCount()]; } - }, null); + }, invoker); } catch (final Exception e) { System.err.println(e); e.printStackTrace(); @@ -172,7 +173,7 @@ class ScreenMenu extends Menu implements ContainerListener, ComponentListener, S fItemBounds = null; } - }, null); + }, invoker); } catch (final Exception e) { e.printStackTrace(); } @@ -200,7 +201,7 @@ class ScreenMenu extends Menu implements ContainerListener, ComponentListener, S if (kind == 0) return; if (fItemBounds == null) return; - SwingUtilities.invokeLater(new Runnable() { + SunToolkit.executeOnEventHandlerThread(fInvoker, new Runnable() { @Override public void run() { Component target = null; diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CCheckboxMenuItem.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CCheckboxMenuItem.java index 9b59ceaef9b..da53c302ad5 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CCheckboxMenuItem.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CCheckboxMenuItem.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -53,7 +53,7 @@ public class CCheckboxMenuItem extends CMenuItem implements CheckboxMenuItemPeer public void handleAction(final boolean state) { final CheckboxMenuItem target = (CheckboxMenuItem)getTarget(); - EventQueue.invokeLater(new Runnable() { + SunToolkit.executeOnEventHandlerThread(target, new Runnable() { public void run() { target.setState(state); } diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java index 0c0f3e7f1df..c46cb52e19e 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java @@ -107,10 +107,6 @@ public final class CDragSourceContextPeer extends SunDragSourceContextPeer { loc = rootComponent.getLocation(); } - //It sure will be LWComponentPeer instance as rootComponent is a Window - PlatformWindow platformWindow = ((LWComponentPeer)rootComponent.getPeer()).getPlatformWindow(); - long nativeViewPtr = CPlatformWindow.getNativeViewPtr(platformWindow); - // If there isn't any drag image make one of default appearance: if (fDragImage == null) this.setDefaultDragImage(component); @@ -137,6 +133,11 @@ public final class CDragSourceContextPeer extends SunDragSourceContextPeer { } try { + //It sure will be LWComponentPeer instance as rootComponent is a Window + PlatformWindow platformWindow = ((LWComponentPeer)rootComponent.getPeer()).getPlatformWindow(); + long nativeViewPtr = CPlatformWindow.getNativeViewPtr(platformWindow); + if (nativeViewPtr == 0L) throw new InvalidDnDOperationException("Unsupported platform window implementation"); + // Create native dragging source: final long nativeDragSource = createNativeDragSource(component, nativeViewPtr, transferable, triggerEvent, (int) (dragOrigin.getX()), (int) (dragOrigin.getY()), extModifiers, diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CDropTarget.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CDropTarget.java index 1448424e0ee..7db8c5f52ab 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CDropTarget.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CDropTarget.java @@ -52,6 +52,8 @@ public final class CDropTarget { fPeer = peer; long nativePeer = CPlatformWindow.getNativeViewPtr(((LWComponentPeer) peer).getPlatformWindow()); + if (nativePeer == 0L) return; // Unsupported for a window without a native view (plugin) + // Create native dragging destination: fNativeDropTarget = this.createNativeDropTarget(dropTarget, component, peer, nativePeer); if (fNativeDropTarget == 0) { diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java index 7230b2eeeb5..124e8f73998 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java @@ -479,12 +479,14 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo deliverZoom(true); this.normalBounds = peer.getBounds(); - long screen = CWrapper.NSWindow.screen(getNSWindowPtr()); - Rectangle toBounds = CWrapper.NSScreen.visibleFrame(screen).getBounds(); - // Flip the y coordinate - Rectangle frame = CWrapper.NSScreen.frame(screen).getBounds(); - toBounds.y = frame.height - toBounds.y - toBounds.height; - setBounds(toBounds.x, toBounds.y, toBounds.width, toBounds.height); + + GraphicsConfiguration config = getPeer().getGraphicsConfiguration(); + Insets i = ((CGraphicsDevice)config.getDevice()).getScreenInsets(); + Rectangle toBounds = config.getBounds(); + setBounds(toBounds.x + i.left, + toBounds.y + i.top, + toBounds.width - i.left - i.right, + toBounds.height - i.top - i.bottom); } } @@ -751,13 +753,7 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo // the move/size notification from the underlying system comes // but it contains a bounds smaller than the whole screen // and therefore we need to create the synthetic notifications - Rectangle screenBounds; - final long screenPtr = CWrapper.NSWindow.screen(getNSWindowPtr()); - try { - screenBounds = CWrapper.NSScreen.frame(screenPtr).getBounds(); - } finally { - CWrapper.NSObject.release(screenPtr); - } + Rectangle screenBounds = getPeer().getGraphicsConfiguration().getBounds(); peer.notifyReshape(screenBounds.x, screenBounds.y, screenBounds.width, screenBounds.height); } @@ -900,8 +896,6 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo nativePeer = ((CPlatformWindow) platformWindow).getContentView().getAWTView(); } else if (platformWindow instanceof CViewPlatformEmbeddedFrame){ nativePeer = ((CViewPlatformEmbeddedFrame) platformWindow).getNSViewPtr(); - } else { - throw new IllegalArgumentException("Unsupported platformWindow implementation"); } return nativePeer; } @@ -932,25 +926,19 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo final Rectangle oldB = nativeBounds; nativeBounds = new Rectangle(x, y, width, height); - final GraphicsConfiguration oldGC = peer.getGraphicsConfiguration(); - - final GraphicsConfiguration newGC = peer.getGraphicsConfiguration(); - // System-dependent appearance optimization. if (peer != null) { peer.notifyReshape(x, y, width, height); - } - - if ((byUser && !oldB.getSize().equals(nativeBounds.getSize())) - || isFullScreenAnimationOn || !Objects.equals(newGC, oldGC)) { - flushBuffers(); + // System-dependent appearance optimization. + if ((byUser && !oldB.getSize().equals(nativeBounds.getSize())) + || isFullScreenAnimationOn) { + flushBuffers(); + } } } private void deliverWindowClosingEvent() { - if (peer != null) { - if (peer.getBlocker() == null) { - peer.postEvent(new WindowEvent(target, WindowEvent.WINDOW_CLOSING)); - } + if (peer != null && peer.getBlocker() == null) { + peer.postEvent(new WindowEvent(target, WindowEvent.WINDOW_CLOSING)); } } diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CViewEmbeddedFrame.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CViewEmbeddedFrame.java index 306cfb1e12e..28acc26f6cc 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CViewEmbeddedFrame.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CViewEmbeddedFrame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -96,7 +96,7 @@ public class CViewEmbeddedFrame extends EmbeddedFrame { validate(); setVisible(true); } - }, null); + }, this); } catch (InterruptedException | InvocationTargetException ex) {} } } diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CWrapper.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CWrapper.java index 67d3ea1cf1f..7dc421e26b1 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CWrapper.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CWrapper.java @@ -71,8 +71,6 @@ public final class CWrapper { public static native void zoom(long window); public static native void makeFirstResponder(long window, long responder); - - public static native long screen(long window); } public static final class NSView { @@ -95,12 +93,6 @@ public final class CWrapper { public static native void release(long object); } - public static final class NSScreen { - public static native Rectangle2D frame(long screen); - public static native Rectangle2D visibleFrame(long screen); - public static native long screenByDisplayId(int displayID); - } - public static final class NSColor { public static native long clearColor(); } diff --git a/jdk/src/macosx/native/sun/awt/CMenuItem.m b/jdk/src/macosx/native/sun/awt/CMenuItem.m index eaabb3e06ab..0d1ade68ab6 100644 --- a/jdk/src/macosx/native/sun/awt/CMenuItem.m +++ b/jdk/src/macosx/native/sun/awt/CMenuItem.m @@ -82,8 +82,13 @@ JNF_COCOA_ENTER(env); // keys, so we need to do the same translation here that we do // for the regular key down events if ([eventKey length] == 1) { - unichar ch = NsCharToJavaChar([eventKey characterAtIndex:0], 0); - eventKey = [NSString stringWithCharacters: &ch length: 1]; + unichar origChar = [eventKey characterAtIndex:0]; + unichar newChar = NsCharToJavaChar(origChar, 0); + if (newChar == java_awt_event_KeyEvent_CHAR_UNDEFINED) { + newChar = origChar; + } + + eventKey = [NSString stringWithCharacters: &newChar length: 1]; } if ([menuKey isEqualToString:eventKey]) { diff --git a/jdk/src/macosx/native/sun/awt/CWrapper.m b/jdk/src/macosx/native/sun/awt/CWrapper.m index bef1d47cb9f..ccc688e802d 100644 --- a/jdk/src/macosx/native/sun/awt/CWrapper.m +++ b/jdk/src/macosx/native/sun/awt/CWrapper.m @@ -396,31 +396,6 @@ JNF_COCOA_ENTER(env); JNF_COCOA_EXIT(env); } -/* - * Class: sun_lwawt_macosx_CWrapper$NSWindow - * Method: screen - * Signature: (J)J - */ -JNIEXPORT jlong JNICALL -Java_sun_lwawt_macosx_CWrapper_00024NSWindow_screen -(JNIEnv *env, jclass cls, jlong windowPtr) -{ - __block jlong screenPtr = 0L; - -JNF_COCOA_ENTER(env); - - AWTWindow *window = (AWTWindow *)jlong_to_ptr(windowPtr); - [ThreadUtilities performOnMainThreadWaiting:YES block:^(){ - const NSScreen *screen = [window screen]; - CFRetain(screen); // GC - screenPtr = ptr_to_jlong(screen); - }]; - -JNF_COCOA_EXIT(env); - - return screenPtr; -} - /* * Method: miniaturize * Signature: (J)V @@ -690,92 +665,6 @@ JNF_COCOA_ENTER(env); JNF_COCOA_EXIT(env); } - -/* - * Class: sun_lwawt_macosx_CWrapper$NSScreen - * Method: frame - * Signature: (J)Ljava/awt/Rectangle; - */ -JNIEXPORT jobject JNICALL -Java_sun_lwawt_macosx_CWrapper_00024NSScreen_frame -(JNIEnv *env, jclass cls, jlong screenPtr) -{ - jobject jRect = NULL; - -JNF_COCOA_ENTER(env); - - __block NSRect rect = NSZeroRect; - - NSScreen *screen = (NSScreen *)jlong_to_ptr(screenPtr); - [ThreadUtilities performOnMainThreadWaiting:YES block:^(){ - rect = [screen frame]; - }]; - - jRect = NSToJavaRect(env, rect); - -JNF_COCOA_EXIT(env); - - return jRect; -} - -/* - * Class: sun_lwawt_macosx_CWrapper_NSScreen - * Method: visibleFrame - * Signature: (J)Ljava/awt/geom/Rectangle2D; - */ -JNIEXPORT jobject JNICALL -Java_sun_lwawt_macosx_CWrapper_00024NSScreen_visibleFrame -(JNIEnv *env, jclass cls, jlong screenPtr) -{ - jobject jRect = NULL; - -JNF_COCOA_ENTER(env); - - __block NSRect rect = NSZeroRect; - - NSScreen *screen = (NSScreen *)jlong_to_ptr(screenPtr); - [ThreadUtilities performOnMainThreadWaiting:YES block:^(){ - rect = [screen visibleFrame]; - }]; - - jRect = NSToJavaRect(env, rect); - -JNF_COCOA_EXIT(env); - - return jRect; -} - -/* - * Class: sun_lwawt_macosx_CWrapper_NSScreen - * Method: screenByDisplayId - * Signature: (J)J - */ -JNIEXPORT jlong JNICALL -Java_sun_lwawt_macosx_CWrapper_00024NSScreen_screenByDisplayId -(JNIEnv *env, jclass cls, jint displayID) -{ - __block jlong screenPtr = 0L; - -JNF_COCOA_ENTER(env); - - [ThreadUtilities performOnMainThreadWaiting:YES block:^(){ - NSArray *screens = [NSScreen screens]; - for (NSScreen *screen in screens) { - NSDictionary *screenInfo = [screen deviceDescription]; - NSNumber *screenID = [screenInfo objectForKey:@"NSScreenNumber"]; - if ([screenID intValue] == displayID){ - CFRetain(screen); // GC - screenPtr = ptr_to_jlong(screen); - break; - } - } - }]; - -JNF_COCOA_EXIT(env); - - return screenPtr; -} - /* * Class: sun_lwawt_macosx_CWrapper$NSColor * Method: clearColor diff --git a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility.properties b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility.properties index 384409f726d..fd7314333e9 100644 --- a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility.properties +++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility.properties @@ -102,7 +102,7 @@ horizontal=horizontal # # accessible actions # -toggle expand=toggle expand +toggleexpand=toggle expand # new relations, roles and states for J2SE 1.5.0 diff --git a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_de.properties b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_de.properties index 1cedaeb67c2..fe0f918d9bf 100644 --- a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_de.properties +++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_de.properties @@ -102,7 +102,7 @@ horizontal=horizontal # # accessible actions # -toggle expand=ein-/ausblenden +toggleexpand=ein-/ausblenden # new relations, roles and states for J2SE 1.5.0 diff --git a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_es.properties b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_es.properties index b1e2e9ba1ea..c3f90416a30 100644 --- a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_es.properties +++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_es.properties @@ -102,7 +102,7 @@ horizontal=horizontal # # accessible actions # -toggle expand=activar/desactivar ampliaci\u00F3n +toggleexpand=activar/desactivar ampliaci\u00F3n # new relations, roles and states for J2SE 1.5.0 diff --git a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_fr.properties b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_fr.properties index f41a5427605..c399d9a0b32 100644 --- a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_fr.properties +++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_fr.properties @@ -102,7 +102,7 @@ horizontal=horizontal # # accessible actions # -toggle expand=basculer le d\u00E9veloppement +toggleexpand=basculer le d\u00E9veloppement # new relations, roles and states for J2SE 1.5.0 diff --git a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_it.properties b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_it.properties index 2d5cfa39504..94eefb0a2a3 100644 --- a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_it.properties +++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_it.properties @@ -102,7 +102,7 @@ horizontal=orizzontale # # accessible actions # -toggle expand=abilita/disabilita espansione +toggleexpand=abilita/disabilita espansione # new relations, roles and states for J2SE 1.5.0 diff --git a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ja.properties b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ja.properties index e266fff6723..eefc1784ba8 100644 --- a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ja.properties +++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ja.properties @@ -102,7 +102,7 @@ horizontal=\u6C34\u5E73 # # accessible actions # -toggle expand=\u5C55\u958B\u306E\u30C8\u30B0\u30EB +toggleexpand=\u5C55\u958B\u306E\u30C8\u30B0\u30EB # new relations, roles and states for J2SE 1.5.0 diff --git a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ko.properties b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ko.properties index 1a3da2e1b79..530caa68999 100644 --- a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ko.properties +++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ko.properties @@ -102,7 +102,7 @@ horizontal=\uAC00\uB85C # # accessible actions # -toggle expand=\uD1A0\uAE00 \uD655\uC7A5 +toggleexpand=\uD1A0\uAE00 \uD655\uC7A5 # new relations, roles and states for J2SE 1.5.0 diff --git a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_pt_BR.properties b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_pt_BR.properties index cdae36aaaaa..f8aaf355040 100644 --- a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_pt_BR.properties +++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_pt_BR.properties @@ -102,7 +102,7 @@ horizontal=horizontal # # accessible actions # -toggle expand=alternar expans\u00E3o +toggleexpand=alternar expans\u00E3o # new relations, roles and states for J2SE 1.5.0 diff --git a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_sv.properties b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_sv.properties index 553098d8289..962b9d35dc5 100644 --- a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_sv.properties +++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_sv.properties @@ -102,7 +102,7 @@ horizontal=horisontell # # accessible actions # -toggle expand=v\u00E4xla ut\u00F6ka +toggleexpand=v\u00E4xla ut\u00F6ka # new relations, roles and states for J2SE 1.5.0 diff --git a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_zh_CN.properties b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_zh_CN.properties index 0a117037660..da67e241eba 100644 --- a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_zh_CN.properties +++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_zh_CN.properties @@ -102,7 +102,7 @@ horizontal=\u6C34\u5E73 # # accessible actions # -toggle expand=\u5207\u6362\u5C55\u5F00 +toggleexpand=\u5207\u6362\u5C55\u5F00 # new relations, roles and states for J2SE 1.5.0 diff --git a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_zh_TW.properties b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_zh_TW.properties index f4d11b45411..1de30c27f89 100644 --- a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_zh_TW.properties +++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_zh_TW.properties @@ -102,7 +102,7 @@ horizontal=\u6C34\u5E73 # # accessible actions # -toggle expand=\u5207\u63DB\u64F4\u5C55 +toggleexpand=\u5207\u63DB\u64F4\u5C55 # new relations, roles and states for J2SE 1.5.0 diff --git a/jdk/src/share/classes/com/sun/crypto/provider/DESKeyFactory.java b/jdk/src/share/classes/com/sun/crypto/provider/DESKeyFactory.java index 47f0b26a27d..f51de29ba8b 100644 --- a/jdk/src/share/classes/com/sun/crypto/provider/DESKeyFactory.java +++ b/jdk/src/share/classes/com/sun/crypto/provider/DESKeyFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,6 +31,7 @@ import javax.crypto.spec.DESKeySpec; import java.security.InvalidKeyException; import java.security.spec.KeySpec; import java.security.spec.InvalidKeySpecException; +import javax.crypto.spec.SecretKeySpec; /** * This class implements the DES key factory of the Sun provider. @@ -60,20 +61,22 @@ public final class DESKeyFactory extends SecretKeyFactorySpi { */ protected SecretKey engineGenerateSecret(KeySpec keySpec) throws InvalidKeySpecException { - DESKey desKey = null; try { - if (!(keySpec instanceof DESKeySpec)) { - throw new InvalidKeySpecException - ("Inappropriate key specification"); + if (keySpec instanceof DESKeySpec) { + return new DESKey(((DESKeySpec)keySpec).getKey()); } - else { - DESKeySpec desKeySpec = (DESKeySpec)keySpec; - desKey = new DESKey(desKeySpec.getKey()); + + if (keySpec instanceof SecretKeySpec) { + return new DESKey(((SecretKeySpec)keySpec).getEncoded()); } + + throw new InvalidKeySpecException( + "Inappropriate key specification"); + } catch (InvalidKeyException e) { + throw new InvalidKeySpecException(e.getMessage()); } - return desKey; } /** diff --git a/jdk/src/share/classes/com/sun/crypto/provider/DESedeKeyFactory.java b/jdk/src/share/classes/com/sun/crypto/provider/DESedeKeyFactory.java index 9caabc3d80b..d2d2d7d47ea 100644 --- a/jdk/src/share/classes/com/sun/crypto/provider/DESedeKeyFactory.java +++ b/jdk/src/share/classes/com/sun/crypto/provider/DESedeKeyFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,6 +31,7 @@ import javax.crypto.spec.DESedeKeySpec; import java.security.InvalidKeyException; import java.security.spec.KeySpec; import java.security.spec.InvalidKeySpecException; +import javax.crypto.spec.SecretKeySpec; /** * This class implements the DES-EDE key factory of the Sun provider. @@ -60,20 +61,20 @@ public final class DESedeKeyFactory extends SecretKeyFactorySpi { */ protected SecretKey engineGenerateSecret(KeySpec keySpec) throws InvalidKeySpecException { - DESedeKey desEdeKey = null; try { if (keySpec instanceof DESedeKeySpec) { - DESedeKeySpec desEdeKeySpec = (DESedeKeySpec)keySpec; - desEdeKey = new DESedeKey(desEdeKeySpec.getKey()); - - } else { - throw new InvalidKeySpecException - ("Inappropriate key specification"); + return new DESedeKey(((DESedeKeySpec)keySpec).getKey()); } + if (keySpec instanceof SecretKeySpec) { + return new DESedeKey(((SecretKeySpec)keySpec).getEncoded()); + + } + throw new InvalidKeySpecException + ("Inappropriate key specification"); } catch (InvalidKeyException e) { + throw new InvalidKeySpecException(e.getMessage()); } - return desEdeKey; } /** diff --git a/jdk/src/share/classes/com/sun/crypto/provider/DHKeyFactory.java b/jdk/src/share/classes/com/sun/crypto/provider/DHKeyFactory.java index 38e7d36f3f2..273d49eb076 100644 --- a/jdk/src/share/classes/com/sun/crypto/provider/DHKeyFactory.java +++ b/jdk/src/share/classes/com/sun/crypto/provider/DHKeyFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -83,7 +83,7 @@ public final class DHKeyFactory extends KeyFactorySpi { } } catch (InvalidKeyException e) { throw new InvalidKeySpecException - ("Inappropriate key specification"); + ("Inappropriate key specification", e); } } @@ -118,7 +118,7 @@ public final class DHKeyFactory extends KeyFactorySpi { } } catch (InvalidKeyException e) { throw new InvalidKeySpecException - ("Inappropriate key specification"); + ("Inappropriate key specification", e); } } @@ -227,7 +227,7 @@ public final class DHKeyFactory extends KeyFactorySpi { } } catch (InvalidKeySpecException e) { - throw new InvalidKeyException("Cannot translate key"); + throw new InvalidKeyException("Cannot translate key", e); } } } diff --git a/jdk/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java b/jdk/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java index 6ae39e25e7e..c71d6ab3fa8 100644 --- a/jdk/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java +++ b/jdk/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java @@ -167,15 +167,16 @@ public final class DHKeyPairGenerator extends KeyPairGeneratorSpi { BigInteger pMinus2 = p.subtract(BigInteger.valueOf(2)); // - // Handbook of Applied Cryptography: Menezes, et.al. - // Repeat if the following does not hold: - // 1 <= x <= p-2 + // PKCS#3 section 7.1 "Private-value generation" + // Repeat if either of the followings does not hold: + // 0 < x < p-1 + // 2^(lSize-1) <= x < 2^(lSize) // do { // generate random x up to 2^lSize bits long x = new BigInteger(lSize, random); } while ((x.compareTo(BigInteger.ONE) < 0) || - ((x.compareTo(pMinus2) > 0))); + ((x.compareTo(pMinus2) > 0)) || (x.bitLength() != lSize)); // calculate public value y BigInteger y = g.modPow(x, p); diff --git a/jdk/src/share/classes/com/sun/crypto/provider/DHPrivateKey.java b/jdk/src/share/classes/com/sun/crypto/provider/DHPrivateKey.java index 1653a239960..e3254c4fc34 100644 --- a/jdk/src/share/classes/com/sun/crypto/provider/DHPrivateKey.java +++ b/jdk/src/share/classes/com/sun/crypto/provider/DHPrivateKey.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ package com.sun.crypto.provider; import java.io.*; +import java.util.Objects; import java.math.BigInteger; import java.security.KeyRep; import java.security.PrivateKey; @@ -67,7 +68,7 @@ javax.crypto.interfaces.DHPrivateKey, Serializable { // the base generator private BigInteger g; - // the private-value length + // the private-value length (optional) private int l; private int DH_data[] = { 1, 2, 840, 113549, 1, 3, 1 }; @@ -179,20 +180,9 @@ javax.crypto.interfaces.DHPrivateKey, Serializable { this.key = val.data.getOctetString(); parseKeyBits(); - // ignore OPTIONAL attributes - this.encodedKey = encodedKey.clone(); - - } catch (NumberFormatException e) { - InvalidKeyException ike = new InvalidKeyException( - "Private-value length too big"); - ike.initCause(e); - throw ike; - } catch (IOException e) { - InvalidKeyException ike = new InvalidKeyException( - "Error parsing key encoding: " + e.getMessage()); - ike.initCause(e); - throw ike; + } catch (IOException | NumberFormatException e) { + throw new InvalidKeyException("Error parsing key encoding", e); } } @@ -234,8 +224,9 @@ javax.crypto.interfaces.DHPrivateKey, Serializable { DerOutputStream params = new DerOutputStream(); params.putInteger(this.p); params.putInteger(this.g); - if (this.l != 0) + if (this.l != 0) { params.putInteger(this.l); + } // wrap parameters into SEQUENCE DerValue paramSequence = new DerValue(DerValue.tag_Sequence, params.toByteArray()); @@ -273,10 +264,11 @@ javax.crypto.interfaces.DHPrivateKey, Serializable { * @return the key parameters */ public DHParameterSpec getParams() { - if (this.l != 0) + if (this.l != 0) { return new DHParameterSpec(this.p, this.g, this.l); - else + } else { return new DHParameterSpec(this.p, this.g); + } } public String toString() { @@ -312,26 +304,21 @@ javax.crypto.interfaces.DHPrivateKey, Serializable { * Objects that are equal will also have the same hashcode. */ public int hashCode() { - int retval = 0; - byte[] enc = getEncoded(); - - for (int i = 1; i < enc.length; i++) { - retval += enc[i] * i; - } - return(retval); + return Objects.hash(x, p, g); } public boolean equals(Object obj) { - if (this == obj) - return true; + if (this == obj) return true; - if (!(obj instanceof PrivateKey)) + if (!(obj instanceof javax.crypto.interfaces.DHPrivateKey)) { return false; - - byte[] thisEncoded = this.getEncoded(); - byte[] thatEncoded = ((PrivateKey)obj).getEncoded(); - - return java.util.Arrays.equals(thisEncoded, thatEncoded); + } + javax.crypto.interfaces.DHPrivateKey other = + (javax.crypto.interfaces.DHPrivateKey) obj; + DHParameterSpec otherParams = other.getParams(); + return ((this.x.compareTo(other.getX()) == 0) && + (this.p.compareTo(otherParams.getP()) == 0) && + (this.g.compareTo(otherParams.getG()) == 0)); } /** diff --git a/jdk/src/share/classes/com/sun/crypto/provider/DHPublicKey.java b/jdk/src/share/classes/com/sun/crypto/provider/DHPublicKey.java index a9062e50797..7293c945768 100644 --- a/jdk/src/share/classes/com/sun/crypto/provider/DHPublicKey.java +++ b/jdk/src/share/classes/com/sun/crypto/provider/DHPublicKey.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ package com.sun.crypto.provider; import java.io.*; +import java.util.Objects; import java.math.BigInteger; import java.security.KeyRep; import java.security.InvalidKeyException; @@ -64,7 +65,7 @@ javax.crypto.interfaces.DHPublicKey, Serializable { // the base generator private BigInteger g; - // the private-value length + // the private-value length (optional) private int l; private int DH_data[] = { 1, 2, 840, 113549, 1, 3, 1 }; @@ -173,13 +174,8 @@ javax.crypto.interfaces.DHPublicKey, Serializable { } this.encodedKey = encodedKey.clone(); - - } catch (NumberFormatException e) { - throw new InvalidKeyException("Private-value length too big"); - - } catch (IOException e) { - throw new InvalidKeyException( - "Error parsing key encoding: " + e.toString()); + } catch (IOException | NumberFormatException e) { + throw new InvalidKeyException("Error parsing key encoding", e); } } @@ -212,8 +208,9 @@ javax.crypto.interfaces.DHPublicKey, Serializable { DerOutputStream params = new DerOutputStream(); params.putInteger(this.p); params.putInteger(this.g); - if (this.l != 0) + if (this.l != 0) { params.putInteger(this.l); + } // wrap parameters into SEQUENCE DerValue paramSequence = new DerValue(DerValue.tag_Sequence, params.toByteArray()); @@ -253,10 +250,11 @@ javax.crypto.interfaces.DHPublicKey, Serializable { * @return the key parameters */ public DHParameterSpec getParams() { - if (this.l != 0) + if (this.l != 0) { return new DHParameterSpec(this.p, this.g, this.l); - else + } else { return new DHParameterSpec(this.p, this.g); + } } public String toString() { @@ -290,26 +288,22 @@ javax.crypto.interfaces.DHPublicKey, Serializable { * Objects that are equal will also have the same hashcode. */ public int hashCode() { - int retval = 0; - byte[] enc = getEncoded(); - - for (int i = 1; i < enc.length; i++) { - retval += enc[i] * i; - } - return(retval); + return Objects.hash(y, p, g); } public boolean equals(Object obj) { - if (this == obj) - return true; + if (this == obj) return true; - if (!(obj instanceof PublicKey)) + if (!(obj instanceof javax.crypto.interfaces.DHPublicKey)) { return false; + } - byte[] thisEncoded = this.getEncoded(); - byte[] thatEncoded = ((PublicKey)obj).getEncoded(); - - return java.util.Arrays.equals(thisEncoded, thatEncoded); + javax.crypto.interfaces.DHPublicKey other = + (javax.crypto.interfaces.DHPublicKey) obj; + DHParameterSpec otherParams = other.getParams(); + return ((this.y.compareTo(other.getY()) == 0) && + (this.p.compareTo(otherParams.getP()) == 0) && + (this.g.compareTo(otherParams.getG()) == 0)); } /** diff --git a/jdk/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java b/jdk/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java index 5bfe096893c..9044d92b86f 100644 --- a/jdk/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java +++ b/jdk/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java @@ -134,7 +134,7 @@ public class UnpackerImpl extends TLGlobals implements Pack200.Unpacker { } else { try { (new NativeUnpack(this)).run(in0, out); - } catch (UnsatisfiedLinkError ule) { + } catch (UnsatisfiedLinkError | NoClassDefFoundError ex) { // failover to java implementation (new DoUnpack()).run(in0, out); } diff --git a/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java b/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java index 732c280f7dd..0e08177d7f2 100644 --- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java +++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java @@ -52,6 +52,7 @@ import javax.management.NotCompliantMBeanException; import com.sun.jmx.remote.util.EnvHelp; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; +import java.security.AccessController; import javax.management.AttributeNotFoundException; import javax.management.openmbean.CompositeData; import sun.reflect.misc.MethodUtil; @@ -64,7 +65,11 @@ import sun.reflect.misc.ReflectUtil; * @since 1.5 */ public class Introspector { - + final public static boolean ALLOW_NONPUBLIC_MBEAN; + static { + String val = AccessController.doPrivileged(new GetPropertyAction("jdk.jmx.mbeans.allowNonPublic")); + ALLOW_NONPUBLIC_MBEAN = Boolean.parseBoolean(val); + } /* * ------------------------------------------ @@ -223,11 +228,27 @@ public class Introspector { return testCompliance(baseClass, null); } + /** + * Tests the given interface class for being a compliant MXBean interface. + * A compliant MXBean interface is any publicly accessible interface + * following the {@link MXBean} conventions. + * @param interfaceClass An interface class to test for the MXBean compliance + * @throws NotCompliantMBeanException Thrown when the tested interface + * is not public or contradicts the {@link MXBean} conventions. + */ public static void testComplianceMXBeanInterface(Class interfaceClass) throws NotCompliantMBeanException { MXBeanIntrospector.getInstance().getAnalyzer(interfaceClass); } + /** + * Tests the given interface class for being a compliant MBean interface. + * A compliant MBean interface is any publicly accessible interface + * following the {@code MBean} conventions. + * @param interfaceClass An interface class to test for the MBean compliance + * @throws NotCompliantMBeanException Thrown when the tested interface + * is not public or contradicts the {@code MBean} conventions. + */ public static void testComplianceMBeanInterface(Class interfaceClass) throws NotCompliantMBeanException{ StandardMBeanIntrospector.getInstance().getAnalyzer(interfaceClass); @@ -299,18 +320,18 @@ public class Introspector { * not a JMX compliant Standard MBean. */ public static Class getStandardMBeanInterface(Class baseClass) - throws NotCompliantMBeanException { - Class current = baseClass; - Class mbeanInterface = null; - while (current != null) { - mbeanInterface = - findMBeanInterface(current, current.getName()); - if (mbeanInterface != null) break; - current = current.getSuperclass(); - } - if (mbeanInterface != null) { - return mbeanInterface; - } else { + throws NotCompliantMBeanException { + Class current = baseClass; + Class mbeanInterface = null; + while (current != null) { + mbeanInterface = + findMBeanInterface(current, current.getName()); + if (mbeanInterface != null) break; + current = current.getSuperclass(); + } + if (mbeanInterface != null) { + return mbeanInterface; + } else { final String msg = "Class " + baseClass.getName() + " is not a JMX compliant Standard MBean"; @@ -507,8 +528,11 @@ public class Introspector { } Class[] interfaces = c.getInterfaces(); for (int i = 0;i < interfaces.length; i++) { - if (interfaces[i].getName().equals(clMBeanName)) + if (interfaces[i].getName().equals(clMBeanName) && + (Modifier.isPublic(interfaces[i].getModifiers()) || + ALLOW_NONPUBLIC_MBEAN)) { return Util.cast(interfaces[i]); + } } return null; diff --git a/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java b/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java index 5e5375d0974..d7d06a04a73 100644 --- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java +++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java @@ -28,6 +28,8 @@ package com.sun.jmx.mbeanserver; import static com.sun.jmx.mbeanserver.Util.*; import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.security.AccessController; import java.util.Arrays; import java.util.Comparator; import java.util.List; @@ -50,7 +52,6 @@ import javax.management.NotCompliantMBeanException; * @since 1.6 */ class MBeanAnalyzer { - static interface MBeanVisitor { public void visitAttribute(String attributeName, M getter, @@ -107,6 +108,10 @@ class MBeanAnalyzer { if (!mbeanType.isInterface()) { throw new NotCompliantMBeanException("Not an interface: " + mbeanType.getName()); + } else if (!Modifier.isPublic(mbeanType.getModifiers()) && + !Introspector.ALLOW_NONPUBLIC_MBEAN) { + throw new NotCompliantMBeanException("Interface is not public: " + + mbeanType.getName()); } try { diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java index 62fd0fe4964..6b661bb31f3 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java @@ -2,82 +2,78 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.algorithms; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * The Algorithm class which stores the Algorithm URI as a string. - * */ public abstract class Algorithm extends SignatureElementProxy { - /** - * - * @param doc - * @param algorithmURI is the URI of the algorithm as String - */ - public Algorithm(Document doc, String algorithmURI) { + /** + * + * @param doc + * @param algorithmURI is the URI of the algorithm as String + */ + public Algorithm(Document doc, String algorithmURI) { + super(doc); - super(doc); + this.setAlgorithmURI(algorithmURI); + } - this.setAlgorithmURI(algorithmURI); - } + /** + * Constructor Algorithm + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public Algorithm(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } - /** - * Constructor Algorithm - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public Algorithm(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Method getAlgorithmURI + * + * @return The URI of the algorithm + */ + public String getAlgorithmURI() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM); + } - /** - * Method getAlgorithmURI - * - * @return The URI of the alogrithm - */ - public String getAlgorithmURI() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM); - } - - /** - * Sets the algorithm's URI as used in the signature. - * - * @param algorithmURI is the URI of the algorithm as String - */ - protected void setAlgorithmURI(String algorithmURI) { - - if ( (algorithmURI != null)) { - this._constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, - algorithmURI); - } - } + /** + * Sets the algorithm's URI as used in the signature. + * + * @param algorithmURI is the URI of the algorithm as String + */ + protected void setAlgorithmURI(String algorithmURI) { + if (algorithmURI != null) { + this.constructionElement.setAttributeNS( + null, Constants._ATT_ALGORITHM, algorithmURI + ); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java index 9e736518936..ca7d42a869a 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java @@ -114,6 +114,18 @@ public class JCEMapper { XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1, new Algorithm("", "SHA1withECDSA", "Signature") ); + algorithmsMap.put( + XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256, + new Algorithm("", "SHA256withECDSA", "Signature") + ); + algorithmsMap.put( + XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384, + new Algorithm("", "SHA384withECDSA", "Signature") + ); + algorithmsMap.put( + XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512, + new Algorithm("", "SHA512withECDSA", "Signature") + ); algorithmsMap.put( XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5, new Algorithm("", "HmacMD5", "Mac") @@ -154,6 +166,18 @@ public class JCEMapper { XMLCipher.AES_256, new Algorithm("AES", "AES/CBC/ISO10126Padding", "BlockEncryption", 256) ); + algorithmsMap.put( + XMLCipher.AES_128_GCM, + new Algorithm("AES", "AES/GCM/NoPadding", "BlockEncryption", 128) + ); + algorithmsMap.put( + XMLCipher.AES_192_GCM, + new Algorithm("AES", "AES/GCM/NoPadding", "BlockEncryption", 192) + ); + algorithmsMap.put( + XMLCipher.AES_256_GCM, + new Algorithm("AES", "AES/GCM/NoPadding", "BlockEncryption", 256) + ); algorithmsMap.put( XMLCipher.RSA_v1dot5, new Algorithm("RSA", "RSA/ECB/PKCS1Padding", "KeyTransport") @@ -162,6 +186,10 @@ public class JCEMapper { XMLCipher.RSA_OAEP, new Algorithm("RSA", "RSA/ECB/OAEPPadding", "KeyTransport") ); + algorithmsMap.put( + XMLCipher.RSA_OAEP_11, + new Algorithm("RSA", "RSA/ECB/OAEPPadding", "KeyTransport") + ); algorithmsMap.put( XMLCipher.DIFFIE_HELLMAN, new Algorithm("", "", "KeyAgreement") diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java index 63a808ba745..d10c88c78bd 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java @@ -2,265 +2,254 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.algorithms; import java.security.MessageDigest; import java.security.NoSuchProviderException; -import java.util.HashMap; -import java.util.Map; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants; import org.w3c.dom.Document; - /** * Digest Message wrapper & selector class. * *
  * MessageDigestAlgorithm.getInstance()
  * 
- * */ public class MessageDigestAlgorithm extends Algorithm { /** Message Digest - NOT RECOMMENDED MD5*/ - public static final String ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5 = Constants.MoreAlgorithmsSpecNS + "md5"; - /** Digest - Required SHA1*/ - public static final String ALGO_ID_DIGEST_SHA1 = Constants.SignatureSpecNS + "sha1"; - /** Message Digest - RECOMMENDED SHA256*/ - public static final String ALGO_ID_DIGEST_SHA256 = EncryptionConstants.EncryptionSpecNS + "sha256"; - /** Message Digest - OPTIONAL SHA384*/ - public static final String ALGO_ID_DIGEST_SHA384 = Constants.MoreAlgorithmsSpecNS + "sha384"; - /** Message Digest - OPTIONAL SHA512*/ - public static final String ALGO_ID_DIGEST_SHA512 = EncryptionConstants.EncryptionSpecNS + "sha512"; - /** Message Digest - OPTIONAL RIPEMD-160*/ - public static final String ALGO_ID_DIGEST_RIPEMD160 = EncryptionConstants.EncryptionSpecNS + "ripemd160"; + public static final String ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5 = + Constants.MoreAlgorithmsSpecNS + "md5"; + /** Digest - Required SHA1*/ + public static final String ALGO_ID_DIGEST_SHA1 = Constants.SignatureSpecNS + "sha1"; + /** Message Digest - RECOMMENDED SHA256*/ + public static final String ALGO_ID_DIGEST_SHA256 = + EncryptionConstants.EncryptionSpecNS + "sha256"; + /** Message Digest - OPTIONAL SHA384*/ + public static final String ALGO_ID_DIGEST_SHA384 = + Constants.MoreAlgorithmsSpecNS + "sha384"; + /** Message Digest - OPTIONAL SHA512*/ + public static final String ALGO_ID_DIGEST_SHA512 = + EncryptionConstants.EncryptionSpecNS + "sha512"; + /** Message Digest - OPTIONAL RIPEMD-160*/ + public static final String ALGO_ID_DIGEST_RIPEMD160 = + EncryptionConstants.EncryptionSpecNS + "ripemd160"; - /** Field algorithm stores the actual {@link java.security.MessageDigest} */ - java.security.MessageDigest algorithm = null; + /** Field algorithm stores the actual {@link java.security.MessageDigest} */ + private final MessageDigest algorithm; - /** - * Constructor for the brave who pass their own message digest algorithms and the corresponding URI. - * @param doc - * @param messageDigest - * @param algorithmURI - */ - private MessageDigestAlgorithm(Document doc, MessageDigest messageDigest, - String algorithmURI) { + /** + * Constructor for the brave who pass their own message digest algorithms and the + * corresponding URI. + * @param doc + * @param algorithmURI + */ + private MessageDigestAlgorithm(Document doc, String algorithmURI) + throws XMLSignatureException { + super(doc, algorithmURI); - super(doc, algorithmURI); + algorithm = getDigestInstance(algorithmURI); + } - this.algorithm = messageDigest; - } + /** + * Factory method for constructing a message digest algorithm by name. + * + * @param doc + * @param algorithmURI + * @return The MessageDigestAlgorithm element to attach in document and to digest + * @throws XMLSignatureException + */ + public static MessageDigestAlgorithm getInstance( + Document doc, String algorithmURI + ) throws XMLSignatureException { + return new MessageDigestAlgorithm(doc, algorithmURI); + } - static ThreadLocal> instances=new - ThreadLocal>() { - protected Map initialValue() { - return new HashMap(); - }; - }; + private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSignatureException { + String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI); - /** - * Factory method for constructing a message digest algorithm by name. - * - * @param doc - * @param algorithmURI - * @return The MessageDigestAlgorithm element to attach in document and to digest - * @throws XMLSignatureException - */ - public static MessageDigestAlgorithm getInstance( - Document doc, String algorithmURI) throws XMLSignatureException { - MessageDigest md = getDigestInstance(algorithmURI); - return new MessageDigestAlgorithm(doc, md, algorithmURI); - } - -private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSignatureException { - MessageDigest result= instances.get().get(algorithmURI); - if (result!=null) - return result; - String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI); - - if (algorithmID == null) { - Object[] exArgs = { algorithmURI }; - throw new XMLSignatureException("algorithms.NoSuchMap", exArgs); - } - - MessageDigest md; - String provider=JCEMapper.getProviderId(); - try { - if (provider==null) { - md = MessageDigest.getInstance(algorithmID); - } else { - md = MessageDigest.getInstance(algorithmID,provider); - } - } catch (java.security.NoSuchAlgorithmException ex) { - Object[] exArgs = { algorithmID, - ex.getLocalizedMessage() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); - } catch (NoSuchProviderException ex) { - Object[] exArgs = { algorithmID, - ex.getLocalizedMessage() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + if (algorithmID == null) { + Object[] exArgs = { algorithmURI }; + throw new XMLSignatureException("algorithms.NoSuchMap", exArgs); } - instances.get().put(algorithmURI, md); + + MessageDigest md; + String provider = JCEMapper.getProviderId(); + try { + if (provider == null) { + md = MessageDigest.getInstance(algorithmID); + } else { + md = MessageDigest.getInstance(algorithmID, provider); + } + } catch (java.security.NoSuchAlgorithmException ex) { + Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; + + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } catch (NoSuchProviderException ex) { + Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; + + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } + return md; -} - - /** - * Returns the actual {@link java.security.MessageDigest} algorithm object - * - * @return the actual {@link java.security.MessageDigest} algorithm object - */ - public java.security.MessageDigest getAlgorithm() { - return this.algorithm; - } - - /** - * Proxy method for {@link java.security.MessageDigest#isEqual} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @param digesta - * @param digestb - * @return the result of the {@link java.security.MessageDigest#isEqual} method - */ - public static boolean isEqual(byte[] digesta, byte[] digestb) { - return java.security.MessageDigest.isEqual(digesta, digestb); - } - - /** - * Proxy method for {@link java.security.MessageDigest#digest()} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @return the result of the {@link java.security.MessageDigest#digest()} method - */ - public byte[] digest() { - return this.algorithm.digest(); - } - - /** - * Proxy method for {@link java.security.MessageDigest#digest(byte[])} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @param input - * @return the result of the {@link java.security.MessageDigest#digest(byte[])} method - */ - public byte[] digest(byte input[]) { - return this.algorithm.digest(input); - } - - /** - * Proxy method for {@link java.security.MessageDigest#digest(byte[], int, int)} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @param buf - * @param offset - * @param len - * @return the result of the {@link java.security.MessageDigest#digest(byte[], int, int)} method - * @throws java.security.DigestException - */ - public int digest(byte buf[], int offset, int len) - throws java.security.DigestException { - return this.algorithm.digest(buf, offset, len); - } - - /** - * Proxy method for {@link java.security.MessageDigest#getAlgorithm} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @return the result of the {@link java.security.MessageDigest#getAlgorithm} method - */ - public String getJCEAlgorithmString() { - return this.algorithm.getAlgorithm(); - } - - /** - * Proxy method for {@link java.security.MessageDigest#getProvider} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @return the result of the {@link java.security.MessageDigest#getProvider} method - */ - public java.security.Provider getJCEProvider() { - return this.algorithm.getProvider(); - } - - /** - * Proxy method for {@link java.security.MessageDigest#getDigestLength} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @return the result of the {@link java.security.MessageDigest#getDigestLength} method - */ - public int getDigestLength() { - return this.algorithm.getDigestLength(); - } - - /** - * Proxy method for {@link java.security.MessageDigest#reset} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - */ - public void reset() { - this.algorithm.reset(); - } - - /** - * Proxy method for {@link java.security.MessageDigest#update(byte[])} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @param input - */ - public void update(byte[] input) { - this.algorithm.update(input); - } - - /** - * Proxy method for {@link java.security.MessageDigest#update(byte)} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @param input - */ - public void update(byte input) { - this.algorithm.update(input); - } - - /** - * Proxy method for {@link java.security.MessageDigest#update(byte[], int, int)} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @param buf - * @param offset - * @param len - */ - public void update(byte buf[], int offset, int len) { - this.algorithm.update(buf, offset, len); - } - - /** @inheritDoc */ - public String getBaseNamespace() { - return Constants.SignatureSpecNS; - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_DIGESTMETHOD; - } + } + + /** + * Returns the actual {@link java.security.MessageDigest} algorithm object + * + * @return the actual {@link java.security.MessageDigest} algorithm object + */ + public java.security.MessageDigest getAlgorithm() { + return algorithm; + } + + /** + * Proxy method for {@link java.security.MessageDigest#isEqual} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @param digesta + * @param digestb + * @return the result of the {@link java.security.MessageDigest#isEqual} method + */ + public static boolean isEqual(byte[] digesta, byte[] digestb) { + return java.security.MessageDigest.isEqual(digesta, digestb); + } + + /** + * Proxy method for {@link java.security.MessageDigest#digest()} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @return the result of the {@link java.security.MessageDigest#digest()} method + */ + public byte[] digest() { + return algorithm.digest(); + } + + /** + * Proxy method for {@link java.security.MessageDigest#digest(byte[])} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @param input + * @return the result of the {@link java.security.MessageDigest#digest(byte[])} method + */ + public byte[] digest(byte input[]) { + return algorithm.digest(input); + } + + /** + * Proxy method for {@link java.security.MessageDigest#digest(byte[], int, int)} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @param buf + * @param offset + * @param len + * @return the result of the {@link java.security.MessageDigest#digest(byte[], int, int)} method + * @throws java.security.DigestException + */ + public int digest(byte buf[], int offset, int len) throws java.security.DigestException { + return algorithm.digest(buf, offset, len); + } + + /** + * Proxy method for {@link java.security.MessageDigest#getAlgorithm} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @return the result of the {@link java.security.MessageDigest#getAlgorithm} method + */ + public String getJCEAlgorithmString() { + return algorithm.getAlgorithm(); + } + + /** + * Proxy method for {@link java.security.MessageDigest#getProvider} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @return the result of the {@link java.security.MessageDigest#getProvider} method + */ + public java.security.Provider getJCEProvider() { + return algorithm.getProvider(); + } + + /** + * Proxy method for {@link java.security.MessageDigest#getDigestLength} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @return the result of the {@link java.security.MessageDigest#getDigestLength} method + */ + public int getDigestLength() { + return algorithm.getDigestLength(); + } + + /** + * Proxy method for {@link java.security.MessageDigest#reset} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + */ + public void reset() { + algorithm.reset(); + } + + /** + * Proxy method for {@link java.security.MessageDigest#update(byte[])} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @param input + */ + public void update(byte[] input) { + algorithm.update(input); + } + + /** + * Proxy method for {@link java.security.MessageDigest#update(byte)} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @param input + */ + public void update(byte input) { + algorithm.update(input); + } + + /** + * Proxy method for {@link java.security.MessageDigest#update(byte[], int, int)} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @param buf + * @param offset + * @param len + */ + public void update(byte buf[], int offset, int len) { + algorithm.update(buf, offset, len); + } + + /** @inheritDoc */ + public String getBaseNamespace() { + return Constants.SignatureSpecNS; + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_DIGESTMETHOD; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java index 5dbcf58e33b..4748a6bc882 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java @@ -74,7 +74,7 @@ public class SignatureAlgorithm extends Algorithm { this.algorithmURI = algorithmURI; signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI); - signatureAlgorithm.engineGetContextFromElement(this._constructionElement); + signatureAlgorithm.engineGetContextFromElement(this.constructionElement); } /** @@ -92,10 +92,10 @@ public class SignatureAlgorithm extends Algorithm { this.algorithmURI = algorithmURI; signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI); - signatureAlgorithm.engineGetContextFromElement(this._constructionElement); + signatureAlgorithm.engineGetContextFromElement(this.constructionElement); signatureAlgorithm.engineSetHMACOutputLength(hmacOutputLength); - ((IntegrityHmac)signatureAlgorithm).engineAddContextToElement(_constructionElement); + ((IntegrityHmac)signatureAlgorithm).engineAddContextToElement(constructionElement); } /** @@ -136,7 +136,7 @@ public class SignatureAlgorithm extends Algorithm { } signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI); - signatureAlgorithm.engineGetContextFromElement(this._constructionElement); + signatureAlgorithm.engineGetContextFromElement(this.constructionElement); } /** @@ -310,7 +310,7 @@ public class SignatureAlgorithm extends Algorithm { * @return the URI representation of Transformation algorithm */ public final String getURI() { - return _constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM); + return constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM); } /** @@ -380,9 +380,7 @@ public class SignatureAlgorithm extends Algorithm { * This method registers the default algorithms. */ public static void registerDefaultAlgorithms() { - algorithmHash.put( - XMLSignature.ALGO_ID_SIGNATURE_DSA, SignatureDSA.class - ); + algorithmHash.put(SignatureDSA.URI, SignatureDSA.class); algorithmHash.put( XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, SignatureBaseRSA.SignatureRSASHA1.class ); @@ -409,6 +407,15 @@ public class SignatureAlgorithm extends Algorithm { algorithmHash.put( XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1, SignatureECDSA.SignatureECDSASHA1.class ); + algorithmHash.put( + XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256, SignatureECDSA.SignatureECDSASHA256.class + ); + algorithmHash.put( + XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384, SignatureECDSA.SignatureECDSASHA384.class + ); + algorithmHash.put( + XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512, SignatureECDSA.SignatureECDSASHA512.class + ); algorithmHash.put( XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5, IntegrityHmac.IntegrityHmacMD5.class ); diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java index c47be7e2c0d..77bcfa7fd98 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.algorithms; @@ -27,157 +29,149 @@ import java.security.spec.AlgorithmParameterSpec; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import org.w3c.dom.Element; - -/** - * - * @author $Author: mullan $ - */ public abstract class SignatureAlgorithmSpi { - /** - * Returns the URI representation of Transformation algorithm - * - * @return the URI representation of Transformation algorithm - */ - protected abstract String engineGetURI(); + /** + * Returns the URI representation of Transformation algorithm + * + * @return the URI representation of Transformation algorithm + */ + protected abstract String engineGetURI(); - /** - * Proxy method for {@link java.security.Signature#getAlgorithm} - * which is executed on the internal {@link java.security.Signature} object. - * - * @return the result of the {@link java.security.Signature#getAlgorithm} method - */ - protected abstract String engineGetJCEAlgorithmString(); + /** + * Proxy method for {@link java.security.Signature#getAlgorithm} + * which is executed on the internal {@link java.security.Signature} object. + * + * @return the result of the {@link java.security.Signature#getAlgorithm} method + */ + protected abstract String engineGetJCEAlgorithmString(); - /** - * Method engineGetJCEProviderName - * - * @return the JCE ProviderName - */ - protected abstract String engineGetJCEProviderName(); + /** + * Method engineGetJCEProviderName + * + * @return the JCE ProviderName + */ + protected abstract String engineGetJCEProviderName(); - /** - * Proxy method for {@link java.security.Signature#update(byte[])} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param input - * @throws XMLSignatureException - */ - protected abstract void engineUpdate(byte[] input) - throws XMLSignatureException; + /** + * Proxy method for {@link java.security.Signature#update(byte[])} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param input + * @throws XMLSignatureException + */ + protected abstract void engineUpdate(byte[] input) throws XMLSignatureException; - /** - * Proxy method for {@link java.security.Signature#update(byte[])} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param input - * @throws XMLSignatureException - */ - protected abstract void engineUpdate(byte input) - throws XMLSignatureException; + /** + * Proxy method for {@link java.security.Signature#update(byte[])} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param input + * @throws XMLSignatureException + */ + protected abstract void engineUpdate(byte input) throws XMLSignatureException; - /** - * Proxy method for {@link java.security.Signature#update(byte[], int, int)} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param buf - * @param offset - * @param len - * @throws XMLSignatureException - */ - protected abstract void engineUpdate(byte buf[], int offset, int len) - throws XMLSignatureException; + /** + * Proxy method for {@link java.security.Signature#update(byte[], int, int)} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param buf + * @param offset + * @param len + * @throws XMLSignatureException + */ + protected abstract void engineUpdate(byte buf[], int offset, int len) + throws XMLSignatureException; - /** - * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey)} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param signingKey - * @throws XMLSignatureException if this method is called on a MAC - */ - protected abstract void engineInitSign(Key signingKey) - throws XMLSignatureException; + /** + * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey)} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param signingKey + * @throws XMLSignatureException if this method is called on a MAC + */ + protected abstract void engineInitSign(Key signingKey) throws XMLSignatureException; - /** - * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey, java.security.SecureRandom)} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param signingKey - * @param secureRandom - * @throws XMLSignatureException if this method is called on a MAC - */ - protected abstract void engineInitSign( - Key signingKey, SecureRandom secureRandom) throws XMLSignatureException; + /** + * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey, + * java.security.SecureRandom)} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param signingKey + * @param secureRandom + * @throws XMLSignatureException if this method is called on a MAC + */ + protected abstract void engineInitSign(Key signingKey, SecureRandom secureRandom) + throws XMLSignatureException; - /** - * Proxy method for {@link javax.crypto.Mac} - * which is executed on the internal {@link javax.crypto.Mac#init(Key)} object. - * - * @param signingKey - * @param algorithmParameterSpec - * @throws XMLSignatureException if this method is called on a Signature - */ - protected abstract void engineInitSign( - Key signingKey, AlgorithmParameterSpec algorithmParameterSpec) - throws XMLSignatureException; + /** + * Proxy method for {@link javax.crypto.Mac} + * which is executed on the internal {@link javax.crypto.Mac#init(Key)} object. + * + * @param signingKey + * @param algorithmParameterSpec + * @throws XMLSignatureException if this method is called on a Signature + */ + protected abstract void engineInitSign( + Key signingKey, AlgorithmParameterSpec algorithmParameterSpec + ) throws XMLSignatureException; - /** - * Proxy method for {@link java.security.Signature#sign()} - * which is executed on the internal {@link java.security.Signature} object. - * - * @return the result of the {@link java.security.Signature#sign()} method - * @throws XMLSignatureException - */ - protected abstract byte[] engineSign() throws XMLSignatureException; + /** + * Proxy method for {@link java.security.Signature#sign()} + * which is executed on the internal {@link java.security.Signature} object. + * + * @return the result of the {@link java.security.Signature#sign()} method + * @throws XMLSignatureException + */ + protected abstract byte[] engineSign() throws XMLSignatureException; - /** - * Method engineInitVerify - * - * @param verificationKey - * @throws XMLSignatureException - */ - protected abstract void engineInitVerify(Key verificationKey) - throws XMLSignatureException; + /** + * Method engineInitVerify + * + * @param verificationKey + * @throws XMLSignatureException + */ + protected abstract void engineInitVerify(Key verificationKey) throws XMLSignatureException; - /** - * Proxy method for {@link java.security.Signature#verify(byte[])} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param signature - * @return true if the signature is correct - * @throws XMLSignatureException - */ - protected abstract boolean engineVerify(byte[] signature) - throws XMLSignatureException; + /** + * Proxy method for {@link java.security.Signature#verify(byte[])} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param signature + * @return true if the signature is correct + * @throws XMLSignatureException + */ + protected abstract boolean engineVerify(byte[] signature) throws XMLSignatureException; - /** - * Proxy method for {@link java.security.Signature#setParameter(java.security.spec.AlgorithmParameterSpec)} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param params - * @throws XMLSignatureException - */ - protected abstract void engineSetParameter(AlgorithmParameterSpec params) - throws XMLSignatureException; + /** + * Proxy method for {@link java.security.Signature#setParameter( + * java.security.spec.AlgorithmParameterSpec)} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param params + * @throws XMLSignatureException + */ + protected abstract void engineSetParameter(AlgorithmParameterSpec params) + throws XMLSignatureException; - /** - * Method engineGetContextFromElement - * - * @param element - */ - protected void engineGetContextFromElement(Element element) { - } + /** + * Method engineGetContextFromElement + * + * @param element + */ + protected void engineGetContextFromElement(Element element) { + } - /** - * Method engineSetHMACOutputLength - * - * @param HMACOutputLength - * @throws XMLSignatureException - */ - protected abstract void engineSetHMACOutputLength(int HMACOutputLength) - throws XMLSignatureException; + /** + * Method engineSetHMACOutputLength + * + * @param HMACOutputLength + * @throws XMLSignatureException + */ + protected abstract void engineSetHMACOutputLength(int HMACOutputLength) + throws XMLSignatureException; public void reset() { - } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java index 7231b069a18..8935e389728 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.algorithms.implementations; - - import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; @@ -42,570 +42,498 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; - -/** - * - * @author $Author: mullan $ - */ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(IntegrityHmacSHA1.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(IntegrityHmac.class.getName()); - /** - * Method engineGetURI - * - *@inheritDoc - */ - public abstract String engineGetURI(); + /** Field macAlgorithm */ + private Mac macAlgorithm = null; - /** - * Returns the output length of the hash/digest. - */ - abstract int getDigestLength(); + /** Field HMACOutputLength */ + private int HMACOutputLength = 0; + private boolean HMACOutputLengthSet = false; - /** Field _macAlgorithm */ - private Mac _macAlgorithm = null; - private boolean _HMACOutputLengthSet = false; + /** + * Method engineGetURI + * + *@inheritDoc + */ + public abstract String engineGetURI(); - /** Field _HMACOutputLength */ - int _HMACOutputLength = 0; + /** + * Returns the output length of the hash/digest. + */ + abstract int getDigestLength(); - /** - * Method IntegrityHmacSHA1das - * - * @throws XMLSignatureException - */ - public IntegrityHmac() throws XMLSignatureException { + /** + * Method IntegrityHmac + * + * @throws XMLSignatureException + */ + public IntegrityHmac() throws XMLSignatureException { + String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Created IntegrityHmacSHA1 using " + algorithmID); + } - String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Created IntegrityHmacSHA1 using " + algorithmID); + try { + this.macAlgorithm = Mac.getInstance(algorithmID); + } catch (java.security.NoSuchAlgorithmException ex) { + Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; - try { - this._macAlgorithm = Mac.getInstance(algorithmID); - } catch (java.security.NoSuchAlgorithmException ex) { - Object[] exArgs = { algorithmID, - ex.getLocalizedMessage() }; + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } + } - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); - } - } + /** + * Proxy method for {@link java.security.Signature#setParameter( + * java.security.spec.AlgorithmParameterSpec)} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param params + * @throws XMLSignatureException + */ + protected void engineSetParameter(AlgorithmParameterSpec params) throws XMLSignatureException { + throw new XMLSignatureException("empty"); + } - /** - * Proxy method for {@link java.security.Signature#setParameter(java.security.spec.AlgorithmParameterSpec)} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param params - * @throws XMLSignatureException - */ - protected void engineSetParameter(AlgorithmParameterSpec params) - throws XMLSignatureException { - throw new XMLSignatureException("empty"); - } + public void reset() { + HMACOutputLength = 0; + HMACOutputLengthSet = false; + this.macAlgorithm.reset(); + } - public void reset() { - _HMACOutputLength=0; - _HMACOutputLengthSet = false; - _macAlgorithm.reset(); - } - - /** - * Proxy method for {@link java.security.Signature#verify(byte[])} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param signature - * @return true if the signature is correct - * @throws XMLSignatureException - */ - protected boolean engineVerify(byte[] signature) - throws XMLSignatureException { - - try { - if (this._HMACOutputLengthSet && this._HMACOutputLength < getDigestLength()) { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, - "HMACOutputLength must not be less than " + getDigestLength()); + /** + * Proxy method for {@link java.security.Signature#verify(byte[])} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param signature + * @return true if the signature is correct + * @throws XMLSignatureException + */ + protected boolean engineVerify(byte[] signature) throws XMLSignatureException { + try { + if (this.HMACOutputLengthSet && this.HMACOutputLength < getDigestLength()) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "HMACOutputLength must not be less than " + getDigestLength()); + } + Object[] exArgs = { String.valueOf(getDigestLength()) }; + throw new XMLSignatureException("algorithms.HMACOutputLengthMin", exArgs); + } else { + byte[] completeResult = this.macAlgorithm.doFinal(); + return MessageDigestAlgorithm.isEqual(completeResult, signature); } - throw new XMLSignatureException("errorMessages.XMLSignatureException"); - } else { - byte[] completeResult = this._macAlgorithm.doFinal(); - return MessageDigestAlgorithm.isEqual(completeResult, signature); - } - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } + } catch (IllegalStateException ex) { + throw new XMLSignatureException("empty", ex); + } + } - /** - * Proxy method for {@link java.security.Signature#initVerify(java.security.PublicKey)} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param secretKey - * @throws XMLSignatureException - */ - protected void engineInitVerify(Key secretKey) throws XMLSignatureException { + /** + * Proxy method for {@link java.security.Signature#initVerify(java.security.PublicKey)} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param secretKey + * @throws XMLSignatureException + */ + protected void engineInitVerify(Key secretKey) throws XMLSignatureException { + if (!(secretKey instanceof SecretKey)) { + String supplied = secretKey.getClass().getName(); + String needed = SecretKey.class.getName(); + Object exArgs[] = { supplied, needed }; - if (!(secretKey instanceof SecretKey)) { - String supplied = secretKey.getClass().getName(); - String needed = SecretKey.class.getName(); - Object exArgs[] = { supplied, needed }; + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } - - try { - this._macAlgorithm.init(secretKey); - } catch (InvalidKeyException ex) { + try { + this.macAlgorithm.init(secretKey); + } catch (InvalidKeyException ex) { // reinstantiate Mac object to work around bug in JDK // see: http://bugs.sun.com/view_bug.do?bug_id=4953555 - Mac mac = this._macAlgorithm; + Mac mac = this.macAlgorithm; try { - this._macAlgorithm = Mac.getInstance - (_macAlgorithm.getAlgorithm()); + this.macAlgorithm = Mac.getInstance(macAlgorithm.getAlgorithm()); } catch (Exception e) { // this shouldn't occur, but if it does, restore previous Mac if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Mac:" + e); } - this._macAlgorithm = mac; + this.macAlgorithm = mac; } throw new XMLSignatureException("empty", ex); - } - } + } + } - /** - * Proxy method for {@link java.security.Signature#sign()} - * which is executed on the internal {@link java.security.Signature} object. - * - * @return the result of the {@link java.security.Signature#sign()} method - * @throws XMLSignatureException - */ - protected byte[] engineSign() throws XMLSignatureException { - - try { - if (this._HMACOutputLengthSet && this._HMACOutputLength < getDigestLength()) { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, - "HMACOutputLength must not be less than " + getDigestLength()); + /** + * Proxy method for {@link java.security.Signature#sign()} + * which is executed on the internal {@link java.security.Signature} object. + * + * @return the result of the {@link java.security.Signature#sign()} method + * @throws XMLSignatureException + */ + protected byte[] engineSign() throws XMLSignatureException { + try { + if (this.HMACOutputLengthSet && this.HMACOutputLength < getDigestLength()) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "HMACOutputLength must not be less than " + getDigestLength()); + } + Object[] exArgs = { String.valueOf(getDigestLength()) }; + throw new XMLSignatureException("algorithms.HMACOutputLengthMin", exArgs); + } else { + return this.macAlgorithm.doFinal(); } - throw new XMLSignatureException("errorMessages.XMLSignatureException"); - } else { - return this._macAlgorithm.doFinal(); - } - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } + } catch (IllegalStateException ex) { + throw new XMLSignatureException("empty", ex); + } + } - /** - * Method reduceBitLength - * - * @param completeResult - * @return the reduced bits. - * @param length - * - */ - private static byte[] reduceBitLength(byte completeResult[], int length) { + /** + * Method engineInitSign + * + * @param secretKey + * @throws XMLSignatureException + */ + protected void engineInitSign(Key secretKey) throws XMLSignatureException { + if (!(secretKey instanceof SecretKey)) { + String supplied = secretKey.getClass().getName(); + String needed = SecretKey.class.getName(); + Object exArgs[] = { supplied, needed }; - int bytes = length / 8; - int abits = length % 8; - byte[] strippedResult = new byte[bytes + ((abits == 0) - ? 0 - : 1)]; + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } - System.arraycopy(completeResult, 0, strippedResult, 0, bytes); + try { + this.macAlgorithm.init(secretKey); + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } + } - if (abits > 0) { - byte[] MASK = { (byte) 0x00, (byte) 0x80, (byte) 0xC0, (byte) 0xE0, - (byte) 0xF0, (byte) 0xF8, (byte) 0xFC, (byte) 0xFE }; + /** + * Method engineInitSign + * + * @param secretKey + * @param algorithmParameterSpec + * @throws XMLSignatureException + */ + protected void engineInitSign( + Key secretKey, AlgorithmParameterSpec algorithmParameterSpec + ) throws XMLSignatureException { + if (!(secretKey instanceof SecretKey)) { + String supplied = secretKey.getClass().getName(); + String needed = SecretKey.class.getName(); + Object exArgs[] = { supplied, needed }; - strippedResult[bytes] = (byte) (completeResult[bytes] & MASK[abits]); - } + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } - return strippedResult; - } + try { + this.macAlgorithm.init(secretKey, algorithmParameterSpec); + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } catch (InvalidAlgorithmParameterException ex) { + throw new XMLSignatureException("empty", ex); + } + } - /** - * Method engineInitSign - * - * @param secretKey - * @throws XMLSignatureException - */ - protected void engineInitSign(Key secretKey) throws XMLSignatureException { + /** + * Method engineInitSign + * + * @param secretKey + * @param secureRandom + * @throws XMLSignatureException + */ + protected void engineInitSign(Key secretKey, SecureRandom secureRandom) + throws XMLSignatureException { + throw new XMLSignatureException("algorithms.CannotUseSecureRandomOnMAC"); + } - if (!(secretKey instanceof SecretKey)) { - String supplied = secretKey.getClass().getName(); - String needed = SecretKey.class.getName(); - Object exArgs[] = { supplied, needed }; + /** + * Proxy method for {@link java.security.Signature#update(byte[])} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param input + * @throws XMLSignatureException + */ + protected void engineUpdate(byte[] input) throws XMLSignatureException { + try { + this.macAlgorithm.update(input); + } catch (IllegalStateException ex) { + throw new XMLSignatureException("empty", ex); + } + } - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } + /** + * Proxy method for {@link java.security.Signature#update(byte)} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param input + * @throws XMLSignatureException + */ + protected void engineUpdate(byte input) throws XMLSignatureException { + try { + this.macAlgorithm.update(input); + } catch (IllegalStateException ex) { + throw new XMLSignatureException("empty", ex); + } + } - try { - this._macAlgorithm.init(secretKey); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * Proxy method for {@link java.security.Signature#update(byte[], int, int)} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param buf + * @param offset + * @param len + * @throws XMLSignatureException + */ + protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException { + try { + this.macAlgorithm.update(buf, offset, len); + } catch (IllegalStateException ex) { + throw new XMLSignatureException("empty", ex); + } + } - /** - * Method engineInitSign - * - * @param secretKey - * @param algorithmParameterSpec - * @throws XMLSignatureException - */ - protected void engineInitSign( - Key secretKey, AlgorithmParameterSpec algorithmParameterSpec) - throws XMLSignatureException { + /** + * Method engineGetJCEAlgorithmString + * @inheritDoc + * + */ + protected String engineGetJCEAlgorithmString() { + return this.macAlgorithm.getAlgorithm(); + } - if (!(secretKey instanceof SecretKey)) { - String supplied = secretKey.getClass().getName(); - String needed = SecretKey.class.getName(); - Object exArgs[] = { supplied, needed }; + /** + * Method engineGetJCEAlgorithmString + * + * @inheritDoc + */ + protected String engineGetJCEProviderName() { + return this.macAlgorithm.getProvider().getName(); + } - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } + /** + * Method engineSetHMACOutputLength + * + * @param HMACOutputLength + */ + protected void engineSetHMACOutputLength(int HMACOutputLength) { + this.HMACOutputLength = HMACOutputLength; + this.HMACOutputLengthSet = true; + } - try { - this._macAlgorithm.init(secretKey, algorithmParameterSpec); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } catch (InvalidAlgorithmParameterException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * Method engineGetContextFromElement + * + * @param element + */ + protected void engineGetContextFromElement(Element element) { + super.engineGetContextFromElement(element); - /** - * Method engineInitSign - * - * @param secretKey - * @param secureRandom - * @throws XMLSignatureException - */ - protected void engineInitSign(Key secretKey, SecureRandom secureRandom) - throws XMLSignatureException { - throw new XMLSignatureException("algorithms.CannotUseSecureRandomOnMAC"); - } + if (element == null) { + throw new IllegalArgumentException("element null"); + } - /** - * Proxy method for {@link java.security.Signature#update(byte[])} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param input - * @throws XMLSignatureException - */ - protected void engineUpdate(byte[] input) throws XMLSignatureException { + Text hmaclength = + XMLUtils.selectDsNodeText(element.getFirstChild(), Constants._TAG_HMACOUTPUTLENGTH, 0); - try { - this._macAlgorithm.update(input); - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } + if (hmaclength != null) { + this.HMACOutputLength = Integer.parseInt(hmaclength.getData()); + this.HMACOutputLengthSet = true; + } + } - /** - * Proxy method for {@link java.security.Signature#update(byte)} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param input - * @throws XMLSignatureException - */ - protected void engineUpdate(byte input) throws XMLSignatureException { + /** + * Method engineAddContextToElement + * + * @param element + */ + public void engineAddContextToElement(Element element) { + if (element == null) { + throw new IllegalArgumentException("null element"); + } - try { - this._macAlgorithm.update(input); - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } + if (this.HMACOutputLengthSet) { + Document doc = element.getOwnerDocument(); + Element HMElem = + XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_HMACOUTPUTLENGTH); + Text HMText = + doc.createTextNode(Integer.valueOf(this.HMACOutputLength).toString()); - /** - * Proxy method for {@link java.security.Signature#update(byte[], int, int)} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param buf - * @param offset - * @param len - * @throws XMLSignatureException - */ - protected void engineUpdate(byte buf[], int offset, int len) - throws XMLSignatureException { + HMElem.appendChild(HMText); + XMLUtils.addReturnToElement(element); + element.appendChild(HMElem); + XMLUtils.addReturnToElement(element); + } + } - try { - this._macAlgorithm.update(buf, offset, len); - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * Class IntegrityHmacSHA1 + */ + public static class IntegrityHmacSHA1 extends IntegrityHmac { - /** - * Method engineGetJCEAlgorithmString - * @inheritDoc - * - */ - protected String engineGetJCEAlgorithmString() { + /** + * Constructor IntegrityHmacSHA1 + * + * @throws XMLSignatureException + */ + public IntegrityHmacSHA1() throws XMLSignatureException { + super(); + } - log.log(java.util.logging.Level.FINE, "engineGetJCEAlgorithmString()"); + /** + * Method engineGetURI + * @inheritDoc + * + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_SHA1; + } - return this._macAlgorithm.getAlgorithm(); - } + int getDigestLength() { + return 160; + } + } - /** - * Method engineGetJCEAlgorithmString - * - * @inheritDoc - */ - protected String engineGetJCEProviderName() { - return this._macAlgorithm.getProvider().getName(); - } + /** + * Class IntegrityHmacSHA256 + */ + public static class IntegrityHmacSHA256 extends IntegrityHmac { - /** - * Method engineSetHMACOutputLength - * - * @param HMACOutputLength - */ - protected void engineSetHMACOutputLength(int HMACOutputLength) { - this._HMACOutputLength = HMACOutputLength; - this._HMACOutputLengthSet = true; - } + /** + * Constructor IntegrityHmacSHA256 + * + * @throws XMLSignatureException + */ + public IntegrityHmacSHA256() throws XMLSignatureException { + super(); + } - /** - * Method engineGetContextFromElement - * - * @param element - */ - protected void engineGetContextFromElement(Element element) { + /** + * Method engineGetURI + * + * @inheritDoc + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_SHA256; + } - super.engineGetContextFromElement(element); + int getDigestLength() { + return 256; + } + } - if (element == null) { - throw new IllegalArgumentException("element null"); - } + /** + * Class IntegrityHmacSHA384 + */ + public static class IntegrityHmacSHA384 extends IntegrityHmac { - Text hmaclength =XMLUtils.selectDsNodeText(element.getFirstChild(), - Constants._TAG_HMACOUTPUTLENGTH,0); + /** + * Constructor IntegrityHmacSHA384 + * + * @throws XMLSignatureException + */ + public IntegrityHmacSHA384() throws XMLSignatureException { + super(); + } - if (hmaclength != null) { - this._HMACOutputLength = Integer.parseInt(hmaclength.getData()); - this._HMACOutputLengthSet = true; - } + /** + * Method engineGetURI + * @inheritDoc + * + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_SHA384; + } - } + int getDigestLength() { + return 384; + } + } - /** - * Method engineAddContextToElement - * - * @param element - */ - public void engineAddContextToElement(Element element) { + /** + * Class IntegrityHmacSHA512 + */ + public static class IntegrityHmacSHA512 extends IntegrityHmac { - if (element == null) { - throw new IllegalArgumentException("null element"); - } + /** + * Constructor IntegrityHmacSHA512 + * + * @throws XMLSignatureException + */ + public IntegrityHmacSHA512() throws XMLSignatureException { + super(); + } - if (this._HMACOutputLengthSet) { - Document doc = element.getOwnerDocument(); - Element HMElem = XMLUtils.createElementInSignatureSpace(doc, - Constants._TAG_HMACOUTPUTLENGTH); - Text HMText = - doc.createTextNode(new Integer(this._HMACOutputLength).toString()); + /** + * Method engineGetURI + * @inheritDoc + * + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_SHA512; + } - HMElem.appendChild(HMText); - XMLUtils.addReturnToElement(element); - element.appendChild(HMElem); - XMLUtils.addReturnToElement(element); - } - } + int getDigestLength() { + return 512; + } + } - /** - * Class IntegrityHmacSHA1 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - public static class IntegrityHmacSHA1 extends IntegrityHmac { + /** + * Class IntegrityHmacRIPEMD160 + */ + public static class IntegrityHmacRIPEMD160 extends IntegrityHmac { - /** - * Constructor IntegrityHmacSHA1 - * - * @throws XMLSignatureException - */ - public IntegrityHmacSHA1() throws XMLSignatureException { - super(); - } + /** + * Constructor IntegrityHmacRIPEMD160 + * + * @throws XMLSignatureException + */ + public IntegrityHmacRIPEMD160() throws XMLSignatureException { + super(); + } - /** - * Method engineGetURI - * @inheritDoc - * - */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_MAC_HMAC_SHA1; - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160; + } - int getDigestLength() { - return 160; - } - } + int getDigestLength() { + return 160; + } + } - /** - * Class IntegrityHmacSHA256 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - public static class IntegrityHmacSHA256 extends IntegrityHmac { + /** + * Class IntegrityHmacMD5 + */ + public static class IntegrityHmacMD5 extends IntegrityHmac { - /** - * Constructor IntegrityHmacSHA256 - * - * @throws XMLSignatureException - */ - public IntegrityHmacSHA256() throws XMLSignatureException { - super(); - } + /** + * Constructor IntegrityHmacMD5 + * + * @throws XMLSignatureException + */ + public IntegrityHmacMD5() throws XMLSignatureException { + super(); + } - /** - * Method engineGetURI - * - * @inheritDoc - */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_MAC_HMAC_SHA256; - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5; + } - int getDigestLength() { - return 256; - } - } - - /** - * Class IntegrityHmacSHA384 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - public static class IntegrityHmacSHA384 extends IntegrityHmac { - - /** - * Constructor IntegrityHmacSHA384 - * - * @throws XMLSignatureException - */ - public IntegrityHmacSHA384() throws XMLSignatureException { - super(); - } - - /** - * Method engineGetURI - * @inheritDoc - * - */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_MAC_HMAC_SHA384; - } - - int getDigestLength() { - return 384; - } - } - - /** - * Class IntegrityHmacSHA512 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - public static class IntegrityHmacSHA512 extends IntegrityHmac { - - /** - * Constructor IntegrityHmacSHA512 - * - * @throws XMLSignatureException - */ - public IntegrityHmacSHA512() throws XMLSignatureException { - super(); - } - - /** - * Method engineGetURI - * @inheritDoc - * - */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_MAC_HMAC_SHA512; - } - - int getDigestLength() { - return 512; - } - } - - /** - * Class IntegrityHmacRIPEMD160 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - public static class IntegrityHmacRIPEMD160 extends IntegrityHmac { - - /** - * Constructor IntegrityHmacRIPEMD160 - * - * @throws XMLSignatureException - */ - public IntegrityHmacRIPEMD160() throws XMLSignatureException { - super(); - } - - /** - * Method engineGetURI - * - * @inheritDoc - */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160; - } - - int getDigestLength() { - return 160; - } - } - - /** - * Class IntegrityHmacMD5 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - public static class IntegrityHmacMD5 extends IntegrityHmac { - - /** - * Constructor IntegrityHmacMD5 - * - * @throws XMLSignatureException - */ - public IntegrityHmacMD5() throws XMLSignatureException { - super(); - } - - /** - * Method engineGetURI - * - * @inheritDoc - */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5; - } - - int getDigestLength() { - return 128; - } - } + int getDigestLength() { + return 128; + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java index ccc01b01c58..7460f66ffd6 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2007 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.algorithms.implementations; @@ -36,22 +38,17 @@ import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithmSpi import com.sun.org.apache.xml.internal.security.signature.XMLSignature; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; -/** - * - * @author $Author: mullan $ - */ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger - (SignatureBaseRSA.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(SignatureBaseRSA.class.getName()); /** @inheritDoc */ public abstract String engineGetURI(); /** Field algorithm */ - private java.security.Signature _signatureAlgorithm = null; + private java.security.Signature signatureAlgorithm = null; /** * Constructor SignatureRSA @@ -59,17 +56,17 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { * @throws XMLSignatureException */ public SignatureBaseRSA() throws XMLSignatureException { - String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); - if (log.isLoggable(java.util.logging.Level.FINE)) + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Created SignatureRSA using " + algorithmID); - String provider=JCEMapper.getProviderId(); + } + String provider = JCEMapper.getProviderId(); try { - if (provider==null) { - this._signatureAlgorithm = Signature.getInstance(algorithmID); + if (provider == null) { + this.signatureAlgorithm = Signature.getInstance(algorithmID); } else { - this._signatureAlgorithm = Signature.getInstance(algorithmID,provider); + this.signatureAlgorithm = Signature.getInstance(algorithmID,provider); } } catch (java.security.NoSuchAlgorithmException ex) { Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; @@ -85,20 +82,17 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @inheritDoc */ protected void engineSetParameter(AlgorithmParameterSpec params) throws XMLSignatureException { - try { - this._signatureAlgorithm.setParameter(params); + this.signatureAlgorithm.setParameter(params); } catch (InvalidAlgorithmParameterException ex) { throw new XMLSignatureException("empty", ex); } } /** @inheritDoc */ - protected boolean engineVerify(byte[] signature) - throws XMLSignatureException { - + protected boolean engineVerify(byte[] signature) throws XMLSignatureException { try { - return this._signatureAlgorithm.verify(signature); + return this.signatureAlgorithm.verify(signature); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } @@ -106,32 +100,29 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @inheritDoc */ protected void engineInitVerify(Key publicKey) throws XMLSignatureException { - if (!(publicKey instanceof PublicKey)) { String supplied = publicKey.getClass().getName(); String needed = PublicKey.class.getName(); Object exArgs[] = { supplied, needed }; - throw new XMLSignatureException - ("algorithms.WrongKeyForThisOperation", exArgs); + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); } try { - this._signatureAlgorithm.initVerify((PublicKey) publicKey); + this.signatureAlgorithm.initVerify((PublicKey) publicKey); } catch (InvalidKeyException ex) { // reinstantiate Signature object to work around bug in JDK // see: http://bugs.sun.com/view_bug.do?bug_id=4953555 - Signature sig = this._signatureAlgorithm; + Signature sig = this.signatureAlgorithm; try { - this._signatureAlgorithm = Signature.getInstance - (_signatureAlgorithm.getAlgorithm()); + this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm()); } catch (Exception e) { // this shouldn't occur, but if it does, restore previous // Signature if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e); } - this._signatureAlgorithm = sig; + this.signatureAlgorithm = sig; } throw new XMLSignatureException("empty", ex); } @@ -140,7 +131,7 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @inheritDoc */ protected byte[] engineSign() throws XMLSignatureException { try { - return this._signatureAlgorithm.sign(); + return this.signatureAlgorithm.sign(); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } @@ -149,19 +140,16 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @inheritDoc */ protected void engineInitSign(Key privateKey, SecureRandom secureRandom) throws XMLSignatureException { - if (!(privateKey instanceof PrivateKey)) { String supplied = privateKey.getClass().getName(); String needed = PrivateKey.class.getName(); Object exArgs[] = { supplied, needed }; - throw new XMLSignatureException - ("algorithms.WrongKeyForThisOperation", exArgs); + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); } try { - this._signatureAlgorithm.initSign - ((PrivateKey) privateKey, secureRandom); + this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom); } catch (InvalidKeyException ex) { throw new XMLSignatureException("empty", ex); } @@ -169,18 +157,16 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @inheritDoc */ protected void engineInitSign(Key privateKey) throws XMLSignatureException { - if (!(privateKey instanceof PrivateKey)) { String supplied = privateKey.getClass().getName(); String needed = PrivateKey.class.getName(); Object exArgs[] = { supplied, needed }; - throw new XMLSignatureException - ("algorithms.WrongKeyForThisOperation", exArgs); + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); } try { - this._signatureAlgorithm.initSign((PrivateKey) privateKey); + this.signatureAlgorithm.initSign((PrivateKey) privateKey); } catch (InvalidKeyException ex) { throw new XMLSignatureException("empty", ex); } @@ -189,7 +175,7 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @inheritDoc */ protected void engineUpdate(byte[] input) throws XMLSignatureException { try { - this._signatureAlgorithm.update(input); + this.signatureAlgorithm.update(input); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } @@ -198,17 +184,16 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @inheritDoc */ protected void engineUpdate(byte input) throws XMLSignatureException { try { - this._signatureAlgorithm.update(input); + this.signatureAlgorithm.update(input); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } } /** @inheritDoc */ - protected void engineUpdate(byte buf[], int offset, int len) - throws XMLSignatureException { + protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException { try { - this._signatureAlgorithm.update(buf, offset, len); + this.signatureAlgorithm.update(buf, offset, len); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } @@ -216,34 +201,29 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @inheritDoc */ protected String engineGetJCEAlgorithmString() { - return this._signatureAlgorithm.getAlgorithm(); + return this.signatureAlgorithm.getAlgorithm(); } /** @inheritDoc */ protected String engineGetJCEProviderName() { - return this._signatureAlgorithm.getProvider().getName(); + return this.signatureAlgorithm.getProvider().getName(); } /** @inheritDoc */ protected void engineSetHMACOutputLength(int HMACOutputLength) throws XMLSignatureException { - throw new XMLSignatureException - ("algorithms.HMACOutputLengthOnlyForHMAC"); + throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC"); } /** @inheritDoc */ protected void engineInitSign( - Key signingKey, AlgorithmParameterSpec algorithmParameterSpec) - throws XMLSignatureException { - throw new XMLSignatureException( - "algorithms.CannotUseAlgorithmParameterSpecOnRSA"); + Key signingKey, AlgorithmParameterSpec algorithmParameterSpec + ) throws XMLSignatureException { + throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnRSA"); } /** * Class SignatureRSASHA1 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSASHA1 extends SignatureBaseRSA { @@ -264,9 +244,6 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** * Class SignatureRSASHA256 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSASHA256 extends SignatureBaseRSA { @@ -287,9 +264,6 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** * Class SignatureRSASHA384 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSASHA384 extends SignatureBaseRSA { @@ -310,9 +284,6 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** * Class SignatureRSASHA512 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSASHA512 extends SignatureBaseRSA { @@ -333,9 +304,6 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** * Class SignatureRSARIPEMD160 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSARIPEMD160 extends SignatureBaseRSA { @@ -356,9 +324,6 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** * Class SignatureRSAMD5 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSAMD5 extends SignatureBaseRSA { diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java index 615aa436e46..0c6aca1361a 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.algorithms.implementations; @@ -37,21 +39,17 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import com.sun.org.apache.xml.internal.security.utils.Base64; import com.sun.org.apache.xml.internal.security.utils.Constants; -/** - * - * @author $Author: mullan $ - */ public class SignatureDSA extends SignatureAlgorithmSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(SignatureDSA.class.getName()); - /** Field _URI */ - public static final String _URI = Constants.SignatureSpecNS + "dsa-sha1"; + /** Field URI */ + public static final String URI = Constants.SignatureSpecNS + "dsa-sha1"; /** Field algorithm */ - private java.security.Signature _signatureAlgorithm = null; + private java.security.Signature signatureAlgorithm = null; /** * Method engineGetURI @@ -59,7 +57,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @inheritDoc */ protected String engineGetURI() { - return SignatureDSA._URI; + return SignatureDSA.URI; } /** @@ -68,17 +66,17 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @throws XMLSignatureException */ public SignatureDSA() throws XMLSignatureException { - - String algorithmID = JCEMapper.translateURItoJCEID(SignatureDSA._URI); - if (log.isLoggable(java.util.logging.Level.FINE)) + String algorithmID = JCEMapper.translateURItoJCEID(SignatureDSA.URI); + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Created SignatureDSA using " + algorithmID); + } String provider = JCEMapper.getProviderId(); try { if (provider == null) { - this._signatureAlgorithm = Signature.getInstance(algorithmID); + this.signatureAlgorithm = Signature.getInstance(algorithmID); } else { - this._signatureAlgorithm = + this.signatureAlgorithm = Signature.getInstance(algorithmID, provider); } } catch (java.security.NoSuchAlgorithmException ex) { @@ -95,9 +93,8 @@ public class SignatureDSA extends SignatureAlgorithmSpi { */ protected void engineSetParameter(AlgorithmParameterSpec params) throws XMLSignatureException { - try { - this._signatureAlgorithm.setParameter(params); + this.signatureAlgorithm.setParameter(params); } catch (InvalidAlgorithmParameterException ex) { throw new XMLSignatureException("empty", ex); } @@ -107,15 +104,15 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @inheritDoc */ protected boolean engineVerify(byte[] signature) - throws XMLSignatureException { - + throws XMLSignatureException { try { - if (log.isLoggable(java.util.logging.Level.FINE)) + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Called DSA.verify() on " + Base64.encode(signature)); + } byte[] jcebytes = SignatureDSA.convertXMLDSIGtoASN1(signature); - return this._signatureAlgorithm.verify(jcebytes); + return this.signatureAlgorithm.verify(jcebytes); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } catch (IOException ex) { @@ -127,32 +124,29 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @inheritDoc */ protected void engineInitVerify(Key publicKey) throws XMLSignatureException { - if (!(publicKey instanceof PublicKey)) { String supplied = publicKey.getClass().getName(); String needed = PublicKey.class.getName(); Object exArgs[] = { supplied, needed }; - throw new XMLSignatureException - ("algorithms.WrongKeyForThisOperation", exArgs); + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); } try { - this._signatureAlgorithm.initVerify((PublicKey) publicKey); + this.signatureAlgorithm.initVerify((PublicKey) publicKey); } catch (InvalidKeyException ex) { // reinstantiate Signature object to work around bug in JDK // see: http://bugs.sun.com/view_bug.do?bug_id=4953555 - Signature sig = this._signatureAlgorithm; + Signature sig = this.signatureAlgorithm; try { - this._signatureAlgorithm = Signature.getInstance - (_signatureAlgorithm.getAlgorithm()); + this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm()); } catch (Exception e) { // this shouldn't occur, but if it does, restore previous // Signature if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e); } - this._signatureAlgorithm = sig; + this.signatureAlgorithm = sig; } throw new XMLSignatureException("empty", ex); } @@ -162,9 +156,8 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @inheritDoc */ protected byte[] engineSign() throws XMLSignatureException { - try { - byte jcebytes[] = this._signatureAlgorithm.sign(); + byte jcebytes[] = this.signatureAlgorithm.sign(); return SignatureDSA.convertASN1toXMLDSIG(jcebytes); } catch (IOException ex) { @@ -178,20 +171,17 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @inheritDoc */ protected void engineInitSign(Key privateKey, SecureRandom secureRandom) - throws XMLSignatureException { - + throws XMLSignatureException { if (!(privateKey instanceof PrivateKey)) { String supplied = privateKey.getClass().getName(); String needed = PrivateKey.class.getName(); Object exArgs[] = { supplied, needed }; - throw new XMLSignatureException - ("algorithms.WrongKeyForThisOperation", exArgs); + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); } try { - this._signatureAlgorithm.initSign((PrivateKey) privateKey, - secureRandom); + this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom); } catch (InvalidKeyException ex) { throw new XMLSignatureException("empty", ex); } @@ -201,18 +191,16 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @inheritDoc */ protected void engineInitSign(Key privateKey) throws XMLSignatureException { - if (!(privateKey instanceof PrivateKey)) { String supplied = privateKey.getClass().getName(); String needed = PrivateKey.class.getName(); Object exArgs[] = { supplied, needed }; - throw new XMLSignatureException - ("algorithms.WrongKeyForThisOperation", exArgs); + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); } try { - this._signatureAlgorithm.initSign((PrivateKey) privateKey); + this.signatureAlgorithm.initSign((PrivateKey) privateKey); } catch (InvalidKeyException ex) { throw new XMLSignatureException("empty", ex); } @@ -223,7 +211,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { */ protected void engineUpdate(byte[] input) throws XMLSignatureException { try { - this._signatureAlgorithm.update(input); + this.signatureAlgorithm.update(input); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } @@ -234,7 +222,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { */ protected void engineUpdate(byte input) throws XMLSignatureException { try { - this._signatureAlgorithm.update(input); + this.signatureAlgorithm.update(input); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } @@ -243,10 +231,9 @@ public class SignatureDSA extends SignatureAlgorithmSpi { /** * @inheritDoc */ - protected void engineUpdate(byte buf[], int offset, int len) - throws XMLSignatureException { + protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException { try { - this._signatureAlgorithm.update(buf, offset, len); + this.signatureAlgorithm.update(buf, offset, len); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } @@ -258,7 +245,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @inheritDoc */ protected String engineGetJCEAlgorithmString() { - return this._signatureAlgorithm.getAlgorithm(); + return this.signatureAlgorithm.getAlgorithm(); } /** @@ -267,7 +254,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @inheritDoc */ protected String engineGetJCEProviderName() { - return this._signatureAlgorithm.getProvider().getName(); + return this.signatureAlgorithm.getProvider().getName(); } /** @@ -282,8 +269,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @throws IOException * @see 6.4.1 DSA */ - private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) - throws IOException { + private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) throws IOException { byte rLength = asn1Bytes[3]; int i; @@ -294,19 +280,18 @@ public class SignatureDSA extends SignatureAlgorithmSpi { int j; for (j = sLength; - (j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--); + (j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--); if ((asn1Bytes[0] != 48) || (asn1Bytes[1] != asn1Bytes.length - 2) - || (asn1Bytes[2] != 2) || (i > 20) - || (asn1Bytes[4 + rLength] != 2) || (j > 20)) { + || (asn1Bytes[2] != 2) || (i > 20) + || (asn1Bytes[4 + rLength] != 2) || (j > 20)) { throw new IOException("Invalid ASN.1 format of DSA signature"); } byte xmldsigBytes[] = new byte[40]; - System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 20 - i, - i); + System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 20 - i, i); System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes, - 40 - j, j); + 40 - j, j); return xmldsigBytes; } @@ -323,8 +308,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @throws IOException * @see 6.4.1 DSA */ - private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) - throws IOException { + private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException { if (xmldsigBytes.length != 40) { throw new IOException("Invalid XMLDSIG format of DSA signature"); @@ -337,7 +321,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { int j = i; if (xmldsigBytes[20 - i] < 0) { - j += 1; + j += 1; } int k; @@ -373,10 +357,8 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @param HMACOutputLength * @throws XMLSignatureException */ - protected void engineSetHMACOutputLength(int HMACOutputLength) - throws XMLSignatureException { - throw new XMLSignatureException( - "algorithms.HMACOutputLengthOnlyForHMAC"); + protected void engineSetHMACOutputLength(int HMACOutputLength) throws XMLSignatureException { + throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC"); } /** @@ -387,9 +369,8 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @throws XMLSignatureException */ protected void engineInitSign( - Key signingKey, AlgorithmParameterSpec algorithmParameterSpec) - throws XMLSignatureException { - throw new XMLSignatureException( - "algorithms.CannotUseAlgorithmParameterSpecOnDSA"); + Key signingKey, AlgorithmParameterSpec algorithmParameterSpec + ) throws XMLSignatureException { + throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnDSA"); } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java index 18fdffe28fb..8da7a8c6e67 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.algorithms.implementations; - - import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; @@ -40,345 +40,417 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignature; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import com.sun.org.apache.xml.internal.security.utils.Base64; - /** * - * @author $Author: mullan $ + * @author $Author: raul $ + * @author Alex Dupre */ public abstract class SignatureECDSA extends SignatureAlgorithmSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(SignatureECDSA.class.getName()); /** @inheritDoc */ - public abstract String engineGetURI(); + public abstract String engineGetURI(); - /** Field algorithm */ - private java.security.Signature _signatureAlgorithm = null; + /** Field algorithm */ + private java.security.Signature signatureAlgorithm = null; - /** - * Converts an ASN.1 ECDSA value to a XML Signature ECDSA Value. - * - * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value - * pairs; the XML Signature requires the core BigInteger values. - * - * @param asn1Bytes - * @return the decode bytes - * - * @throws IOException - * @see 6.4.1 DSA - * @see 3.3. ECDSA Signatures - */ - private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) - throws IOException { + /** + * Converts an ASN.1 ECDSA value to a XML Signature ECDSA Value. + * + * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value + * pairs; the XML Signature requires the core BigInteger values. + * + * @param asn1Bytes + * @return the decode bytes + * + * @throws IOException + * @see 6.4.1 DSA + * @see 3.3. ECDSA Signatures + */ + public static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) throws IOException { - byte rLength = asn1Bytes[3]; - int i; - - for (i = rLength; (i > 0) && (asn1Bytes[(4 + rLength) - i] == 0); i--); - - byte sLength = asn1Bytes[5 + rLength]; - int j; - - for (j = sLength; - (j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--); - - if ((asn1Bytes[0] != 48) || (asn1Bytes[1] != asn1Bytes.length - 2) - || (asn1Bytes[2] != 2) || (i > 24) - || (asn1Bytes[4 + rLength] != 2) || (j > 24)) { - throw new IOException("Invalid ASN.1 format of ECDSA signature"); - } - byte xmldsigBytes[] = new byte[48]; - - System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 24 - i, - i); - System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes, - 48 - j, j); - - return xmldsigBytes; - } - - /** - * Converts a XML Signature ECDSA Value to an ASN.1 DSA value. - * - * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value - * pairs; the XML Signature requires the core BigInteger values. - * - * @param xmldsigBytes - * @return the encoded ASN.1 bytes - * - * @throws IOException - * @see 6.4.1 DSA - * @see 3.3. ECDSA Signatures - */ - private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) - throws IOException { - - if (xmldsigBytes.length != 48) { - throw new IOException("Invalid XMLDSIG format of ECDSA signature"); - } - - int i; - - for (i = 24; (i > 0) && (xmldsigBytes[24 - i] == 0); i--); - - int j = i; - - if (xmldsigBytes[24 - i] < 0) { - j += 1; - } - - int k; - - for (k = 24; (k > 0) && (xmldsigBytes[48 - k] == 0); k--); - - int l = k; - - if (xmldsigBytes[48 - k] < 0) { - l += 1; - } - - byte asn1Bytes[] = new byte[6 + j + l]; - - asn1Bytes[0] = 48; - asn1Bytes[1] = (byte) (4 + j + l); - asn1Bytes[2] = 2; - asn1Bytes[3] = (byte) j; - - System.arraycopy(xmldsigBytes, 24 - i, asn1Bytes, (4 + j) - i, i); - - asn1Bytes[4 + j] = 2; - asn1Bytes[5 + j] = (byte) l; - - System.arraycopy(xmldsigBytes, 48 - k, asn1Bytes, (6 + j + l) - k, k); - - return asn1Bytes; - } - - /** - * Constructor SignatureRSA - * - * @throws XMLSignatureException - */ - public SignatureECDSA() throws XMLSignatureException { - - String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); - - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Created SignatureECDSA using " + algorithmID); - String provider=JCEMapper.getProviderId(); - try { - if (provider==null) { - this._signatureAlgorithm = Signature.getInstance(algorithmID); - } else { - this._signatureAlgorithm = Signature.getInstance(algorithmID,provider); - } - } catch (java.security.NoSuchAlgorithmException ex) { - Object[] exArgs = { algorithmID, - ex.getLocalizedMessage() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); - } catch (NoSuchProviderException ex) { - Object[] exArgs = { algorithmID, - ex.getLocalizedMessage() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + if (asn1Bytes.length < 8 || asn1Bytes[0] != 48) { + throw new IOException("Invalid ASN.1 format of ECDSA signature"); + } + int offset; + if (asn1Bytes[1] > 0) { + offset = 2; + } else if (asn1Bytes[1] == (byte) 0x81) { + offset = 3; + } else { + throw new IOException("Invalid ASN.1 format of ECDSA signature"); } - } - /** @inheritDoc */ - protected void engineSetParameter(AlgorithmParameterSpec params) - throws XMLSignatureException { + byte rLength = asn1Bytes[offset + 1]; + int i; - try { - this._signatureAlgorithm.setParameter(params); - } catch (InvalidAlgorithmParameterException ex) { - throw new XMLSignatureException("empty", ex); - } - } + for (i = rLength; (i > 0) && (asn1Bytes[(offset + 2 + rLength) - i] == 0); i--); - /** @inheritDoc */ - protected boolean engineVerify(byte[] signature) - throws XMLSignatureException { + byte sLength = asn1Bytes[offset + 2 + rLength + 1]; + int j; - try { - byte[] jcebytes = SignatureECDSA.convertXMLDSIGtoASN1(signature); + for (j = sLength; + (j > 0) && (asn1Bytes[(offset + 2 + rLength + 2 + sLength) - j] == 0); j--); - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Called ECDSA.verify() on " + Base64.encode(signature)); + int rawLen = Math.max(i, j); - return this._signatureAlgorithm.verify(jcebytes); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } catch (IOException ex) { - throw new XMLSignatureException("empty", ex); - } - } + if ((asn1Bytes[offset - 1] & 0xff) != asn1Bytes.length - offset + || (asn1Bytes[offset - 1] & 0xff) != 2 + rLength + 2 + sLength + || asn1Bytes[offset] != 2 + || asn1Bytes[offset + 2 + rLength] != 2) { + throw new IOException("Invalid ASN.1 format of ECDSA signature"); + } + byte xmldsigBytes[] = new byte[2*rawLen]; - /** @inheritDoc */ - protected void engineInitVerify(Key publicKey) throws XMLSignatureException { + System.arraycopy(asn1Bytes, (offset + 2 + rLength) - i, xmldsigBytes, rawLen - i, i); + System.arraycopy(asn1Bytes, (offset + 2 + rLength + 2 + sLength) - j, xmldsigBytes, + 2*rawLen - j, j); - if (!(publicKey instanceof PublicKey)) { - String supplied = publicKey.getClass().getName(); - String needed = PublicKey.class.getName(); - Object exArgs[] = { supplied, needed }; + return xmldsigBytes; + } - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } + /** + * Converts a XML Signature ECDSA Value to an ASN.1 DSA value. + * + * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value + * pairs; the XML Signature requires the core BigInteger values. + * + * @param xmldsigBytes + * @return the encoded ASN.1 bytes + * + * @throws IOException + * @see 6.4.1 DSA + * @see 3.3. ECDSA Signatures + */ + public static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException { - try { - this._signatureAlgorithm.initVerify((PublicKey) publicKey); - } catch (InvalidKeyException ex) { + int rawLen = xmldsigBytes.length/2; + + int i; + + for (i = rawLen; (i > 0) && (xmldsigBytes[rawLen - i] == 0); i--); + + int j = i; + + if (xmldsigBytes[rawLen - i] < 0) { + j += 1; + } + + int k; + + for (k = rawLen; (k > 0) && (xmldsigBytes[2*rawLen - k] == 0); k--); + + int l = k; + + if (xmldsigBytes[2*rawLen - k] < 0) { + l += 1; + } + + int len = 2 + j + 2 + l; + if (len > 255) { + throw new IOException("Invalid XMLDSIG format of ECDSA signature"); + } + int offset; + byte asn1Bytes[]; + if (len < 128) { + asn1Bytes = new byte[2 + 2 + j + 2 + l]; + offset = 1; + } else { + asn1Bytes = new byte[3 + 2 + j + 2 + l]; + asn1Bytes[1] = (byte) 0x81; + offset = 2; + } + asn1Bytes[0] = 48; + asn1Bytes[offset++] = (byte) len; + asn1Bytes[offset++] = 2; + asn1Bytes[offset++] = (byte) j; + + System.arraycopy(xmldsigBytes, rawLen - i, asn1Bytes, (offset + j) - i, i); + + offset += j; + + asn1Bytes[offset++] = 2; + asn1Bytes[offset++] = (byte) l; + + System.arraycopy(xmldsigBytes, 2*rawLen - k, asn1Bytes, (offset + l) - k, k); + + return asn1Bytes; + } + + /** + * Constructor SignatureRSA + * + * @throws XMLSignatureException + */ + public SignatureECDSA() throws XMLSignatureException { + + String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Created SignatureECDSA using " + algorithmID); + } + String provider = JCEMapper.getProviderId(); + try { + if (provider == null) { + this.signatureAlgorithm = Signature.getInstance(algorithmID); + } else { + this.signatureAlgorithm = Signature.getInstance(algorithmID,provider); + } + } catch (java.security.NoSuchAlgorithmException ex) { + Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; + + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } catch (NoSuchProviderException ex) { + Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; + + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } + } + + /** @inheritDoc */ + protected void engineSetParameter(AlgorithmParameterSpec params) + throws XMLSignatureException { + try { + this.signatureAlgorithm.setParameter(params); + } catch (InvalidAlgorithmParameterException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected boolean engineVerify(byte[] signature) throws XMLSignatureException { + try { + byte[] jcebytes = SignatureECDSA.convertXMLDSIGtoASN1(signature); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Called ECDSA.verify() on " + Base64.encode(signature)); + } + + return this.signatureAlgorithm.verify(jcebytes); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } catch (IOException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected void engineInitVerify(Key publicKey) throws XMLSignatureException { + + if (!(publicKey instanceof PublicKey)) { + String supplied = publicKey.getClass().getName(); + String needed = PublicKey.class.getName(); + Object exArgs[] = { supplied, needed }; + + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } + + try { + this.signatureAlgorithm.initVerify((PublicKey) publicKey); + } catch (InvalidKeyException ex) { // reinstantiate Signature object to work around bug in JDK // see: http://bugs.sun.com/view_bug.do?bug_id=4953555 - Signature sig = this._signatureAlgorithm; + Signature sig = this.signatureAlgorithm; try { - this._signatureAlgorithm = Signature.getInstance - (_signatureAlgorithm.getAlgorithm()); + this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm()); } catch (Exception e) { // this shouldn't occur, but if it does, restore previous // Signature if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e); } - this._signatureAlgorithm = sig; + this.signatureAlgorithm = sig; } throw new XMLSignatureException("empty", ex); - } - } + } + } - /** @inheritDoc */ - protected byte[] engineSign() throws XMLSignatureException { + /** @inheritDoc */ + protected byte[] engineSign() throws XMLSignatureException { + try { + byte jcebytes[] = this.signatureAlgorithm.sign(); - try { - byte jcebytes[] = this._signatureAlgorithm.sign(); + return SignatureECDSA.convertASN1toXMLDSIG(jcebytes); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } catch (IOException ex) { + throw new XMLSignatureException("empty", ex); + } + } - return SignatureECDSA.convertASN1toXMLDSIG(jcebytes); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } catch (IOException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** @inheritDoc */ + protected void engineInitSign(Key privateKey, SecureRandom secureRandom) + throws XMLSignatureException { + if (!(privateKey instanceof PrivateKey)) { + String supplied = privateKey.getClass().getName(); + String needed = PrivateKey.class.getName(); + Object exArgs[] = { supplied, needed }; - /** @inheritDoc */ - protected void engineInitSign(Key privateKey, SecureRandom secureRandom) - throws XMLSignatureException { + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } - if (!(privateKey instanceof PrivateKey)) { - String supplied = privateKey.getClass().getName(); - String needed = PrivateKey.class.getName(); - Object exArgs[] = { supplied, needed }; + try { + this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom); + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } + } - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } + /** @inheritDoc */ + protected void engineInitSign(Key privateKey) throws XMLSignatureException { + if (!(privateKey instanceof PrivateKey)) { + String supplied = privateKey.getClass().getName(); + String needed = PrivateKey.class.getName(); + Object exArgs[] = { supplied, needed }; - try { - this._signatureAlgorithm.initSign((PrivateKey) privateKey, - secureRandom); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } - } + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } - /** @inheritDoc */ - protected void engineInitSign(Key privateKey) throws XMLSignatureException { + try { + this.signatureAlgorithm.initSign((PrivateKey) privateKey); + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } + } - if (!(privateKey instanceof PrivateKey)) { - String supplied = privateKey.getClass().getName(); - String needed = PrivateKey.class.getName(); - Object exArgs[] = { supplied, needed }; + /** @inheritDoc */ + protected void engineUpdate(byte[] input) throws XMLSignatureException { + try { + this.signatureAlgorithm.update(input); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } + } - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } + /** @inheritDoc */ + protected void engineUpdate(byte input) throws XMLSignatureException { + try { + this.signatureAlgorithm.update(input); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } + } - try { - this._signatureAlgorithm.initSign((PrivateKey) privateKey); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** @inheritDoc */ + protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException { + try { + this.signatureAlgorithm.update(buf, offset, len); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } + } - /** @inheritDoc */ - protected void engineUpdate(byte[] input) throws XMLSignatureException { + /** @inheritDoc */ + protected String engineGetJCEAlgorithmString() { + return this.signatureAlgorithm.getAlgorithm(); + } - try { - this._signatureAlgorithm.update(input); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** @inheritDoc */ + protected String engineGetJCEProviderName() { + return this.signatureAlgorithm.getProvider().getName(); + } - /** @inheritDoc */ - protected void engineUpdate(byte input) throws XMLSignatureException { + /** @inheritDoc */ + protected void engineSetHMACOutputLength(int HMACOutputLength) + throws XMLSignatureException { + throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC"); + } - try { - this._signatureAlgorithm.update(input); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** @inheritDoc */ + protected void engineInitSign( + Key signingKey, AlgorithmParameterSpec algorithmParameterSpec + ) throws XMLSignatureException { + throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnRSA"); + } - /** @inheritDoc */ - protected void engineUpdate(byte buf[], int offset, int len) - throws XMLSignatureException { + /** + * Class SignatureRSASHA1 + * + * @author $Author: marcx $ + */ + public static class SignatureECDSASHA1 extends SignatureECDSA { + /** + * Constructor SignatureRSASHA1 + * + * @throws XMLSignatureException + */ + public SignatureECDSASHA1() throws XMLSignatureException { + super(); + } - try { - this._signatureAlgorithm.update(buf, offset, len); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** @inheritDoc */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1; + } + } - /** @inheritDoc */ - protected String engineGetJCEAlgorithmString() { - return this._signatureAlgorithm.getAlgorithm(); - } + /** + * Class SignatureRSASHA256 + * + * @author Alex Dupre + */ + public static class SignatureECDSASHA256 extends SignatureECDSA { - /** @inheritDoc */ - protected String engineGetJCEProviderName() { - return this._signatureAlgorithm.getProvider().getName(); - } + /** + * Constructor SignatureRSASHA256 + * + * @throws XMLSignatureException + */ + public SignatureECDSASHA256() throws XMLSignatureException { + super(); + } - /** @inheritDoc */ - protected void engineSetHMACOutputLength(int HMACOutputLength) - throws XMLSignatureException { - throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC"); - } + /** @inheritDoc */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256; + } + } - /** @inheritDoc */ - protected void engineInitSign( - Key signingKey, AlgorithmParameterSpec algorithmParameterSpec) - throws XMLSignatureException { - throw new XMLSignatureException( - "algorithms.CannotUseAlgorithmParameterSpecOnRSA"); - } + /** + * Class SignatureRSASHA384 + * + * @author Alex Dupre + */ + public static class SignatureECDSASHA384 extends SignatureECDSA { - /** - * Class SignatureRSASHA1 - * - * @author $Author: mullan $ - * @version $Revision: 1.2 $ - */ - public static class SignatureECDSASHA1 extends SignatureECDSA { + /** + * Constructor SignatureRSASHA384 + * + * @throws XMLSignatureException + */ + public SignatureECDSASHA384() throws XMLSignatureException { + super(); + } - /** - * Constructor SignatureRSASHA1 - * - * @throws XMLSignatureException - */ - public SignatureECDSASHA1() throws XMLSignatureException { - super(); - } + /** @inheritDoc */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384; + } + } - /** @inheritDoc */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1; - } - } + /** + * Class SignatureRSASHA512 + * + * @author Alex Dupre + */ + public static class SignatureECDSASHA512 extends SignatureECDSA { + + /** + * Constructor SignatureRSASHA512 + * + * @throws XMLSignatureException + */ + public SignatureECDSASHA512() throws XMLSignatureException { + super(); + } + + /** @inheritDoc */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512; + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java index 36c98cfe790..aae62133dcc 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java @@ -2,29 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.c14n; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - /** * Class CanonicalizationException * @@ -32,57 +31,58 @@ import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; */ public class CanonicalizationException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor CanonicalizationException - * - */ - public CanonicalizationException() { - super(); - } + /** + * Constructor CanonicalizationException + * + */ + public CanonicalizationException() { + super(); + } - /** - * Constructor CanonicalizationException - * - * @param _msgID - */ - public CanonicalizationException(String _msgID) { - super(_msgID); - } + /** + * Constructor CanonicalizationException + * + * @param msgID + */ + public CanonicalizationException(String msgID) { + super(msgID); + } - /** - * Constructor CanonicalizationException - * - * @param _msgID - * @param exArgs - */ - public CanonicalizationException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor CanonicalizationException + * + * @param msgID + * @param exArgs + */ + public CanonicalizationException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor CanonicalizationException - * - * @param _msgID - * @param _originalException - */ - public CanonicalizationException(String _msgID, Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor CanonicalizationException + * + * @param msgID + * @param originalException + */ + public CanonicalizationException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor CanonicalizationException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public CanonicalizationException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * Constructor CanonicalizationException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public CanonicalizationException( + String msgID, Object exArgs[], Exception originalException + ) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java index db1d4c261b7..2f0b31f5ed4 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java @@ -39,6 +39,7 @@ import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicaliz import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315ExclWithComments; import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315OmitComments; import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315WithComments; +import com.sun.org.apache.xml.internal.security.c14n.implementations.CanonicalizerPhysical; import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException; import org.w3c.dom.Document; import org.w3c.dom.Node; @@ -91,6 +92,11 @@ public class Canonicalizer { */ public static final String ALGO_ID_C14N11_WITH_COMMENTS = ALGO_ID_C14N11_OMIT_COMMENTS + "#WithComments"; + /** + * Non-standard algorithm to serialize the physical representation for XML Encryption + */ + public static final String ALGO_ID_C14N_PHYSICAL = + "http://santuario.apache.org/c14n/physical"; private static Map> canonicalizerHash = new ConcurrentHashMap>(); @@ -202,6 +208,10 @@ public class Canonicalizer { Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS, Canonicalizer11_WithComments.class ); + canonicalizerHash.put( + Canonicalizer.ALGO_ID_C14N_PHYSICAL, + CanonicalizerPhysical.class + ); } /** diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java index 7e150e365b4..da5047d2052 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.c14n; - - import java.io.ByteArrayInputStream; import java.io.OutputStream; import java.util.Set; @@ -29,7 +29,6 @@ import java.util.Set; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.xpath.XPath; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Document; @@ -37,166 +36,134 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; - /** - * Base class which all Caninicalization algorithms extend. + * Base class which all Canonicalization algorithms extend. * - * $todo$ cange JavaDoc * @author Christian Geuer-Pollmann */ public abstract class CanonicalizerSpi { - /** - * Method canonicalize - * - * - * @param inputBytes - * @return the c14n bytes. - * - * - * @throws CanonicalizationException - * @throws java.io.IOException - * @throws javax.xml.parsers.ParserConfigurationException - * @throws org.xml.sax.SAXException - * - */ - public byte[] engineCanonicalize(byte[] inputBytes) - throws javax.xml.parsers.ParserConfigurationException, - java.io.IOException, org.xml.sax.SAXException, - CanonicalizationException { + /** Reset the writer after a c14n */ + protected boolean reset = false; - java.io.ByteArrayInputStream bais = new ByteArrayInputStream(inputBytes); - InputSource in = new InputSource(bais); - DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); - dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + /** + * Method canonicalize + * + * @param inputBytes + * @return the c14n bytes. + * + * @throws CanonicalizationException + * @throws java.io.IOException + * @throws javax.xml.parsers.ParserConfigurationException + * @throws org.xml.sax.SAXException + */ + public byte[] engineCanonicalize(byte[] inputBytes) + throws javax.xml.parsers.ParserConfigurationException, java.io.IOException, + org.xml.sax.SAXException, CanonicalizationException { - // needs to validate for ID attribute nomalization - dfactory.setNamespaceAware(true); + java.io.InputStream bais = new ByteArrayInputStream(inputBytes); + InputSource in = new InputSource(bais); + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); - DocumentBuilder db = dfactory.newDocumentBuilder(); + // needs to validate for ID attribute normalization + dfactory.setNamespaceAware(true); - /* - * for some of the test vectors from the specification, - * there has to be a validatin parser for ID attributes, default - * attribute values, NMTOKENS, etc. - * Unfortunaltely, the test vectors do use different DTDs or - * even no DTD. So Xerces 1.3.1 fires many warnings about using - * ErrorHandlers. - * - * Text from the spec: - * - * The input octet stream MUST contain a well-formed XML document, - * but the input need not be validated. However, the attribute - * value normalization and entity reference resolution MUST be - * performed in accordance with the behaviors of a validating - * XML processor. As well, nodes for default attributes (declared - * in the ATTLIST with an AttValue but not specified) are created - * in each element. Thus, the declarations in the document type - * declaration are used to help create the canonical form, even - * though the document type declaration is not retained in the - * canonical form. - * - */ + DocumentBuilder db = dfactory.newDocumentBuilder(); - // ErrorHandler eh = new C14NErrorHandler(); - // db.setErrorHandler(eh); - Document document = db.parse(in); - byte result[] = this.engineCanonicalizeSubTree(document); - return result; - } + Document document = db.parse(in); + return this.engineCanonicalizeSubTree(document); + } - /** - * Method engineCanonicalizeXPathNodeSet - * - * @param xpathNodeSet - * @return the c14n bytes - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet) - throws CanonicalizationException { + /** + * Method engineCanonicalizeXPathNodeSet + * + * @param xpathNodeSet + * @return the c14n bytes + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet) + throws CanonicalizationException { + return this.engineCanonicalizeXPathNodeSet( + XMLUtils.convertNodelistToSet(xpathNodeSet) + ); + } - return this - .engineCanonicalizeXPathNodeSet(XMLUtils - .convertNodelistToSet(xpathNodeSet)); - } + /** + * Method engineCanonicalizeXPathNodeSet + * + * @param xpathNodeSet + * @param inclusiveNamespaces + * @return the c14n bytes + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet, String inclusiveNamespaces) + throws CanonicalizationException { + return this.engineCanonicalizeXPathNodeSet( + XMLUtils.convertNodelistToSet(xpathNodeSet), inclusiveNamespaces + ); + } - /** - * Method engineCanonicalizeXPathNodeSet - * - * @param xpathNodeSet - * @param inclusiveNamespaces - * @return the c14n bytes - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet, String inclusiveNamespaces) - throws CanonicalizationException { + /** + * Returns the URI of this engine. + * @return the URI + */ + public abstract String engineGetURI(); - return this - .engineCanonicalizeXPathNodeSet(XMLUtils - .convertNodelistToSet(xpathNodeSet), inclusiveNamespaces); - } + /** + * Returns true if comments are included + * @return true if comments are included + */ + public abstract boolean engineGetIncludeComments(); - //J- - /** Returns the URI of this engine. - * @return the URI - */ - public abstract String engineGetURI(); + /** + * C14n a nodeset + * + * @param xpathNodeSet + * @return the c14n bytes + * @throws CanonicalizationException + */ + public abstract byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet) + throws CanonicalizationException; - /** Returns the URI if include comments - * @return true if include. - */ - public abstract boolean engineGetIncludeComments(); + /** + * C14n a nodeset + * + * @param xpathNodeSet + * @param inclusiveNamespaces + * @return the c14n bytes + * @throws CanonicalizationException + */ + public abstract byte[] engineCanonicalizeXPathNodeSet( + Set xpathNodeSet, String inclusiveNamespaces + ) throws CanonicalizationException; - /** - * C14n a nodeset - * - * @param xpathNodeSet - * @return the c14n bytes - * @throws CanonicalizationException - */ - public abstract byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet) - throws CanonicalizationException; + /** + * C14n a node tree. + * + * @param rootNode + * @return the c14n bytes + * @throws CanonicalizationException + */ + public abstract byte[] engineCanonicalizeSubTree(Node rootNode) + throws CanonicalizationException; - /** - * C14n a nodeset - * - * @param xpathNodeSet - * @param inclusiveNamespaces - * @return the c14n bytes - * @throws CanonicalizationException - */ - public abstract byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet, String inclusiveNamespaces) - throws CanonicalizationException; + /** + * C14n a node tree. + * + * @param rootNode + * @param inclusiveNamespaces + * @return the c14n bytes + * @throws CanonicalizationException + */ + public abstract byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces) + throws CanonicalizationException; - /** - * C14n a node tree. - * - * @param rootNode - * @return the c14n bytes - * @throws CanonicalizationException - */ - public abstract byte[] engineCanonicalizeSubTree(Node rootNode) - throws CanonicalizationException; + /** + * Sets the writer where the canonicalization ends. ByteArrayOutputStream if + * none is set. + * @param os + */ + public abstract void setWriter(OutputStream os); - /** - * C14n a node tree. - * - * @param rootNode - * @param inclusiveNamespaces - * @return the c14n bytes - * @throws CanonicalizationException - */ - public abstract byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces) - throws CanonicalizationException; - - /** - * Sets the writter where the cannocalization ends. ByteArrayOutputStream if - * none is setted. - * @param os - */ - public abstract void setWriter(OutputStream os); - - /** Reset the writter after a c14n */ - protected boolean reset=false; - //J+ } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java index 9fb1531b7e9..c0dee5e93f3 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java @@ -2,87 +2,82 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.c14n; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - -/** - * - * @author Christian Geuer-Pollmann - */ public class InvalidCanonicalizerException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor InvalidCanonicalizerException - * - */ - public InvalidCanonicalizerException() { - super(); - } + /** + * Constructor InvalidCanonicalizerException + * + */ + public InvalidCanonicalizerException() { + super(); + } - /** - * Constructor InvalidCanonicalizerException - * - * @param _msgID - */ - public InvalidCanonicalizerException(String _msgID) { - super(_msgID); - } + /** + * Constructor InvalidCanonicalizerException + * + * @param msgID + */ + public InvalidCanonicalizerException(String msgID) { + super(msgID); + } - /** - * Constructor InvalidCanonicalizerException - * - * @param _msgID - * @param exArgs - */ - public InvalidCanonicalizerException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor InvalidCanonicalizerException + * + * @param msgID + * @param exArgs + */ + public InvalidCanonicalizerException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor InvalidCanonicalizerException - * - * @param _msgID - * @param _originalException - */ - public InvalidCanonicalizerException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor InvalidCanonicalizerException + * + * @param msgID + * @param originalException + */ + public InvalidCanonicalizerException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor InvalidCanonicalizerException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public InvalidCanonicalizerException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * Constructor InvalidCanonicalizerException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public InvalidCanonicalizerException( + String msgID, Object exArgs[], Exception originalException + ) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java index 8675b673c72..f17a6b0d469 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.c14n.helper; @@ -43,10 +45,10 @@ import java.util.Comparator; */ public class AttrCompare implements Comparator, Serializable { - private final static long serialVersionUID = -7113259629930576230L; - private final static int ATTR0_BEFORE_ATTR1 = -1; - private final static int ATTR1_BEFORE_ATTR0 = 1; - private final static String XMLNS=Constants.NamespaceSpecNS; + private static final long serialVersionUID = -7113259629930576230L; + private static final int ATTR0_BEFORE_ATTR1 = -1; + private static final int ATTR1_BEFORE_ATTR0 = 1; + private static final String XMLNS = Constants.NamespaceSpecNS; /** * Compares two attributes based on the C14n specification. @@ -69,12 +71,11 @@ public class AttrCompare implements Comparator, Serializable { * */ public int compare(Attr attr0, Attr attr1) { - String namespaceURI0 = attr0.getNamespaceURI(); String namespaceURI1 = attr1.getNamespaceURI(); - boolean isNamespaceAttr0 = XMLNS==namespaceURI0; - boolean isNamespaceAttr1 = XMLNS==namespaceURI1; + boolean isNamespaceAttr0 = XMLNS.equals(namespaceURI0); + boolean isNamespaceAttr1 = XMLNS.equals(namespaceURI1); if (isNamespaceAttr0) { if (isNamespaceAttr1) { @@ -82,11 +83,11 @@ public class AttrCompare implements Comparator, Serializable { String localname0 = attr0.getLocalName(); String localname1 = attr1.getLocalName(); - if (localname0.equals("xmlns")) { + if ("xmlns".equals(localname0)) { localname0 = ""; } - if (localname1.equals("xmlns")) { + if ("xmlns".equals(localname1)) { localname1 = ""; } @@ -94,9 +95,7 @@ public class AttrCompare implements Comparator, Serializable { } // attr0 is a namespace, attr1 is not return ATTR0_BEFORE_ATTR1; - } - - if (isNamespaceAttr1) { + } else if (isNamespaceAttr1) { // attr1 is a namespace, attr0 is not return ATTR1_BEFORE_ATTR0; } @@ -109,9 +108,7 @@ public class AttrCompare implements Comparator, Serializable { return name0.compareTo(name1); } return ATTR0_BEFORE_ATTR1; - } - - if (namespaceURI1 == null) { + } else if (namespaceURI1 == null) { return ATTR1_BEFORE_ATTR0; } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java index 0c720fd35f9..ecd0c52899c 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java @@ -2,33 +2,32 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.c14n.helper; - - import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; - /** * Temporary swapped static functions from the normalizer Section * @@ -36,129 +35,121 @@ import org.w3c.dom.NamedNodeMap; */ public class C14nHelper { - /** - * Constructor C14nHelper - * - */ - private C14nHelper() { + /** + * Constructor C14nHelper + * + */ + private C14nHelper() { + // don't allow instantiation + } - // don't allow instantiation - } + /** + * Method namespaceIsRelative + * + * @param namespace + * @return true if the given namespace is relative. + */ + public static boolean namespaceIsRelative(Attr namespace) { + return !namespaceIsAbsolute(namespace); + } - /** - * Method namespaceIsRelative - * - * @param namespace - * @return true if the given namespace is relative. - */ - public static boolean namespaceIsRelative(Attr namespace) { - return !namespaceIsAbsolute(namespace); - } + /** + * Method namespaceIsRelative + * + * @param namespaceValue + * @return true if the given namespace is relative. + */ + public static boolean namespaceIsRelative(String namespaceValue) { + return !namespaceIsAbsolute(namespaceValue); + } - /** - * Method namespaceIsRelative - * - * @param namespaceValue - * @return true if the given namespace is relative. - */ - public static boolean namespaceIsRelative(String namespaceValue) { - return !namespaceIsAbsolute(namespaceValue); - } + /** + * Method namespaceIsAbsolute + * + * @param namespace + * @return true if the given namespace is absolute. + */ + public static boolean namespaceIsAbsolute(Attr namespace) { + return namespaceIsAbsolute(namespace.getValue()); + } - /** - * Method namespaceIsAbsolute - * - * @param namespace - * @return true if the given namespace is absolute. - */ - public static boolean namespaceIsAbsolute(Attr namespace) { - return namespaceIsAbsolute(namespace.getValue()); - } + /** + * Method namespaceIsAbsolute + * + * @param namespaceValue + * @return true if the given namespace is absolute. + */ + public static boolean namespaceIsAbsolute(String namespaceValue) { + // assume empty namespaces are absolute + if (namespaceValue.length() == 0) { + return true; + } + return namespaceValue.indexOf(':') > 0; + } - /** - * Method namespaceIsAbsolute - * - * @param namespaceValue - * @return true if the given namespace is absolute. - */ - public static boolean namespaceIsAbsolute(String namespaceValue) { + /** + * This method throws an exception if the Attribute value contains + * a relative URI. + * + * @param attr + * @throws CanonicalizationException + */ + public static void assertNotRelativeNS(Attr attr) throws CanonicalizationException { + if (attr == null) { + return; + } - // assume empty namespaces are absolute - if (namespaceValue.length() == 0) { - return true; - } - return namespaceValue.indexOf(':')>0; - } + String nodeAttrName = attr.getNodeName(); + boolean definesDefaultNS = nodeAttrName.equals("xmlns"); + boolean definesNonDefaultNS = nodeAttrName.startsWith("xmlns:"); - /** - * This method throws an exception if the Attribute value contains - * a relative URI. - * - * @param attr - * @throws CanonicalizationException - */ - public static void assertNotRelativeNS(Attr attr) - throws CanonicalizationException { - - if (attr == null) { - return; - } - - String nodeAttrName = attr.getNodeName(); - boolean definesDefaultNS = nodeAttrName.equals("xmlns"); - boolean definesNonDefaultNS = nodeAttrName.startsWith("xmlns:"); - - if (definesDefaultNS || definesNonDefaultNS) { - if (namespaceIsRelative(attr)) { + if ((definesDefaultNS || definesNonDefaultNS) && namespaceIsRelative(attr)) { String parentName = attr.getOwnerElement().getTagName(); String attrValue = attr.getValue(); Object exArgs[] = { parentName, nodeAttrName, attrValue }; throw new CanonicalizationException( - "c14n.Canonicalizer.RelativeNamespace", exArgs); - } - } - } + "c14n.Canonicalizer.RelativeNamespace", exArgs + ); + } + } - /** - * This method throws a CanonicalizationException if the supplied Document - * is not able to be traversed using a TreeWalker. - * - * @param document - * @throws CanonicalizationException - */ - public static void checkTraversability(Document document) - throws CanonicalizationException { + /** + * This method throws a CanonicalizationException if the supplied Document + * is not able to be traversed using a TreeWalker. + * + * @param document + * @throws CanonicalizationException + */ + public static void checkTraversability(Document document) + throws CanonicalizationException { + if (!document.isSupported("Traversal", "2.0")) { + Object exArgs[] = {document.getImplementation().getClass().getName() }; - if (!document.isSupported("Traversal", "2.0")) { - Object exArgs[] = { - document.getImplementation().getClass().getName() }; + throw new CanonicalizationException( + "c14n.Canonicalizer.TraversalNotSupported", exArgs + ); + } + } - throw new CanonicalizationException( - "c14n.Canonicalizer.TraversalNotSupported", exArgs); - } - } + /** + * This method throws a CanonicalizationException if the supplied Element + * contains any relative namespaces. + * + * @param ctxNode + * @throws CanonicalizationException + * @see C14nHelper#assertNotRelativeNS(Attr) + */ + public static void checkForRelativeNamespace(Element ctxNode) + throws CanonicalizationException { + if (ctxNode != null) { + NamedNodeMap attributes = ctxNode.getAttributes(); - /** - * This method throws a CanonicalizationException if the supplied Element - * contains any relative namespaces. - * - * @param ctxNode - * @throws CanonicalizationException - * @see C14nHelper#assertNotRelativeNS(Attr) - */ - public static void checkForRelativeNamespace(Element ctxNode) - throws CanonicalizationException { - - if (ctxNode != null) { - NamedNodeMap attributes = ctxNode.getAttributes(); - - for (int i = 0; i < attributes.getLength(); i++) { - C14nHelper.assertNotRelativeNS((Attr) attributes.item(i)); - } - } else { - throw new CanonicalizationException( - "Called checkForRelativeNamespace() on null"); - } - } + for (int i = 0; i < attributes.getLength(); i++) { + C14nHelper.assertNotRelativeNS((Attr) attributes.item(i)); + } + } else { + throw new CanonicalizationException("Called checkForRelativeNamespace() on null"); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java index e0a46963ace..4d1fcbc0e6d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.c14n.implementations; @@ -25,7 +27,6 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; -import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -34,7 +35,6 @@ import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.xml.parsers.ParserConfigurationException; -import javax.xml.xpath.XPath; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -42,8 +42,6 @@ import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.xml.sax.SAXException; -import java.util.logging.Logger; -import java.util.logging.Logger; import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; import com.sun.org.apache.xml.internal.security.c14n.helper.C14nHelper; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; @@ -57,40 +55,46 @@ import com.sun.org.apache.xml.internal.security.utils.XMLUtils; * * @author Sean Mullan * @author Raul Benito - * @version $Revision: 1.2 $ */ public abstract class Canonicalizer11 extends CanonicalizerBase { - boolean firstCall = true; - final SortedSet result = new TreeSet(COMPARE); - static final String XMLNS_URI = Constants.NamespaceSpecNS; - static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS; - static Logger log = Logger.getLogger(Canonicalizer11.class.getName()); + private static final String XMLNS_URI = Constants.NamespaceSpecNS; + private static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS; + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(Canonicalizer11.class.getName()); + private final SortedSet result = new TreeSet(COMPARE); - static class XmlAttrStack { - int currentLevel = 0; - int lastlevel = 0; - XmlsStackElement cur; + private boolean firstCall = true; + + private static class XmlAttrStack { static class XmlsStackElement { int level; boolean rendered = false; List nodes = new ArrayList(); }; + + int currentLevel = 0; + int lastlevel = 0; + XmlsStackElement cur; List levels = new ArrayList(); + void push(int level) { currentLevel = level; - if (currentLevel == -1) + if (currentLevel == -1) { return; + } cur = null; while (lastlevel >= currentLevel) { levels.remove(levels.size() - 1); - if (levels.size() == 0) { + int newSize = levels.size(); + if (newSize == 0) { lastlevel = 0; return; } - lastlevel=(levels.get(levels.size()-1)).level; + lastlevel = (levels.get(newSize - 1)).level; } } + void addXmlnsAttr(Attr n) { if (cur == null) { cur = new XmlsStackElement(); @@ -100,22 +104,24 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { } cur.nodes.add(n); } + void getXmlnsAttr(Collection col) { + int size = levels.size() - 1; if (cur == null) { cur = new XmlsStackElement(); cur.level = currentLevel; lastlevel = currentLevel; levels.add(cur); } - int size = levels.size() - 2; boolean parentRendered = false; XmlsStackElement e = null; if (size == -1) { parentRendered = true; } else { e = levels.get(size); - if (e.rendered && e.level+1 == currentLevel) + if (e.rendered && e.level + 1 == currentLevel) { parentRendered = true; + } } if (parentRendered) { col.addAll(cur.nodes); @@ -126,7 +132,7 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { Map loa = new HashMap(); List baseAttrs = new ArrayList(); boolean successiveOmitted = true; - for (;size>=0;size--) { + for (; size >= 0; size--) { e = levels.get(size); if (e.rendered) { successiveOmitted = false; @@ -134,16 +140,15 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { Iterator it = e.nodes.iterator(); while (it.hasNext() && successiveOmitted) { Attr n = it.next(); - if (n.getLocalName().equals("base")) { - if (!e.rendered) { - baseAttrs.add(n); - } - } else if (!loa.containsKey(n.getName())) + if (n.getLocalName().equals("base") && !e.rendered) { + baseAttrs.add(n); + } else if (!loa.containsKey(n.getName())) { loa.put(n.getName(), n); + } } } if (!baseAttrs.isEmpty()) { - Iterator it = cur.nodes.iterator(); + Iterator it = col.iterator(); String base = null; Attr baseAttr = null; while (it.hasNext()) { @@ -164,7 +169,9 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { try { base = joinURI(n.getValue(), base); } catch (URISyntaxException ue) { - ue.printStackTrace(); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ue.getMessage(), ue); + } } } } @@ -178,7 +185,8 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { col.addAll(loa.values()); } }; - XmlAttrStack xmlattrStack = new XmlAttrStack(); + + private XmlAttrStack xmlattrStack = new XmlAttrStack(); /** * Constructor Canonicalizer11 @@ -189,194 +197,6 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { super(includeComments); } - /** - * Returns the Attr[]s to be outputted for the given element. - *
- * The code of this method is a copy of {@link #handleAttributes(Element, - * NameSpaceSymbTable)}, - * whereas it takes into account that subtree-c14n is -- well -- - * subtree-based. - * So if the element in question isRoot of c14n, it's parent is not in the - * node set, as well as all other ancestors. - * - * @param E - * @param ns - * @return the Attr[]s to be outputted - * @throws CanonicalizationException - */ - Iterator handleAttributesSubtree(Element E, NameSpaceSymbTable ns) - throws CanonicalizationException { - if (!E.hasAttributes() && !firstCall) { - return null; - } - // result will contain the attrs which have to be outputted - final SortedSet result = this.result; - result.clear(); - NamedNodeMap attrs = E.getAttributes(); - int attrsLength = attrs.getLength(); - - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); - String NUri = N.getNamespaceURI(); - - if (XMLNS_URI != NUri) { - // It's not a namespace attr node. Add to the result and - // continue. - result.add(N); - continue; - } - - String NName = N.getLocalName(); - String NValue = N.getValue(); - if (XML.equals(NName) - && XML_LANG_URI.equals(NValue)) { - // The default mapping for xml must not be output. - continue; - } - - Node n = ns.addMappingAndRender(NName, NValue, N); - - if (n != null) { - // Render the ns definition - result.add((Attr)n); - if (C14nHelper.namespaceIsRelative(N)) { - Object exArgs[] = {E.getTagName(), NName, N.getNodeValue()}; - throw new CanonicalizationException( - "c14n.Canonicalizer.RelativeNamespace", exArgs); - } - } - } - - if (firstCall) { - // It is the first node of the subtree - // Obtain all the namespaces defined in the parents, and added - // to the output. - ns.getUnrenderedNodes(result); - // output the attributes in the xml namespace. - xmlattrStack.getXmlnsAttr(getSortedSetAsCollection(result)); - firstCall = false; - } - - return result.iterator(); - } - - - - /** - * Returns the Attr[]s to be outputted for the given element. - *
- * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a - * DOM which has been prepared using - * {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650( - * org.w3c.dom.Document)}. - * - * @param E - * @param ns - * @return the Attr[]s to be outputted - * @throws CanonicalizationException - */ - Iterator handleAttributes(Element E, NameSpaceSymbTable ns) - throws CanonicalizationException { - // result will contain the attrs which have to be output - xmlattrStack.push(ns.getLevel()); - boolean isRealVisible = isVisibleDO(E, ns.getLevel()) == 1; - NamedNodeMap attrs = null; - int attrsLength = 0; - if (E.hasAttributes()) { - attrs = E.getAttributes(); - attrsLength = attrs.getLength(); - } - - SortedSet result = this.result; - result.clear(); - - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr)attrs.item(i); - String NUri = N.getNamespaceURI(); - - if (XMLNS_URI != NUri) { - // A non namespace definition node. - if (XML_LANG_URI == NUri) { - if (N.getLocalName().equals("id")) { - if (isRealVisible) { - // treat xml:id like any other attribute - // (emit it, but don't inherit it) - result.add(N); - } - } else { - xmlattrStack.addXmlnsAttr(N); - } - } else if (isRealVisible) { - // The node is visible add the attribute to the list of - // output attributes. - result.add(N); - } - // keep working - continue; - } - - String NName = N.getLocalName(); - String NValue = N.getValue(); - if ("xml".equals(NName) - && XML_LANG_URI.equals(NValue)) { - /* except omit namespace node with local name xml, which defines - * the xml prefix, if its string value is - * http://www.w3.org/XML/1998/namespace. - */ - continue; - } - // add the prefix binding to the ns symb table. - // ns.addInclusiveMapping(NName,NValue,N,isRealVisible); - if (isVisible(N)) { - if (!isRealVisible && ns.removeMappingIfRender(NName)) { - continue; - } - // The xpath select this node output it if needed. - // Node n = ns.addMappingAndRenderXNodeSet - // (NName, NValue, N, isRealVisible); - Node n = ns.addMappingAndRender(NName, NValue, N); - if (n != null) { - result.add((Attr)n); - if (C14nHelper.namespaceIsRelative(N)) { - Object exArgs[] = - { E.getTagName(), NName, N.getNodeValue() }; - throw new CanonicalizationException( - "c14n.Canonicalizer.RelativeNamespace", exArgs); - } - } - } else { - if (isRealVisible && NName != XMLNS) { - ns.removeMapping(NName); - } else { - ns.addMapping(NName, NValue, N); - } - } - } - if (isRealVisible) { - // The element is visible, handle the xmlns definition - Attr xmlns = E.getAttributeNodeNS(XMLNS_URI, XMLNS); - Node n = null; - if (xmlns == null) { - // No xmlns def just get the already defined. - n = ns.getMapping(XMLNS); - } else if (!isVisible(xmlns)) { - // There is a defn but the xmlns is not selected by the xpath. - // then xmlns="" - n = ns.addMappingAndRender(XMLNS, "", nullNode); - } - // output the xmlns def if needed. - if (n != null) { - result.add((Attr)n); - } - // Float all xml:* attributes of the unselected parent elements to - // this one. addXmlAttributes(E,result); - xmlattrStack.getXmlnsAttr(result); - ns.getUnrenderedNodes(result); - } - - return result.iterator(); - } - /** * Always throws a CanonicalizationException because this is inclusive c14n. * @@ -385,10 +205,10 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { * @return none it always fails * @throws CanonicalizationException always */ - public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet, - String inclusiveNamespaces) throws CanonicalizationException { - throw new CanonicalizationException( - "c14n.Canonicalizer.UnsupportedOperation"); + public byte[] engineCanonicalizeXPathNodeSet( + Set xpathNodeSet, String inclusiveNamespaces + ) throws CanonicalizationException { + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); } /** @@ -399,17 +219,189 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { * @return none it always fails * @throws CanonicalizationException */ - public byte[] engineCanonicalizeSubTree(Node rootNode, - String inclusiveNamespaces) throws CanonicalizationException { - throw new CanonicalizationException( - "c14n.Canonicalizer.UnsupportedOperation"); + public byte[] engineCanonicalizeSubTree( + Node rootNode, String inclusiveNamespaces + ) throws CanonicalizationException { + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); } - void circumventBugIfNeeded(XMLSignatureInput input) + /** + * Returns the Attr[]s to be output for the given element. + *
+ * The code of this method is a copy of {@link #handleAttributes(Element, + * NameSpaceSymbTable)}, + * whereas it takes into account that subtree-c14n is -- well -- + * subtree-based. + * So if the element in question isRoot of c14n, it's parent is not in the + * node set, as well as all other ancestors. + * + * @param element + * @param ns + * @return the Attr[]s to be output + * @throws CanonicalizationException + */ + @Override + protected Iterator handleAttributesSubtree(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + if (!element.hasAttributes() && !firstCall) { + return null; + } + // result will contain the attrs which have to be output + final SortedSet result = this.result; + result.clear(); + + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + String NUri = attribute.getNamespaceURI(); + String NName = attribute.getLocalName(); + String NValue = attribute.getValue(); + + if (!XMLNS_URI.equals(NUri)) { + // It's not a namespace attr node. Add to the result and continue. + result.add(attribute); + } else if (!(XML.equals(NName) && XML_LANG_URI.equals(NValue))) { + // The default mapping for xml must not be output. + Node n = ns.addMappingAndRender(NName, NValue, attribute); + + if (n != null) { + // Render the ns definition + result.add((Attr)n); + if (C14nHelper.namespaceIsRelative(attribute)) { + Object exArgs[] = {element.getTagName(), NName, attribute.getNodeValue()}; + throw new CanonicalizationException( + "c14n.Canonicalizer.RelativeNamespace", exArgs + ); + } + } + } + } + } + + if (firstCall) { + // It is the first node of the subtree + // Obtain all the namespaces defined in the parents, and added to the output. + ns.getUnrenderedNodes(result); + // output the attributes in the xml namespace. + xmlattrStack.getXmlnsAttr(result); + firstCall = false; + } + + return result.iterator(); + } + + /** + * Returns the Attr[]s to be output for the given element. + *
+ * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a + * DOM which has been prepared using + * {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650( + * org.w3c.dom.Document)}. + * + * @param element + * @param ns + * @return the Attr[]s to be output + * @throws CanonicalizationException + */ + @Override + protected Iterator handleAttributes(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + // result will contain the attrs which have to be output + xmlattrStack.push(ns.getLevel()); + boolean isRealVisible = isVisibleDO(element, ns.getLevel()) == 1; + final SortedSet result = this.result; + result.clear(); + + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + String NUri = attribute.getNamespaceURI(); + String NName = attribute.getLocalName(); + String NValue = attribute.getValue(); + + if (!XMLNS_URI.equals(NUri)) { + //A non namespace definition node. + if (XML_LANG_URI.equals(NUri)) { + if (NName.equals("id")) { + if (isRealVisible) { + // treat xml:id like any other attribute + // (emit it, but don't inherit it) + result.add(attribute); + } + } else { + xmlattrStack.addXmlnsAttr(attribute); + } + } else if (isRealVisible) { + //The node is visible add the attribute to the list of output attributes. + result.add(attribute); + } + } else if (!XML.equals(NName) || !XML_LANG_URI.equals(NValue)) { + /* except omit namespace node with local name xml, which defines + * the xml prefix, if its string value is + * http://www.w3.org/XML/1998/namespace. + */ + // add the prefix binding to the ns symb table. + if (isVisible(attribute)) { + if (isRealVisible || !ns.removeMappingIfRender(NName)) { + // The xpath select this node output it if needed. + Node n = ns.addMappingAndRender(NName, NValue, attribute); + if (n != null) { + result.add((Attr)n); + if (C14nHelper.namespaceIsRelative(attribute)) { + Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() }; + throw new CanonicalizationException( + "c14n.Canonicalizer.RelativeNamespace", exArgs + ); + } + } + } + } else { + if (isRealVisible && !XMLNS.equals(NName)) { + ns.removeMapping(NName); + } else { + ns.addMapping(NName, NValue, attribute); + } + } + } + } + } + + if (isRealVisible) { + //The element is visible, handle the xmlns definition + Attr xmlns = element.getAttributeNodeNS(XMLNS_URI, XMLNS); + Node n = null; + if (xmlns == null) { + //No xmlns def just get the already defined. + n = ns.getMapping(XMLNS); + } else if (!isVisible(xmlns)) { + //There is a definition but the xmlns is not selected by the xpath. + //then xmlns="" + n = ns.addMappingAndRender(XMLNS, "", nullNode); + } + //output the xmlns def if needed. + if (n != null) { + result.add((Attr)n); + } + //Float all xml:* attributes of the unselected parent elements to this one. + xmlattrStack.getXmlnsAttr(result); + ns.getUnrenderedNodes(result); + } + + return result.iterator(); + } + + protected void circumventBugIfNeeded(XMLSignatureInput input) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException { - if (!input.isNeedsToBeExpanded()) + if (!input.isNeedsToBeExpanded()) { return; + } Document doc = null; if (input.getSubNode() != null) { doc = XMLUtils.getOwnerDocument(input.getSubNode()); @@ -419,40 +411,47 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { XMLUtils.circumventBug2650(doc); } - void handleParent(Element e, NameSpaceSymbTable ns) { - if (!e.hasAttributes()) { + protected void handleParent(Element e, NameSpaceSymbTable ns) { + if (!e.hasAttributes() && e.getNamespaceURI() == null) { return; } xmlattrStack.push(-1); NamedNodeMap attrs = e.getAttributes(); int attrsLength = attrs.getLength(); for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); - if (Constants.NamespaceSpecNS != N.getNamespaceURI()) { - // Not a namespace definition, ignore. - if (XML_LANG_URI == N.getNamespaceURI()) { - xmlattrStack.addXmlnsAttr(N); - } - continue; - } + Attr attribute = (Attr) attrs.item(i); + String NName = attribute.getLocalName(); + String NValue = attribute.getNodeValue(); - String NName = N.getLocalName(); - String NValue = N.getNodeValue(); - if (XML.equals(NName) - && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) { - continue; + if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI())) { + if (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) { + ns.addMapping(NName, NValue, attribute); + } + } else if (!"id".equals(NName) && XML_LANG_URI.equals(attribute.getNamespaceURI())) { + xmlattrStack.addXmlnsAttr(attribute); } - ns.addMapping(NName,NValue,N); + } + if (e.getNamespaceURI() != null) { + String NName = e.getPrefix(); + String NValue = e.getNamespaceURI(); + String Name; + if (NName == null || NName.equals("")) { + NName = "xmlns"; + Name = "xmlns"; + } else { + Name = "xmlns:" + NName; + } + Attr n = e.getOwnerDocument().createAttributeNS("http://www.w3.org/2000/xmlns/", Name); + n.setValue(NValue); + ns.addMapping(NName, NValue, n); } } - private static String joinURI(String baseURI, String relativeURI) - throws URISyntaxException { + private static String joinURI(String baseURI, String relativeURI) throws URISyntaxException { String bscheme = null; String bauthority = null; String bpath = ""; String bquery = null; - String bfragment = null; // Is this correct? // pre-parse the baseURI if (baseURI != null) { @@ -464,7 +463,6 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { bauthority = base.getAuthority(); bpath = base.getPath(); bquery = base.getQuery(); - bfragment = base.getFragment(); } URI r = new URI(relativeURI); @@ -472,9 +470,8 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { String rauthority = r.getAuthority(); String rpath = r.getPath(); String rquery = r.getQuery(); - String rfragment = null; - String tscheme, tauthority, tpath, tquery, tfragment; + String tscheme, tauthority, tpath, tquery; if (rscheme != null && rscheme.equals(bscheme)) { rscheme = null; } @@ -518,13 +515,13 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { } tscheme = bscheme; } - tfragment = rfragment; - return new URI(tscheme, tauthority, tpath, tquery, tfragment).toString(); + return new URI(tscheme, tauthority, tpath, tquery, null).toString(); } private static String removeDotSegments(String path) { - - log.log(java.util.logging.Level.FINE, "STEP OUTPUT BUFFER\t\tINPUT BUFFER"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "STEP OUTPUT BUFFER\t\tINPUT BUFFER"); + } // 1. The input buffer is initialized with the now-appended path // components then replace occurrences of "//" in the input buffer @@ -535,7 +532,7 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { } // Initialize the output buffer with the empty string. - StringBuffer output = new StringBuffer(); + StringBuilder output = new StringBuilder(); // If the input buffer starts with a root slash "/" then move this // character to the output buffer. @@ -563,9 +560,9 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { output.append("../"); } printStep("2A", output.toString(), input); - // 2B. if the input buffer begins with a prefix of "/./" or "/.", - // where "." is a complete path segment, then replace that prefix - // with "/" in the input buffer; otherwise, + // 2B. if the input buffer begins with a prefix of "/./" or "/.", + // where "." is a complete path segment, then replace that prefix + // with "/" in the input buffer; otherwise, } else if (input.startsWith("/./")) { input = input.substring(2); printStep("2B", output.toString(), input); @@ -573,16 +570,16 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { // FIXME: what is complete path segment? input = input.replaceFirst("/.", "/"); printStep("2B", output.toString(), input); - // 2C. if the input buffer begins with a prefix of "/../" or "/..", - // where ".." is a complete path segment, then replace that prefix - // with "/" in the input buffer and if also the output buffer is - // empty, last segment in the output buffer equals "../" or "..", - // where ".." is a complete path segment, then append ".." or "/.." - // for the latter case respectively to the output buffer else - // remove the last segment and its preceding "/" (if any) from the - // output buffer and if hereby the first character in the output - // buffer was removed and it was not the root slash then delete a - // leading slash from the input buffer; otherwise, + // 2C. if the input buffer begins with a prefix of "/../" or "/..", + // where ".." is a complete path segment, then replace that prefix + // with "/" in the input buffer and if also the output buffer is + // empty, last segment in the output buffer equals "../" or "..", + // where ".." is a complete path segment, then append ".." or "/.." + // for the latter case respectively to the output buffer else + // remove the last segment and its preceding "/" (if any) from the + // output buffer and if hereby the first character in the output + // buffer was removed and it was not the root slash then delete a + // leading slash from the input buffer; otherwise, } else if (input.startsWith("/../")) { input = input.substring(3); if (output.length() == 0) { @@ -594,7 +591,7 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { } else { int index = output.lastIndexOf("/"); if (index == -1) { - output = new StringBuffer(); + output = new StringBuilder(); if (input.charAt(0) == '/') { input = input.substring(1); } @@ -615,7 +612,7 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { } else { int index = output.lastIndexOf("/"); if (index == -1) { - output = new StringBuffer(); + output = new StringBuilder(); if (input.charAt(0) == '/') { input = input.substring(1); } @@ -624,23 +621,24 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { } } printStep("2C", output.toString(), input); - // 2D. if the input buffer consists only of ".", then remove - // that from the input buffer else if the input buffer consists - // only of ".." and if the output buffer does not contain only - // the root slash "/", then move the ".." to the output buffer - // else delte it.; otherwise, + // 2D. if the input buffer consists only of ".", then remove + // that from the input buffer else if the input buffer consists + // only of ".." and if the output buffer does not contain only + // the root slash "/", then move the ".." to the output buffer + // else delte it.; otherwise, } else if (input.equals(".")) { input = ""; printStep("2D", output.toString(), input); } else if (input.equals("..")) { - if (!output.toString().equals("/")) + if (!output.toString().equals("/")) { output.append(".."); + } input = ""; printStep("2D", output.toString(), input); - // 2E. move the first path segment (if any) in the input buffer - // to the end of the output buffer, including the initial "/" - // character (if any) and any subsequent characters up to, but not - // including, the next "/" character or the end of the input buffer. + // 2E. move the first path segment (if any) in the input buffer + // to the end of the output buffer, including the initial "/" + // character (if any) and any subsequent characters up to, but not + // including, the next "/" character or the end of the input buffer. } else { int end = -1; int begin = input.indexOf('/'); diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java index 31903667f60..12a31f67d80 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.c14n.implementations; diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java index ba650c10872..635e778b7a2 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.c14n.implementations; diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java index b0b2e0b729c..3af83dd11f1 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.c14n.implementations; - - import java.io.IOException; import java.util.ArrayList; import java.util.Collection; @@ -47,344 +47,348 @@ import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.xml.sax.SAXException; - /** * Implements Canonical * XML Version 1.0, a W3C Recommendation from 15 March 2001. * * @author Christian Geuer-Pollmann - * @version $Revision: 1.5 $ */ public abstract class Canonicalizer20010315 extends CanonicalizerBase { - boolean firstCall=true; - final SortedSet result= new TreeSet(COMPARE); - static final String XMLNS_URI=Constants.NamespaceSpecNS; - static final String XML_LANG_URI=Constants.XML_LANG_SPACE_SpecNS; - static class XmlAttrStack { - int currentLevel=0; - int lastlevel=0; - XmlsStackElement cur; + private static final String XMLNS_URI = Constants.NamespaceSpecNS; + private static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS; + + private boolean firstCall = true; + private final SortedSet result = new TreeSet(COMPARE); + + private static class XmlAttrStack { static class XmlsStackElement { - int level; - boolean rendered=false; - List nodes=new ArrayList(); + int level; + boolean rendered = false; + List nodes = new ArrayList(); }; - List levels=new ArrayList(); + + int currentLevel = 0; + int lastlevel = 0; + XmlsStackElement cur; + List levels = new ArrayList(); + void push(int level) { - currentLevel=level; - if (currentLevel==-1) - return; - cur=null; - while (lastlevel>=currentLevel) { - levels.remove(levels.size()-1); - if (levels.size()==0) { - lastlevel=0; - return; - } - lastlevel=(levels.get(levels.size()-1)).level; + currentLevel = level; + if (currentLevel == -1) { + return; + } + cur = null; + while (lastlevel >= currentLevel) { + levels.remove(levels.size() - 1); + int newSize = levels.size(); + if (newSize == 0) { + lastlevel = 0; + return; } + lastlevel = (levels.get(newSize - 1)).level; + } } + void addXmlnsAttr(Attr n) { - if (cur==null) { - cur=new XmlsStackElement(); - cur.level=currentLevel; - levels.add(cur); - lastlevel=currentLevel; - } - cur.nodes.add(n); + if (cur == null) { + cur = new XmlsStackElement(); + cur.level = currentLevel; + levels.add(cur); + lastlevel = currentLevel; + } + cur.nodes.add(n); } + void getXmlnsAttr(Collection col) { - int size=levels.size()-1; - if (cur==null) { - cur=new XmlsStackElement(); - cur.level=currentLevel; - lastlevel=currentLevel; - levels.add(cur); + int size = levels.size() - 1; + if (cur == null) { + cur = new XmlsStackElement(); + cur.level = currentLevel; + lastlevel = currentLevel; + levels.add(cur); + } + boolean parentRendered = false; + XmlsStackElement e = null; + if (size == -1) { + parentRendered = true; + } else { + e = levels.get(size); + if (e.rendered && e.level + 1 == currentLevel) { + parentRendered = true; } - boolean parentRendered=false; - XmlsStackElement e=null; - if (size==-1) { - parentRendered=true; - } else { - e=levels.get(size); - if (e.rendered && e.level+1==currentLevel) - parentRendered=true; + } + if (parentRendered) { + col.addAll(cur.nodes); + cur.rendered = true; + return; + } + Map loa = new HashMap(); + for (; size >= 0; size--) { + e = levels.get(size); + Iterator it = e.nodes.iterator(); + while (it.hasNext()) { + Attr n = it.next(); + if (!loa.containsKey(n.getName())) { + loa.put(n.getName(), n); + } } - if (parentRendered) { - col.addAll(cur.nodes); - cur.rendered=true; - return; - } + } - Map loa = new HashMap(); - for (;size>=0;size--) { - e=levels.get(size); - Iterator it=e.nodes.iterator(); - while (it.hasNext()) { - Attr n=it.next(); - if (!loa.containsKey(n.getName())) - loa.put(n.getName(),n); - } - //if (e.rendered) - //break; - - }; - //cur.nodes.clear(); - //cur.nodes.addAll(loa.values()); - cur.rendered=true; - col.addAll(loa.values()); + cur.rendered = true; + col.addAll(loa.values()); } } - XmlAttrStack xmlattrStack=new XmlAttrStack(); + + private XmlAttrStack xmlattrStack = new XmlAttrStack(); + /** - * Constructor Canonicalizer20010315 - * - * @param includeComments - */ - public Canonicalizer20010315(boolean includeComments) { - super(includeComments); - } - - /** - * Returns the Attr[]s to be outputted for the given element. - *
- * The code of this method is a copy of {@link #handleAttributes(Element, - * NameSpaceSymbTable)}, - * whereas it takes into account that subtree-c14n is -- well -- subtree-based. - * So if the element in question isRoot of c14n, it's parent is not in the - * node set, as well as all other ancestors. - * - * @param E - * @param ns - * @return the Attr[]s to be outputted - * @throws CanonicalizationException - */ - Iterator handleAttributesSubtree(Element E, NameSpaceSymbTable ns ) - throws CanonicalizationException { - if (!E.hasAttributes() && !firstCall) { - return null; - } - // result will contain the attrs which have to be outputted - final SortedSet result = this.result; - result.clear(); - NamedNodeMap attrs = E.getAttributes(); - int attrsLength = attrs.getLength(); - - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); - String NUri =N.getNamespaceURI(); - - if (XMLNS_URI!=NUri) { - //It's not a namespace attr node. Add to the result and continue. - result.add(N); - continue; - } - - String NName=N.getLocalName(); - String NValue=N.getValue(); - if (XML.equals(NName) - && XML_LANG_URI.equals(NValue)) { - //The default mapping for xml must not be output. - continue; - } - - Node n=ns.addMappingAndRender(NName,NValue,N); - - if (n!=null) { - //Render the ns definition - result.add((Attr)n); - if (C14nHelper.namespaceIsRelative(N)) { - Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() }; - throw new CanonicalizationException( - "c14n.Canonicalizer.RelativeNamespace", exArgs); - } - } - } - - if (firstCall) { - //It is the first node of the subtree - //Obtain all the namespaces defined in the parents, and added to the output. - ns.getUnrenderedNodes(getSortedSetAsCollection(result)); - //output the attributes in the xml namespace. - xmlattrStack.getXmlnsAttr(result); - firstCall=false; - } - - return result.iterator(); - } - - /** - * Returns the Attr[]s to be outputted for the given element. - *
- * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a DOM which has - * been prepared using {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650( - * org.w3c.dom.Document)}. - * - * @param E - * @param ns - * @return the Attr[]s to be outputted - * @throws CanonicalizationException - */ - Iterator handleAttributes(Element E, NameSpaceSymbTable ns ) throws CanonicalizationException { - // result will contain the attrs which have to be outputted - xmlattrStack.push(ns.getLevel()); - boolean isRealVisible=isVisibleDO(E,ns.getLevel())==1; - NamedNodeMap attrs = null; - int attrsLength = 0; - if (E.hasAttributes()) { - attrs=E.getAttributes(); - attrsLength= attrs.getLength(); + * Constructor Canonicalizer20010315 + * + * @param includeComments + */ + public Canonicalizer20010315(boolean includeComments) { + super(includeComments); } + /** + * Always throws a CanonicalizationException because this is inclusive c14n. + * + * @param xpathNodeSet + * @param inclusiveNamespaces + * @return none it always fails + * @throws CanonicalizationException always + */ + public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet, String inclusiveNamespaces) + throws CanonicalizationException { - SortedSet result = this.result; - result.clear(); + /** $todo$ well, should we throw UnsupportedOperationException ? */ + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); + } - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); - String NUri =N.getNamespaceURI(); + /** + * Always throws a CanonicalizationException because this is inclusive c14n. + * + * @param rootNode + * @param inclusiveNamespaces + * @return none it always fails + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces) + throws CanonicalizationException { - if (XMLNS_URI!=NUri) { - //A non namespace definition node. - if (XML_LANG_URI==NUri) { - xmlattrStack.addXmlnsAttr(N); - } else if (isRealVisible){ - //The node is visible add the attribute to the list of output attributes. - result.add(N); - } - //keep working - continue; - } + /** $todo$ well, should we throw UnsupportedOperationException ? */ + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); + } - String NName=N.getLocalName(); - String NValue=N.getValue(); - if ("xml".equals(NName) - && XML_LANG_URI.equals(NValue)) { - /* except omit namespace node with local name xml, which defines - * the xml prefix, if its string value is http://www.w3.org/XML/1998/namespace. - */ - continue; - } - //add the prefix binding to the ns symb table. - //ns.addInclusiveMapping(NName,NValue,N,isRealVisible); - if (isVisible(N)) { - if (!isRealVisible && ns.removeMappingIfRender(NName)) { - continue; - } - //The xpath select this node output it if needed. - //Node n=ns.addMappingAndRenderXNodeSet(NName,NValue,N,isRealVisible); - Node n=ns.addMappingAndRender(NName,NValue,N); - if (n!=null) { - result.add((Attr)n); - if (C14nHelper.namespaceIsRelative(N)) { - Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() }; - throw new CanonicalizationException( - "c14n.Canonicalizer.RelativeNamespace", exArgs); - } - } - } else { - if (isRealVisible && NName!=XMLNS) { - ns.removeMapping(NName); - } else { - ns.addMapping(NName,NValue,N); - } + /** + * Returns the Attr[]s to be output for the given element. + *
+ * The code of this method is a copy of {@link #handleAttributes(Element, + * NameSpaceSymbTable)}, + * whereas it takes into account that subtree-c14n is -- well -- subtree-based. + * So if the element in question isRoot of c14n, it's parent is not in the + * node set, as well as all other ancestors. + * + * @param element + * @param ns + * @return the Attr[]s to be output + * @throws CanonicalizationException + */ + @Override + protected Iterator handleAttributesSubtree(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + if (!element.hasAttributes() && !firstCall) { + return null; } + // result will contain the attrs which have to be output + final SortedSet result = this.result; + result.clear(); + + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + String NUri = attribute.getNamespaceURI(); + String NName = attribute.getLocalName(); + String NValue = attribute.getValue(); + + if (!XMLNS_URI.equals(NUri)) { + //It's not a namespace attr node. Add to the result and continue. + result.add(attribute); + } else if (!(XML.equals(NName) && XML_LANG_URI.equals(NValue))) { + //The default mapping for xml must not be output. + Node n = ns.addMappingAndRender(NName, NValue, attribute); + + if (n != null) { + //Render the ns definition + result.add((Attr)n); + if (C14nHelper.namespaceIsRelative(attribute)) { + Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() }; + throw new CanonicalizationException( + "c14n.Canonicalizer.RelativeNamespace", exArgs + ); + } + } + } + } + } + + if (firstCall) { + //It is the first node of the subtree + //Obtain all the namespaces defined in the parents, and added to the output. + ns.getUnrenderedNodes(result); + //output the attributes in the xml namespace. + xmlattrStack.getXmlnsAttr(result); + firstCall = false; + } + + return result.iterator(); } - if (isRealVisible) { - //The element is visible, handle the xmlns definition - Attr xmlns = E.getAttributeNodeNS(XMLNS_URI, XMLNS); - Node n=null; - if (xmlns == null) { + + /** + * Returns the Attr[]s to be output for the given element. + *
+ * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a DOM which has + * been prepared using {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650( + * org.w3c.dom.Document)}. + * + * @param element + * @param ns + * @return the Attr[]s to be output + * @throws CanonicalizationException + */ + @Override + protected Iterator handleAttributes(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + // result will contain the attrs which have to be output + xmlattrStack.push(ns.getLevel()); + boolean isRealVisible = isVisibleDO(element, ns.getLevel()) == 1; + final SortedSet result = this.result; + result.clear(); + + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + String NUri = attribute.getNamespaceURI(); + String NName = attribute.getLocalName(); + String NValue = attribute.getValue(); + + if (!XMLNS_URI.equals(NUri)) { + //A non namespace definition node. + if (XML_LANG_URI.equals(NUri)) { + xmlattrStack.addXmlnsAttr(attribute); + } else if (isRealVisible) { + //The node is visible add the attribute to the list of output attributes. + result.add(attribute); + } + } else if (!XML.equals(NName) || !XML_LANG_URI.equals(NValue)) { + /* except omit namespace node with local name xml, which defines + * the xml prefix, if its string value is http://www.w3.org/XML/1998/namespace. + */ + //add the prefix binding to the ns symb table. + if (isVisible(attribute)) { + if (isRealVisible || !ns.removeMappingIfRender(NName)) { + //The xpath select this node output it if needed. + Node n = ns.addMappingAndRender(NName, NValue, attribute); + if (n != null) { + result.add((Attr)n); + if (C14nHelper.namespaceIsRelative(attribute)) { + Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() }; + throw new CanonicalizationException( + "c14n.Canonicalizer.RelativeNamespace", exArgs + ); + } + } + } + } else { + if (isRealVisible && !XMLNS.equals(NName)) { + ns.removeMapping(NName); + } else { + ns.addMapping(NName, NValue, attribute); + } + } + } + } + } + if (isRealVisible) { + //The element is visible, handle the xmlns definition + Attr xmlns = element.getAttributeNodeNS(XMLNS_URI, XMLNS); + Node n = null; + if (xmlns == null) { //No xmlns def just get the already defined. - n=ns.getMapping(XMLNS); - } else if ( !isVisible(xmlns)) { + n = ns.getMapping(XMLNS); + } else if (!isVisible(xmlns)) { //There is a definition but the xmlns is not selected by the xpath. //then xmlns="" - n=ns.addMappingAndRender(XMLNS,"",nullNode); + n = ns.addMappingAndRender(XMLNS, "", nullNode); + } + //output the xmlns def if needed. + if (n != null) { + result.add((Attr)n); + } + //Float all xml:* attributes of the unselected parent elements to this one. + xmlattrStack.getXmlnsAttr(result); + ns.getUnrenderedNodes(result); } - //output the xmlns def if needed. - if (n!=null) { - result.add((Attr)n); - } - //Float all xml:* attributes of the unselected parent elements to this one. - //addXmlAttributes(E,result); - xmlattrStack.getXmlnsAttr(result); - ns.getUnrenderedNodes(getSortedSetAsCollection(result)); + return result.iterator(); } - return result.iterator(); - } - /** - * Always throws a CanonicalizationException because this is inclusive c14n. - * - * @param xpathNodeSet - * @param inclusiveNamespaces - * @return none it always fails - * @throws CanonicalizationException always - */ - public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet, String inclusiveNamespaces) - throws CanonicalizationException { + protected void circumventBugIfNeeded(XMLSignatureInput input) + throws CanonicalizationException, ParserConfigurationException, IOException, SAXException { + if (!input.isNeedsToBeExpanded()) { + return; + } + Document doc = null; + if (input.getSubNode() != null) { + doc = XMLUtils.getOwnerDocument(input.getSubNode()); + } else { + doc = XMLUtils.getOwnerDocument(input.getNodeSet()); + } + XMLUtils.circumventBug2650(doc); + } - /** $todo$ well, should we throw UnsupportedOperationException ? */ - throw new CanonicalizationException( - "c14n.Canonicalizer.UnsupportedOperation"); - } + @Override + protected void handleParent(Element e, NameSpaceSymbTable ns) { + if (!e.hasAttributes() && e.getNamespaceURI() == null) { + return; + } + xmlattrStack.push(-1); + NamedNodeMap attrs = e.getAttributes(); + int attrsLength = attrs.getLength(); + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + String NName = attribute.getLocalName(); + String NValue = attribute.getNodeValue(); - /** - * Always throws a CanonicalizationException because this is inclusive c14n. - * - * @param rootNode - * @param inclusiveNamespaces - * @return none it always fails - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces) - throws CanonicalizationException { - - /** $todo$ well, should we throw UnsupportedOperationException ? */ - throw new CanonicalizationException( - "c14n.Canonicalizer.UnsupportedOperation"); - } - void circumventBugIfNeeded(XMLSignatureInput input) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException { - if (!input.isNeedsToBeExpanded()) - return; - Document doc = null; - if (input.getSubNode() != null) { - doc=XMLUtils.getOwnerDocument(input.getSubNode()); - } else { - doc=XMLUtils.getOwnerDocument(input.getNodeSet()); - } - XMLUtils.circumventBug2650(doc); - - } - - void handleParent(Element e, NameSpaceSymbTable ns) { - if (!e.hasAttributes()) { - return; - } - xmlattrStack.push(-1); - NamedNodeMap attrs = e.getAttributes(); - int attrsLength = attrs.getLength(); - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); - if (Constants.NamespaceSpecNS!=N.getNamespaceURI()) { - //Not a namespace definition, ignore. - if (XML_LANG_URI==N.getNamespaceURI()) { - xmlattrStack.addXmlnsAttr(N); - } - continue; - } - - String NName=N.getLocalName(); - String NValue=N.getNodeValue(); - if (XML.equals(NName) - && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) { - continue; - } - ns.addMapping(NName,NValue,N); - } - } + if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI())) { + if (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) { + ns.addMapping(NName, NValue, attribute); + } + } else if (XML_LANG_URI.equals(attribute.getNamespaceURI())) { + xmlattrStack.addXmlnsAttr(attribute); + } + } + if (e.getNamespaceURI() != null) { + String NName = e.getPrefix(); + String NValue = e.getNamespaceURI(); + String Name; + if (NName == null || NName.equals("")) { + NName = "xmlns"; + Name = "xmlns"; + } else { + Name = "xmlns:" + NName; + } + Attr n = e.getOwnerDocument().createAttributeNS("http://www.w3.org/2000/xmlns/", Name); + n.setValue(NValue); + ns.addMapping(NName, NValue, n); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java index 9dec09b4588..b8c869c83f7 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * 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 +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. - * + * 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 com.sun.org.apache.xml.internal.security.c14n.implementations; @@ -25,7 +27,6 @@ import java.util.Iterator; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; - import javax.xml.parsers.ParserConfigurationException; import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; @@ -40,6 +41,7 @@ import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.xml.sax.SAXException; + /** * Implements " Exclusive XML @@ -52,301 +54,279 @@ import org.xml.sax.SAXException; * THIS implementation is a complete rewrite of the algorithm. * * @author Christian Geuer-Pollmann - * @version $Revision: 1.5 $ + * @version $Revision: 1147448 $ * @see * XML Canonicalization, Version 1.0 */ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { + + private static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS; + private static final String XMLNS_URI = Constants.NamespaceSpecNS; + /** * This Set contains the names (Strings like "xmlns" or "xmlns:foo") of * the inclusive namespaces. */ - TreeSet _inclusiveNSSet = new TreeSet(); - static final String XMLNS_URI=Constants.NamespaceSpecNS; - final SortedSet result = new TreeSet(COMPARE); - /** - * Constructor Canonicalizer20010315Excl - * - * @param includeComments - */ - public Canonicalizer20010315Excl(boolean includeComments) { - super(includeComments); - } + private SortedSet inclusiveNSSet; - /** - * Method engineCanonicalizeSubTree - * @inheritDoc - * @param rootNode - * - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeSubTree(Node rootNode) - throws CanonicalizationException { - return this.engineCanonicalizeSubTree(rootNode, "",null); - } - /** - * Method engineCanonicalizeSubTree - * @inheritDoc - * @param rootNode - * @param inclusiveNamespaces - * - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeSubTree(Node rootNode, - String inclusiveNamespaces) throws CanonicalizationException { - return this.engineCanonicalizeSubTree(rootNode, inclusiveNamespaces,null); - } - /** - * Method engineCanonicalizeSubTree - * @param rootNode + private final SortedSet result = new TreeSet(COMPARE); + + /** + * Constructor Canonicalizer20010315Excl + * + * @param includeComments + */ + public Canonicalizer20010315Excl(boolean includeComments) { + super(includeComments); + } + + /** + * Method engineCanonicalizeSubTree + * @inheritDoc + * @param rootNode + * + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeSubTree(Node rootNode) + throws CanonicalizationException { + return engineCanonicalizeSubTree(rootNode, "", null); + } + + /** + * Method engineCanonicalizeSubTree + * @inheritDoc + * @param rootNode + * @param inclusiveNamespaces + * + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeSubTree( + Node rootNode, String inclusiveNamespaces + ) throws CanonicalizationException { + return engineCanonicalizeSubTree(rootNode, inclusiveNamespaces, null); + } + + /** + * Method engineCanonicalizeSubTree + * @param rootNode * @param inclusiveNamespaces * @param excl A element to exclude from the c14n process. - * @return the rootNode c14n. - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeSubTree(Node rootNode, - String inclusiveNamespaces,Node excl) throws CanonicalizationException { - this._inclusiveNSSet = getInclusiveNameSpace(inclusiveNamespaces); - return super.engineCanonicalizeSubTree(rootNode,excl); - } - /** - * - * @param rootNode - * @param inclusiveNamespaces - * @return the rootNode c14n. - * @throws CanonicalizationException - */ - @SuppressWarnings("unchecked") - public byte[] engineCanonicalize(XMLSignatureInput rootNode, - String inclusiveNamespaces) throws CanonicalizationException { - this._inclusiveNSSet = getInclusiveNameSpace(inclusiveNamespaces); - return super.engineCanonicalize(rootNode); - } - - /** - * Method handleAttributesSubtree - * @inheritDoc - * @param E - * @throws CanonicalizationException - */ - Iterator handleAttributesSubtree(Element E,NameSpaceSymbTable ns) - throws CanonicalizationException { - // System.out.println("During the traversal, I encountered " + - // XMLUtils.getXPath(E)); - // result will contain the attrs which have to be outputted - SortedSet result = this.result; - result.clear(); - NamedNodeMap attrs=null; - - int attrsLength = 0; - if (E.hasAttributes()) { - attrs = E.getAttributes(); - attrsLength = attrs.getLength(); - } - //The prefix visibly utilized(in the attribute or in the name) in the element - SortedSet visiblyUtilized = getNSSetClone(); - - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); - - if (XMLNS_URI!=N.getNamespaceURI()) { - //Not a namespace definition. - //The Element is output element, add his prefix(if used) to visibyUtilized - String prefix = N.getPrefix(); - if ( (prefix != null) && (!prefix.equals(XML) && !prefix.equals(XMLNS)) ) { - visiblyUtilized.add(prefix); - } - //Add to the result. - result.add(N); - continue; - } - String NName=N.getLocalName(); - String NNodeValue=N.getNodeValue(); - - if (ns.addMapping(NName, NNodeValue,N)) { - //New definition check if it is relative. - if (C14nHelper.namespaceIsRelative(NNodeValue)) { - Object exArgs[] = {E.getTagName(), NName, - N.getNodeValue()}; - throw new CanonicalizationException( - "c14n.Canonicalizer.RelativeNamespace", exArgs); - } - } - } - String prefix; - if (E.getNamespaceURI() != null) { - prefix = E.getPrefix(); - if ((prefix == null) || (prefix.length() == 0)) { - prefix=XMLNS; - } - - } else { - prefix=XMLNS; - } - visiblyUtilized.add(prefix); - - //This can be optimezed by I don't have time - Iterator it=visiblyUtilized.iterator(); - while (it.hasNext()) { - String s=it.next(); - Attr key=ns.getMapping(s); - if (key==null) { - continue; - } - result.add(key); - } - - return result.iterator(); - } - - /** - * Method engineCanonicalizeXPathNodeSet - * @inheritDoc - * @param xpathNodeSet - * @param inclusiveNamespaces - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet, - String inclusiveNamespaces) throws CanonicalizationException { - - this._inclusiveNSSet = getInclusiveNameSpace(inclusiveNamespaces); - return super.engineCanonicalizeXPathNodeSet(xpathNodeSet); - - } - - @SuppressWarnings("unchecked") - private TreeSet getInclusiveNameSpace(String inclusiveNameSpaces) { - return (TreeSet)InclusiveNamespaces.prefixStr2Set(inclusiveNameSpaces); + * @return the rootNode c14n. + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeSubTree( + Node rootNode, String inclusiveNamespaces, Node excl + ) throws CanonicalizationException{ + inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces); + return super.engineCanonicalizeSubTree(rootNode, excl); } - - @SuppressWarnings("unchecked") - private SortedSet getNSSetClone() { - return (SortedSet) this._inclusiveNSSet.clone(); + /** + * + * @param rootNode + * @param inclusiveNamespaces + * @return the rootNode c14n. + * @throws CanonicalizationException + */ + public byte[] engineCanonicalize( + XMLSignatureInput rootNode, String inclusiveNamespaces + ) throws CanonicalizationException { + inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces); + return super.engineCanonicalize(rootNode); } - - /** + /** + * Method engineCanonicalizeXPathNodeSet * @inheritDoc - * @param E - * @throws CanonicalizationException - */ - final Iterator handleAttributes(Element E, NameSpaceSymbTable ns) - throws CanonicalizationException { - // result will contain the attrs which have to be outputted - SortedSet result = this.result; - result.clear(); - NamedNodeMap attrs = null; - int attrsLength = 0; - if (E.hasAttributes()) { - attrs = E.getAttributes(); - attrsLength = attrs.getLength(); + * @param xpathNodeSet + * @param inclusiveNamespaces + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeXPathNodeSet( + Set xpathNodeSet, String inclusiveNamespaces + ) throws CanonicalizationException { + inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces); + return super.engineCanonicalizeXPathNodeSet(xpathNodeSet); + } + + @Override + protected Iterator handleAttributesSubtree(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + // result will contain the attrs which have to be output + final SortedSet result = this.result; + result.clear(); + + // The prefix visibly utilized (in the attribute or in the name) in + // the element + SortedSet visiblyUtilized = new TreeSet(); + if (inclusiveNSSet != null && !inclusiveNSSet.isEmpty()) { + visiblyUtilized.addAll(inclusiveNSSet); } - //The prefix visibly utilized(in the attribute or in the name) in the element - Set visiblyUtilized =null; - //It's the output selected. - boolean isOutputElement=isVisibleDO(E,ns.getLevel())==1; - if (isOutputElement) { - visiblyUtilized = getNSSetClone(); - } - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + String NName = attribute.getLocalName(); + String NNodeValue = attribute.getNodeValue(); - - if (XMLNS_URI!=N.getNamespaceURI()) { - if ( !isVisible(N) ) { - //The node is not in the nodeset(if there is a nodeset) - continue; - } - //Not a namespace definition. - if (isOutputElement) { - //The Element is output element, add his prefix(if used) to visibyUtilized - String prefix = N.getPrefix(); - if ((prefix != null) && (!prefix.equals(XML) && !prefix.equals(XMLNS)) ){ - visiblyUtilized.add(prefix); - } - //Add to the result. - result.add(N); - } - continue; - } - String NName=N.getLocalName(); - if (isOutputElement && !isVisible(N) && NName!=XMLNS) { - ns.removeMappingIfNotRender(NName); - continue; - } - String NNodeValue=N.getNodeValue(); - - if (!isOutputElement && isVisible(N) && _inclusiveNSSet.contains(NName) && !ns.removeMappingIfRender(NName)) { - Node n=ns.addMappingAndRender(NName,NNodeValue,N); - if (n!=null) { - result.add((Attr)n); - if (C14nHelper.namespaceIsRelative(N)) { - Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() }; - throw new CanonicalizationException( - "c14n.Canonicalizer.RelativeNamespace", exArgs); - } - } - } - - - - if (ns.addMapping(NName, NNodeValue,N)) { - //New definiton check if it is relative - if (C14nHelper.namespaceIsRelative(NNodeValue)) { - Object exArgs[] = {E.getTagName(), NName, - N.getNodeValue()}; + if (!XMLNS_URI.equals(attribute.getNamespaceURI())) { + // Not a namespace definition. + // The Element is output element, add the prefix (if used) to + // visiblyUtilized + String prefix = attribute.getPrefix(); + if (prefix != null && !(prefix.equals(XML) || prefix.equals(XMLNS))) { + visiblyUtilized.add(prefix); + } + // Add to the result. + result.add(attribute); + } else if (!(XML.equals(NName) && XML_LANG_URI.equals(NNodeValue)) + && ns.addMapping(NName, NNodeValue, attribute) + && C14nHelper.namespaceIsRelative(NNodeValue)) { + // The default mapping for xml must not be output. + // New definition check if it is relative. + Object exArgs[] = {element.getTagName(), NName, attribute.getNodeValue()}; throw new CanonicalizationException( - "c14n.Canonicalizer.RelativeNamespace", exArgs); + "c14n.Canonicalizer.RelativeNamespace", exArgs + ); } } - } - - if (isOutputElement) { - //The element is visible, handle the xmlns definition - Attr xmlns = E.getAttributeNodeNS(XMLNS_URI, XMLNS); - if ((xmlns!=null) && (!isVisible(xmlns))) { - //There is a definition but the xmlns is not selected by the xpath. - //then xmlns="" - ns.addMapping(XMLNS,"",nullNode); - } - - if (E.getNamespaceURI() != null) { - String prefix = E.getPrefix(); - if ((prefix == null) || (prefix.length() == 0)) { - visiblyUtilized.add(XMLNS); - } else { - visiblyUtilized.add( prefix); - } - } else { - visiblyUtilized.add(XMLNS); - } - //This can be optimezed by I don't have time - //visiblyUtilized.addAll(this._inclusiveNSSet); - Iterator it=visiblyUtilized.iterator(); - while (it.hasNext()) { - String s=it.next(); - Attr key=ns.getMapping(s); - if (key==null) { - continue; - } - result.add(key); - } - } - - return result.iterator(); } - void circumventBugIfNeeded(XMLSignatureInput input) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException { - if (!input.isNeedsToBeExpanded() || _inclusiveNSSet.isEmpty()) - return; - Document doc = null; - if (input.getSubNode() != null) { - doc=XMLUtils.getOwnerDocument(input.getSubNode()); - } else { - doc=XMLUtils.getOwnerDocument(input.getNodeSet()); - } + String prefix = null; + if (element.getNamespaceURI() != null + && !(element.getPrefix() == null || element.getPrefix().length() == 0)) { + prefix = element.getPrefix(); + } else { + prefix = XMLNS; + } + visiblyUtilized.add(prefix); - XMLUtils.circumventBug2650(doc); - } + for (String s : visiblyUtilized) { + Attr key = ns.getMapping(s); + if (key != null) { + result.add(key); + } + } + + return result.iterator(); + } + + /** + * @inheritDoc + * @param element + * @throws CanonicalizationException + */ + @Override + protected final Iterator handleAttributes(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + // result will contain the attrs which have to be output + final SortedSet result = this.result; + result.clear(); + + // The prefix visibly utilized (in the attribute or in the name) in + // the element + Set visiblyUtilized = null; + // It's the output selected. + boolean isOutputElement = isVisibleDO(element, ns.getLevel()) == 1; + if (isOutputElement) { + visiblyUtilized = new TreeSet(); + if (inclusiveNSSet != null && !inclusiveNSSet.isEmpty()) { + visiblyUtilized.addAll(inclusiveNSSet); + } + } + + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + + String NName = attribute.getLocalName(); + String NNodeValue = attribute.getNodeValue(); + + if (!XMLNS_URI.equals(attribute.getNamespaceURI())) { + if (isVisible(attribute) && isOutputElement) { + // The Element is output element, add the prefix (if used) + // to visibyUtilized + String prefix = attribute.getPrefix(); + if (prefix != null && !(prefix.equals(XML) || prefix.equals(XMLNS))) { + visiblyUtilized.add(prefix); + } + // Add to the result. + result.add(attribute); + } + } else if (isOutputElement && !isVisible(attribute) && !XMLNS.equals(NName)) { + ns.removeMappingIfNotRender(NName); + } else { + if (!isOutputElement && isVisible(attribute) + && inclusiveNSSet.contains(NName) + && !ns.removeMappingIfRender(NName)) { + Node n = ns.addMappingAndRender(NName, NNodeValue, attribute); + if (n != null) { + result.add((Attr)n); + if (C14nHelper.namespaceIsRelative(attribute)) { + Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() }; + throw new CanonicalizationException( + "c14n.Canonicalizer.RelativeNamespace", exArgs + ); + } + } + } + + if (ns.addMapping(NName, NNodeValue, attribute) + && C14nHelper.namespaceIsRelative(NNodeValue)) { + // New definition check if it is relative + Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() }; + throw new CanonicalizationException( + "c14n.Canonicalizer.RelativeNamespace", exArgs + ); + } + } + } + } + + if (isOutputElement) { + // The element is visible, handle the xmlns definition + Attr xmlns = element.getAttributeNodeNS(XMLNS_URI, XMLNS); + if (xmlns != null && !isVisible(xmlns)) { + // There is a definition but the xmlns is not selected by the + // xpath. then xmlns="" + ns.addMapping(XMLNS, "", nullNode); + } + + String prefix = null; + if (element.getNamespaceURI() != null + && !(element.getPrefix() == null || element.getPrefix().length() == 0)) { + prefix = element.getPrefix(); + } else { + prefix = XMLNS; + } + visiblyUtilized.add(prefix); + + for (String s : visiblyUtilized) { + Attr key = ns.getMapping(s); + if (key != null) { + result.add(key); + } + } + } + + return result.iterator(); + } + + protected void circumventBugIfNeeded(XMLSignatureInput input) + throws CanonicalizationException, ParserConfigurationException, + IOException, SAXException { + if (!input.isNeedsToBeExpanded() || inclusiveNSSet.isEmpty() || inclusiveNSSet.isEmpty()) { + return; + } + Document doc = null; + if (input.getSubNode() != null) { + doc = XMLUtils.getOwnerDocument(input.getSubNode()); + } else { + doc = XMLUtils.getOwnerDocument(input.getNodeSet()); + } + XMLUtils.circumventBug2650(doc); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java index 0910b980484..0fb402275a1 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java @@ -2,48 +2,44 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.c14n.implementations; import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; -/** - * - * - */ -public class Canonicalizer20010315ExclOmitComments - extends Canonicalizer20010315Excl { +public class Canonicalizer20010315ExclOmitComments extends Canonicalizer20010315Excl { - /** - * - */ - public Canonicalizer20010315ExclOmitComments() { - super(false); - } + /** + * + */ + public Canonicalizer20010315ExclOmitComments() { + super(false); + } - /** @inheritDoc */ - public final String engineGetURI() { - return Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; - } + /** @inheritDoc */ + public final String engineGetURI() { + return Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; + } - /** @inheritDoc */ - public final boolean engineGetIncludeComments() { - return false; - } + /** @inheritDoc */ + public final boolean engineGetIncludeComments() { + return false; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java index 37550124879..1ea477ac970 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java @@ -2,52 +2,48 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.c14n.implementations; - - import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; - /** * Class Canonicalizer20010315ExclWithComments - * - * @version $Revision: 1.5 $ */ -public class Canonicalizer20010315ExclWithComments - extends Canonicalizer20010315Excl { +public class Canonicalizer20010315ExclWithComments extends Canonicalizer20010315Excl { - /** - * Constructor Canonicalizer20010315ExclWithComments - * - */ - public Canonicalizer20010315ExclWithComments() { - super(true); - } + /** + * Constructor Canonicalizer20010315ExclWithComments + * + */ + public Canonicalizer20010315ExclWithComments() { + super(true); + } - /** @inheritDoc */ - public final String engineGetURI() { - return Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS; - } + /** @inheritDoc */ + public final String engineGetURI() { + return Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS; + } - /** @inheritDoc */ - public final boolean engineGetIncludeComments() { - return true; - } + /** @inheritDoc */ + public final boolean engineGetIncludeComments() { + return true; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java index 481642e6bac..2e21cc0b2dd 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java @@ -2,50 +2,48 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.c14n.implementations; - - import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; - /** - * * @author Christian Geuer-Pollmann */ public class Canonicalizer20010315OmitComments extends Canonicalizer20010315 { - /** - * Constructor Canonicalizer20010315WithXPathOmitComments - * - */ - public Canonicalizer20010315OmitComments() { - super(false); - } + /** + * Constructor Canonicalizer20010315WithXPathOmitComments + * + */ + public Canonicalizer20010315OmitComments() { + super(false); + } - /** @inheritDoc */ - public final String engineGetURI() { - return Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS; - } + /** @inheritDoc */ + public final String engineGetURI() { + return Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS; + } - /** @inheritDoc */ - public final boolean engineGetIncludeComments() { - return false; - } + /** @inheritDoc */ + public final boolean engineGetIncludeComments() { + return false; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java index 4714e165bba..bf56bfb6950 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java @@ -2,47 +2,47 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.c14n.implementations; import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; /** - * * @author Christian Geuer-Pollmann */ public class Canonicalizer20010315WithComments extends Canonicalizer20010315 { - /** - * Constructor Canonicalizer20010315WithXPathWithComments - * - */ - public Canonicalizer20010315WithComments() { - super(true); - } + /** + * Constructor Canonicalizer20010315WithXPathWithComments + */ + public Canonicalizer20010315WithComments() { + super(true); + } - /** @inheritDoc */ - public final String engineGetURI() { - return Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS; - } + /** @inheritDoc */ + public final String engineGetURI() { + return Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS; + } - /** @inheritDoc */ - public final boolean engineGetIncludeComments() { - return true; - } + /** @inheritDoc */ + public final boolean engineGetIncludeComments() { + return true; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java index 2f5f28904d2..4c9f277f65e 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.c14n.implementations; - - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; @@ -33,12 +33,10 @@ import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; -import java.util.SortedSet; -import java.util.Collection; +import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; -import javax.xml.xpath.XPath; import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; import com.sun.org.apache.xml.internal.security.c14n.CanonicalizerSpi; @@ -56,794 +54,829 @@ import org.w3c.dom.Node; import org.w3c.dom.ProcessingInstruction; import org.xml.sax.SAXException; - /** * Abstract base class for canonicalization algorithms. * * @author Christian Geuer-Pollmann - * @version $Revision: 1.5 $ */ public abstract class CanonicalizerBase extends CanonicalizerSpi { - //Constants to be outputed, In char array form, so - //less garbage is generate when outputed. - private static final byte[] _END_PI = {'?','>'}; - private static final byte[] _BEGIN_PI = {'<','?'}; - private static final byte[] _END_COMM = {'-','-','>'}; - private static final byte[] _BEGIN_COMM = {'<','!','-','-'}; - private static final byte[] __XA_ = {'&','#','x','A',';'}; - private static final byte[] __X9_ = {'&','#','x','9',';'}; - private static final byte[] _QUOT_ = {'&','q','u','o','t',';'}; - private static final byte[] __XD_ = {'&','#','x','D',';'}; - private static final byte[] _GT_ = {'&','g','t',';'}; - private static final byte[] _LT_ = {'&','l','t',';'}; - private static final byte[] _END_TAG = {'<','/'}; - private static final byte[] _AMP_ = {'&','a','m','p',';'}; - final static AttrCompare COMPARE=new AttrCompare(); - final static String XML="xml"; - final static String XMLNS="xmlns"; - final static byte[] equalsStr= {'=','\"'}; - static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1; - static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0; - static final int NODE_AFTER_DOCUMENT_ELEMENT = 1; - //The null xmlns definiton. - protected static final Attr nullNode; - static { - try { - nullNode=DocumentBuilderFactory.newInstance(). - newDocumentBuilder().newDocument().createAttributeNS(Constants.NamespaceSpecNS,XMLNS); - nullNode.setValue(""); - } catch (Exception e) { - throw new RuntimeException("Unable to create nullNode"/*,*/+e); - } - } + public static final String XML = "xml"; + public static final String XMLNS = "xmlns"; - List nodeFilter; + protected static final AttrCompare COMPARE = new AttrCompare(); + protected static final Attr nullNode; - boolean _includeComments; - Set _xpathNodeSet = null; - /** - * The node to be skiped/excluded from the DOM tree - * in subtree canonicalizations. - */ - Node _excludeNode =null; - OutputStream _writer = new UnsyncByteArrayOutputStream();//null; + private static final byte[] END_PI = {'?','>'}; + private static final byte[] BEGIN_PI = {'<','?'}; + private static final byte[] END_COMM = {'-','-','>'}; + private static final byte[] BEGIN_COMM = {'<','!','-','-'}; + private static final byte[] XA = {'&','#','x','A',';'}; + private static final byte[] X9 = {'&','#','x','9',';'}; + private static final byte[] QUOT = {'&','q','u','o','t',';'}; + private static final byte[] XD = {'&','#','x','D',';'}; + private static final byte[] GT = {'&','g','t',';'}; + private static final byte[] LT = {'&','l','t',';'}; + private static final byte[] END_TAG = {'<','/'}; + private static final byte[] AMP = {'&','a','m','p',';'}; + private static final byte[] equalsStr = {'=','\"'}; - /** - * Constructor CanonicalizerBase - * - * @param includeComments - */ - public CanonicalizerBase(boolean includeComments) { - this._includeComments = includeComments; - } + protected static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1; + protected static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0; + protected static final int NODE_AFTER_DOCUMENT_ELEMENT = 1; - /** - * Method engineCanonicalizeSubTree - * @inheritDoc - * @param rootNode - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeSubTree(Node rootNode) - throws CanonicalizationException { - return engineCanonicalizeSubTree(rootNode,(Node)null); - } - /** - * Method engineCanonicalizeXPathNodeSet - * @inheritDoc - * @param xpathNodeSet - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet) - throws CanonicalizationException { - this._xpathNodeSet = xpathNodeSet; - return engineCanonicalizeXPathNodeSetInternal(XMLUtils.getOwnerDocument(this._xpathNodeSet)); - } - - /** - * Canonicalizes a Subtree node. - * @param input the root of the subtree to canicalize - * @return The canonicalize stream. - * @throws CanonicalizationException - */ - public byte[] engineCanonicalize(XMLSignatureInput input) - throws CanonicalizationException { + static { + // The null xmlns definition. try { - if (input.isExcludeComments()) - _includeComments = false; - byte[] bytes; - if (input.isOctetStream()) { - return engineCanonicalize(input.getBytes()); - } - if (input.isElement()) { - bytes = engineCanonicalizeSubTree(input.getSubNode(), input - .getExcludeNode()); - return bytes; - } else if (input.isNodeSet()) { - nodeFilter=input.getNodeFilters(); + DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + nullNode = documentBuilder.newDocument().createAttributeNS(Constants.NamespaceSpecNS, XMLNS); + nullNode.setValue(""); + } catch (Exception e) { + throw new RuntimeException("Unable to create nullNode: " + e); + } + } - circumventBugIfNeeded(input); + private List nodeFilter; - if (input.getSubNode() != null) { - bytes = engineCanonicalizeXPathNodeSetInternal(input.getSubNode()); - } else { - bytes = engineCanonicalizeXPathNodeSet(input.getNodeSet()); - } - return bytes; + private boolean includeComments; + private Set xpathNodeSet; + /** + * The node to be skipped/excluded from the DOM tree + * in subtree canonicalizations. + */ + private Node excludeNode; + private OutputStream writer = new ByteArrayOutputStream(); - } - return null; - } catch (CanonicalizationException ex) { - throw new CanonicalizationException("empty", ex); - } catch (ParserConfigurationException ex) { - throw new CanonicalizationException("empty", ex); - } catch (IOException ex) { - throw new CanonicalizationException("empty", ex); - } catch (SAXException ex) { - throw new CanonicalizationException("empty", ex); - } - } - /** - * @param _writer The _writer to set. - */ - public void setWriter(OutputStream _writer) { - this._writer = _writer; + /** + * Constructor CanonicalizerBase + * + * @param includeComments + */ + public CanonicalizerBase(boolean includeComments) { + this.includeComments = includeComments; } /** - * Canonicalizes a Subtree node. - * - * @param rootNode - * the root of the subtree to canicalize - * @param excludeNode - * a node to be excluded from the canicalize operation - * @return The canonicalize stream. - * @throws CanonicalizationException - */ - byte[] engineCanonicalizeSubTree(Node rootNode,Node excludeNode) - throws CanonicalizationException { - this._excludeNode = excludeNode; + * Method engineCanonicalizeSubTree + * @inheritDoc + * @param rootNode + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeSubTree(Node rootNode) + throws CanonicalizationException { + return engineCanonicalizeSubTree(rootNode, (Node)null); + } + + /** + * Method engineCanonicalizeXPathNodeSet + * @inheritDoc + * @param xpathNodeSet + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet) + throws CanonicalizationException { + this.xpathNodeSet = xpathNodeSet; + return engineCanonicalizeXPathNodeSetInternal(XMLUtils.getOwnerDocument(this.xpathNodeSet)); + } + + /** + * Canonicalizes a Subtree node. + * @param input the root of the subtree to canicalize + * @return The canonicalize stream. + * @throws CanonicalizationException + */ + public byte[] engineCanonicalize(XMLSignatureInput input) throws CanonicalizationException { try { - NameSpaceSymbTable ns=new NameSpaceSymbTable(); - int nodeLevel=NODE_BEFORE_DOCUMENT_ELEMENT; - if (rootNode != null && rootNode.getNodeType() == Node.ELEMENT_NODE) { - //Fills the nssymbtable with the definitions of the parent of the root subnode - getParentNameSpaces((Element)rootNode,ns); - nodeLevel=NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - } - this.canonicalizeSubTree(rootNode,ns,rootNode,nodeLevel); - this._writer.close(); - if (this._writer instanceof ByteArrayOutputStream) { - byte []result=((ByteArrayOutputStream)this._writer).toByteArray(); - if (reset) { - ((ByteArrayOutputStream)this._writer).reset(); + if (input.isExcludeComments()) { + includeComments = false; } + if (input.isOctetStream()) { + return engineCanonicalize(input.getBytes()); + } + if (input.isElement()) { + return engineCanonicalizeSubTree(input.getSubNode(), input.getExcludeNode()); + } else if (input.isNodeSet()) { + nodeFilter = input.getNodeFilters(); + + circumventBugIfNeeded(input); + + if (input.getSubNode() != null) { + return engineCanonicalizeXPathNodeSetInternal(input.getSubNode()); + } else { + return engineCanonicalizeXPathNodeSet(input.getNodeSet()); + } + } + return null; + } catch (CanonicalizationException ex) { + throw new CanonicalizationException("empty", ex); + } catch (ParserConfigurationException ex) { + throw new CanonicalizationException("empty", ex); + } catch (IOException ex) { + throw new CanonicalizationException("empty", ex); + } catch (SAXException ex) { + throw new CanonicalizationException("empty", ex); + } + } + + /** + * @param writer The writer to set. + */ + public void setWriter(OutputStream writer) { + this.writer = writer; + } + + /** + * Canonicalizes a Subtree node. + * + * @param rootNode + * the root of the subtree to canonicalize + * @param excludeNode + * a node to be excluded from the canonicalize operation + * @return The canonicalize stream. + * @throws CanonicalizationException + */ + protected byte[] engineCanonicalizeSubTree(Node rootNode, Node excludeNode) + throws CanonicalizationException { + this.excludeNode = excludeNode; + try { + NameSpaceSymbTable ns = new NameSpaceSymbTable(); + int nodeLevel = NODE_BEFORE_DOCUMENT_ELEMENT; + if (rootNode != null && Node.ELEMENT_NODE == rootNode.getNodeType()) { + //Fills the nssymbtable with the definitions of the parent of the root subnode + getParentNameSpaces((Element)rootNode, ns); + nodeLevel = NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; + } + this.canonicalizeSubTree(rootNode, ns, rootNode, nodeLevel); + this.writer.flush(); + if (this.writer instanceof ByteArrayOutputStream) { + byte[] result = ((ByteArrayOutputStream)this.writer).toByteArray(); + if (reset) { + ((ByteArrayOutputStream)this.writer).reset(); + } else { + this.writer.close(); + } return result; - } else if (this._writer instanceof UnsyncByteArrayOutputStream) { - byte []result=((UnsyncByteArrayOutputStream)this._writer).toByteArray(); - if (reset) { - ((UnsyncByteArrayOutputStream)this._writer).reset(); - } - return result; - } - return null; + } else if (this.writer instanceof UnsyncByteArrayOutputStream) { + byte[] result = ((UnsyncByteArrayOutputStream)this.writer).toByteArray(); + if (reset) { + ((UnsyncByteArrayOutputStream)this.writer).reset(); + } else { + this.writer.close(); + } + return result; + } else { + this.writer.close(); + } + return null; - } catch (UnsupportedEncodingException ex) { - throw new CanonicalizationException("empty", ex); - } catch (IOException ex) { - throw new CanonicalizationException("empty", ex); - } - } + } catch (UnsupportedEncodingException ex) { + throw new CanonicalizationException("empty", ex); + } catch (IOException ex) { + throw new CanonicalizationException("empty", ex); + } + } - /** - * Method canonicalizeSubTree, this function is a recursive one. - * - * @param currentNode - * @param ns - * @param endnode - * @throws CanonicalizationException - * @throws IOException - */ - final void canonicalizeSubTree(Node currentNode, NameSpaceSymbTable ns,Node endnode, - int documentLevel) - throws CanonicalizationException, IOException { - if (isVisibleInt(currentNode)==-1) - return; - Node sibling=null; - Node parentNode=null; - final OutputStream writer=this._writer; - final Node excludeNode=this._excludeNode; - final boolean includeComments=this._includeComments; - Map cache=new HashMap(); + /** + * Method canonicalizeSubTree, this function is a recursive one. + * + * @param currentNode + * @param ns + * @param endnode + * @throws CanonicalizationException + * @throws IOException + */ + protected final void canonicalizeSubTree( + Node currentNode, NameSpaceSymbTable ns, Node endnode, int documentLevel + ) throws CanonicalizationException, IOException { + if (isVisibleInt(currentNode) == -1) { + return; + } + Node sibling = null; + Node parentNode = null; + final OutputStream writer = this.writer; + final Node excludeNode = this.excludeNode; + final boolean includeComments = this.includeComments; + Map cache = new HashMap(); do { - switch (currentNode.getNodeType()) { + switch (currentNode.getNodeType()) { - case Node.DOCUMENT_TYPE_NODE : - default : - break; - - case Node.ENTITY_NODE : - case Node.NOTATION_NODE : - case Node.ATTRIBUTE_NODE : - // illegal node type during traversal - throw new CanonicalizationException("empty"); + case Node.ENTITY_NODE : + case Node.NOTATION_NODE : + case Node.ATTRIBUTE_NODE : + // illegal node type during traversal + throw new CanonicalizationException("empty"); case Node.DOCUMENT_FRAGMENT_NODE : - case Node.DOCUMENT_NODE : - ns.outputNodePush(); - sibling= currentNode.getFirstChild(); - break; + case Node.DOCUMENT_NODE : + ns.outputNodePush(); + sibling = currentNode.getFirstChild(); + break; - case Node.COMMENT_NODE : - if (includeComments) { - outputCommentToWriter((Comment) currentNode, writer, documentLevel); - } - break; - - case Node.PROCESSING_INSTRUCTION_NODE : - outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel); - break; - - case Node.TEXT_NODE : - case Node.CDATA_SECTION_NODE : - outputTextToWriter(currentNode.getNodeValue(), writer); - break; - - case Node.ELEMENT_NODE : - documentLevel=NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - if (currentNode==excludeNode) { - break; - } - Element currentElement = (Element) currentNode; - //Add a level to the nssymbtable. So latter can be pop-back. - ns.outputNodePush(); - writer.write('<'); - String name=currentElement.getTagName(); - UtfHelpper.writeByte(name,writer,cache); - - Iterator attrs = this.handleAttributesSubtree(currentElement,ns); - if (attrs!=null) { - //we output all Attrs which are available - while (attrs.hasNext()) { - Attr attr = attrs.next(); - outputAttrToWriter(attr.getNodeName(),attr.getNodeValue(), writer,cache); - } - } - writer.write('>'); - sibling= currentNode.getFirstChild(); - if (sibling==null) { - writer.write(_END_TAG); - UtfHelpper.writeStringToUtf8(name,writer); - writer.write('>'); - //We fineshed with this level, pop to the previous definitions. - ns.outputNodePop(); - if (parentNode != null) { - sibling= currentNode.getNextSibling(); - } - } else { - parentNode=currentElement; - } - break; + case Node.COMMENT_NODE : + if (includeComments) { + outputCommentToWriter((Comment) currentNode, writer, documentLevel); } - while (sibling==null && parentNode!=null) { - writer.write(_END_TAG); - UtfHelpper.writeByte(((Element)parentNode).getTagName(),writer,cache); - writer.write('>'); - //We fineshed with this level, pop to the previous definitions. - ns.outputNodePop(); - if (parentNode==endnode) - return; - sibling=parentNode.getNextSibling(); - parentNode=parentNode.getParentNode(); - if (parentNode !=null && parentNode.getNodeType() != Node.ELEMENT_NODE) { - documentLevel=NODE_AFTER_DOCUMENT_ELEMENT; - parentNode=null; - } - } - if (sibling==null) - return; - currentNode=sibling; - sibling=currentNode.getNextSibling(); - } while(true); - } + break; + case Node.PROCESSING_INSTRUCTION_NODE : + outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel); + break; + case Node.TEXT_NODE : + case Node.CDATA_SECTION_NODE : + outputTextToWriter(currentNode.getNodeValue(), writer); + break; - private byte[] engineCanonicalizeXPathNodeSetInternal(Node doc) - throws CanonicalizationException { - - try { - this.canonicalizeXPathNodeSet(doc,doc); - this._writer.close(); - if (this._writer instanceof ByteArrayOutputStream) { - byte [] sol=((ByteArrayOutputStream)this._writer).toByteArray(); - if (reset) { - ((ByteArrayOutputStream)this._writer).reset(); - } - return sol; - } else if (this._writer instanceof UnsyncByteArrayOutputStream) { - byte []result=((UnsyncByteArrayOutputStream)this._writer).toByteArray(); - if (reset) { - ((UnsyncByteArrayOutputStream)this._writer).reset(); - } - return result; - } - return null; - } catch (UnsupportedEncodingException ex) { - throw new CanonicalizationException("empty", ex); - } catch (IOException ex) { - throw new CanonicalizationException("empty", ex); - } - } - - /** - * Canoicalizes all the nodes included in the currentNode and contained in the - * _xpathNodeSet field. - * - * @param currentNode - * @param endnode - * @throws CanonicalizationException - * @throws IOException - */ - final void canonicalizeXPathNodeSet(Node currentNode,Node endnode ) - throws CanonicalizationException, IOException { - if (isVisibleInt(currentNode)==-1) - return; - boolean currentNodeIsVisible = false; - NameSpaceSymbTable ns=new NameSpaceSymbTable(); - if (currentNode != null && currentNode.getNodeType() == Node.ELEMENT_NODE) - getParentNameSpaces((Element)currentNode,ns); - Node sibling=null; - Node parentNode=null; - OutputStream writer=this._writer; - int documentLevel=NODE_BEFORE_DOCUMENT_ELEMENT; - Map cache=new HashMap(); - do { - switch (currentNode.getNodeType()) { - - case Node.DOCUMENT_TYPE_NODE : - default : - break; - - case Node.ENTITY_NODE : - case Node.NOTATION_NODE : - case Node.ATTRIBUTE_NODE : - // illegal node type during traversal - throw new CanonicalizationException("empty"); - - case Node.DOCUMENT_FRAGMENT_NODE : - case Node.DOCUMENT_NODE : - ns.outputNodePush(); - //currentNode = currentNode.getFirstChild(); - sibling= currentNode.getFirstChild(); - break; - - case Node.COMMENT_NODE : - if (this._includeComments && (isVisibleDO(currentNode,ns.getLevel())==1)) { - outputCommentToWriter((Comment) currentNode, writer, documentLevel); - } - break; - - case Node.PROCESSING_INSTRUCTION_NODE : - if (isVisible(currentNode)) - outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel); - break; - - case Node.TEXT_NODE : - case Node.CDATA_SECTION_NODE : - if (isVisible(currentNode)) { - outputTextToWriter(currentNode.getNodeValue(), writer); - for (Node nextSibling = currentNode.getNextSibling(); - (nextSibling != null) - && ((nextSibling.getNodeType() == Node.TEXT_NODE) - || (nextSibling.getNodeType() - == Node.CDATA_SECTION_NODE)); - nextSibling = nextSibling.getNextSibling()) { - outputTextToWriter(nextSibling.getNodeValue(), writer); - currentNode=nextSibling; - sibling=currentNode.getNextSibling(); - } - - } - break; - - case Node.ELEMENT_NODE : - documentLevel=NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - Element currentElement = (Element) currentNode; - //Add a level to the nssymbtable. So latter can be pop-back. - String name=null; - int i=isVisibleDO(currentNode,ns.getLevel()); - if (i==-1) { - sibling= currentNode.getNextSibling(); - break; - } - currentNodeIsVisible=(i==1); - if (currentNodeIsVisible) { - ns.outputNodePush(); - writer.write('<'); - name=currentElement.getTagName(); - UtfHelpper.writeByte(name,writer,cache); - } else { - ns.push(); - } - - Iterator attrs = handleAttributes(currentElement,ns); - if (attrs!=null) { - //we output all Attrs which are available - while (attrs.hasNext()) { - Attr attr = attrs.next(); - outputAttrToWriter(attr.getNodeName(),attr.getNodeValue(), writer,cache); - } - } - if (currentNodeIsVisible) { - writer.write('>'); - } - sibling= currentNode.getFirstChild(); - - if (sibling==null) { - if (currentNodeIsVisible) { - writer.write(_END_TAG); - UtfHelpper.writeByte(name,writer,cache); - writer.write('>'); - //We fineshed with this level, pop to the previous definitions. - ns.outputNodePop(); - } else { - ns.pop(); - } - if (parentNode != null) { - sibling= currentNode.getNextSibling(); - } - } else { - parentNode=currentElement; - } - break; - } - while (sibling==null && parentNode!=null) { - if (isVisible(parentNode)) { - writer.write(_END_TAG); - UtfHelpper.writeByte(((Element)parentNode).getTagName(),writer,cache); - writer.write('>'); - //We fineshed with this level, pop to the previous definitions. - ns.outputNodePop(); - } else { - ns.pop(); - } - if (parentNode==endnode) - return; - sibling=parentNode.getNextSibling(); - parentNode=parentNode.getParentNode(); - if (parentNode != null && parentNode.getNodeType() != Node.ELEMENT_NODE) { - parentNode=null; - documentLevel=NODE_AFTER_DOCUMENT_ELEMENT; - } - } - if (sibling==null) - return; - currentNode=sibling; - sibling=currentNode.getNextSibling(); - } while(true); - } - int isVisibleDO(Node currentNode,int level) { - if (nodeFilter!=null) { - Iterator it=nodeFilter.iterator(); - while (it.hasNext()) { - int i=(it.next()).isNodeIncludeDO(currentNode,level); - if (i!=1) - return i; - } - } - if ((this._xpathNodeSet!=null) && !this._xpathNodeSet.contains(currentNode)) - return 0; - return 1; - } - int isVisibleInt(Node currentNode) { - if (nodeFilter!=null) { - Iterator it=nodeFilter.iterator(); - while (it.hasNext()) { - int i=(it.next()).isNodeInclude(currentNode); - if (i!=1) - return i; - } - } - if ((this._xpathNodeSet!=null) && !this._xpathNodeSet.contains(currentNode)) - return 0; - return 1; - } - - boolean isVisible(Node currentNode) { - if (nodeFilter!=null) { - Iterator it=nodeFilter.iterator(); - while (it.hasNext()) { - if ((it.next()).isNodeInclude(currentNode)!=1) - return false; - } - } - if ((this._xpathNodeSet!=null) && !this._xpathNodeSet.contains(currentNode)) - return false; - return true; - } - - void handleParent(Element e,NameSpaceSymbTable ns) { - if (!e.hasAttributes()) { - return; - } - NamedNodeMap attrs = e.getAttributes(); - int attrsLength = attrs.getLength(); - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); - if (Constants.NamespaceSpecNS!=N.getNamespaceURI()) { - //Not a namespace definition, ignore. - continue; - } - - String NName=N.getLocalName(); - String NValue=N.getNodeValue(); - if (XML.equals(NName) - && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) { - continue; - } - ns.addMapping(NName,NValue,N); - } - } - - /** - * Adds to ns the definitons from the parent elements of el - * @param el - * @param ns - */ - final void getParentNameSpaces(Element el,NameSpaceSymbTable ns) { - List parents=new ArrayList(10); - Node n1=el.getParentNode(); - if (n1 == null || n1.getNodeType() != Node.ELEMENT_NODE) { - return; - } - //Obtain all the parents of the elemnt - Node parent = n1; - while (parent!=null && parent.getNodeType() == Node.ELEMENT_NODE) { - parents.add((Element)parent); - parent = parent.getParentNode(); - } - //Visit them in reverse order. - ListIterator it=parents.listIterator(parents.size()); - while (it.hasPrevious()) { - Element ele=it.previous(); - handleParent(ele, ns); - } - Attr nsprefix; - if (((nsprefix=ns.getMappingWithoutRendered("xmlns"))!=null) - && "".equals(nsprefix.getValue())) { - ns.addMappingAndRender("xmlns","",nullNode); - } - } - /** - * Obtain the attributes to output for this node in XPathNodeSet c14n. - * - * @param E - * @param ns - * @return the attributes nodes to output. - * @throws CanonicalizationException - */ - abstract Iterator handleAttributes(Element E, NameSpaceSymbTable ns ) - throws CanonicalizationException; - - /** - * Obtain the attributes to output for this node in a Subtree c14n. - * - * @param E - * @param ns - * @return the attributes nodes to output. - * @throws CanonicalizationException - */ - abstract Iterator handleAttributesSubtree(Element E, NameSpaceSymbTable ns) - throws CanonicalizationException; - - abstract void circumventBugIfNeeded(XMLSignatureInput input) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException; - - /** - * Outputs an Attribute to the internal Writer. - * - * The string value of the node is modified by replacing - *
    - *
  • all ampersands (&) with &amp;
  • - *
  • all open angle brackets (<) with &lt;
  • - *
  • all quotation mark characters with &quot;
  • - *
  • and the whitespace characters #x9, #xA, and #xD, with character - * references. The character references are written in uppercase - * hexadecimal with no leading zeroes (for example, #xD is represented - * by the character reference &#xD;)
  • - *
- * - * @param name - * @param value - * @param writer - * @throws IOException - */ - static final void outputAttrToWriter(final String name, final String value, final OutputStream writer, - final Map cache) throws IOException { - writer.write(' '); - UtfHelpper.writeByte(name,writer,cache); - writer.write(equalsStr); - byte []toWrite; - final int length = value.length(); - int i=0; - while (i < length) { - char c = value.charAt(i++); - - switch (c) { - - case '&' : - toWrite=_AMP_; + case Node.ELEMENT_NODE : + documentLevel = NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; + if (currentNode == excludeNode) { break; + } + Element currentElement = (Element)currentNode; + //Add a level to the nssymbtable. So latter can be pop-back. + ns.outputNodePush(); + writer.write('<'); + String name = currentElement.getTagName(); + UtfHelpper.writeByte(name, writer, cache); - case '<' : - toWrite=_LT_; - break; - - case '"' : - toWrite=_QUOT_; - break; - - case 0x09 : // '\t' - toWrite=__X9_; - break; - - case 0x0A : // '\n' - toWrite=__XA_; - break; - - case 0x0D : // '\r' - toWrite=__XD_; - break; - - default : - if (c < 0x80 ) { - writer.write(c); - } else { - UtfHelpper.writeCharToUtf8(c,writer); - }; - continue; - } - writer.write(toWrite); - } - - writer.write('\"'); - } - - /** - * Outputs a PI to the internal Writer. - * - * @param currentPI - * @param writer where to write the things - * @throws IOException - */ - static final void outputPItoWriter(ProcessingInstruction currentPI, OutputStream writer,int position) throws IOException { - - if (position == NODE_AFTER_DOCUMENT_ELEMENT) { - writer.write('\n'); - } - writer.write(_BEGIN_PI); - - final String target = currentPI.getTarget(); - int length = target.length(); - - for (int i = 0; i < length; i++) { - char c=target.charAt(i); - if (c==0x0D) { - writer.write(__XD_); - } else { - if (c < 0x80) { - writer.write(c); - } else { - UtfHelpper.writeCharToUtf8(c,writer); - }; - } - } - - final String data = currentPI.getData(); - - length = data.length(); - - if (length > 0) { - writer.write(' '); - - for (int i = 0; i < length; i++) { - char c=data.charAt(i); - if (c==0x0D) { - writer.write(__XD_); - } else { - UtfHelpper.writeCharToUtf8(c,writer); + Iterator attrs = this.handleAttributesSubtree(currentElement, ns); + if (attrs != null) { + //we output all Attrs which are available + while (attrs.hasNext()) { + Attr attr = attrs.next(); + outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache); } - } - } + } + writer.write('>'); + sibling = currentNode.getFirstChild(); + if (sibling == null) { + writer.write(END_TAG); + UtfHelpper.writeStringToUtf8(name, writer); + writer.write('>'); + //We finished with this level, pop to the previous definitions. + ns.outputNodePop(); + if (parentNode != null) { + sibling = currentNode.getNextSibling(); + } + } else { + parentNode = currentElement; + } + break; - writer.write(_END_PI); - if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { - writer.write('\n'); - } - } - - /** - * Method outputCommentToWriter - * - * @param currentComment - * @param writer writer where to write the things - * @throws IOException - */ - static final void outputCommentToWriter(Comment currentComment, OutputStream writer,int position) throws IOException { - if (position == NODE_AFTER_DOCUMENT_ELEMENT) { - writer.write('\n'); - } - writer.write(_BEGIN_COMM); - - final String data = currentComment.getData(); - final int length = data.length(); - - for (int i = 0; i < length; i++) { - char c=data.charAt(i); - if (c==0x0D) { - writer.write(__XD_); - } else { - if (c < 0x80) { - writer.write(c); - } else { - UtfHelpper.writeCharToUtf8(c,writer); - }; - } - } - - writer.write(_END_COMM); - if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { - writer.write('\n'); - } - } - - /** - * Outputs a Text of CDATA section to the internal Writer. - * - * @param text - * @param writer writer where to write the things - * @throws IOException - */ - static final void outputTextToWriter(final String text, final OutputStream writer) throws IOException { - final int length = text.length(); - byte []toWrite; - for (int i = 0; i < length; i++) { - char c = text.charAt(i); - - switch (c) { - - case '&' : - toWrite=_AMP_; - break; - - case '<' : - toWrite=_LT_; - break; - - case '>' : - toWrite=_GT_; - break; - - case 0xD : - toWrite=__XD_; - break; - - default : - if (c < 0x80) { - writer.write(c); - } else { - UtfHelpper.writeCharToUtf8(c,writer); - }; - continue; - } - writer.write(toWrite); - } - } - - @SuppressWarnings("unchecked") - protected Collection getSortedSetAsCollection(SortedSet result) { - return (Collection)(Collection)result; + case Node.DOCUMENT_TYPE_NODE : + default : + break; + } + while (sibling == null && parentNode != null) { + writer.write(END_TAG); + UtfHelpper.writeByte(((Element)parentNode).getTagName(), writer, cache); + writer.write('>'); + //We finished with this level, pop to the previous definitions. + ns.outputNodePop(); + if (parentNode == endnode) { + return; + } + sibling = parentNode.getNextSibling(); + parentNode = parentNode.getParentNode(); + if (parentNode == null || Node.ELEMENT_NODE != parentNode.getNodeType()) { + documentLevel = NODE_AFTER_DOCUMENT_ELEMENT; + parentNode = null; + } + } + if (sibling == null) { + return; + } + currentNode = sibling; + sibling = currentNode.getNextSibling(); + } while(true); } + private byte[] engineCanonicalizeXPathNodeSetInternal(Node doc) + throws CanonicalizationException { + try { + this.canonicalizeXPathNodeSet(doc, doc); + this.writer.flush(); + if (this.writer instanceof ByteArrayOutputStream) { + byte[] sol = ((ByteArrayOutputStream)this.writer).toByteArray(); + if (reset) { + ((ByteArrayOutputStream)this.writer).reset(); + } else { + this.writer.close(); + } + return sol; + } else if (this.writer instanceof UnsyncByteArrayOutputStream) { + byte[] result = ((UnsyncByteArrayOutputStream)this.writer).toByteArray(); + if (reset) { + ((UnsyncByteArrayOutputStream)this.writer).reset(); + } else { + this.writer.close(); + } + return result; + } else { + this.writer.close(); + } + return null; + } catch (UnsupportedEncodingException ex) { + throw new CanonicalizationException("empty", ex); + } catch (IOException ex) { + throw new CanonicalizationException("empty", ex); + } + } + + /** + * Canonicalizes all the nodes included in the currentNode and contained in the + * xpathNodeSet field. + * + * @param currentNode + * @param endnode + * @throws CanonicalizationException + * @throws IOException + */ + protected final void canonicalizeXPathNodeSet(Node currentNode, Node endnode) + throws CanonicalizationException, IOException { + if (isVisibleInt(currentNode) == -1) { + return; + } + boolean currentNodeIsVisible = false; + NameSpaceSymbTable ns = new NameSpaceSymbTable(); + if (currentNode != null && Node.ELEMENT_NODE == currentNode.getNodeType()) { + getParentNameSpaces((Element)currentNode, ns); + } + if (currentNode == null) { + return; + } + Node sibling = null; + Node parentNode = null; + OutputStream writer = this.writer; + int documentLevel = NODE_BEFORE_DOCUMENT_ELEMENT; + Map cache = new HashMap(); + do { + switch (currentNode.getNodeType()) { + + case Node.ENTITY_NODE : + case Node.NOTATION_NODE : + case Node.ATTRIBUTE_NODE : + // illegal node type during traversal + throw new CanonicalizationException("empty"); + + case Node.DOCUMENT_FRAGMENT_NODE : + case Node.DOCUMENT_NODE : + ns.outputNodePush(); + sibling = currentNode.getFirstChild(); + break; + + case Node.COMMENT_NODE : + if (this.includeComments && (isVisibleDO(currentNode, ns.getLevel()) == 1)) { + outputCommentToWriter((Comment) currentNode, writer, documentLevel); + } + break; + + case Node.PROCESSING_INSTRUCTION_NODE : + if (isVisible(currentNode)) { + outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel); + } + break; + + case Node.TEXT_NODE : + case Node.CDATA_SECTION_NODE : + if (isVisible(currentNode)) { + outputTextToWriter(currentNode.getNodeValue(), writer); + for (Node nextSibling = currentNode.getNextSibling(); + (nextSibling != null) && ((nextSibling.getNodeType() == Node.TEXT_NODE) + || (nextSibling.getNodeType() == Node.CDATA_SECTION_NODE)); + nextSibling = nextSibling.getNextSibling()) { + outputTextToWriter(nextSibling.getNodeValue(), writer); + currentNode = nextSibling; + sibling = currentNode.getNextSibling(); + } + } + break; + + case Node.ELEMENT_NODE : + documentLevel = NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; + Element currentElement = (Element) currentNode; + //Add a level to the nssymbtable. So latter can be pop-back. + String name = null; + int i = isVisibleDO(currentNode, ns.getLevel()); + if (i == -1) { + sibling = currentNode.getNextSibling(); + break; + } + currentNodeIsVisible = (i == 1); + if (currentNodeIsVisible) { + ns.outputNodePush(); + writer.write('<'); + name = currentElement.getTagName(); + UtfHelpper.writeByte(name, writer, cache); + } else { + ns.push(); + } + + Iterator attrs = handleAttributes(currentElement,ns); + if (attrs != null) { + //we output all Attrs which are available + while (attrs.hasNext()) { + Attr attr = attrs.next(); + outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache); + } + } + if (currentNodeIsVisible) { + writer.write('>'); + } + sibling = currentNode.getFirstChild(); + + if (sibling == null) { + if (currentNodeIsVisible) { + writer.write(END_TAG); + UtfHelpper.writeByte(name, writer, cache); + writer.write('>'); + //We finished with this level, pop to the previous definitions. + ns.outputNodePop(); + } else { + ns.pop(); + } + if (parentNode != null) { + sibling = currentNode.getNextSibling(); + } + } else { + parentNode = currentElement; + } + break; + + case Node.DOCUMENT_TYPE_NODE : + default : + break; + } + while (sibling == null && parentNode != null) { + if (isVisible(parentNode)) { + writer.write(END_TAG); + UtfHelpper.writeByte(((Element)parentNode).getTagName(), writer, cache); + writer.write('>'); + //We finished with this level, pop to the previous definitions. + ns.outputNodePop(); + } else { + ns.pop(); + } + if (parentNode == endnode) { + return; + } + sibling = parentNode.getNextSibling(); + parentNode = parentNode.getParentNode(); + if (parentNode == null || Node.ELEMENT_NODE != parentNode.getNodeType()) { + parentNode = null; + documentLevel = NODE_AFTER_DOCUMENT_ELEMENT; + } + } + if (sibling == null) { + return; + } + currentNode = sibling; + sibling = currentNode.getNextSibling(); + } while(true); + } + + protected int isVisibleDO(Node currentNode, int level) { + if (nodeFilter != null) { + Iterator it = nodeFilter.iterator(); + while (it.hasNext()) { + int i = (it.next()).isNodeIncludeDO(currentNode, level); + if (i != 1) { + return i; + } + } + } + if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) { + return 0; + } + return 1; + } + + protected int isVisibleInt(Node currentNode) { + if (nodeFilter != null) { + Iterator it = nodeFilter.iterator(); + while (it.hasNext()) { + int i = (it.next()).isNodeInclude(currentNode); + if (i != 1) { + return i; + } + } + } + if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) { + return 0; + } + return 1; + } + + protected boolean isVisible(Node currentNode) { + if (nodeFilter != null) { + Iterator it = nodeFilter.iterator(); + while (it.hasNext()) { + if (it.next().isNodeInclude(currentNode) != 1) { + return false; + } + } + } + if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) { + return false; + } + return true; + } + + protected void handleParent(Element e, NameSpaceSymbTable ns) { + if (!e.hasAttributes() && e.getNamespaceURI() == null) { + return; + } + NamedNodeMap attrs = e.getAttributes(); + int attrsLength = attrs.getLength(); + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + String NName = attribute.getLocalName(); + String NValue = attribute.getNodeValue(); + + if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI()) + && (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue))) { + ns.addMapping(NName, NValue, attribute); + } + } + if (e.getNamespaceURI() != null) { + String NName = e.getPrefix(); + String NValue = e.getNamespaceURI(); + String Name; + if (NName == null || NName.equals("")) { + NName = XMLNS; + Name = XMLNS; + } else { + Name = XMLNS + ":" + NName; + } + Attr n = e.getOwnerDocument().createAttributeNS("http://www.w3.org/2000/xmlns/", Name); + n.setValue(NValue); + ns.addMapping(NName, NValue, n); + } + } + + /** + * Adds to ns the definitions from the parent elements of el + * @param el + * @param ns + */ + protected final void getParentNameSpaces(Element el, NameSpaceSymbTable ns) { + Node n1 = el.getParentNode(); + if (n1 == null || Node.ELEMENT_NODE != n1.getNodeType()) { + return; + } + //Obtain all the parents of the element + List parents = new ArrayList(); + Node parent = n1; + while (parent != null && Node.ELEMENT_NODE == parent.getNodeType()) { + parents.add((Element)parent); + parent = parent.getParentNode(); + } + //Visit them in reverse order. + ListIterator it = parents.listIterator(parents.size()); + while (it.hasPrevious()) { + Element ele = it.previous(); + handleParent(ele, ns); + } + parents.clear(); + Attr nsprefix; + if (((nsprefix = ns.getMappingWithoutRendered(XMLNS)) != null) + && "".equals(nsprefix.getValue())) { + ns.addMappingAndRender(XMLNS, "", nullNode); + } + } + + /** + * Obtain the attributes to output for this node in XPathNodeSet c14n. + * + * @param element + * @param ns + * @return the attributes nodes to output. + * @throws CanonicalizationException + */ + abstract Iterator handleAttributes(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException; + + /** + * Obtain the attributes to output for this node in a Subtree c14n. + * + * @param element + * @param ns + * @return the attributes nodes to output. + * @throws CanonicalizationException + */ + abstract Iterator handleAttributesSubtree(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException; + + abstract void circumventBugIfNeeded(XMLSignatureInput input) + throws CanonicalizationException, ParserConfigurationException, IOException, SAXException; + + /** + * Outputs an Attribute to the internal Writer. + * + * The string value of the node is modified by replacing + *
    + *
  • all ampersands (&) with &amp;
  • + *
  • all open angle brackets (<) with &lt;
  • + *
  • all quotation mark characters with &quot;
  • + *
  • and the whitespace characters #x9, #xA, and #xD, with character + * references. The character references are written in uppercase + * hexadecimal with no leading zeroes (for example, #xD is represented + * by the character reference &#xD;)
  • + *
+ * + * @param name + * @param value + * @param writer + * @throws IOException + */ + protected static final void outputAttrToWriter( + final String name, final String value, + final OutputStream writer, final Map cache + ) throws IOException { + writer.write(' '); + UtfHelpper.writeByte(name, writer, cache); + writer.write(equalsStr); + byte[] toWrite; + final int length = value.length(); + int i = 0; + while (i < length) { + char c = value.charAt(i++); + + switch (c) { + + case '&' : + toWrite = AMP; + break; + + case '<' : + toWrite = LT; + break; + + case '"' : + toWrite = QUOT; + break; + + case 0x09 : // '\t' + toWrite = X9; + break; + + case 0x0A : // '\n' + toWrite = XA; + break; + + case 0x0D : // '\r' + toWrite = XD; + break; + + default : + if (c < 0x80) { + writer.write(c); + } else { + UtfHelpper.writeCharToUtf8(c, writer); + } + continue; + } + writer.write(toWrite); + } + + writer.write('\"'); + } + + /** + * Outputs a PI to the internal Writer. + * + * @param currentPI + * @param writer where to write the things + * @throws IOException + */ + protected void outputPItoWriter( + ProcessingInstruction currentPI, OutputStream writer, int position + ) throws IOException { + if (position == NODE_AFTER_DOCUMENT_ELEMENT) { + writer.write('\n'); + } + writer.write(BEGIN_PI); + + final String target = currentPI.getTarget(); + int length = target.length(); + + for (int i = 0; i < length; i++) { + char c = target.charAt(i); + if (c == 0x0D) { + writer.write(XD); + } else { + if (c < 0x80) { + writer.write(c); + } else { + UtfHelpper.writeCharToUtf8(c, writer); + } + } + } + + final String data = currentPI.getData(); + + length = data.length(); + + if (length > 0) { + writer.write(' '); + + for (int i = 0; i < length; i++) { + char c = data.charAt(i); + if (c == 0x0D) { + writer.write(XD); + } else { + UtfHelpper.writeCharToUtf8(c, writer); + } + } + } + + writer.write(END_PI); + if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { + writer.write('\n'); + } + } + + /** + * Method outputCommentToWriter + * + * @param currentComment + * @param writer writer where to write the things + * @throws IOException + */ + protected void outputCommentToWriter( + Comment currentComment, OutputStream writer, int position + ) throws IOException { + if (position == NODE_AFTER_DOCUMENT_ELEMENT) { + writer.write('\n'); + } + writer.write(BEGIN_COMM); + + final String data = currentComment.getData(); + final int length = data.length(); + + for (int i = 0; i < length; i++) { + char c = data.charAt(i); + if (c == 0x0D) { + writer.write(XD); + } else { + if (c < 0x80) { + writer.write(c); + } else { + UtfHelpper.writeCharToUtf8(c, writer); + } + } + } + + writer.write(END_COMM); + if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { + writer.write('\n'); + } + } + + /** + * Outputs a Text of CDATA section to the internal Writer. + * + * @param text + * @param writer writer where to write the things + * @throws IOException + */ + protected static final void outputTextToWriter( + final String text, final OutputStream writer + ) throws IOException { + final int length = text.length(); + byte[] toWrite; + for (int i = 0; i < length; i++) { + char c = text.charAt(i); + + switch (c) { + + case '&' : + toWrite = AMP; + break; + + case '<' : + toWrite = LT; + break; + + case '>' : + toWrite = GT; + break; + + case 0xD : + toWrite = XD; + break; + + default : + if (c < 0x80) { + writer.write(c); + } else { + UtfHelpper.writeCharToUtf8(c, writer); + } + continue; + } + writer.write(toWrite); + } + } + } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java new file mode 100644 index 00000000000..17d8705a210 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java @@ -0,0 +1,184 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 com.sun.org.apache.xml.internal.security.c14n.implementations; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.Iterator; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; + +import javax.xml.parsers.ParserConfigurationException; + +import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; +import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; +import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; +import org.w3c.dom.Attr; +import org.w3c.dom.Comment; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.ProcessingInstruction; +import org.xml.sax.SAXException; + +/** + * Serializes the physical representation of the subtree. All the attributes + * present in the subtree are emitted. The attributes are sorted within an element, + * with the namespace declarations appearing before the regular attributes. + * This algorithm is not a true canonicalization since equivalent subtrees + * may produce different output. It is therefore unsuitable for digital signatures. + * This same property makes it ideal for XML Encryption Syntax and Processing, + * because the decrypted XML content will share the same physical representation + * as the original XML content that was encrypted. + */ +public class CanonicalizerPhysical extends CanonicalizerBase { + + private final SortedSet result = new TreeSet(COMPARE); + + /** + * Constructor Canonicalizer20010315 + */ + public CanonicalizerPhysical() { + super(true); + } + + /** + * Always throws a CanonicalizationException. + * + * @param xpathNodeSet + * @param inclusiveNamespaces + * @return none it always fails + * @throws CanonicalizationException always + */ + public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet, String inclusiveNamespaces) + throws CanonicalizationException { + + /** $todo$ well, should we throw UnsupportedOperationException ? */ + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); + } + + /** + * Always throws a CanonicalizationException. + * + * @param rootNode + * @param inclusiveNamespaces + * @return none it always fails + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces) + throws CanonicalizationException { + + /** $todo$ well, should we throw UnsupportedOperationException ? */ + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); + } + + /** + * Returns the Attr[]s to be output for the given element. + *
+ * The code of this method is a copy of {@link #handleAttributes(Element, + * NameSpaceSymbTable)}, + * whereas it takes into account that subtree-c14n is -- well -- subtree-based. + * So if the element in question isRoot of c14n, it's parent is not in the + * node set, as well as all other ancestors. + * + * @param element + * @param ns + * @return the Attr[]s to be output + * @throws CanonicalizationException + */ + @Override + protected Iterator handleAttributesSubtree(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + if (!element.hasAttributes()) { + return null; + } + + // result will contain all the attrs declared directly on that element + final SortedSet result = this.result; + result.clear(); + + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + result.add(attribute); + } + } + + return result.iterator(); + } + + /** + * Returns the Attr[]s to be output for the given element. + * + * @param element + * @param ns + * @return the Attr[]s to be output + * @throws CanonicalizationException + */ + @Override + protected Iterator handleAttributes(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + + /** $todo$ well, should we throw UnsupportedOperationException ? */ + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); + } + + protected void circumventBugIfNeeded(XMLSignatureInput input) + throws CanonicalizationException, ParserConfigurationException, IOException, SAXException { + // nothing to do + } + + @Override + protected void handleParent(Element e, NameSpaceSymbTable ns) { + // nothing to do + } + + /** @inheritDoc */ + public final String engineGetURI() { + return Canonicalizer.ALGO_ID_C14N_PHYSICAL; + } + + /** @inheritDoc */ + public final boolean engineGetIncludeComments() { + return true; + } + + @Override + protected void outputPItoWriter(ProcessingInstruction currentPI, + OutputStream writer, int position) throws IOException { + // Processing Instructions before or after the document element are not treated specially + super.outputPItoWriter(currentPI, writer, NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT); + } + + @Override + protected void outputCommentToWriter(Comment currentComment, + OutputStream writer, int position) throws IOException { + // Comments before or after the document element are not treated specially + super.outputCommentToWriter(currentComment, writer, NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT); + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java index 114bf7e0a86..54ae150b30e 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.c14n.implementations; @@ -29,191 +31,185 @@ import java.util.List; import org.w3c.dom.Attr; import org.w3c.dom.Node; - - /** - * A stack based Symble Table. + * A stack based Symbol Table. *
For speed reasons all the symbols are introduced in the same map, * and at the same time in a list so it can be removed when the frame is pop back. * @author Raul Benito - **/ + */ public class NameSpaceSymbTable { - /**The map betwen prefix-> entry table. */ - SymbMap symb; - /**The level of nameSpaces (for Inclusive visibility).*/ - int nameSpaces=0; - /**The stacks for removing the definitions when doing pop.*/ - List level; - boolean cloned=true; - static final String XMLNS="xmlns"; - final static SymbMap initialMap=new SymbMap(); - static { - NameSpaceSymbEntry ne=new NameSpaceSymbEntry("",null,true,XMLNS); - ne.lastrendered=""; - initialMap.put(XMLNS,ne); - } + private static final String XMLNS = "xmlns"; + private static final SymbMap initialMap = new SymbMap(); + + static { + NameSpaceSymbEntry ne = new NameSpaceSymbEntry("", null, true, XMLNS); + ne.lastrendered = ""; + initialMap.put(XMLNS, ne); + } + + /**The map betwen prefix-> entry table. */ + private SymbMap symb; + + /**The stacks for removing the definitions when doing pop.*/ + private List level; + private boolean cloned = true; + /** * Default constractor **/ public NameSpaceSymbTable() { - level = new ArrayList(10); + level = new ArrayList(); //Insert the default binding for xmlns. - symb=(SymbMap) initialMap.clone(); + symb = (SymbMap) initialMap.clone(); } /** - * Get all the unrendered nodes in the name space. - * For Inclusive rendering + * Get all the unrendered nodes in the name space. + * For Inclusive rendering * @param result the list where to fill the unrendered xmlns definitions. - **/ - public void getUnrenderedNodes(Collection result) { - //List result=new ArrayList(); - Iterator it=symb.entrySet().iterator(); - while (it.hasNext()) { - NameSpaceSymbEntry n= it.next(); - //put them rendered? - if ((!n.rendered) && (n.n!=null)) { - n=(NameSpaceSymbEntry) n.clone(); + **/ + public void getUnrenderedNodes(Collection result) { + Iterator it = symb.entrySet().iterator(); + while (it.hasNext()) { + NameSpaceSymbEntry n = it.next(); + //put them rendered? + if ((!n.rendered) && (n.n != null)) { + n = (NameSpaceSymbEntry) n.clone(); needsClone(); - symb.put(n.prefix,n); - n.lastrendered=n.uri; - n.rendered=true; + symb.put(n.prefix, n); + n.lastrendered = n.uri; + n.rendered = true; - result.add(n.n); - - } - } + result.add(n.n); + } } + } - /** + /** * Push a frame for visible namespace. * For Inclusive rendering. **/ - public void outputNodePush() { - nameSpaces++; - push(); - } + public void outputNodePush() { + push(); + } - /** + /** * Pop a frame for visible namespace. **/ - public void outputNodePop() { - nameSpaces--; - pop(); - } + public void outputNodePop() { + pop(); + } - /** + /** * Push a frame for a node. * Inclusive or Exclusive. **/ - public void push() { - //Put the number of namespace definitions in the stack. + public void push() { + //Put the number of namespace definitions in the stack. level.add(null); - cloned=false; - } + cloned = false; + } - /** + /** * Pop a frame. * Inclusive or Exclusive. **/ - public void pop() { - int size=level.size()-1; - Object ob= level.remove(size); - if (ob!=null) { - symb=(SymbMap)ob; - if (size==0) { - cloned=false; - } else - cloned=(level.get(size-1)!=symb); + public void pop() { + int size = level.size() - 1; + Object ob = level.remove(size); + if (ob != null) { + symb = (SymbMap)ob; + if (size == 0) { + cloned = false; + } else { + cloned = (level.get(size - 1) != symb); + } } else { - cloned=false; + cloned = false; } + } - - } - - final void needsClone() { - if (!cloned) { - level.set(level.size()-1,symb); - symb=(SymbMap) symb.clone(); - cloned=true; + final void needsClone() { + if (!cloned) { + level.set(level.size() - 1, symb); + symb = (SymbMap) symb.clone(); + cloned = true; } } - /** - * Gets the attribute node that defines the binding for the prefix. + /** + * Gets the attribute node that defines the binding for the prefix. * @param prefix the prefix to obtain the attribute. * @return null if there is no need to render the prefix. Otherwise the node of * definition. **/ - public Attr getMapping(String prefix) { - NameSpaceSymbEntry entry=symb.get(prefix); - if (entry==null) { - //There is no definition for the prefix(a bug?). - return null; - } - if (entry.rendered) { - //No need to render an entry already rendered. - return null; - } - // Mark this entry as render. - entry=(NameSpaceSymbEntry) entry.clone(); - needsClone(); - symb.put(prefix,entry); - entry.rendered=true; - entry.level=nameSpaces; - entry.lastrendered=entry.uri; - // Return the node for outputing. - return entry.n; + public Attr getMapping(String prefix) { + NameSpaceSymbEntry entry = symb.get(prefix); + if (entry == null) { + //There is no definition for the prefix(a bug?). + return null; } + if (entry.rendered) { + //No need to render an entry already rendered. + return null; + } + // Mark this entry as render. + entry = (NameSpaceSymbEntry) entry.clone(); + needsClone(); + symb.put(prefix, entry); + entry.rendered = true; + entry.lastrendered = entry.uri; + // Return the node for outputing. + return entry.n; + } - /** + /** * Gets a definition without mark it as render. * For render in exclusive c14n the namespaces in the include prefixes. * @param prefix The prefix whose definition is neaded. * @return the attr to render, null if there is no need to render **/ - public Attr getMappingWithoutRendered(String prefix) { - NameSpaceSymbEntry entry= symb.get(prefix); - if (entry==null) { - return null; - } - if (entry.rendered) { - return null; - } - return entry.n; + public Attr getMappingWithoutRendered(String prefix) { + NameSpaceSymbEntry entry = symb.get(prefix); + if (entry == null) { + return null; } + if (entry.rendered) { + return null; + } + return entry.n; + } - /** + /** * Adds the mapping for a prefix. * @param prefix the prefix of definition * @param uri the Uri of the definition * @param n the attribute that have the definition * @return true if there is already defined. **/ - public boolean addMapping(String prefix, String uri,Attr n) { - NameSpaceSymbEntry ob = symb.get(prefix); - if ((ob!=null) && uri.equals(ob.uri)) { - //If we have it previously defined. Don't keep working. - return false; - } - //Creates and entry in the table for this new definition. - NameSpaceSymbEntry ne=new NameSpaceSymbEntry(uri,n,false,prefix); - needsClone(); - symb.put(prefix, ne); - if (ob != null) { - //We have a previous definition store it for the pop. - //Check if a previous definition(not the inmidiatly one) has been rendered. - ne.lastrendered=ob.lastrendered; - if ((ob.lastrendered!=null)&& (ob.lastrendered.equals(uri))) { - //Yes it is. Mark as rendered. - ne.rendered=true; - } - } - return true; + public boolean addMapping(String prefix, String uri, Attr n) { + NameSpaceSymbEntry ob = symb.get(prefix); + if ((ob != null) && uri.equals(ob.uri)) { + //If we have it previously defined. Don't keep working. + return false; } + //Creates and entry in the table for this new definition. + NameSpaceSymbEntry ne = new NameSpaceSymbEntry(uri, n, false, prefix); + needsClone(); + symb.put(prefix, ne); + if (ob != null) { + //We have a previous definition store it for the pop. + //Check if a previous definition(not the inmidiatly one) has been rendered. + ne.lastrendered = ob.lastrendered; + if ((ob.lastrendered != null) && (ob.lastrendered.equals(uri))) { + //Yes it is. Mark as rendered. + ne.rendered = true; + } + } + return true; + } /** * Adds a definition and mark it as render. @@ -223,79 +219,91 @@ public class NameSpaceSymbTable { * @param n the attribute that have the definition * @return the attr to render, null if there is no need to render **/ - public Node addMappingAndRender(String prefix, String uri,Attr n) { + public Node addMappingAndRender(String prefix, String uri, Attr n) { NameSpaceSymbEntry ob = symb.get(prefix); - if ((ob!=null) && uri.equals(ob.uri)) { + if ((ob != null) && uri.equals(ob.uri)) { if (!ob.rendered) { - ob=(NameSpaceSymbEntry) ob.clone(); + ob = (NameSpaceSymbEntry) ob.clone(); needsClone(); - symb.put(prefix,ob); - ob.lastrendered=uri; - ob.rendered=true; + symb.put(prefix, ob); + ob.lastrendered = uri; + ob.rendered = true; return ob.n; } return null; } - NameSpaceSymbEntry ne=new NameSpaceSymbEntry(uri,n,true,prefix); - ne.lastrendered=uri; + NameSpaceSymbEntry ne = new NameSpaceSymbEntry(uri,n,true,prefix); + ne.lastrendered = uri; needsClone(); symb.put(prefix, ne); - if (ob != null) { - - if ((ob.lastrendered!=null)&& (ob.lastrendered.equals(uri))) { - ne.rendered=true; - return null; - } + if ((ob != null) && (ob.lastrendered != null) && (ob.lastrendered.equals(uri))) { + ne.rendered = true; + return null; } return ne.n; } - public int getLevel() { - // TODO Auto-generated method stub - return level.size(); - } + public int getLevel() { + return level.size(); + } - public void removeMapping(String prefix) { - NameSpaceSymbEntry ob = symb.get(prefix); + public void removeMapping(String prefix) { + NameSpaceSymbEntry ob = symb.get(prefix); - if (ob!=null) { + if (ob != null) { needsClone(); - symb.put(prefix,null); - } + symb.put(prefix, null); } + } - public void removeMappingIfNotRender(String prefix) { - NameSpaceSymbEntry ob = symb.get(prefix); + public void removeMappingIfNotRender(String prefix) { + NameSpaceSymbEntry ob = symb.get(prefix); - if (ob!=null && !ob.rendered) { + if (ob != null && !ob.rendered) { needsClone(); - symb.put(prefix,null); - } + symb.put(prefix, null); } + } - public boolean removeMappingIfRender(String prefix) { - NameSpaceSymbEntry ob = symb.get(prefix); + public boolean removeMappingIfRender(String prefix) { + NameSpaceSymbEntry ob = symb.get(prefix); - if (ob!=null && ob.rendered) { + if (ob != null && ob.rendered) { needsClone(); - symb.put(prefix,null); + symb.put(prefix, null); } return false; - } + } } /** * The internal structure of NameSpaceSymbTable. **/ class NameSpaceSymbEntry implements Cloneable { - NameSpaceSymbEntry(String name,Attr n,boolean rendered,String prefix) { - this.uri=name; - this.rendered=rendered; - this.n=n; - this.prefix=prefix; + + String prefix; + + /**The URI that the prefix defines */ + String uri; + + /**The last output in the URI for this prefix (This for speed reason).*/ + String lastrendered = null; + + /**This prefix-URI has been already render or not.*/ + boolean rendered = false; + + /**The attribute to include.*/ + Attr n; + + NameSpaceSymbEntry(String name, Attr n, boolean rendered, String prefix) { + this.uri = name; + this.rendered = rendered; + this.n = n; + this.prefix = prefix; } + /** @inheritDoc */ public Object clone() { try { @@ -304,46 +312,35 @@ class NameSpaceSymbEntry implements Cloneable { return null; } } - /** The level where the definition was rendered(Only for inclusive) */ - int level=0; - String prefix; - /**The URI that the prefix defines */ - String uri; - /**The last output in the URI for this prefix (This for speed reason).*/ - String lastrendered=null; - /**This prefix-URI has been already render or not.*/ - boolean rendered=false; - /**The attribute to include.*/ - Attr n; }; class SymbMap implements Cloneable { - int free=23; + int free = 23; NameSpaceSymbEntry[] entries; String[] keys; - SymbMap() { - entries=new NameSpaceSymbEntry[free]; - keys=new String[free]; - } + + SymbMap() { + entries = new NameSpaceSymbEntry[free]; + keys = new String[free]; + } + void put(String key, NameSpaceSymbEntry value) { int index = index(key); Object oldKey = keys[index]; keys[index] = key; entries[index] = value; - if (oldKey==null || !oldKey.equals(key)) { - if (--free == 0) { - free=entries.length; - int newCapacity = free<<2; - rehash(newCapacity); - } + if ((oldKey == null || !oldKey.equals(key)) && (--free == 0)) { + free = entries.length; + int newCapacity = free << 2; + rehash(newCapacity); } } List entrySet() { - List a=new ArrayList(); - for (int i=0;i a = new ArrayList(); + for (int i = 0;i < entries.length;i++) { + if ((entries[i] != null) && !("".equals(entries[i].uri))) { + a.add(entries[i]); } } return a; @@ -353,16 +350,16 @@ class SymbMap implements Cloneable { Object[] set = keys; int length = set.length; //abs of index - int index = (obj.hashCode() & 0x7fffffff) % length; + int index = (obj.hashCode() & 0x7fffffff) % length; Object cur = set[index]; - if (cur == null || (cur.equals( obj))) { - return index; + if (cur == null || (cur.equals(obj))) { + return index; } - length=length-1; + length--; do { - index=index==length? 0:++index; - cur = set[index]; + index = index == length ? 0 : ++index; + cur = set[index]; } while (cur != null && (!cur.equals(obj))); return index; } @@ -381,7 +378,7 @@ class SymbMap implements Cloneable { entries = new NameSpaceSymbEntry[newCapacity]; for (int i = oldCapacity; i-- > 0;) { - if(oldKeys[i] != null) { + if (oldKeys[i] != null) { String o = oldKeys[i]; int index = index(o); keys[index] = o; @@ -391,20 +388,19 @@ class SymbMap implements Cloneable { } NameSpaceSymbEntry get(String key) { - return entries[index(key)]; + return entries[index(key)]; } protected Object clone() { try { - SymbMap copy=(SymbMap) super.clone(); - copy.entries=new NameSpaceSymbEntry[entries.length]; - System.arraycopy(entries,0,copy.entries,0,entries.length); - copy.keys=new String[keys.length]; - System.arraycopy(keys,0,copy.keys,0,keys.length); + SymbMap copy = (SymbMap) super.clone(); + copy.entries = new NameSpaceSymbEntry[entries.length]; + System.arraycopy(entries, 0, copy.entries, 0, entries.length); + copy.keys = new String[keys.length]; + System.arraycopy(keys, 0, copy.keys, 0, keys.length); - return copy; + return copy; } catch (CloneNotSupportedException e) { - // TODO Auto-generated catch block e.printStackTrace(); } return null; diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java index b62dd3b0869..0ba49747f31 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java @@ -1,3 +1,25 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 com.sun.org.apache.xml.internal.security.c14n.implementations; import java.io.IOException; @@ -6,150 +28,153 @@ import java.util.Map; public class UtfHelpper { - final static void writeByte(final String str,final OutputStream out,Map cache) throws IOException { - byte []result= cache.get(str); - if (result==null) { - result=getStringInUtf8(str); - cache.put(str,result); - } + static final void writeByte( + final String str, + final OutputStream out, + Map cache + ) throws IOException { + byte[] result = cache.get(str); + if (result == null) { + result = getStringInUtf8(str); + cache.put(str, result); + } - out.write(result); + out.write(result); + } - } - - final static void writeCharToUtf8(final char c,final OutputStream out) throws IOException{ - if (c < 0x80) { - out.write(c); - return; + static final void writeCharToUtf8(final char c, final OutputStream out) throws IOException { + if (c < 0x80) { + out.write(c); + return; + } + if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF)) { + //No Surrogates in sun java + out.write(0x3f); + return; + } + int bias; + int write; + char ch; + if (c > 0x07FF) { + ch = (char)(c>>>12); + write = 0xE0; + if (ch > 0) { + write |= (ch & 0x0F); } - if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){ + out.write(write); + write = 0x80; + bias = 0x3F; + } else { + write = 0xC0; + bias = 0x1F; + } + ch = (char)(c>>>6); + if (ch > 0) { + write |= (ch & bias); + } + out.write(write); + out.write(0x80 | ((c) & 0x3F)); + + } + + static final void writeStringToUtf8( + final String str, + final OutputStream out + ) throws IOException{ + final int length = str.length(); + int i = 0; + char c; + while (i < length) { + c = str.charAt(i++); + if (c < 0x80) { + out.write(c); + continue; + } + if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF)) { //No Surrogates in sun java out.write(0x3f); - return; - } + continue; + } + char ch; int bias; int write; - char ch; if (c > 0x07FF) { - ch=(char)(c>>>12); - write=0xE0; - if (ch>0) { - write |= ( ch & 0x0F); + ch = (char)(c>>>12); + write = 0xE0; + if (ch > 0) { + write |= (ch & 0x0F); } out.write(write); - write=0x80; - bias=0x3F; + write = 0x80; + bias = 0x3F; } else { - write=0xC0; - bias=0x1F; + write = 0xC0; + bias = 0x1F; } - ch=(char)(c>>>6); - if (ch>0) { - write|= (ch & bias); + ch = (char)(c>>>6); + if (ch > 0) { + write |= (ch & bias); } out.write(write); out.write(0x80 | ((c) & 0x3F)); - } + } - final static void writeStringToUtf8(final String str,final OutputStream out) throws IOException{ - final int length=str.length(); - int i=0; - char c; - while (i= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF)) { + //No Surrogates in sun java + result[out++] = 0x3f; + continue; + } + if (!expanded) { + byte newResult[] = new byte[3*length]; + System.arraycopy(result, 0, newResult, 0, out); + result = newResult; + expanded = true; + } + char ch; + int bias; + byte write; + if (c > 0x07FF) { + ch = (char)(c>>>12); + write = (byte)0xE0; + if (ch > 0) { + write |= (ch & 0x0F); } - if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){ - //No Surrogates in sun java - out.write(0x3f); - continue; - } - char ch; - int bias; - int write; - if (c > 0x07FF) { - ch=(char)(c>>>12); - write=0xE0; - if (ch>0) { - write |= ( ch & 0x0F); - } - out.write(write); - write=0x80; - bias=0x3F; - } else { - write=0xC0; - bias=0x1F; - } - ch=(char)(c>>>6); - if (ch>0) { - write|= (ch & bias); - } - out.write(write); - out.write(0x80 | ((c) & 0x3F)); - - } - - } - public final static byte[] getStringInUtf8(final String str) { - final int length=str.length(); - boolean expanded=false; - byte []result=new byte[length]; - int i=0; - int out=0; - char c; - while (i= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){ - //No Surrogates in sun java - result[out++]=0x3f; - - continue; - } - if (!expanded) { - byte newResult[]=new byte[3*length]; - System.arraycopy(result, 0, newResult, 0, out); - result=newResult; - expanded=true; - } - char ch; - int bias; - byte write; - if (c > 0x07FF) { - ch=(char)(c>>>12); - write=(byte)0xE0; - if (ch>0) { - write |= ( ch & 0x0F); - } - result[out++]=write; - write=(byte)0x80; - bias=0x3F; - } else { - write=(byte)0xC0; - bias=0x1F; - } - ch=(char)(c>>>6); - if (ch>0) { - write|= (ch & bias); - } - result[out++]=write; - result[out++]=(byte)(0x80 | ((c) & 0x3F));/**/ - - } - if (expanded) { - byte newResult[]=new byte[out]; - System.arraycopy(result, 0, newResult, 0, out); - result=newResult; - } - return result; - } - - + result[out++] = write; + write = (byte)0x80; + bias = 0x3F; + } else { + write = (byte)0xC0; + bias = 0x1F; + } + ch = (char)(c>>>6); + if (ch > 0) { + write |= (ch & bias); + } + result[out++] = write; + result[out++] = (byte)(0x80 | ((c) & 0x3F)); + } + if (expanded) { + byte newResult[] = new byte[out]; + System.arraycopy(result, 0, newResult, 0, out); + result = newResult; + } + return result; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AbstractSerializer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AbstractSerializer.java new file mode 100644 index 00000000000..a21f1488ec7 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AbstractSerializer.java @@ -0,0 +1,249 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 com.sun.org.apache.xml.internal.security.encryption; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.util.HashMap; +import java.util.Map; + +import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * Converts Strings into Nodes and visa versa. + * + * An abstract class for common Serializer functionality + */ +public abstract class AbstractSerializer implements Serializer { + + protected Canonicalizer canon; + + public void setCanonicalizer(Canonicalizer canon) { + this.canon = canon; + } + + /** + * Returns a String representation of the specified + * Element. + *

+ * Refer also to comments about setup of format. + * + * @param element the Element to serialize. + * @return the String representation of the serilaized + * Element. + * @throws Exception + */ + public String serialize(Element element) throws Exception { + return canonSerialize(element); + } + + /** + * Returns a byte[] representation of the specified + * Element. + * + * @param element the Element to serialize. + * @return the byte[] representation of the serilaized + * Element. + * @throws Exception + */ + public byte[] serializeToByteArray(Element element) throws Exception { + return canonSerializeToByteArray(element); + } + + /** + * Returns a String representation of the specified + * NodeList. + *

+ * This is a special case because the NodeList may represent a + * DocumentFragment. A document fragment may be a + * non-valid XML document (refer to appropriate description of + * W3C) because it my start with a non-element node, e.g. a text + * node. + *

+ * The methods first converts the node list into a document fragment. + * Special care is taken to not destroy the current document, thus + * the method clones the nodes (deep cloning) before it appends + * them to the document fragment. + *

+ * Refer also to comments about setup of format. + * + * @param content the NodeList to serialize. + * @return the String representation of the serialized + * NodeList. + * @throws Exception + */ + public String serialize(NodeList content) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + canon.setWriter(baos); + canon.notReset(); + for (int i = 0; i < content.getLength(); i++) { + canon.canonicalizeSubtree(content.item(i)); + } + String ret = baos.toString("UTF-8"); + baos.reset(); + return ret; + } + + /** + * Returns a byte[] representation of the specified + * NodeList. + * + * @param content the NodeList to serialize. + * @return the byte[] representation of the serialized + * NodeList. + * @throws Exception + */ + public byte[] serializeToByteArray(NodeList content) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + canon.setWriter(baos); + canon.notReset(); + for (int i = 0; i < content.getLength(); i++) { + canon.canonicalizeSubtree(content.item(i)); + } + return baos.toByteArray(); + } + + /** + * Use the Canonicalizer to serialize the node + * @param node + * @return the canonicalization of the node + * @throws Exception + */ + public String canonSerialize(Node node) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + canon.setWriter(baos); + canon.notReset(); + canon.canonicalizeSubtree(node); + String ret = baos.toString("UTF-8"); + baos.reset(); + return ret; + } + + /** + * Use the Canonicalizer to serialize the node + * @param node + * @return the (byte[]) canonicalization of the node + * @throws Exception + */ + public byte[] canonSerializeToByteArray(Node node) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + canon.setWriter(baos); + canon.notReset(); + canon.canonicalizeSubtree(node); + return baos.toByteArray(); + } + + /** + * @param source + * @param ctx + * @return the Node resulting from the parse of the source + * @throws XMLEncryptionException + */ + public abstract Node deserialize(String source, Node ctx) throws XMLEncryptionException; + + /** + * @param source + * @param ctx + * @return the Node resulting from the parse of the source + * @throws XMLEncryptionException + */ + public abstract Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException; + + protected static byte[] createContext(byte[] source, Node ctx) throws XMLEncryptionException { + // Create the context to parse the document against + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + try { + OutputStreamWriter outputStreamWriter = new OutputStreamWriter(byteArrayOutputStream, "UTF-8"); + outputStreamWriter.write(" storedNamespaces = new HashMap(); + Node wk = ctx; + while (wk != null) { + NamedNodeMap atts = wk.getAttributes(); + if (atts != null) { + for (int i = 0; i < atts.getLength(); ++i) { + Node att = atts.item(i); + String nodeName = att.getNodeName(); + if ((nodeName.equals("xmlns") || nodeName.startsWith("xmlns:")) + && !storedNamespaces.containsKey(att.getNodeName())) { + outputStreamWriter.write(" "); + outputStreamWriter.write(nodeName); + outputStreamWriter.write("=\""); + outputStreamWriter.write(att.getNodeValue()); + outputStreamWriter.write("\""); + storedNamespaces.put(nodeName, att.getNodeValue()); + } + } + } + wk = wk.getParentNode(); + } + outputStreamWriter.write(">"); + outputStreamWriter.flush(); + byteArrayOutputStream.write(source); + + outputStreamWriter.write(""); + outputStreamWriter.close(); + + return byteArrayOutputStream.toByteArray(); + } catch (UnsupportedEncodingException e) { + throw new XMLEncryptionException("empty", e); + } catch (IOException e) { + throw new XMLEncryptionException("empty", e); + } + } + + protected static String createContext(String source, Node ctx) { + // Create the context to parse the document against + StringBuilder sb = new StringBuilder(); + sb.append(" storedNamespaces = new HashMap(); + Node wk = ctx; + while (wk != null) { + NamedNodeMap atts = wk.getAttributes(); + if (atts != null) { + for (int i = 0; i < atts.getLength(); ++i) { + Node att = atts.item(i); + String nodeName = att.getNodeName(); + if ((nodeName.equals("xmlns") || nodeName.startsWith("xmlns:")) + && !storedNamespaces.containsKey(att.getNodeName())) { + sb.append(" " + nodeName + "=\"" + att.getNodeValue() + "\""); + storedNamespaces.put(nodeName, att.getNodeValue()); + } + } + } + wk = wk.getParentNode(); + } + sb.append(">" + source + ""); + return sb.toString(); + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java index 803fca8c65f..c1da9befd71 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java @@ -2,30 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.encryption; - import java.util.Iterator; import com.sun.org.apache.xml.internal.security.keys.KeyInfo; import org.w3c.dom.Element; - /** * A Key Agreement algorithm provides for the derivation of a shared secret key * based on a shared secret computed from certain types of compatible public @@ -79,9 +79,10 @@ import org.w3c.dom.Element; * @author Axl Mattheus */ public interface AgreementMethod { + /** - * Returns an byte array. - * @return + * Returns a byte array. + * @return a byte array. */ byte[] getKANonce(); @@ -92,8 +93,8 @@ public interface AgreementMethod { void setKANonce(byte[] kanonce); /** - * Returns aditional information regarding the AgreementMethod. - * @return + * Returns additional information regarding the AgreementMethod. + * @return additional information regarding the AgreementMethod. */ Iterator getAgreementMethodInformation(); @@ -134,7 +135,7 @@ public interface AgreementMethod { void setOriginatorKeyInfo(KeyInfo keyInfo); /** - * Retruns information relating to the recipient's shared secret. + * Returns information relating to the recipient's shared secret. * * @return information relating to the recipient's shared secret. */ diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java index 8a03d389d7b..39654a9ff8d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java @@ -2,25 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.encryption; - /** * CipherData provides encrypted data. It must either contain the * encrypted octet sequence as base64 encoded text of the @@ -42,10 +43,12 @@ package com.sun.org.apache.xml.internal.security.encryption; * @author Axl Mattheus */ public interface CipherData { + /** VALUE_TYPE ASN */ - public static final int VALUE_TYPE = 0x00000001; + int VALUE_TYPE = 0x00000001; + /** REFERENCE_TYPE ASN */ - public static final int REFERENCE_TYPE = 0x00000002; + int REFERENCE_TYPE = 0x00000002; /** * Returns the type of encrypted data contained in the @@ -76,18 +79,17 @@ public interface CipherData { * Returns a reference to an external location containing the encrypted * octet sequence (byte array). * - * @return the reference to an external location containing the enctrypted - * octet sequence. + * @return the reference to an external location containing the encrypted + * octet sequence. */ CipherReference getCipherReference(); /** * Sets the CipherData's reference. * - * @param reference an external location containing the enctrypted octet - * sequence. + * @param reference an external location containing the encrypted octet sequence. * @throws XMLEncryptionException */ - void setCipherReference(CipherReference reference) throws - XMLEncryptionException; + void setCipherReference(CipherReference reference) throws XMLEncryptionException; } + diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java index 1610741193f..75b0dcb7971 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java @@ -2,34 +2,34 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.encryption; import org.w3c.dom.Attr; - /** * CipherReference identifies a source which, when processed, * yields the encrypted octet sequence. *

* The actual value is obtained as follows. The CipherReference URI * contains an identifier that is dereferenced. Should the - * CipherReference element contain an OPTIONAL sequence of * Transforms, the data resulting from dereferencing the URI is * transformed as specified so as to yield the intended cipher value. For * example, if the value is base64 encoded within an XML document; the @@ -62,20 +62,21 @@ public interface CipherReference { /** * Returns an URI that contains an identifier that should be * dereferenced. - * @return + * @return an URI that contains an identifier that should be + * dereferenced. */ String getURI(); - /** - * Gets the URI as an Attribute node. Used to meld the CipherREference - * with the XMLSignature ResourceResolvers - * @return - */ - public Attr getURIAsAttr(); + /** + * Gets the URI as an Attribute node. Used to meld the CipherReference + * with the XMLSignature ResourceResolvers + * @return the URI as an Attribute node + */ + Attr getURIAsAttr(); /** * Returns the Transforms that specifies how to transform the - * URI to yield the appropiate cipher value. + * URI to yield the appropriate cipher value. * * @return the transform that specifies how to transform the reference to * yield the intended cipher value. @@ -84,10 +85,11 @@ public interface CipherReference { /** * Sets the Transforms that specifies how to transform the - * URI to yield the appropiate cipher value. + * URI to yield the appropriate cipher value. * * @param transforms the set of Transforms that specifies how * to transform the reference to yield the intended cipher value. */ void setTransforms(Transforms transforms); } + diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java index 28486365d72..193aef8a908 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java @@ -2,25 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.encryption; - /** * CipherValue is the wrapper for cipher text. * @@ -28,20 +29,18 @@ package com.sun.org.apache.xml.internal.security.encryption; */ public interface CipherValue { /** - * Resturns the Base 64 encoded, encrypted octets that is the - * CihperValue. + * Returns the Base 64 encoded, encrypted octets that is the + * CipherValue. * * @return cipher value. */ - String getValue(); - // byte[] getValue(); + String getValue(); /** * Sets the Base 64 encoded, encrypted octets that is the - * CihperValue. + * CipherValue. * * @param value the cipher value. */ - void setValue(String value); - // void setValue(byte[] value); + void setValue(String value); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/DocumentSerializer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/DocumentSerializer.java new file mode 100644 index 00000000000..f0ffb91f1c2 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/DocumentSerializer.java @@ -0,0 +1,114 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 com.sun.org.apache.xml.internal.security.encryption; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.StringReader; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.Document; +import org.w3c.dom.DocumentFragment; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +/** + * Converts Strings into Nodes and visa versa. + */ +public class DocumentSerializer extends AbstractSerializer { + + protected DocumentBuilderFactory dbf; + + /** + * @param source + * @param ctx + * @return the Node resulting from the parse of the source + * @throws XMLEncryptionException + */ + public Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException { + byte[] fragment = createContext(source, ctx); + return deserialize(ctx, new InputSource(new ByteArrayInputStream(fragment))); + } + + /** + * @param source + * @param ctx + * @return the Node resulting from the parse of the source + * @throws XMLEncryptionException + */ + public Node deserialize(String source, Node ctx) throws XMLEncryptionException { + String fragment = createContext(source, ctx); + return deserialize(ctx, new InputSource(new StringReader(fragment))); + } + + /** + * @param ctx + * @param inputSource + * @return the Node resulting from the parse of the source + * @throws XMLEncryptionException + */ + private Node deserialize(Node ctx, InputSource inputSource) throws XMLEncryptionException { + try { + if (dbf == null) { + dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE); + dbf.setValidating(false); + } + DocumentBuilder db = dbf.newDocumentBuilder(); + Document d = db.parse(inputSource); + + Document contextDocument = null; + if (Node.DOCUMENT_NODE == ctx.getNodeType()) { + contextDocument = (Document)ctx; + } else { + contextDocument = ctx.getOwnerDocument(); + } + + Element fragElt = + (Element) contextDocument.importNode(d.getDocumentElement(), true); + DocumentFragment result = contextDocument.createDocumentFragment(); + Node child = fragElt.getFirstChild(); + while (child != null) { + fragElt.removeChild(child); + result.appendChild(child); + child = fragElt.getFirstChild(); + } + return result; + } catch (SAXException se) { + throw new XMLEncryptionException("empty", se); + } catch (ParserConfigurationException pce) { + throw new XMLEncryptionException("empty", pce); + } catch (IOException ioe) { + throw new XMLEncryptionException("empty", ioe); + } + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java index 79038a67cb5..c09eeceaa59 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java @@ -2,25 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.encryption; - /** * The EncryptedData element is the core element in the syntax. Not * only does its CipherData child contain the encrypted data, but @@ -42,3 +43,4 @@ package com.sun.org.apache.xml.internal.security.encryption; */ public interface EncryptedData extends EncryptedType { } + diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java index 9607917108b..05fafaf873b 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.encryption; - - /** * The EncryptedKey element is used to transport encryption keys * from the originator to a known recipient(s). It may be used as a stand-alone @@ -51,9 +51,9 @@ package com.sun.org.apache.xml.internal.security.encryption; * @author Axl Mattheus */ public interface EncryptedKey extends EncryptedType { + /** - * Returns a hint as to which recipient this encrypted key value is intended - * for. + * Returns a hint as to which recipient this encrypted key value is intended for. * * @return the recipient of the EncryptedKey. */ @@ -110,3 +110,4 @@ public interface EncryptedKey extends EncryptedType { */ void setCarriedName(String name); } + diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java index 17ffded82a5..61e7e51df9d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java @@ -2,28 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.encryption; - import com.sun.org.apache.xml.internal.security.keys.KeyInfo; - /** * EncryptedType is the abstract type from which EncryptedData and * EncryptedKey are derived. While these two latter element types @@ -50,6 +50,7 @@ import com.sun.org.apache.xml.internal.security.keys.KeyInfo; * @author Axl Mattheus */ public interface EncryptedType { + /** * Returns a String providing for the standard method of * assigning an id to the element within the document context. @@ -61,7 +62,7 @@ public interface EncryptedType { /** * Sets the id. * - * @param id. + * @param id */ void setId(String id); @@ -117,7 +118,7 @@ public interface EncryptedType { void setMimeType(String type); /** - * Retusn an URI representing the encoding of the + * Return an URI representing the encoding of the * EncryptedType. * * @return the encoding of this EncryptedType. @@ -128,7 +129,7 @@ public interface EncryptedType { * Sets the URI representing the encoding of the * EncryptedType. * - * @param encoding. + * @param encoding */ void setEncoding(String encoding); @@ -189,7 +190,8 @@ public interface EncryptedType { * Sets the EncryptionProperties that supplies additional * information about the generation of the EncryptedType. * - * @param properties. + * @param properties */ void setEncryptionProperties(EncryptionProperties properties); } + diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java index 2664db9ae94..05c3cdc76cd 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java @@ -2,29 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.encryption; - import java.util.Iterator; import org.w3c.dom.Element; - /** * EncryptionMethod describes the encryption algorithm applied to * the cipher data. If the element is absent, the encryption algorithm must be @@ -82,6 +82,30 @@ public interface EncryptionMethod { */ void setOAEPparams(byte[] parameters); + /** + * Set the Digest Algorithm to use + * @param digestAlgorithm the Digest Algorithm to use + */ + void setDigestAlgorithm(String digestAlgorithm); + + /** + * Get the Digest Algorithm to use + * @return the Digest Algorithm to use + */ + String getDigestAlgorithm(); + + /** + * Set the MGF Algorithm to use + * @param mgfAlgorithm the MGF Algorithm to use + */ + void setMGFAlgorithm(String mgfAlgorithm); + + /** + * Get the MGF Algorithm to use + * @return the MGF Algorithm to use + */ + String getMGFAlgorithm(); + /** * Returns an iterator over all the additional elements contained in the * EncryptionMethod. @@ -106,3 +130,4 @@ public interface EncryptionMethod { */ void removeEncryptionMethodInformation(Element information); } + diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java index da1eb65d255..736d63f151a 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java @@ -2,28 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.encryption; - import java.util.Iterator; - /** * EncryptionProperties can hold additional information concerning * the generation of the EncryptedData or @@ -46,6 +46,7 @@ import java.util.Iterator; * @author Axl Mattheus */ public interface EncryptionProperties { + /** * Returns the EncryptionProperties' id. * @@ -72,14 +73,15 @@ public interface EncryptionProperties { /** * Adds an EncryptionProperty. * - * @param property. + * @param property */ void addEncryptionProperty(EncryptionProperty property); /** * Removes the specified EncryptionProperty. * - * @param property. + * @param property */ void removeEncryptionProperty(EncryptionProperty property); } + diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java index 4cd6c4696cd..fc969018033 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java @@ -2,25 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.encryption; - import java.util.Iterator; import org.w3c.dom.Element; @@ -50,6 +51,7 @@ import org.w3c.dom.Element; * @author Axl Mattheus */ public interface EncryptionProperty { + /** * Returns the EncryptedType being described. * @@ -61,7 +63,7 @@ public interface EncryptionProperty { /** * Sets the target. * - * @param target. + * @param target */ void setTarget(String target); @@ -75,7 +77,7 @@ public interface EncryptionProperty { /** * Sets the id. * - * @param id. + * @param id */ void setId(String id); @@ -98,7 +100,7 @@ public interface EncryptionProperty { /** * Returns the properties of the EncryptionProperty. * - * @return an Iterator over all the addiitonal encryption + * @return an Iterator over all the additional encryption * information contained in this class. */ Iterator getEncryptionInformation(); diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java index 4523a895aaf..dc528ce1a06 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java @@ -2,29 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.encryption; - import java.util.Iterator; import org.w3c.dom.Element; - /** * A wrapper for a pointer from a key value of an EncryptedKey to * items encrypted by that key value (EncryptedData or @@ -44,6 +44,13 @@ import org.w3c.dom.Element; * @see ReferenceList */ public interface Reference { + /** + * Returns the Element tag name for this Reference. + * + * @return the tag name of this Reference. + */ + String getType(); + /** * Returns a URI that points to an Element that * were encrypted using the key defined in the enclosing @@ -79,14 +86,14 @@ public interface Reference { /** * Adds retrieval information. * - * @param info. + * @param info */ void addElementRetrievalInformation(Element info); /** * Removes the specified retrieval information. * - * @param info. + * @param info */ void removeElementRetrievalInformation(Element info); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java index 2cf0ec5ed44..73d46a2f0b9 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java @@ -2,28 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.encryption; - import java.util.Iterator; - /** * ReferenceList is an element that contains pointers from a key * value of an EncryptedKey to items encrypted by that key value @@ -45,10 +45,12 @@ import java.util.Iterator; * @see Reference */ public interface ReferenceList { - /** DATA TAG */ - public static final int DATA_REFERENCE = 0x00000001; + + /** DATA TAG */ + int DATA_REFERENCE = 0x00000001; + /** KEY TAG */ - public static final int KEY_REFERENCE = 0x00000002; + int KEY_REFERENCE = 0x00000002; /** * Adds a reference to this reference list. @@ -57,21 +59,21 @@ public interface ReferenceList { * @throws IllegalAccessException if the Reference is not an * instance of DataReference or KeyReference. */ - public void add(Reference reference); + void add(Reference reference); /** * Removes a reference from the ReferenceList. * * @param reference the reference to remove. */ - public void remove(Reference reference); + void remove(Reference reference); /** * Returns the size of the ReferenceList. * * @return the size of the ReferenceList. */ - public int size(); + int size(); /** * Indicates if the ReferenceList is empty. @@ -79,29 +81,29 @@ public interface ReferenceList { * @return true if the ReferenceList is * empty, else false. */ - public boolean isEmpty(); + boolean isEmpty(); /** * Returns an Iterator over all the References - * contatined in this ReferenceList. + * contained in this ReferenceList. * * @return Iterator. */ - public Iterator getReferences(); + Iterator getReferences(); /** * DataReference factory method. Returns a * DataReference. * @param uri - * @return + * @return a DataReference. */ - public Reference newDataReference(String uri); + Reference newDataReference(String uri); /** * KeyReference factory method. Returns a * KeyReference. * @param uri - * @return + * @return a KeyReference. */ - public Reference newKeyReference(String uri); + Reference newKeyReference(String uri); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Serializer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Serializer.java new file mode 100644 index 00000000000..8f3cd8fac9a --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Serializer.java @@ -0,0 +1,77 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 com.sun.org.apache.xml.internal.security.encryption; + +import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * Converts Strings into Nodes and visa versa. + */ +public interface Serializer { + + /** + * Set the Canonicalizer object to use. + */ + void setCanonicalizer(Canonicalizer canon); + + /** + * Returns a byte[] representation of the specified + * Element. + * + * @param element the Element to serialize. + * @return the byte[] representation of the serilaized + * Element. + * @throws Exception + */ + byte[] serializeToByteArray(Element element) throws Exception; + + /** + * Returns a byte[] representation of the specified + * NodeList. + * + * @param content the NodeList to serialize. + * @return the byte[] representation of the serialized + * NodeList. + * @throws Exception + */ + byte[] serializeToByteArray(NodeList content) throws Exception; + + /** + * Use the Canonicalizer to serialize the node + * @param node + * @return the (byte[]) canonicalization of the node + * @throws Exception + */ + byte[] canonSerializeToByteArray(Node node) throws Exception; + + /** + * @param source + * @param ctx + * @return the Node resulting from the parse of the source + * @throws XMLEncryptionException + */ + Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException; +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java index b2434c025a5..02d083b65ee 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java @@ -2,27 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.encryption; - - - /** * A container for ds:Transforms. *

@@ -40,36 +39,12 @@ package com.sun.org.apache.xml.internal.security.encryption; */ public interface Transforms { /** - * Returns an Iterator over all the transforms contained in - * this transform list. - * - * @return all transforms. + * Temporary method to turn the XMLEncryption Transforms class + * into a DS class. The main logic is currently implemented in the + * DS class, so we need to get to get the base class. + *

+ * Note This will be removed in future versions */ - /* Iterator getTransforms(); */ - - /** - * Adds a ds:Transform to the list of transforms. - * - * @param transform. - */ - /* void addTransform(Transform transform); */ - - /** - * Removes the specified transform. - * - * @param transform. - */ - /* void removeTransform(Transform transform); */ - - /** - * Temporary method to turn the XMLEncryption Transforms class - * into a DS class. The main logic is currently implemented in the - * DS class, so we need to get to get the base class. - *

- * Note This will be removed in future versions - * @return - */ - - com.sun.org.apache.xml.internal.security.transforms.Transforms getDSTransforms(); + com.sun.org.apache.xml.internal.security.transforms.Transforms getDSTransforms(); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java index 8177cf34546..81d79b040cf 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java @@ -2,57 +2,62 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.encryption; - import java.io.ByteArrayOutputStream; import java.io.InputStream; -import java.io.IOException; -import java.io.StringReader; import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; +import java.security.SecureRandom; +import java.security.spec.MGF1ParameterSpec; +import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; +import java.util.Map; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; +import javax.crypto.spec.OAEPParameterSpec; +import javax.crypto.spec.PSource; import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper; import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm; import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException; +import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.keys.KeyInfo; import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.EncryptedKeyResolver; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import com.sun.org.apache.xml.internal.security.transforms.InvalidTransformException; @@ -62,17 +67,11 @@ import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.ElementProxy; import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; -import com.sun.org.apache.xml.internal.utils.URI; import org.w3c.dom.Attr; import org.w3c.dom.Document; -import org.w3c.dom.DocumentFragment; import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - /** * XMLCipher encrypts and decrypts the contents of @@ -85,133 +84,245 @@ import org.xml.sax.SAXException; */ public class XMLCipher { - private static java.util.logging.Logger logger = + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(XMLCipher.class.getName()); - //J- - /** Triple DES EDE (192 bit key) in CBC mode */ + /** Triple DES EDE (192 bit key) in CBC mode */ public static final String TRIPLEDES = EncryptionConstants.ALGO_ID_BLOCKCIPHER_TRIPLEDES; + /** AES 128 Cipher */ public static final String AES_128 = EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128; + /** AES 256 Cipher */ public static final String AES_256 = EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256; + /** AES 192 Cipher */ public static final String AES_192 = EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES192; + + /** AES 128 GCM Cipher */ + public static final String AES_128_GCM = + EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128_GCM; + + /** AES 192 GCM Cipher */ + public static final String AES_192_GCM = + EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES192_GCM; + + /** AES 256 GCM Cipher */ + public static final String AES_256_GCM = + EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256_GCM; + /** RSA 1.5 Cipher */ public static final String RSA_v1dot5 = EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15; + /** RSA OAEP Cipher */ public static final String RSA_OAEP = EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP; + + /** RSA OAEP Cipher */ + public static final String RSA_OAEP_11 = + EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP_11; + /** DIFFIE_HELLMAN Cipher */ public static final String DIFFIE_HELLMAN = EncryptionConstants.ALGO_ID_KEYAGREEMENT_DH; + /** Triple DES EDE (192 bit key) in CBC mode KEYWRAP*/ public static final String TRIPLEDES_KeyWrap = EncryptionConstants.ALGO_ID_KEYWRAP_TRIPLEDES; + /** AES 128 Cipher KeyWrap */ public static final String AES_128_KeyWrap = EncryptionConstants.ALGO_ID_KEYWRAP_AES128; + /** AES 256 Cipher KeyWrap */ public static final String AES_256_KeyWrap = EncryptionConstants.ALGO_ID_KEYWRAP_AES256; + /** AES 192 Cipher KeyWrap */ public static final String AES_192_KeyWrap = EncryptionConstants.ALGO_ID_KEYWRAP_AES192; + /** SHA1 Cipher */ public static final String SHA1 = Constants.ALGO_ID_DIGEST_SHA1; + /** SHA256 Cipher */ public static final String SHA256 = MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256; + /** SHA512 Cipher */ public static final String SHA512 = MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA512; + /** RIPEMD Cipher */ public static final String RIPEMD_160 = MessageDigestAlgorithm.ALGO_ID_DIGEST_RIPEMD160; + /** XML Signature NS */ public static final String XML_DSIG = Constants.SignatureSpecNS; + /** N14C_XML */ public static final String N14C_XML = Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS; + /** N14C_XML with comments*/ public static final String N14C_XML_WITH_COMMENTS = Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS; - /** N14C_XML excluisve */ + + /** N14C_XML exclusive */ public static final String EXCL_XML_N14C = Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; - /** N14C_XML exclusive with commetns*/ + + /** N14C_XML exclusive with comments*/ public static final String EXCL_XML_N14C_WITH_COMMENTS = Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS; + + /** N14C_PHYSICAL preserve the physical representation*/ + public static final String PHYSICAL_XML_N14C = + Canonicalizer.ALGO_ID_C14N_PHYSICAL; + /** Base64 encoding */ public static final String BASE64_ENCODING = com.sun.org.apache.xml.internal.security.transforms.Transforms.TRANSFORM_BASE64_DECODE; - //J+ /** ENCRYPT Mode */ public static final int ENCRYPT_MODE = Cipher.ENCRYPT_MODE; + /** DECRYPT Mode */ public static final int DECRYPT_MODE = Cipher.DECRYPT_MODE; + /** UNWRAP Mode */ public static final int UNWRAP_MODE = Cipher.UNWRAP_MODE; + /** WRAP Mode */ public static final int WRAP_MODE = Cipher.WRAP_MODE; private static final String ENC_ALGORITHMS = TRIPLEDES + "\n" + - AES_128 + "\n" + AES_256 + "\n" + AES_192 + "\n" + RSA_v1dot5 + "\n" + - RSA_OAEP + "\n" + TRIPLEDES_KeyWrap + "\n" + AES_128_KeyWrap + "\n" + - AES_256_KeyWrap + "\n" + AES_192_KeyWrap+ "\n"; + AES_128 + "\n" + AES_256 + "\n" + AES_192 + "\n" + RSA_v1dot5 + "\n" + + RSA_OAEP + "\n" + RSA_OAEP_11 + "\n" + TRIPLEDES_KeyWrap + "\n" + + AES_128_KeyWrap + "\n" + AES_256_KeyWrap + "\n" + AES_192_KeyWrap + "\n" + + AES_128_GCM + "\n" + AES_192_GCM + "\n" + AES_256_GCM + "\n"; - /** Cipher created during initialisation that is used for encryption */ - private Cipher _contextCipher; - /** Mode that the XMLCipher object is operating in */ - private int _cipherMode = Integer.MIN_VALUE; - /** URI of algorithm that is being used for cryptographic operation */ - private String _algorithm = null; - /** Cryptographic provider requested by caller */ - private String _requestedJCEProvider = null; - /** Holds c14n to serialize, if initialized then _always_ use this c14n to serialize */ - private Canonicalizer _canon; - /** Used for creation of DOM nodes in WRAP and ENCRYPT modes */ - private Document _contextDocument; - /** Instance of factory used to create XML Encryption objects */ - private Factory _factory; - /** Internal serializer class for going to/from UTF-8 */ - private Serializer _serializer; + /** Cipher created during initialisation that is used for encryption */ + private Cipher contextCipher; - /** Local copy of user's key */ - private Key _key; - /** Local copy of the kek (used to decrypt EncryptedKeys during a + /** Mode that the XMLCipher object is operating in */ + private int cipherMode = Integer.MIN_VALUE; + + /** URI of algorithm that is being used for cryptographic operation */ + private String algorithm = null; + + /** Cryptographic provider requested by caller */ + private String requestedJCEProvider = null; + + /** Holds c14n to serialize, if initialized then _always_ use this c14n to serialize */ + private Canonicalizer canon; + + /** Used for creation of DOM nodes in WRAP and ENCRYPT modes */ + private Document contextDocument; + + /** Instance of factory used to create XML Encryption objects */ + private Factory factory; + + /** Serializer class for going to/from UTF-8 */ + private Serializer serializer; + + /** Local copy of user's key */ + private Key key; + + /** Local copy of the kek (used to decrypt EncryptedKeys during a * DECRYPT_MODE operation */ - private Key _kek; + private Key kek; - // The EncryptedKey being built (part of a WRAP operation) or read - // (part of an UNWRAP operation) + // The EncryptedKey being built (part of a WRAP operation) or read + // (part of an UNWRAP operation) + private EncryptedKey ek; - private EncryptedKey _ek; + // The EncryptedData being built (part of a WRAP operation) or read + // (part of an UNWRAP operation) + private EncryptedData ed; - // The EncryptedData being built (part of a WRAP operation) or read - // (part of an UNWRAP operation) + private SecureRandom random; - private EncryptedData _ed; + private boolean secureValidation; + + private String digestAlg; + + /** List of internal KeyResolvers for DECRYPT and UNWRAP modes. */ + private List internalKeyResolvers; + + /** + * Set the Serializer algorithm to use + */ + public void setSerializer(Serializer serializer) { + this.serializer = serializer; + serializer.setCanonicalizer(this.canon); + } + + /** + * Get the Serializer algorithm to use + */ + public Serializer getSerializer() { + return serializer; + } /** * Creates a new XMLCipher. * - * @since 1.0. + * @param transformation the name of the transformation, e.g., + * XMLCipher.TRIPLEDES. If null the XMLCipher can only + * be used for decrypt or unwrap operations where the encryption method + * is defined in the EncryptionMethod element. + * @param provider the JCE provider that supplies the transformation, + * if null use the default provider. + * @param canon the name of the c14n algorithm, if + * null use standard serializer + * @param digestMethod An optional digestMethod to use. */ - private XMLCipher() { - logger.log(java.util.logging.Level.FINE, "Constructing XMLCipher..."); + private XMLCipher( + String transformation, + String provider, + String canonAlg, + String digestMethod + ) throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Constructing XMLCipher..."); + } - _factory = new Factory(); - _serializer = new Serializer(); + factory = new Factory(); + algorithm = transformation; + requestedJCEProvider = provider; + digestAlg = digestMethod; + + // Create a canonicalizer - used when serializing DOM to octets + // prior to encryption (and for the reverse) + + try { + if (canonAlg == null) { + // The default is to preserve the physical representation. + this.canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_PHYSICAL); + } else { + this.canon = Canonicalizer.getInstance(canonAlg); + } + } catch (InvalidCanonicalizerException ice) { + throw new XMLEncryptionException("empty", ice); + } + + if (serializer == null) { + serializer = new DocumentSerializer(); + } + serializer.setCanonicalizer(this.canon); + + if (transformation != null) { + contextCipher = constructCipher(transformation, digestMethod); + } } /** @@ -222,20 +333,38 @@ public class XMLCipher { * @since 1.0. */ private static boolean isValidEncryptionAlgorithm(String algorithm) { - boolean result = ( + return ( algorithm.equals(TRIPLEDES) || algorithm.equals(AES_128) || algorithm.equals(AES_256) || algorithm.equals(AES_192) || + algorithm.equals(AES_128_GCM) || + algorithm.equals(AES_192_GCM) || + algorithm.equals(AES_256_GCM) || algorithm.equals(RSA_v1dot5) || algorithm.equals(RSA_OAEP) || + algorithm.equals(RSA_OAEP_11) || algorithm.equals(TRIPLEDES_KeyWrap) || algorithm.equals(AES_128_KeyWrap) || algorithm.equals(AES_256_KeyWrap) || algorithm.equals(AES_192_KeyWrap) ); + } - return (result); + /** + * Validate the transformation argument of getInstance or getProviderInstance + * + * @param transformation the name of the transformation, e.g., + * XMLCipher.TRIPLEDES which is shorthand for + * "http://www.w3.org/2001/04/xmlenc#tripledes-cbc" + */ + private static void validateTransformation(String transformation) { + if (null == transformation) { + throw new NullPointerException("Transformation unexpectedly null..."); + } + if (!isValidEncryptionAlgorithm(transformation)) { + log.log(java.util.logging.Level.WARNING, "Algorithm non-standard, expected one of " + ENC_ALGORITHMS); + } } /** @@ -248,7 +377,7 @@ public class XMLCipher { * the default provider package, other provider packages are searched. *

* NOTE1: The transformation name does not follow the same - * pattern as that oulined in the Java Cryptography Extension Reference + * pattern as that outlined in the Java Cryptography Extension Reference * Guide but rather that specified by the XML Encryption Syntax and * Processing document. The rational behind this is to make it easier for a * novice at writing Java Encryption software to use the library. @@ -257,7 +386,7 @@ public class XMLCipher { * same pattern regarding exceptional conditions as that used in * javax.crypto.Cipher. Instead, it only throws an * XMLEncryptionException which wraps an underlying exception. - * The stack trace from the exception should be self explanitory. + * The stack trace from the exception should be self explanatory. * * @param transformation the name of the transformation, e.g., * XMLCipher.TRIPLEDES which is shorthand for @@ -266,293 +395,169 @@ public class XMLCipher { * @return the XMLCipher * @see javax.crypto.Cipher#getInstance(java.lang.String) */ - public static XMLCipher getInstance(String transformation) throws - XMLEncryptionException { - // sanity checks - logger.log(java.util.logging.Level.FINE, "Getting XMLCipher..."); - if (null == transformation) - logger.log(java.util.logging.Level.SEVERE, "Transformation unexpectedly null..."); - if(!isValidEncryptionAlgorithm(transformation)) - logger.log(java.util.logging.Level.WARNING, "Algorithm non-standard, expected one of " + ENC_ALGORITHMS); - - XMLCipher instance = new XMLCipher(); - - instance._algorithm = transformation; - instance._key = null; - instance._kek = null; - - - /* Create a canonicaliser - used when serialising DOM to octets - * prior to encryption (and for the reverse) */ - - try { - instance._canon = Canonicalizer.getInstance - (Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS); - - } catch (InvalidCanonicalizerException ice) { - throw new XMLEncryptionException("empty", ice); - } - - String jceAlgorithm = JCEMapper.translateURItoJCEID(transformation); - - try { - instance._contextCipher = Cipher.getInstance(jceAlgorithm); - logger.log(java.util.logging.Level.FINE, "cihper.algoritm = " + - instance._contextCipher.getAlgorithm()); - } catch (NoSuchAlgorithmException nsae) { - throw new XMLEncryptionException("empty", nsae); - } catch (NoSuchPaddingException nspe) { - throw new XMLEncryptionException("empty", nspe); + public static XMLCipher getInstance(String transformation) throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation"); } - - return (instance); + validateTransformation(transformation); + return new XMLCipher(transformation, null, null, null); } - /** - * Returns an XMLCipher that implements the specified - * transformation, operates on the specified context document and serializes - * the document with the specified canonicalization algorithm before it - * encrypts the document. - *

- * - * @param transformation the name of the transformation, e.g., - * XMLCipher.TRIPLEDES which is - * shorthand for - * "http://www.w3.org/2001/04/xmlenc#tripledes-cbc" - * @param canon the name of the c14n algorithm, if - * null use standard serializer - * @return - * @throws XMLEncryptionException - */ - - public static XMLCipher getInstance(String transformation, String canon) - throws XMLEncryptionException { - XMLCipher instance = XMLCipher.getInstance(transformation); - - if (canon != null) { - try { - instance._canon = Canonicalizer.getInstance(canon); - } catch (InvalidCanonicalizerException ice) { - throw new XMLEncryptionException("empty", ice); - } - } - - return instance; + /** + * Returns an XMLCipher that implements the specified + * transformation, operates on the specified context document and serializes + * the document with the specified canonicalization algorithm before it + * encrypts the document. + *

+ * + * @param transformation the name of the transformation + * @param canon the name of the c14n algorithm, if null use + * standard serializer + * @return the XMLCipher + * @throws XMLEncryptionException + */ + public static XMLCipher getInstance(String transformation, String canon) + throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation and c14n algorithm"); } + validateTransformation(transformation); + return new XMLCipher(transformation, null, canon, null); + } - public static XMLCipher getInstance(String transformation,Cipher cipher) throws XMLEncryptionException { - // sanity checks - logger.log(java.util.logging.Level.FINE, "Getting XMLCipher..."); - if (null == transformation) - logger.log(java.util.logging.Level.SEVERE, "Transformation unexpectedly null..."); - if(!isValidEncryptionAlgorithm(transformation)) - logger.log(java.util.logging.Level.WARNING, "Algorithm non-standard, expected one of " + ENC_ALGORITHMS); - - XMLCipher instance = new XMLCipher(); - - instance._algorithm = transformation; - instance._key = null; - instance._kek = null; - - - /* Create a canonicaliser - used when serialising DOM to octets - * prior to encryption (and for the reverse) */ - - try { - instance._canon = Canonicalizer.getInstance - (Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS); - - } catch (InvalidCanonicalizerException ice) { - throw new XMLEncryptionException("empty", ice); + /** + * Returns an XMLCipher that implements the specified + * transformation, operates on the specified context document and serializes + * the document with the specified canonicalization algorithm before it + * encrypts the document. + *

+ * + * @param transformation the name of the transformation + * @param canon the name of the c14n algorithm, if null use + * standard serializer + * @param digestMethod An optional digestMethod to use + * @return the XMLCipher + * @throws XMLEncryptionException + */ + public static XMLCipher getInstance(String transformation, String canon, String digestMethod) + throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation and c14n algorithm"); } - - String jceAlgorithm = JCEMapper.translateURItoJCEID(transformation); - - try { - instance._contextCipher = cipher; - //Cipher.getInstance(jceAlgorithm); - logger.log(java.util.logging.Level.FINE, "cihper.algoritm = " + - instance._contextCipher.getAlgorithm()); - }catch(Exception ex) { - throw new XMLEncryptionException("empty", ex); - } - - return (instance); + validateTransformation(transformation); + return new XMLCipher(transformation, null, canon, digestMethod); } /** * Returns an XMLCipher that implements the specified * transformation and operates on the specified context document. * - * @param transformation the name of the transformation, e.g., - * XMLCipher.TRIPLEDES which is shorthand for - * "http://www.w3.org/2001/04/xmlenc#tripledes-cbc" - * @param provider the JCE provider that supplies the transformation + * @param transformation the name of the transformation + * @param provider the JCE provider that supplies the transformation * @return the XMLCipher * @throws XMLEncryptionException */ - public static XMLCipher getProviderInstance(String transformation, String provider) - throws XMLEncryptionException { - // sanity checks - logger.log(java.util.logging.Level.FINE, "Getting XMLCipher..."); - if (null == transformation) - logger.log(java.util.logging.Level.SEVERE, "Transformation unexpectedly null..."); - if(null == provider) - logger.log(java.util.logging.Level.SEVERE, "Provider unexpectedly null.."); - if("" == provider) - logger.log(java.util.logging.Level.SEVERE, "Provider's value unexpectedly not specified..."); - if(!isValidEncryptionAlgorithm(transformation)) - logger.log(java.util.logging.Level.WARNING, "Algorithm non-standard, expected one of " + ENC_ALGORITHMS); - - XMLCipher instance = new XMLCipher(); - - instance._algorithm = transformation; - instance._requestedJCEProvider = provider; - instance._key = null; - instance._kek = null; - - /* Create a canonicaliser - used when serialising DOM to octets - * prior to encryption (and for the reverse) */ - - try { - instance._canon = Canonicalizer.getInstance - (Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS); - } catch (InvalidCanonicalizerException ice) { - throw new XMLEncryptionException("empty", ice); - } - - try { - String jceAlgorithm = - JCEMapper.translateURItoJCEID(transformation); - - instance._contextCipher = Cipher.getInstance(jceAlgorithm, provider); - - logger.log(java.util.logging.Level.FINE, "cipher._algorithm = " + - instance._contextCipher.getAlgorithm()); - logger.log(java.util.logging.Level.FINE, "provider.name = " + provider); - } catch (NoSuchAlgorithmException nsae) { - throw new XMLEncryptionException("empty", nsae); - } catch (NoSuchProviderException nspre) { - throw new XMLEncryptionException("empty", nspre); - } catch (NoSuchPaddingException nspe) { - throw new XMLEncryptionException("empty", nspe); + throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation and provider"); } - - return (instance); + if (null == provider) { + throw new NullPointerException("Provider unexpectedly null.."); + } + validateTransformation(transformation); + return new XMLCipher(transformation, provider, null, null); } - /** - * Returns an XMLCipher that implements the specified + /** + * Returns an XMLCipher that implements the specified * transformation, operates on the specified context document and serializes * the document with the specified canonicalization algorithm before it * encrypts the document. *

- * - * @param transformation the name of the transformation, e.g., - * XMLCipher.TRIPLEDES which is - * shorthand for - * "http://www.w3.org/2001/04/xmlenc#tripledes-cbc" - * @param provider the JCE provider that supplies the transformation - * @param canon the name of the c14n algorithm, if - * null use standard serializer - * @return - * @throws XMLEncryptionException - */ - public static XMLCipher getProviderInstance( - String transformation, - String provider, - String canon) - throws XMLEncryptionException { - - XMLCipher instance = XMLCipher.getProviderInstance(transformation, provider); - if (canon != null) { - try { - instance._canon = Canonicalizer.getInstance(canon); - } catch (InvalidCanonicalizerException ice) { - throw new XMLEncryptionException("empty", ice); - } - } - return instance; - } - - /** - * Returns an XMLCipher that implements no specific - * transformation, and can therefore only be used for decrypt or - * unwrap operations where the encryption method is defined in the - * EncryptionMethod element. - * - * @return The XMLCipher + * + * @param transformation the name of the transformation + * @param provider the JCE provider that supplies the transformation + * @param canon the name of the c14n algorithm, if null use standard + * serializer + * @return the XMLCipher * @throws XMLEncryptionException */ + public static XMLCipher getProviderInstance( + String transformation, String provider, String canon + ) throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation, provider and c14n algorithm"); + } + if (null == provider) { + throw new NullPointerException("Provider unexpectedly null.."); + } + validateTransformation(transformation); + return new XMLCipher(transformation, provider, canon, null); + } - public static XMLCipher getInstance() - throws XMLEncryptionException { - // sanity checks - logger.log(java.util.logging.Level.FINE, "Getting XMLCipher for no transformation..."); - - XMLCipher instance = new XMLCipher(); - - instance._algorithm = null; - instance._requestedJCEProvider = null; - instance._key = null; - instance._kek = null; - instance._contextCipher = null; - - /* Create a canonicaliser - used when serialising DOM to octets - * prior to encryption (and for the reverse) */ - - try { - instance._canon = Canonicalizer.getInstance - (Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS); - } catch (InvalidCanonicalizerException ice) { - throw new XMLEncryptionException("empty", ice); - } - - return (instance); + /** + * Returns an XMLCipher that implements the specified + * transformation, operates on the specified context document and serializes + * the document with the specified canonicalization algorithm before it + * encrypts the document. + *

+ * + * @param transformation the name of the transformation + * @param provider the JCE provider that supplies the transformation + * @param canon the name of the c14n algorithm, if null use standard + * serializer + * @param digestMethod An optional digestMethod to use + * @return the XMLCipher + * @throws XMLEncryptionException + */ + public static XMLCipher getProviderInstance( + String transformation, String provider, String canon, String digestMethod + ) throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation, provider and c14n algorithm"); + } + if (null == provider) { + throw new NullPointerException("Provider unexpectedly null.."); + } + validateTransformation(transformation); + return new XMLCipher(transformation, provider, canon, digestMethod); } /** * Returns an XMLCipher that implements no specific - * transformation, and can therefore only be used for decrypt or - * unwrap operations where the encryption method is defined in the - * EncryptionMethod element. - * - * Allows the caller to specify a provider that will be used for - * cryptographic operations. + * transformation, and can therefore only be used for decrypt or + * unwrap operations where the encryption method is defined in the + * EncryptionMethod element. * - * @param provider the JCE provider that supplies the cryptographic - * needs. + * @return The XMLCipher + * @throws XMLEncryptionException + */ + public static XMLCipher getInstance() throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Getting XMLCipher with no arguments"); + } + return new XMLCipher(null, null, null, null); + } + + /** + * Returns an XMLCipher that implements no specific + * transformation, and can therefore only be used for decrypt or + * unwrap operations where the encryption method is defined in the + * EncryptionMethod element. + * + * Allows the caller to specify a provider that will be used for + * cryptographic operations. + * + * @param provider the JCE provider that supplies the transformation * @return the XMLCipher * @throws XMLEncryptionException */ - - public static XMLCipher getProviderInstance(String provider) - throws XMLEncryptionException { - // sanity checks - - logger.log(java.util.logging.Level.FINE, "Getting XMLCipher, provider but no transformation"); - if(null == provider) - logger.log(java.util.logging.Level.SEVERE, "Provider unexpectedly null.."); - if("" == provider) - logger.log(java.util.logging.Level.SEVERE, "Provider's value unexpectedly not specified..."); - - XMLCipher instance = new XMLCipher(); - - instance._algorithm = null; - instance._requestedJCEProvider = provider; - instance._key = null; - instance._kek = null; - instance._contextCipher = null; - - try { - instance._canon = Canonicalizer.getInstance - (Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS); - } catch (InvalidCanonicalizerException ice) { - throw new XMLEncryptionException("empty", ice); - } - - return (instance); + public static XMLCipher getProviderInstance(String provider) throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Getting XMLCipher with provider"); + } + return new XMLCipher(null, provider, null, null); } /** @@ -561,13 +566,13 @@ public class XMLCipher { * The cipher is initialized for one of the following four operations: * encryption, decryption, key wrapping or key unwrapping, depending on the * value of opmode. - * - * For WRAP and ENCRYPT modes, this also initialises the internal - * EncryptedKey or EncryptedData (with a CipherValue) - * structure that will be used during the ensuing operations. This - * can be obtained (in order to modify KeyInfo elements etc. prior to - * finalising the encryption) by calling - * {@link #getEncryptedData} or {@link #getEncryptedKey}. + * + * For WRAP and ENCRYPT modes, this also initialises the internal + * EncryptedKey or EncryptedData (with a CipherValue) + * structure that will be used during the ensuing operations. This + * can be obtained (in order to modify KeyInfo elements etc. prior to + * finalising the encryption) by calling + * {@link #getEncryptedData} or {@link #getEncryptedKey}. * * @param opmode the operation mode of this cipher (this is one of the * following: ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE or UNWRAP_MODE) @@ -577,164 +582,216 @@ public class XMLCipher { */ public void init(int opmode, Key key) throws XMLEncryptionException { // sanity checks - logger.log(java.util.logging.Level.FINE, "Initializing XMLCipher..."); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Initializing XMLCipher..."); + } - _ek = null; - _ed = null; + ek = null; + ed = null; - switch (opmode) { + switch (opmode) { - case ENCRYPT_MODE : - logger.log(java.util.logging.Level.FINE, "opmode = ENCRYPT_MODE"); - _ed = createEncryptedData(CipherData.VALUE_TYPE, "NO VALUE YET"); - break; - case DECRYPT_MODE : - logger.log(java.util.logging.Level.FINE, "opmode = DECRYPT_MODE"); - break; - case WRAP_MODE : - logger.log(java.util.logging.Level.FINE, "opmode = WRAP_MODE"); - _ek = createEncryptedKey(CipherData.VALUE_TYPE, "NO VALUE YET"); - break; - case UNWRAP_MODE : - logger.log(java.util.logging.Level.FINE, "opmode = UNWRAP_MODE"); - break; - default : - logger.log(java.util.logging.Level.SEVERE, "Mode unexpectedly invalid"); - throw new XMLEncryptionException("Invalid mode in init"); - } - - _cipherMode = opmode; - _key = key; + case ENCRYPT_MODE : + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "opmode = ENCRYPT_MODE"); + } + ed = createEncryptedData(CipherData.VALUE_TYPE, "NO VALUE YET"); + break; + case DECRYPT_MODE : + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "opmode = DECRYPT_MODE"); + } + break; + case WRAP_MODE : + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "opmode = WRAP_MODE"); + } + ek = createEncryptedKey(CipherData.VALUE_TYPE, "NO VALUE YET"); + break; + case UNWRAP_MODE : + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "opmode = UNWRAP_MODE"); + } + break; + default : + log.log(java.util.logging.Level.SEVERE, "Mode unexpectedly invalid"); + throw new XMLEncryptionException("Invalid mode in init"); + } + cipherMode = opmode; + this.key = key; } - /** - * Get the EncryptedData being build - * - * Returns the EncryptedData being built during an ENCRYPT operation. - * This can then be used by applications to add KeyInfo elements and - * set other parameters. - * - * @return The EncryptedData being built - */ - - public EncryptedData getEncryptedData() { - - // Sanity checks - logger.log(java.util.logging.Level.FINE, "Returning EncryptedData"); - return _ed; + /** + * Set whether secure validation is enabled or not. The default is false. + */ + public void setSecureValidation(boolean secureValidation) { + this.secureValidation = secureValidation; + } + /** + * This method is used to add a custom {@link KeyResolverSpi} to an XMLCipher. + * These KeyResolvers are used in KeyInfo objects in DECRYPT and + * UNWRAP modes. + * + * @param keyResolver + */ + public void registerInternalKeyResolver(KeyResolverSpi keyResolver) { + if (internalKeyResolvers == null) { + internalKeyResolvers = new ArrayList(); } + internalKeyResolvers.add(keyResolver); + } - /** - * Get the EncryptedData being build - * - * Returns the EncryptedData being built during an ENCRYPT operation. - * This can then be used by applications to add KeyInfo elements and - * set other parameters. - * - * @return The EncryptedData being built - */ - - public EncryptedKey getEncryptedKey() { - - // Sanity checks - logger.log(java.util.logging.Level.FINE, "Returning EncryptedKey"); - return _ek; + /** + * Get the EncryptedData being built + *

+ * Returns the EncryptedData being built during an ENCRYPT operation. + * This can then be used by applications to add KeyInfo elements and + * set other parameters. + * + * @return The EncryptedData being built + */ + public EncryptedData getEncryptedData() { + // Sanity checks + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Returning EncryptedData"); } + return ed; + } - /** - * Set a Key Encryption Key. - *

- * The Key Encryption Key (KEK) is used for encrypting/decrypting - * EncryptedKey elements. By setting this separately, the XMLCipher - * class can know whether a key applies to the data part or wrapped key - * part of an encrypted object. - * - * @param kek The key to use for de/encrypting key data - */ - - public void setKEK(Key kek) { - - _kek = kek; - + /** + * Get the EncryptedData being build + * + * Returns the EncryptedData being built during an ENCRYPT operation. + * This can then be used by applications to add KeyInfo elements and + * set other parameters. + * + * @return The EncryptedData being built + */ + public EncryptedKey getEncryptedKey() { + // Sanity checks + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Returning EncryptedKey"); } + return ek; + } - /** - * Martial an EncryptedData - * - * Takes an EncryptedData object and returns a DOM Element that - * represents the appropriate EncryptedData - *

- * Note: This should only be used in cases where the context - * document has been passed in via a call to doFinal. - * - * @param encryptedData EncryptedData object to martial - * @return the DOM Element representing the passed in - * object + /** + * Set a Key Encryption Key. + *

+ * The Key Encryption Key (KEK) is used for encrypting/decrypting + * EncryptedKey elements. By setting this separately, the XMLCipher + * class can know whether a key applies to the data part or wrapped key + * part of an encrypted object. + * + * @param kek The key to use for de/encrypting key data */ - public Element martial(EncryptedData encryptedData) { + public void setKEK(Key kek) { + this.kek = kek; + } - return (_factory.toElement (encryptedData)); + /** + * Martial an EncryptedData + * + * Takes an EncryptedData object and returns a DOM Element that + * represents the appropriate EncryptedData + *

+ * Note: This should only be used in cases where the context + * document has been passed in via a call to doFinal. + * + * @param encryptedData EncryptedData object to martial + * @return the DOM Element representing the passed in + * object + */ + public Element martial(EncryptedData encryptedData) { + return factory.toElement(encryptedData); + } - } + /** + * Martial an EncryptedData + * + * Takes an EncryptedData object and returns a DOM Element that + * represents the appropriate EncryptedData + * + * @param context The document that will own the returned nodes + * @param encryptedData EncryptedData object to martial + * @return the DOM Element representing the passed in + * object + */ + public Element martial(Document context, EncryptedData encryptedData) { + contextDocument = context; + return factory.toElement(encryptedData); + } - /** - * Martial an EncryptedKey - * - * Takes an EncryptedKey object and returns a DOM Element that - * represents the appropriate EncryptedKey - * - *

- * Note: This should only be used in cases where the context - * document has been passed in via a call to doFinal. - * - * @param encryptedKey EncryptedKey object to martial - * @return the DOM Element representing the passed in - * object */ + /** + * Martial an EncryptedKey + * + * Takes an EncryptedKey object and returns a DOM Element that + * represents the appropriate EncryptedKey + * + *

+ * Note: This should only be used in cases where the context + * document has been passed in via a call to doFinal. + * + * @param encryptedKey EncryptedKey object to martial + * @return the DOM Element representing the passed in + * object + */ + public Element martial(EncryptedKey encryptedKey) { + return factory.toElement(encryptedKey); + } - public Element martial(EncryptedKey encryptedKey) { + /** + * Martial an EncryptedKey + * + * Takes an EncryptedKey object and returns a DOM Element that + * represents the appropriate EncryptedKey + * + * @param context The document that will own the created nodes + * @param encryptedKey EncryptedKey object to martial + * @return the DOM Element representing the passed in + * object + */ + public Element martial(Document context, EncryptedKey encryptedKey) { + contextDocument = context; + return factory.toElement(encryptedKey); + } - return (_factory.toElement (encryptedKey)); + /** + * Martial a ReferenceList + * + * Takes a ReferenceList object and returns a DOM Element that + * represents the appropriate ReferenceList + * + *

+ * Note: This should only be used in cases where the context + * document has been passed in via a call to doFinal. + * + * @param referenceList ReferenceList object to martial + * @return the DOM Element representing the passed in + * object + */ + public Element martial(ReferenceList referenceList) { + return factory.toElement(referenceList); + } - } - - /** - * Martial an EncryptedData - * - * Takes an EncryptedData object and returns a DOM Element that - * represents the appropriate EncryptedData - * - * @param context The document that will own the returned nodes - * @param encryptedData EncryptedData object to martial - * @return the DOM Element representing the passed in - * object */ - - public Element martial(Document context, EncryptedData encryptedData) { - - _contextDocument = context; - return (_factory.toElement (encryptedData)); - - } - - /** - * Martial an EncryptedKey - * - * Takes an EncryptedKey object and returns a DOM Element that - * represents the appropriate EncryptedKey - * - * @param context The document that will own the created nodes - * @param encryptedKey EncryptedKey object to martial - * @return the DOM Element representing the passed in - * object */ - - public Element martial(Document context, EncryptedKey encryptedKey) { - - _contextDocument = context; - return (_factory.toElement (encryptedKey)); - - } + /** + * Martial a ReferenceList + * + * Takes a ReferenceList object and returns a DOM Element that + * represents the appropriate ReferenceList + * + * @param context The document that will own the created nodes + * @param referenceList ReferenceList object to martial + * @return the DOM Element representing the passed in + * object + */ + public Element martial(Document context, ReferenceList referenceList) { + contextDocument = context; + return factory.toElement(referenceList); + } /** * Encrypts an Element and replaces it with its encrypted @@ -747,25 +804,28 @@ public class XMLCipher { * Element having replaced the source Element. * @throws Exception */ - private Document encryptElement(Element element) throws Exception{ - logger.log(java.util.logging.Level.FINE, "Encrypting element..."); - if(null == element) - logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); - if(_cipherMode != ENCRYPT_MODE) - logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Encrypting element..."); + } + if (null == element) { + log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); + } + if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); + } - if (_algorithm == null) { - throw new XMLEncryptionException("XMLCipher instance without transformation specified"); - } - encryptData(_contextDocument, element, false); + if (algorithm == null) { + throw new XMLEncryptionException("XMLCipher instance without transformation specified"); + } + encryptData(contextDocument, element, false); - Element encryptedElement = _factory.toElement(_ed); + Element encryptedElement = factory.toElement(ed); Node sourceParent = element.getParentNode(); sourceParent.replaceChild(encryptedElement, element); - return (_contextDocument); + return contextDocument; } /** @@ -782,25 +842,28 @@ public class XMLCipher { * Element. * @throws Exception */ - private Document encryptElementContent(Element element) throws - /* XMLEncryption */Exception { - logger.log(java.util.logging.Level.FINE, "Encrypting element content..."); - if(null == element) - logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); - if(_cipherMode != ENCRYPT_MODE) - logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); + private Document encryptElementContent(Element element) throws /* XMLEncryption */Exception { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Encrypting element content..."); + } + if (null == element) { + log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); + } + if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); + } - if (_algorithm == null) { - throw new XMLEncryptionException("XMLCipher instance without transformation specified"); - } - encryptData(_contextDocument, element, true); + if (algorithm == null) { + throw new XMLEncryptionException("XMLCipher instance without transformation specified"); + } + encryptData(contextDocument, element, true); - Element encryptedElement = _factory.toElement(_ed); + Element encryptedElement = factory.toElement(ed); removeContent(element); element.appendChild(encryptedElement); - return (_contextDocument); + return contextDocument; } /** @@ -812,19 +875,22 @@ public class XMLCipher { * @return the processed Document. * @throws Exception to indicate any exceptional conditions. */ - public Document doFinal(Document context, Document source) throws - /* XMLEncryption */Exception { - logger.log(java.util.logging.Level.FINE, "Processing source document..."); - if(null == context) - logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); - if(null == source) - logger.log(java.util.logging.Level.SEVERE, "Source document unexpectedly null..."); + public Document doFinal(Document context, Document source) throws /* XMLEncryption */Exception { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Processing source document..."); + } + if (null == context) { + log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); + } + if (null == source) { + log.log(java.util.logging.Level.SEVERE, "Source document unexpectedly null..."); + } - _contextDocument = context; + contextDocument = context; Document result = null; - switch (_cipherMode) { + switch (cipherMode) { case DECRYPT_MODE: result = decryptElement(source.getDocumentElement()); break; @@ -832,15 +898,13 @@ public class XMLCipher { result = encryptElement(source.getDocumentElement()); break; case UNWRAP_MODE: - break; case WRAP_MODE: break; default: - throw new XMLEncryptionException( - "empty", new IllegalStateException()); + throw new XMLEncryptionException("empty", new IllegalStateException()); } - return (result); + return result; } /** @@ -852,19 +916,22 @@ public class XMLCipher { * @return the processed Document. * @throws Exception to indicate any exceptional conditions. */ - public Document doFinal(Document context, Element element) throws - /* XMLEncryption */Exception { - logger.log(java.util.logging.Level.FINE, "Processing source element..."); - if(null == context) - logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); - if(null == element) - logger.log(java.util.logging.Level.SEVERE, "Source element unexpectedly null..."); + public Document doFinal(Document context, Element element) throws /* XMLEncryption */Exception { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Processing source element..."); + } + if (null == context) { + log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); + } + if (null == element) { + log.log(java.util.logging.Level.SEVERE, "Source element unexpectedly null..."); + } - _contextDocument = context; + contextDocument = context; Document result = null; - switch (_cipherMode) { + switch (cipherMode) { case DECRYPT_MODE: result = decryptElement(element); break; @@ -872,15 +939,13 @@ public class XMLCipher { result = encryptElement(element); break; case UNWRAP_MODE: - break; case WRAP_MODE: break; default: - throw new XMLEncryptionException( - "empty", new IllegalStateException()); + throw new XMLEncryptionException("empty", new IllegalStateException()); } - return (result); + return result; } /** @@ -896,18 +961,22 @@ public class XMLCipher { * @throws Exception to indicate any exceptional conditions. */ public Document doFinal(Document context, Element element, boolean content) - throws /* XMLEncryption*/ Exception { - logger.log(java.util.logging.Level.FINE, "Processing source element..."); - if(null == context) - logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); - if(null == element) - logger.log(java.util.logging.Level.SEVERE, "Source element unexpectedly null..."); + throws /* XMLEncryption*/ Exception { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Processing source element..."); + } + if (null == context) { + log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); + } + if (null == element) { + log.log(java.util.logging.Level.SEVERE, "Source element unexpectedly null..."); + } - _contextDocument = context; + contextDocument = context; Document result = null; - switch (_cipherMode) { + switch (cipherMode) { case DECRYPT_MODE: if (content) { result = decryptElementContent(element); @@ -923,15 +992,13 @@ public class XMLCipher { } break; case UNWRAP_MODE: - break; case WRAP_MODE: break; default: - throw new XMLEncryptionException( - "empty", new IllegalStateException()); + throw new XMLEncryptionException("empty", new IllegalStateException()); } - return (result); + return result; } /** @@ -939,7 +1006,7 @@ public class XMLCipher { * you want to have full control over the contents of the * EncryptedData structure. * - * this does not change the source document in any way. + * This does not change the source document in any way. * * @param context the context Document. * @param element the Element that will be encrypted. @@ -947,7 +1014,7 @@ public class XMLCipher { * @throws Exception */ public EncryptedData encryptData(Document context, Element element) throws - /* XMLEncryption */Exception { + /* XMLEncryption */Exception { return encryptData(context, element, false); } @@ -965,16 +1032,21 @@ public class XMLCipher { * @return the EncryptedData * @throws Exception */ - public EncryptedData encryptData(Document context, String type, - InputStream serializedData) throws Exception { - - logger.log(java.util.logging.Level.FINE, "Encrypting element..."); - if (null == context) - logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); - if (null == serializedData) - logger.log(java.util.logging.Level.SEVERE, "Serialized data unexpectedly null..."); - if (_cipherMode != ENCRYPT_MODE) - logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); + public EncryptedData encryptData( + Document context, String type, InputStream serializedData + ) throws Exception { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Encrypting element..."); + } + if (null == context) { + log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); + } + if (null == serializedData) { + log.log(java.util.logging.Level.SEVERE, "Serialized data unexpectedly null..."); + } + if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); + } return encryptData(context, null, type, serializedData); } @@ -984,7 +1056,7 @@ public class XMLCipher { * you want to have full control over the contents of the * EncryptedData structure. * - * this does not change the source document in any way. + * This does not change the source document in any way. * * @param context the context Document. * @param element the Element that will be encrypted. @@ -994,84 +1066,84 @@ public class XMLCipher { * @throws Exception */ public EncryptedData encryptData( - Document context, Element element, boolean contentMode) - throws /* XMLEncryption */ Exception { - - logger.log(java.util.logging.Level.FINE, "Encrypting element..."); - if (null == context) - logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); - if (null == element) - logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); - if (_cipherMode != ENCRYPT_MODE) - logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); + Document context, Element element, boolean contentMode + ) throws /* XMLEncryption */ Exception { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Encrypting element..."); + } + if (null == context) { + log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); + } + if (null == element) { + log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); + } + if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); + } if (contentMode) { - return encryptData - (context, element, EncryptionConstants.TYPE_CONTENT, null); + return encryptData(context, element, EncryptionConstants.TYPE_CONTENT, null); } else { - return encryptData - (context, element, EncryptionConstants.TYPE_ELEMENT, null); + return encryptData(context, element, EncryptionConstants.TYPE_ELEMENT, null); } } private EncryptedData encryptData( - Document context, Element element, String type, - InputStream serializedData) throws /* XMLEncryption */ Exception { + Document context, Element element, String type, InputStream serializedData + ) throws /* XMLEncryption */ Exception { + contextDocument = context; - _contextDocument = context; - - if (_algorithm == null) { - throw new XMLEncryptionException - ("XMLCipher instance without transformation specified"); + if (algorithm == null) { + throw new XMLEncryptionException("XMLCipher instance without transformation specified"); } - String serializedOctets = null; + byte[] serializedOctets = null; if (serializedData == null) { - if (type == EncryptionConstants.TYPE_CONTENT) { + if (type.equals(EncryptionConstants.TYPE_CONTENT)) { NodeList children = element.getChildNodes(); if (null != children) { - serializedOctets = _serializer.serialize(children); + serializedOctets = serializer.serializeToByteArray(children); } else { Object exArgs[] = { "Element has no content." }; throw new XMLEncryptionException("empty", exArgs); } } else { - serializedOctets = _serializer.serialize(element); + serializedOctets = serializer.serializeToByteArray(element); + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Serialized octets:\n" + new String(serializedOctets, "UTF-8")); } - logger.log(java.util.logging.Level.FINE, "Serialized octets:\n" + serializedOctets); } byte[] encryptedBytes = null; // Now create the working cipher if none was created already Cipher c; - if (_contextCipher == null) { - String jceAlgorithm = JCEMapper.translateURItoJCEID(_algorithm); - logger.log(java.util.logging.Level.FINE, "alg = " + jceAlgorithm); - - try { - if (_requestedJCEProvider == null) - c = Cipher.getInstance(jceAlgorithm); - else - c = Cipher.getInstance(jceAlgorithm, _requestedJCEProvider); - } catch (NoSuchAlgorithmException nsae) { - throw new XMLEncryptionException("empty", nsae); - } catch (NoSuchProviderException nspre) { - throw new XMLEncryptionException("empty", nspre); - } catch (NoSuchPaddingException nspae) { - throw new XMLEncryptionException("empty", nspae); - } + if (contextCipher == null) { + c = constructCipher(algorithm, null); } else { - c = _contextCipher; + c = contextCipher; } // Now perform the encryption try { - // Should internally generate an IV - // todo - allow user to set an IV - c.init(_cipherMode, _key); + // The Spec mandates a 96-bit IV for GCM algorithms + if (AES_128_GCM.equals(algorithm) || AES_192_GCM.equals(algorithm) + || AES_256_GCM.equals(algorithm)) { + if (random == null) { + random = SecureRandom.getInstance("SHA1PRNG"); + } + byte[] temp = new byte[12]; + random.nextBytes(temp); + IvParameterSpec paramSpec = new IvParameterSpec(temp); + c.init(cipherMode, key, paramSpec); + } else { + c.init(cipherMode, key); + } } catch (InvalidKeyException ike) { throw new XMLEncryptionException("empty", ike); + } catch (NoSuchAlgorithmException ex) { + throw new XMLEncryptionException("empty", ex); } try { @@ -1086,13 +1158,16 @@ public class XMLCipher { baos.write(c.doFinal()); encryptedBytes = baos.toByteArray(); } else { - encryptedBytes = c.doFinal(serializedOctets.getBytes("UTF-8")); - logger.log(java.util.logging.Level.FINE, "Expected cipher.outputSize = " + - Integer.toString(c.getOutputSize( - serializedOctets.getBytes().length))); + encryptedBytes = c.doFinal(serializedOctets); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Expected cipher.outputSize = " + + Integer.toString(c.getOutputSize(serializedOctets.length))); + } + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Actual cipher.outputSize = " + + Integer.toString(encryptedBytes.length)); } - logger.log(java.util.logging.Level.FINE, "Actual cipher.outputSize = " + - Integer.toString(encryptedBytes.length)); } catch (IllegalStateException ise) { throw new XMLEncryptionException("empty", ise); } catch (IllegalBlockSizeException ibse) { @@ -1106,308 +1181,418 @@ public class XMLCipher { // Now build up to a properly XML Encryption encoded octet stream // IvParameterSpec iv; byte[] iv = c.getIV(); - byte[] finalEncryptedBytes = - new byte[iv.length + encryptedBytes.length]; + byte[] finalEncryptedBytes = new byte[iv.length + encryptedBytes.length]; System.arraycopy(iv, 0, finalEncryptedBytes, 0, iv.length); - System.arraycopy(encryptedBytes, 0, finalEncryptedBytes, iv.length, - encryptedBytes.length); + System.arraycopy(encryptedBytes, 0, finalEncryptedBytes, iv.length, encryptedBytes.length); String base64EncodedEncryptedOctets = Base64.encode(finalEncryptedBytes); - logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets); - logger.log(java.util.logging.Level.FINE, "Encrypted octets length = " + - base64EncodedEncryptedOctets.length()); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets); + log.log(java.util.logging.Level.FINE, "Encrypted octets length = " + base64EncodedEncryptedOctets.length()); + } try { - CipherData cd = _ed.getCipherData(); + CipherData cd = ed.getCipherData(); CipherValue cv = cd.getCipherValue(); // cv.setValue(base64EncodedEncryptedOctets.getBytes()); cv.setValue(base64EncodedEncryptedOctets); if (type != null) { - _ed.setType(new URI(type).toString()); + ed.setType(new URI(type).toString()); } EncryptionMethod method = - _factory.newEncryptionMethod(new URI(_algorithm).toString()); - _ed.setEncryptionMethod(method); - } catch (URI.MalformedURIException mfue) { - throw new XMLEncryptionException("empty", mfue); + factory.newEncryptionMethod(new URI(algorithm).toString()); + method.setDigestAlgorithm(digestAlg); + ed.setEncryptionMethod(method); + } catch (URISyntaxException ex) { + throw new XMLEncryptionException("empty", ex); } - return (_ed); + return ed; } /** * Returns an EncryptedData interface. Use this operation if * you want to load an EncryptedData structure from a DOM - * structure and manipulate the contents + * structure and manipulate the contents. * * @param context the context Document. * @param element the Element that will be loaded * @throws XMLEncryptionException - * @return + * @return the EncryptedData */ public EncryptedData loadEncryptedData(Document context, Element element) - throws XMLEncryptionException { - logger.log(java.util.logging.Level.FINE, "Loading encrypted element..."); - if(null == context) - logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); - if(null == element) - logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); - if(_cipherMode != DECRYPT_MODE) - logger.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE..."); + throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Loading encrypted element..."); + } + if (null == context) { + throw new NullPointerException("Context document unexpectedly null..."); + } + if (null == element) { + throw new NullPointerException("Element unexpectedly null..."); + } + if (cipherMode != DECRYPT_MODE) { + throw new XMLEncryptionException("XMLCipher unexpectedly not in DECRYPT_MODE..."); + } - _contextDocument = context; - _ed = _factory.newEncryptedData(element); + contextDocument = context; + ed = factory.newEncryptedData(element); - return (_ed); + return ed; } /** * Returns an EncryptedKey interface. Use this operation if * you want to load an EncryptedKey structure from a DOM - * structure and manipulate the contents. + * structure and manipulate the contents. * * @param context the context Document. * @param element the Element that will be loaded - * @return + * @return the EncryptedKey * @throws XMLEncryptionException */ - public EncryptedKey loadEncryptedKey(Document context, Element element) - throws XMLEncryptionException { - logger.log(java.util.logging.Level.FINE, "Loading encrypted key..."); - if(null == context) - logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); - if(null == element) - logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); - if(_cipherMode != UNWRAP_MODE && _cipherMode != DECRYPT_MODE) - logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in UNWRAP_MODE or DECRYPT_MODE..."); + throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Loading encrypted key..."); + } + if (null == context) { + throw new NullPointerException("Context document unexpectedly null..."); + } + if (null == element) { + throw new NullPointerException("Element unexpectedly null..."); + } + if (cipherMode != UNWRAP_MODE && cipherMode != DECRYPT_MODE) { + throw new XMLEncryptionException( + "XMLCipher unexpectedly not in UNWRAP_MODE or DECRYPT_MODE..." + ); + } - _contextDocument = context; - _ek = _factory.newEncryptedKey(element); - return (_ek); + contextDocument = context; + ek = factory.newEncryptedKey(element); + return ek; } /** * Returns an EncryptedKey interface. Use this operation if * you want to load an EncryptedKey structure from a DOM - * structure and manipulate the contents. - * - * Assumes that the context document is the document that owns the element + * structure and manipulate the contents. + * + * Assumes that the context document is the document that owns the element * * @param element the Element that will be loaded - * @return + * @return the EncryptedKey * @throws XMLEncryptionException */ - - public EncryptedKey loadEncryptedKey(Element element) - throws XMLEncryptionException { - - return (loadEncryptedKey(element.getOwnerDocument(), element)); + public EncryptedKey loadEncryptedKey(Element element) throws XMLEncryptionException { + return loadEncryptedKey(element.getOwnerDocument(), element); } /** * Encrypts a key to an EncryptedKey structure - * - * @param doc the Context document that will be used to general DOM - * @param key Key to encrypt (will use previously set KEK to - * perform encryption - * @return + * + * @param doc the Context document that will be used to general DOM + * @param key Key to encrypt (will use previously set KEK to + * perform encryption + * @return the EncryptedKey * @throws XMLEncryptionException */ + public EncryptedKey encryptKey(Document doc, Key key) throws XMLEncryptionException { + return encryptKey(doc, key, null, null); + } - public EncryptedKey encryptKey(Document doc, Key key) throws - XMLEncryptionException { + /** + * Encrypts a key to an EncryptedKey structure + * + * @param doc the Context document that will be used to general DOM + * @param key Key to encrypt (will use previously set KEK to + * perform encryption + * @param mgfAlgorithm The xenc11 MGF Algorithm to use + * @param oaepParams The OAEPParams to use + * @return the EncryptedKey + * @throws XMLEncryptionException + */ + public EncryptedKey encryptKey( + Document doc, + Key key, + String mgfAlgorithm, + byte[] oaepParams + ) throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Encrypting key ..."); + } - logger.log(java.util.logging.Level.FINE, "Encrypting key ..."); + if (null == key) { + log.log(java.util.logging.Level.SEVERE, "Key unexpectedly null..."); + } + if (cipherMode != WRAP_MODE) { + log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in WRAP_MODE..."); + } + if (algorithm == null) { + throw new XMLEncryptionException("XMLCipher instance without transformation specified"); + } - if(null == key) - logger.log(java.util.logging.Level.SEVERE, "Key unexpectedly null..."); - if(_cipherMode != WRAP_MODE) - logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in WRAP_MODE..."); + contextDocument = doc; - if (_algorithm == null) { + byte[] encryptedBytes = null; + Cipher c; - throw new XMLEncryptionException("XMLCipher instance without transformation specified"); - } - - _contextDocument = doc; - - byte[] encryptedBytes = null; - Cipher c; - - if (_contextCipher == null) { - // Now create the working cipher - - String jceAlgorithm = - JCEMapper.translateURItoJCEID(_algorithm); - - logger.log(java.util.logging.Level.FINE, "alg = " + jceAlgorithm); - - try { - if (_requestedJCEProvider == null) - c = Cipher.getInstance(jceAlgorithm); - else - c = Cipher.getInstance(jceAlgorithm, _requestedJCEProvider); - } catch (NoSuchAlgorithmException nsae) { - throw new XMLEncryptionException("empty", nsae); - } catch (NoSuchProviderException nspre) { - throw new XMLEncryptionException("empty", nspre); - } catch (NoSuchPaddingException nspae) { - throw new XMLEncryptionException("empty", nspae); - } - } else { - c = _contextCipher; - } - // Now perform the encryption - - try { - // Should internally generate an IV - // todo - allow user to set an IV - c.init(Cipher.WRAP_MODE, _key); - encryptedBytes = c.wrap(key); - } catch (InvalidKeyException ike) { - throw new XMLEncryptionException("empty", ike); - } catch (IllegalBlockSizeException ibse) { - throw new XMLEncryptionException("empty", ibse); - } - - String base64EncodedEncryptedOctets = Base64.encode(encryptedBytes); - - logger.log(java.util.logging.Level.FINE, "Encrypted key octets:\n" + base64EncodedEncryptedOctets); - logger.log(java.util.logging.Level.FINE, "Encrypted key octets length = " + - base64EncodedEncryptedOctets.length()); - - CipherValue cv = _ek.getCipherData().getCipherValue(); - cv.setValue(base64EncodedEncryptedOctets); + if (contextCipher == null) { + // Now create the working cipher + c = constructCipher(algorithm, null); + } else { + c = contextCipher; + } + // Now perform the encryption try { - EncryptionMethod method = _factory.newEncryptionMethod( - new URI(_algorithm).toString()); - _ek.setEncryptionMethod(method); - } catch (URI.MalformedURIException mfue) { - throw new XMLEncryptionException("empty", mfue); + // Should internally generate an IV + // todo - allow user to set an IV + OAEPParameterSpec oaepParameters = + constructOAEPParameters( + algorithm, digestAlg, mgfAlgorithm, oaepParams + ); + if (oaepParameters == null) { + c.init(Cipher.WRAP_MODE, this.key); + } else { + c.init(Cipher.WRAP_MODE, this.key, oaepParameters); + } + encryptedBytes = c.wrap(key); + } catch (InvalidKeyException ike) { + throw new XMLEncryptionException("empty", ike); + } catch (IllegalBlockSizeException ibse) { + throw new XMLEncryptionException("empty", ibse); + } catch (InvalidAlgorithmParameterException e) { + throw new XMLEncryptionException("empty", e); } - return _ek; + String base64EncodedEncryptedOctets = Base64.encode(encryptedBytes); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Encrypted key octets:\n" + base64EncodedEncryptedOctets); + log.log(java.util.logging.Level.FINE, "Encrypted key octets length = " + base64EncodedEncryptedOctets.length()); + } + + CipherValue cv = ek.getCipherData().getCipherValue(); + cv.setValue(base64EncodedEncryptedOctets); + + try { + EncryptionMethod method = factory.newEncryptionMethod(new URI(algorithm).toString()); + method.setDigestAlgorithm(digestAlg); + method.setMGFAlgorithm(mgfAlgorithm); + method.setOAEPparams(oaepParams); + ek.setEncryptionMethod(method); + } catch (URISyntaxException ex) { + throw new XMLEncryptionException("empty", ex); + } + return ek; } - /** - * Decrypt a key from a passed in EncryptedKey structure - * - * @param encryptedKey Previously loaded EncryptedKey that needs - * to be decrypted. - * @param algorithm Algorithm for the decryption - * @return a key corresponding to the give type + /** + * Decrypt a key from a passed in EncryptedKey structure + * + * @param encryptedKey Previously loaded EncryptedKey that needs + * to be decrypted. + * @param algorithm Algorithm for the decryption + * @return a key corresponding to the given type * @throws XMLEncryptionException - */ + */ + public Key decryptKey(EncryptedKey encryptedKey, String algorithm) + throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Decrypting key from previously loaded EncryptedKey..."); + } - public Key decryptKey(EncryptedKey encryptedKey, String algorithm) throws - XMLEncryptionException { + if (cipherMode != UNWRAP_MODE && log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in UNWRAP_MODE..."); + } - logger.log(java.util.logging.Level.FINE, "Decrypting key from previously loaded EncryptedKey..."); + if (algorithm == null) { + throw new XMLEncryptionException("Cannot decrypt a key without knowing the algorithm"); + } - if(_cipherMode != UNWRAP_MODE) - logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in UNWRAP_MODE..."); - - if (algorithm == null) { - throw new XMLEncryptionException("Cannot decrypt a key without knowing the algorithm"); - } - - if (_key == null) { - - logger.log(java.util.logging.Level.FINE, "Trying to find a KEK via key resolvers"); - - KeyInfo ki = encryptedKey.getKeyInfo(); - if (ki != null) { - try { - _key = ki.getSecretKey(); - } - catch (Exception e) { - } - } - if (_key == null) { - logger.log(java.util.logging.Level.SEVERE, "XMLCipher::decryptKey called without a KEK and cannot resolve"); - throw new XMLEncryptionException("Unable to decrypt without a KEK"); - } - } - - // Obtain the encrypted octets - XMLCipherInput cipherInput = new XMLCipherInput(encryptedKey); - byte [] encryptedBytes = cipherInput.getBytes(); - - String jceKeyAlgorithm = - JCEMapper.getJCEKeyAlgorithmFromURI(algorithm); - - Cipher c; - if (_contextCipher == null) { - // Now create the working cipher - - String jceAlgorithm = - JCEMapper.translateURItoJCEID( - encryptedKey.getEncryptionMethod().getAlgorithm()); - - logger.log(java.util.logging.Level.FINE, "JCE Algorithm = " + jceAlgorithm); - - try { - if (_requestedJCEProvider == null) - c = Cipher.getInstance(jceAlgorithm); - else - c = Cipher.getInstance(jceAlgorithm, _requestedJCEProvider); - } catch (NoSuchAlgorithmException nsae) { - throw new XMLEncryptionException("empty", nsae); - } catch (NoSuchProviderException nspre) { - throw new XMLEncryptionException("empty", nspre); - } catch (NoSuchPaddingException nspae) { - throw new XMLEncryptionException("empty", nspae); - } - } else { - c = _contextCipher; - } - - Key ret; + if (key == null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Trying to find a KEK via key resolvers"); + } + KeyInfo ki = encryptedKey.getKeyInfo(); + if (ki != null) { + ki.setSecureValidation(secureValidation); try { - c.init(Cipher.UNWRAP_MODE, _key); - ret = c.unwrap(encryptedBytes, jceKeyAlgorithm, Cipher.SECRET_KEY); - - } catch (InvalidKeyException ike) { - throw new XMLEncryptionException("empty", ike); - } catch (NoSuchAlgorithmException nsae) { - throw new XMLEncryptionException("empty", nsae); + String keyWrapAlg = encryptedKey.getEncryptionMethod().getAlgorithm(); + String keyType = JCEMapper.getJCEKeyAlgorithmFromURI(keyWrapAlg); + if ("RSA".equals(keyType)) { + key = ki.getPrivateKey(); + } else { + key = ki.getSecretKey(); + } } + catch (Exception e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + } + } + if (key == null) { + log.log(java.util.logging.Level.SEVERE, "XMLCipher::decryptKey called without a KEK and cannot resolve"); + throw new XMLEncryptionException("Unable to decrypt without a KEK"); + } + } - logger.log(java.util.logging.Level.FINE, "Decryption of key type " + algorithm + " OK"); + // Obtain the encrypted octets + XMLCipherInput cipherInput = new XMLCipherInput(encryptedKey); + cipherInput.setSecureValidation(secureValidation); + byte[] encryptedBytes = cipherInput.getBytes(); - return ret; + String jceKeyAlgorithm = JCEMapper.getJCEKeyAlgorithmFromURI(algorithm); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "JCE Key Algorithm: " + jceKeyAlgorithm); + } + Cipher c; + if (contextCipher == null) { + // Now create the working cipher + c = + constructCipher( + encryptedKey.getEncryptionMethod().getAlgorithm(), + encryptedKey.getEncryptionMethod().getDigestAlgorithm() + ); + } else { + c = contextCipher; + } + + Key ret; + + try { + EncryptionMethod encMethod = encryptedKey.getEncryptionMethod(); + OAEPParameterSpec oaepParameters = + constructOAEPParameters( + encMethod.getAlgorithm(), encMethod.getDigestAlgorithm(), + encMethod.getMGFAlgorithm(), encMethod.getOAEPparams() + ); + if (oaepParameters == null) { + c.init(Cipher.UNWRAP_MODE, key); + } else { + c.init(Cipher.UNWRAP_MODE, key, oaepParameters); + } + ret = c.unwrap(encryptedBytes, jceKeyAlgorithm, Cipher.SECRET_KEY); + } catch (InvalidKeyException ike) { + throw new XMLEncryptionException("empty", ike); + } catch (NoSuchAlgorithmException nsae) { + throw new XMLEncryptionException("empty", nsae); + } catch (InvalidAlgorithmParameterException e) { + throw new XMLEncryptionException("empty", e); + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Decryption of key type " + algorithm + " OK"); + } + + return ret; } - /** - * Decrypt a key from a passed in EncryptedKey structure. This version - * is used mainly internally, when the cipher already has an - * EncryptedData loaded. The algorithm URI will be read from the - * EncryptedData - * - * @param encryptedKey Previously loaded EncryptedKey that needs - * to be decrypted. - * @return a key corresponding to the give type - * @throws XMLEncryptionException - */ + /** + * Construct an OAEPParameterSpec object from the given parameters + */ + private OAEPParameterSpec constructOAEPParameters( + String encryptionAlgorithm, + String digestAlgorithm, + String mgfAlgorithm, + byte[] oaepParams + ) { + if (XMLCipher.RSA_OAEP.equals(encryptionAlgorithm) + || XMLCipher.RSA_OAEP_11.equals(encryptionAlgorithm)) { - public Key decryptKey(EncryptedKey encryptedKey) throws - XMLEncryptionException { + String jceDigestAlgorithm = "SHA-1"; + if (digestAlgorithm != null) { + jceDigestAlgorithm = JCEMapper.translateURItoJCEID(digestAlgorithm); + } - return decryptKey(encryptedKey, _ed.getEncryptionMethod().getAlgorithm()); + PSource.PSpecified pSource = PSource.PSpecified.DEFAULT; + if (oaepParams != null) { + pSource = new PSource.PSpecified(oaepParams); + } + MGF1ParameterSpec mgfParameterSpec = new MGF1ParameterSpec("SHA-1"); + if (XMLCipher.RSA_OAEP_11.equals(encryptionAlgorithm)) { + if (EncryptionConstants.MGF1_SHA256.equals(mgfAlgorithm)) { + mgfParameterSpec = new MGF1ParameterSpec("SHA-256"); + } else if (EncryptionConstants.MGF1_SHA384.equals(mgfAlgorithm)) { + mgfParameterSpec = new MGF1ParameterSpec("SHA-384"); + } else if (EncryptionConstants.MGF1_SHA512.equals(mgfAlgorithm)) { + mgfParameterSpec = new MGF1ParameterSpec("SHA-512"); + } + } + return new OAEPParameterSpec(jceDigestAlgorithm, "MGF1", mgfParameterSpec, pSource); } + return null; + } + + /** + * Construct a Cipher object + */ + private Cipher constructCipher(String algorithm, String digestAlgorithm) throws XMLEncryptionException { + String jceAlgorithm = JCEMapper.translateURItoJCEID(algorithm); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "JCE Algorithm = " + jceAlgorithm); + } + + Cipher c; + try { + if (requestedJCEProvider == null) { + c = Cipher.getInstance(jceAlgorithm); + } else { + c = Cipher.getInstance(jceAlgorithm, requestedJCEProvider); + } + } catch (NoSuchAlgorithmException nsae) { + // Check to see if an RSA OAEP MGF-1 with SHA-1 algorithm was requested + // Some JDKs don't support RSA/ECB/OAEPPadding + if (XMLCipher.RSA_OAEP.equals(algorithm) + && (digestAlgorithm == null + || MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1.equals(digestAlgorithm))) { + try { + if (requestedJCEProvider == null) { + c = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding"); + } else { + c = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", requestedJCEProvider); + } + } catch (Exception ex) { + throw new XMLEncryptionException("empty", ex); + } + } else { + throw new XMLEncryptionException("empty", nsae); + } + } catch (NoSuchProviderException nspre) { + throw new XMLEncryptionException("empty", nspre); + } catch (NoSuchPaddingException nspae) { + throw new XMLEncryptionException("empty", nspae); + } + + return c; + } + + /** + * Decrypt a key from a passed in EncryptedKey structure. This version + * is used mainly internally, when the cipher already has an + * EncryptedData loaded. The algorithm URI will be read from the + * EncryptedData + * + * @param encryptedKey Previously loaded EncryptedKey that needs + * to be decrypted. + * @return a key corresponding to the given type + * @throws XMLEncryptionException + */ + public Key decryptKey(EncryptedKey encryptedKey) throws XMLEncryptionException { + return decryptKey(encryptedKey, ed.getEncryptionMethod().getAlgorithm()); + } + /** * Removes the contents of a Node. * * @param node the Node to clear. */ private static void removeContent(Node node) { - while (node.hasChildNodes()) { + while (node.hasChildNodes()) { node.removeChild(node.getFirstChild()); } } @@ -1419,196 +1604,191 @@ public class XMLCipher { * @return the Node as a result of the decrypt operation. * @throws XMLEncryptionException */ - private Document decryptElement(Element element) throws - XMLEncryptionException { - - logger.log(java.util.logging.Level.FINE, "Decrypting element..."); - - if(_cipherMode != DECRYPT_MODE) - logger.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE..."); - - String octets; - try { - octets = new String(decryptToByteArray(element), "UTF-8"); - } catch (UnsupportedEncodingException uee) { - throw new XMLEncryptionException("empty", uee); - } - - - logger.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + octets); - - Node sourceParent = element.getParentNode(); - - DocumentFragment decryptedFragment = - _serializer.deserialize(octets, sourceParent); - - - // The de-serialiser returns a fragment whose children we need to - // take on. - - if (sourceParent != null && sourceParent.getNodeType() == Node.DOCUMENT_NODE) { - - // If this is a content decryption, this may have problems - - _contextDocument.removeChild(_contextDocument.getDocumentElement()); - _contextDocument.appendChild(decryptedFragment); - } - else { - sourceParent.replaceChild(decryptedFragment, element); - - } - - return (_contextDocument); - } - - - /** - * - * @param element - * @return - * @throws XMLEncryptionException - */ - private Document decryptElementContent(Element element) throws - XMLEncryptionException { - Element e = (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTEDDATA).item(0); - - if (null == e) { - throw new XMLEncryptionException("No EncryptedData child element."); + private Document decryptElement(Element element) throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Decrypting element..."); } - return (decryptElement(e)); + if (cipherMode != DECRYPT_MODE) { + log.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE..."); + } + + byte[] octets = decryptToByteArray(element); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + new String(octets)); + } + + Node sourceParent = element.getParentNode(); + Node decryptedNode = serializer.deserialize(octets, sourceParent); + + // The de-serialiser returns a node whose children we need to take on. + if (sourceParent != null && Node.DOCUMENT_NODE == sourceParent.getNodeType()) { + // If this is a content decryption, this may have problems + contextDocument.removeChild(contextDocument.getDocumentElement()); + contextDocument.appendChild(decryptedNode); + } else if (sourceParent != null) { + sourceParent.replaceChild(decryptedNode, element); + } + + return contextDocument; } - /** - * Decrypt an EncryptedData element to a byte array - * - * When passed in an EncryptedData node, returns the decryption - * as a byte array. - * - * Does not modify the source document + /** + * * @param element - * @return + * @return the Node as a result of the decrypt operation. * @throws XMLEncryptionException - */ + */ + private Document decryptElementContent(Element element) throws XMLEncryptionException { + Element e = + (Element) element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_ENCRYPTEDDATA + ).item(0); - public byte[] decryptToByteArray(Element element) - throws XMLEncryptionException { + if (null == e) { + throw new XMLEncryptionException("No EncryptedData child element."); + } - logger.log(java.util.logging.Level.FINE, "Decrypting to ByteArray..."); + return decryptElement(e); + } - if(_cipherMode != DECRYPT_MODE) - logger.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE..."); + /** + * Decrypt an EncryptedData element to a byte array. + * + * When passed in an EncryptedData node, returns the decryption + * as a byte array. + * + * Does not modify the source document. + * @param element + * @return the bytes resulting from the decryption + * @throws XMLEncryptionException + */ + public byte[] decryptToByteArray(Element element) throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Decrypting to ByteArray..."); + } - EncryptedData encryptedData = _factory.newEncryptedData(element); + if (cipherMode != DECRYPT_MODE) { + log.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE..."); + } - if (_key == null) { + EncryptedData encryptedData = factory.newEncryptedData(element); - KeyInfo ki = encryptedData.getKeyInfo(); - - if (ki != null) { - try { - // Add a EncryptedKey resolver - ki.registerInternalKeyResolver( - new EncryptedKeyResolver(encryptedData. - getEncryptionMethod(). - getAlgorithm(), - _kek)); - _key = ki.getSecretKey(); - } catch (KeyResolverException kre) { - // We will throw in a second... - } - } - - if (_key == null) { - logger.log(java.util.logging.Level.SEVERE, "XMLCipher::decryptElement called without a key and unable to resolve"); - - throw new XMLEncryptionException("encryption.nokey"); - } - } - - // Obtain the encrypted octets - XMLCipherInput cipherInput = new XMLCipherInput(encryptedData); - byte [] encryptedBytes = cipherInput.getBytes(); - - // Now create the working cipher - - String jceAlgorithm = - JCEMapper.translateURItoJCEID(encryptedData.getEncryptionMethod().getAlgorithm()); - - Cipher c; + if (key == null) { + KeyInfo ki = encryptedData.getKeyInfo(); + if (ki != null) { try { - if (_requestedJCEProvider == null) - c = Cipher.getInstance(jceAlgorithm); - else - c = Cipher.getInstance(jceAlgorithm, _requestedJCEProvider); - } catch (NoSuchAlgorithmException nsae) { - throw new XMLEncryptionException("empty", nsae); - } catch (NoSuchProviderException nspre) { - throw new XMLEncryptionException("empty", nspre); - } catch (NoSuchPaddingException nspae) { - throw new XMLEncryptionException("empty", nspae); + // Add an EncryptedKey resolver + String encMethodAlgorithm = encryptedData.getEncryptionMethod().getAlgorithm(); + EncryptedKeyResolver resolver = new EncryptedKeyResolver(encMethodAlgorithm, kek); + if (internalKeyResolvers != null) { + int size = internalKeyResolvers.size(); + for (int i = 0; i < size; i++) { + resolver.registerInternalKeyResolver(internalKeyResolvers.get(i)); + } + } + ki.registerInternalKeyResolver(resolver); + ki.setSecureValidation(secureValidation); + key = ki.getSecretKey(); + } catch (KeyResolverException kre) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, kre.getMessage(), kre); + } } + } - // Calculate the IV length and copy out + if (key == null) { + log.log(java.util.logging.Level.SEVERE, + "XMLCipher::decryptElement called without a key and unable to resolve" + ); + throw new XMLEncryptionException("encryption.nokey"); + } + } - // For now, we only work with Block ciphers, so this will work. - // This should probably be put into the JCE mapper. + // Obtain the encrypted octets + XMLCipherInput cipherInput = new XMLCipherInput(encryptedData); + cipherInput.setSecureValidation(secureValidation); + byte[] encryptedBytes = cipherInput.getBytes(); - int ivLen = c.getBlockSize(); - byte[] ivBytes = new byte[ivLen]; + // Now create the working cipher + String jceAlgorithm = + JCEMapper.translateURItoJCEID(encryptedData.getEncryptionMethod().getAlgorithm()); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "JCE Algorithm = " + jceAlgorithm); + } - // You may be able to pass the entire piece in to IvParameterSpec - // and it will only take the first x bytes, but no way to be certain - // that this will work for every JCE provider, so lets copy the - // necessary bytes into a dedicated array. + Cipher c; + try { + if (requestedJCEProvider == null) { + c = Cipher.getInstance(jceAlgorithm); + } else { + c = Cipher.getInstance(jceAlgorithm, requestedJCEProvider); + } + } catch (NoSuchAlgorithmException nsae) { + throw new XMLEncryptionException("empty", nsae); + } catch (NoSuchProviderException nspre) { + throw new XMLEncryptionException("empty", nspre); + } catch (NoSuchPaddingException nspae) { + throw new XMLEncryptionException("empty", nspae); + } - System.arraycopy(encryptedBytes, 0, ivBytes, 0, ivLen); - IvParameterSpec iv = new IvParameterSpec(ivBytes); + // Calculate the IV length and copy out - try { - c.init(_cipherMode, _key, iv); - } catch (InvalidKeyException ike) { - throw new XMLEncryptionException("empty", ike); - } catch (InvalidAlgorithmParameterException iape) { - throw new XMLEncryptionException("empty", iape); - } + // For now, we only work with Block ciphers, so this will work. + // This should probably be put into the JCE mapper. - byte[] plainBytes; + int ivLen = c.getBlockSize(); + String alg = encryptedData.getEncryptionMethod().getAlgorithm(); + if (AES_128_GCM.equals(alg) || AES_192_GCM.equals(alg) || AES_256_GCM.equals(alg)) { + ivLen = 12; + } + byte[] ivBytes = new byte[ivLen]; + + // You may be able to pass the entire piece in to IvParameterSpec + // and it will only take the first x bytes, but no way to be certain + // that this will work for every JCE provider, so lets copy the + // necessary bytes into a dedicated array. + + System.arraycopy(encryptedBytes, 0, ivBytes, 0, ivLen); + IvParameterSpec iv = new IvParameterSpec(ivBytes); try { - plainBytes = c.doFinal(encryptedBytes, - ivLen, - encryptedBytes.length - ivLen); + c.init(cipherMode, key, iv); + } catch (InvalidKeyException ike) { + throw new XMLEncryptionException("empty", ike); + } catch (InvalidAlgorithmParameterException iape) { + throw new XMLEncryptionException("empty", iape); + } + try { + return c.doFinal(encryptedBytes, ivLen, encryptedBytes.length - ivLen); } catch (IllegalBlockSizeException ibse) { throw new XMLEncryptionException("empty", ibse); } catch (BadPaddingException bpe) { throw new XMLEncryptionException("empty", bpe); } - - return (plainBytes); } - /* - * Expose the interface for creating XML Encryption objects - */ + /* + * Expose the interface for creating XML Encryption objects + */ /** * Creates an EncryptedData Element. * - * The newEncryptedData and newEncryptedKey methods create fairly complete - * elements that are immediately useable. All the other create* methods - * return bare elements that still need to be built upon. - *

- * An EncryptionMethod will still need to be added however - * - * @param type Either REFERENCE_TYPE or VALUE_TYPE - defines what kind of - * CipherData this EncryptedData will contain. + * The newEncryptedData and newEncryptedKey methods create fairly complete + * elements that are immediately useable. All the other create* methods + * return bare elements that still need to be built upon. + *

+ * An EncryptionMethod will still need to be added however + * + * @param type Either REFERENCE_TYPE or VALUE_TYPE - defines what kind of + * CipherData this EncryptedData will contain. * @param value the Base 64 encoded, encrypted text to wrap in the * EncryptedData or the URI to set in the CipherReference - * (usage will depend on the type + * (usage will depend on the type * @return the EncryptedData Element. * * * @throws XMLEncryptionException */ - - public EncryptedData createEncryptedData(int type, String value) throws - XMLEncryptionException { + public EncryptedData createEncryptedData(int type, String value) throws XMLEncryptionException { EncryptedData result = null; CipherData data = null; switch (type) { - case CipherData.REFERENCE_TYPE: - CipherReference cipherReference = _factory.newCipherReference( - value); - data = _factory.newCipherData(type); - data.setCipherReference(cipherReference); - result = _factory.newEncryptedData(data); - break; - case CipherData.VALUE_TYPE: - CipherValue cipherValue = _factory.newCipherValue(value); - data = _factory.newCipherData(type); - data.setCipherValue(cipherValue); - result = _factory.newEncryptedData(data); + case CipherData.REFERENCE_TYPE: + CipherReference cipherReference = factory.newCipherReference(value); + data = factory.newCipherData(type); + data.setCipherReference(cipherReference); + result = factory.newEncryptedData(data); + break; + case CipherData.VALUE_TYPE: + CipherValue cipherValue = factory.newCipherValue(value); + data = factory.newCipherData(type); + data.setCipherValue(cipherValue); + result = factory.newEncryptedData(data); } - return (result); + return result; } /** * Creates an EncryptedKey Element. * - * The newEncryptedData and newEncryptedKey methods create fairly complete - * elements that are immediately useable. All the other create* methods - * return bare elements that still need to be built upon. - *

- * An EncryptionMethod will still need to be added however - * - * @param type Either REFERENCE_TYPE or VALUE_TYPE - defines what kind of - * CipherData this EncryptedData will contain. + * The newEncryptedData and newEncryptedKey methods create fairly complete + * elements that are immediately useable. All the other create* methods + * return bare elements that still need to be built upon. + *

+ * An EncryptionMethod will still need to be added however + * + * @param type Either REFERENCE_TYPE or VALUE_TYPE - defines what kind of + * CipherData this EncryptedData will contain. * @param value the Base 64 encoded, encrypted text to wrap in the * EncryptedKey or the URI to set in the CipherReference - * (usage will depend on the type + * (usage will depend on the type * @return the EncryptedKey Element. * * * @throws XMLEncryptionException */ - - public EncryptedKey createEncryptedKey(int type, String value) throws - XMLEncryptionException { + public EncryptedKey createEncryptedKey(int type, String value) throws XMLEncryptionException { EncryptedKey result = null; CipherData data = null; switch (type) { - case CipherData.REFERENCE_TYPE: - CipherReference cipherReference = _factory.newCipherReference( - value); - data = _factory.newCipherData(type); - data.setCipherReference(cipherReference); - result = _factory.newEncryptedKey(data); - break; - case CipherData.VALUE_TYPE: - CipherValue cipherValue = _factory.newCipherValue(value); - data = _factory.newCipherData(type); - data.setCipherValue(cipherValue); - result = _factory.newEncryptedKey(data); + case CipherData.REFERENCE_TYPE: + CipherReference cipherReference = factory.newCipherReference(value); + data = factory.newCipherData(type); + data.setCipherReference(cipherReference); + result = factory.newEncryptedKey(data); + break; + case CipherData.VALUE_TYPE: + CipherValue cipherValue = factory.newCipherValue(value); + data = factory.newCipherData(type); + data.setCipherValue(cipherValue); + result = factory.newEncryptedKey(data); } - return (result); + return result; } - /** - * Create an AgreementMethod object - * - * @param algorithm Algorithm of the agreement method - * @return - */ - - public AgreementMethod createAgreementMethod(String algorithm) { - return (_factory.newAgreementMethod(algorithm)); - } - - /** - * Create a CipherData object - * - * @param type Type of this CipherData (either VALUE_TUPE or - * REFERENCE_TYPE) - * @return - */ - - public CipherData createCipherData(int type) { - return (_factory.newCipherData(type)); - } - - /** - * Create a CipherReference object - * - * @return - * @param uri The URI that the reference will refer - */ - - public CipherReference createCipherReference(String uri) { - return (_factory.newCipherReference(uri)); - } - - /** - * Create a CipherValue element - * - * @param value The value to set the ciphertext to - * @return - */ - - public CipherValue createCipherValue(String value) { - return (_factory.newCipherValue(value)); - } - - /** - * Create an EncryptedMethod object - * - * @param algorithm Algorithm for the encryption - * @return - */ - public EncryptionMethod createEncryptionMethod(String algorithm) { - return (_factory.newEncryptionMethod(algorithm)); - } - - /** - * Create an EncryptedProperties element - * @return - */ - public EncryptionProperties createEncryptionProperties() { - return (_factory.newEncryptionProperties()); - } - - /** - * Create a new EncryptionProperty element - * @return - */ - public EncryptionProperty createEncryptionProperty() { - return (_factory.newEncryptionProperty()); - } - - /** - * Create a new ReferenceList object - * @return - * @param type - */ - public ReferenceList createReferenceList(int type) { - return (_factory.newReferenceList(type)); - } - - /** - * Create a new Transforms object - *

- * Note: A context document must have been set - * elsewhere (possibly via a call to doFinal). If not, use the - * createTransforms(Document) method. - * @return - */ - - public Transforms createTransforms() { - return (_factory.newTransforms()); - } - - /** - * Create a new Transforms object - * - * Because the handling of Transforms is currently done in the signature - * code, the creation of a Transforms object requires a - * context document. - * - * @param doc Document that will own the created Transforms node - * @return - */ - public Transforms createTransforms(Document doc) { - return (_factory.newTransforms(doc)); - } - /** - * Converts Strings into Nodes and visa versa. - *

- * NOTE: For internal use only. + * Create an AgreementMethod object * - * @author Axl Mattheus + * @param algorithm Algorithm of the agreement method + * @return a new AgreementMethod */ - - private class Serializer { - /** - * Initialize the XMLSerializer with the specified context - * Document. - *

- * Setup OutputFormat in a way that the serialization does not - * modifiy the contents, that is it shall not do any pretty printing - * and so on. This would destroy the original content before - * encryption. If that content was signed before encryption and the - * serialization modifies the content the signature verification will - * fail. - */ - Serializer() { - } - - /** - * Returns a String representation of the specified - * Document. - *

- * Refer also to comments about setup of format. - * - * @param document the Document to serialize. - * @return the String representation of the serilaized - * Document. - * @throws Exception - */ - String serialize(Document document) throws Exception { - return canonSerialize(document); - } - - /** - * Returns a String representation of the specified - * Element. - *

- * Refer also to comments about setup of format. - * - * @param element the Element to serialize. - * @return the String representation of the serilaized - * Element. - * @throws Exception - */ - String serialize(Element element) throws Exception { - return canonSerialize(element); - } - - /** - * Returns a String representation of the specified - * NodeList. - *

- * This is a special case because the NodeList may represent a - * DocumentFragment. A document fragement may be a - * non-valid XML document (refer to appropriate description of - * W3C) because it my start with a non-element node, e.g. a text - * node. - *

- * The methods first converts the node list into a document fragment. - * Special care is taken to not destroy the current document, thus - * the method clones the nodes (deep cloning) before it appends - * them to the document fragment. - *

- * Refer also to comments about setup of format. - * - * @param content the NodeList to serialize. - * @return the String representation of the serilaized - * NodeList. - * @throws Exception - */ - String serialize(NodeList content) throws Exception { //XMLEncryptionException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - _canon.setWriter(baos); - _canon.notReset(); - for (int i = 0; i < content.getLength(); i++) { - _canon.canonicalizeSubtree(content.item(i)); - } - baos.close(); - return baos.toString("UTF-8"); - } - - /** - * Use the Canoncializer to serialize the node - * @param node - * @return - * @throws Exception - */ - String canonSerialize(Node node) throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - _canon.setWriter(baos); - _canon.notReset(); - _canon.canonicalizeSubtree(node); - baos.close(); - return baos.toString("UTF-8"); - } - /** - * @param source - * @param ctx - * @return - * @throws XMLEncryptionException - * - */ - DocumentFragment deserialize(String source, Node ctx) throws XMLEncryptionException { - DocumentFragment result; - final String tagname = "fragment"; - - // Create the context to parse the document against - StringBuffer sb; - - sb = new StringBuffer(); - sb.append("<"+tagname); - - // Run through each node up to the document node and find any - // xmlns: nodes - - Node wk = ctx; - - while (wk != null) { - - NamedNodeMap atts = wk.getAttributes(); - int length; - if (atts != null) - length = atts.getLength(); - else - length = 0; - - for (int i = 0 ; i < length ; ++i) { - Node att = atts.item(i); - if (att.getNodeName().startsWith("xmlns:") || - att.getNodeName().equals("xmlns")) { - - // Check to see if this node has already been found - Node p = ctx; - boolean found = false; - while (p != wk) { - NamedNodeMap tstAtts = p.getAttributes(); - if (tstAtts != null && - tstAtts.getNamedItem(att.getNodeName()) != null) { - found = true; - break; - } - p = p.getParentNode(); - } - if (found == false) { - - // This is an attribute node - sb.append(" " + att.getNodeName() + "=\"" + - att.getNodeValue() + "\""); - } - } - } - wk = wk.getParentNode(); - } - sb.append(">" + source + ""); - String fragment = sb.toString(); - - try { - DocumentBuilderFactory dbf = - DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); - dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document d = db.parse( - new InputSource(new StringReader(fragment))); - - Element fragElt = (Element) _contextDocument.importNode( - d.getDocumentElement(), true); - result = _contextDocument.createDocumentFragment(); - Node child = fragElt.getFirstChild(); - while (child != null) { - fragElt.removeChild(child); - result.appendChild(child); - child = fragElt.getFirstChild(); - } - // String outp = serialize(d); - - } catch (SAXException se) { - throw new XMLEncryptionException("empty", se); - } catch (ParserConfigurationException pce) { - throw new XMLEncryptionException("empty", pce); - } catch (IOException ioe) { - throw new XMLEncryptionException("empty", ioe); - } - - return (result); - } + public AgreementMethod createAgreementMethod(String algorithm) { + return factory.newAgreementMethod(algorithm); } + /** + * Create a CipherData object + * + * @param type Type of this CipherData (either VALUE_TUPE or + * REFERENCE_TYPE) + * @return a new CipherData + */ + public CipherData createCipherData(int type) { + return factory.newCipherData(type); + } + + /** + * Create a CipherReference object + * + * @param uri The URI that the reference will refer + * @return a new CipherReference + */ + public CipherReference createCipherReference(String uri) { + return factory.newCipherReference(uri); + } + + /** + * Create a CipherValue element + * + * @param value The value to set the ciphertext to + * @return a new CipherValue + */ + public CipherValue createCipherValue(String value) { + return factory.newCipherValue(value); + } + + /** + * Create an EncryptionMethod object + * + * @param algorithm Algorithm for the encryption + * @return a new EncryptionMethod + */ + public EncryptionMethod createEncryptionMethod(String algorithm) { + return factory.newEncryptionMethod(algorithm); + } + + /** + * Create an EncryptionProperties element + * @return a new EncryptionProperties + */ + public EncryptionProperties createEncryptionProperties() { + return factory.newEncryptionProperties(); + } + + /** + * Create a new EncryptionProperty element + * @return a new EncryptionProperty + */ + public EncryptionProperty createEncryptionProperty() { + return factory.newEncryptionProperty(); + } + + /** + * Create a new ReferenceList object + * @param type ReferenceList.DATA_REFERENCE or ReferenceList.KEY_REFERENCE + * @return a new ReferenceList + */ + public ReferenceList createReferenceList(int type) { + return factory.newReferenceList(type); + } + + /** + * Create a new Transforms object + *

+ * Note: A context document must have been set + * elsewhere (possibly via a call to doFinal). If not, use the + * createTransforms(Document) method. + * @return a new Transforms + */ + public Transforms createTransforms() { + return factory.newTransforms(); + } + + /** + * Create a new Transforms object + * + * Because the handling of Transforms is currently done in the signature + * code, the creation of a Transforms object requires a + * context document. + * + * @param doc Document that will own the created Transforms node + * @return a new Transforms + */ + public Transforms createTransforms(Document doc) { + return factory.newTransforms(doc); + } /** * @@ -2020,201 +1994,110 @@ public class XMLCipher { private class Factory { /** * @param algorithm - * @return - * + * @return a new AgreementMethod */ AgreementMethod newAgreementMethod(String algorithm) { - return (new AgreementMethodImpl(algorithm)); + return new AgreementMethodImpl(algorithm); } /** * @param type - * @return + * @return a new CipherData * */ CipherData newCipherData(int type) { - return (new CipherDataImpl(type)); + return new CipherDataImpl(type); } /** * @param uri - * @return - * + * @return a new CipherReference */ CipherReference newCipherReference(String uri) { - return (new CipherReferenceImpl(uri)); + return new CipherReferenceImpl(uri); } /** * @param value - * @return - * + * @return a new CipherValue */ CipherValue newCipherValue(String value) { - return (new CipherValueImpl(value)); + return new CipherValueImpl(value); } - /** - * - + /* CipherValue newCipherValue(byte[] value) { - return (new CipherValueImpl(value)); + return new CipherValueImpl(value); } - */ + */ + /** * @param data - * @return - * + * @return a new EncryptedData */ EncryptedData newEncryptedData(CipherData data) { - return (new EncryptedDataImpl(data)); + return new EncryptedDataImpl(data); } /** * @param data - * @return - * + * @return a new EncryptedKey */ EncryptedKey newEncryptedKey(CipherData data) { - return (new EncryptedKeyImpl(data)); + return new EncryptedKeyImpl(data); } /** * @param algorithm - * @return - * + * @return a new EncryptionMethod */ EncryptionMethod newEncryptionMethod(String algorithm) { - return (new EncryptionMethodImpl(algorithm)); + return new EncryptionMethodImpl(algorithm); } /** - * @return - * + * @return a new EncryptionProperties */ EncryptionProperties newEncryptionProperties() { - return (new EncryptionPropertiesImpl()); + return new EncryptionPropertiesImpl(); } /** - * @return - * + * @return a new EncryptionProperty */ EncryptionProperty newEncryptionProperty() { - return (new EncryptionPropertyImpl()); + return new EncryptionPropertyImpl(); } /** - * @param type - * @return - * + * @param type ReferenceList.DATA_REFERENCE or ReferenceList.KEY_REFERENCE + * @return a new ReferenceList */ ReferenceList newReferenceList(int type) { - return (new ReferenceListImpl(type)); + return new ReferenceListImpl(type); } /** - * @return - * + * @return a new Transforms */ Transforms newTransforms() { - return (new TransformsImpl()); + return new TransformsImpl(); } /** * @param doc - * @return - * + * @return a new Transforms */ Transforms newTransforms(Document doc) { - return (new TransformsImpl(doc)); + return new TransformsImpl(doc); } /** * @param element - * @return + * @return a new CipherData * @throws XMLEncryptionException - * */ - // - // - // - // - // - // - // - // - // - // - // - AgreementMethod newAgreementMethod(Element element) throws - XMLEncryptionException { - if (null == element) { - throw new NullPointerException("element is null"); - } - - String algorithm = element.getAttributeNS(null, - EncryptionConstants._ATT_ALGORITHM); - AgreementMethod result = newAgreementMethod(algorithm); - - Element kaNonceElement = (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_KA_NONCE).item(0); - if (null != kaNonceElement) { - result.setKANonce(kaNonceElement.getNodeValue().getBytes()); - } - // TODO: /////////////////////////////////////////////////////////// - // Figure out how to make this pesky line work.. - // - - // TODO: Work out how to handle relative URI - - Element originatorKeyInfoElement = - (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ORIGINATORKEYINFO).item(0); - if (null != originatorKeyInfoElement) { - try { - result.setOriginatorKeyInfo( - new KeyInfo(originatorKeyInfoElement, null)); - } catch (XMLSecurityException xse) { - throw new XMLEncryptionException("empty", xse); - } - } - - // TODO: Work out how to handle relative URI - - Element recipientKeyInfoElement = - (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_RECIPIENTKEYINFO).item(0); - if (null != recipientKeyInfoElement) { - try { - result.setRecipientKeyInfo( - new KeyInfo(recipientKeyInfoElement, null)); - } catch (XMLSecurityException xse) { - throw new XMLEncryptionException("empty", xse); - } - } - - return (result); - } - - /** - * @param element - * @return - * @throws XMLEncryptionException - * - */ - // - // - // - // - // - // - // - CipherData newCipherData(Element element) throws - XMLEncryptionException { + CipherData newCipherData(Element element) throws XMLEncryptionException { if (null == element) { throw new NullPointerException("element is null"); } @@ -2223,7 +2106,8 @@ public class XMLCipher { Element e = null; if (element.getElementsByTagNameNS( EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERVALUE).getLength() > 0) { + EncryptionConstants._TAG_CIPHERVALUE).getLength() > 0 + ) { type = CipherData.VALUE_TYPE; e = (Element) element.getElementsByTagNameNS( EncryptionConstants.EncryptionSpecNS, @@ -2244,100 +2128,67 @@ public class XMLCipher { result.setCipherReference(newCipherReference(e)); } - return (result); + return result; } /** * @param element - * @return + * @return a new CipherReference * @throws XMLEncryptionException * */ - // - // - // - // - // - // - // - CipherReference newCipherReference(Element element) throws - XMLEncryptionException { + CipherReference newCipherReference(Element element) throws XMLEncryptionException { - Attr URIAttr = - element.getAttributeNodeNS(null, EncryptionConstants._ATT_URI); - CipherReference result = new CipherReferenceImpl(URIAttr); + Attr uriAttr = + element.getAttributeNodeNS(null, EncryptionConstants._ATT_URI); + CipherReference result = new CipherReferenceImpl(uriAttr); - // Find any Transforms + // Find any Transforms + NodeList transformsElements = + element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_TRANSFORMS); + Element transformsElement = (Element) transformsElements.item(0); - NodeList transformsElements = element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_TRANSFORMS); - Element transformsElement = - (Element) transformsElements.item(0); + if (transformsElement != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Creating a DSIG based Transforms element"); + } + try { + result.setTransforms(new TransformsImpl(transformsElement)); + } catch (XMLSignatureException xse) { + throw new XMLEncryptionException("empty", xse); + } catch (InvalidTransformException ite) { + throw new XMLEncryptionException("empty", ite); + } catch (XMLSecurityException xse) { + throw new XMLEncryptionException("empty", xse); + } + } - if (transformsElement != null) { - logger.log(java.util.logging.Level.FINE, "Creating a DSIG based Transforms element"); - try { - result.setTransforms(new TransformsImpl(transformsElement)); - } - catch (XMLSignatureException xse) { - throw new XMLEncryptionException("empty", xse); - } catch (InvalidTransformException ite) { - throw new XMLEncryptionException("empty", ite); - } catch (XMLSecurityException xse) { - throw new XMLEncryptionException("empty", xse); - } - - } - - return result; + return result; } /** * @param element - * @return - * + * @return a new CipherValue */ CipherValue newCipherValue(Element element) { String value = XMLUtils.getFullTextChildrenFromElement(element); - CipherValue result = newCipherValue(value); - - return (result); + return newCipherValue(value); } /** * @param element - * @return + * @return a new EncryptedData * @throws XMLEncryptionException * */ - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - EncryptedData newEncryptedData(Element element) throws - XMLEncryptionException { + EncryptedData newEncryptedData(Element element) throws XMLEncryptionException { EncryptedData result = null; - NodeList dataElements = element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERDATA); + NodeList dataElements = + element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_CIPHERDATA); // Need to get the last CipherData found, as earlier ones will // be for elements in the KeyInfo lists @@ -2349,22 +2200,17 @@ public class XMLCipher { result = newEncryptedData(data); - result.setId(element.getAttributeNS( - null, EncryptionConstants._ATT_ID)); - result.setType( - element.getAttributeNS(null, EncryptionConstants._ATT_TYPE)); - result.setMimeType(element.getAttributeNS( - null, EncryptionConstants._ATT_MIMETYPE)); - result.setEncoding( - element.getAttributeNS(null, Constants._ATT_ENCODING)); + result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID)); + result.setType(element.getAttributeNS(null, EncryptionConstants._ATT_TYPE)); + result.setMimeType(element.getAttributeNS(null, EncryptionConstants._ATT_MIMETYPE)); + result.setEncoding( element.getAttributeNS(null, Constants._ATT_ENCODING)); Element encryptionMethodElement = (Element) element.getElementsByTagNameNS( EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_ENCRYPTIONMETHOD).item(0); if (null != encryptionMethodElement) { - result.setEncryptionMethod(newEncryptionMethod( - encryptionMethodElement)); + result.setEncryptionMethod(newEncryptionMethod(encryptionMethodElement)); } // BFL 16/7/03 - simple implementation @@ -2374,12 +2220,8 @@ public class XMLCipher { (Element) element.getElementsByTagNameNS( Constants.SignatureSpecNS, Constants._TAG_KEYINFO).item(0); if (null != keyInfoElement) { - try { - result.setKeyInfo(new KeyInfo(keyInfoElement, null)); - } catch (XMLSecurityException xse) { - throw new XMLEncryptionException("Error loading Key Info", - xse); - } + KeyInfo ki = newKeyInfo(keyInfoElement); + result.setKeyInfo(ki); } // TODO: Implement @@ -2389,85 +2231,49 @@ public class XMLCipher { EncryptionConstants._TAG_ENCRYPTIONPROPERTIES).item(0); if (null != encryptionPropertiesElement) { result.setEncryptionProperties( - newEncryptionProperties(encryptionPropertiesElement)); + newEncryptionProperties(encryptionPropertiesElement) + ); } - return (result); + return result; } /** * @param element - * @return + * @return a new EncryptedKey * @throws XMLEncryptionException - * */ - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - EncryptedKey newEncryptedKey(Element element) throws - XMLEncryptionException { + EncryptedKey newEncryptedKey(Element element) throws XMLEncryptionException { EncryptedKey result = null; - NodeList dataElements = element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERDATA); + NodeList dataElements = + element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_CIPHERDATA); Element dataElement = (Element) dataElements.item(dataElements.getLength() - 1); CipherData data = newCipherData(dataElement); result = newEncryptedKey(data); - result.setId(element.getAttributeNS( - null, EncryptionConstants._ATT_ID)); - result.setType( - element.getAttributeNS(null, EncryptionConstants._ATT_TYPE)); - result.setMimeType(element.getAttributeNS( - null, EncryptionConstants._ATT_MIMETYPE)); - result.setEncoding( - element.getAttributeNS(null, Constants._ATT_ENCODING)); - result.setRecipient(element.getAttributeNS( - null, EncryptionConstants._ATT_RECIPIENT)); + result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID)); + result.setType(element.getAttributeNS(null, EncryptionConstants._ATT_TYPE)); + result.setMimeType(element.getAttributeNS(null, EncryptionConstants._ATT_MIMETYPE)); + result.setEncoding(element.getAttributeNS(null, Constants._ATT_ENCODING)); + result.setRecipient(element.getAttributeNS(null, EncryptionConstants._ATT_RECIPIENT)); Element encryptionMethodElement = (Element) element.getElementsByTagNameNS( EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_ENCRYPTIONMETHOD).item(0); if (null != encryptionMethodElement) { - result.setEncryptionMethod(newEncryptionMethod( - encryptionMethodElement)); + result.setEncryptionMethod(newEncryptionMethod(encryptionMethodElement)); } Element keyInfoElement = (Element) element.getElementsByTagNameNS( Constants.SignatureSpecNS, Constants._TAG_KEYINFO).item(0); if (null != keyInfoElement) { - try { - result.setKeyInfo(new KeyInfo(keyInfoElement, null)); - } catch (XMLSecurityException xse) { - throw new XMLEncryptionException - ("Error loading Key Info", xse); - } + KeyInfo ki = newKeyInfo(keyInfoElement); + result.setKeyInfo(ki); } // TODO: Implement @@ -2477,7 +2283,8 @@ public class XMLCipher { EncryptionConstants._TAG_ENCRYPTIONPROPERTIES).item(0); if (null != encryptionPropertiesElement) { result.setEncryptionProperties( - newEncryptionProperties(encryptionPropertiesElement)); + newEncryptionProperties(encryptionPropertiesElement) + ); } Element referenceListElement = @@ -2493,30 +2300,40 @@ public class XMLCipher { EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_CARRIEDKEYNAME).item(0); if (null != carriedNameElement) { - result.setCarriedName - (carriedNameElement.getFirstChild().getNodeValue()); + result.setCarriedName(carriedNameElement.getFirstChild().getNodeValue()); } - return (result); + return result; } /** * @param element - * @return - * + * @return a new KeyInfo + * @throws XMLEncryptionException + */ + KeyInfo newKeyInfo(Element element) throws XMLEncryptionException { + try { + KeyInfo ki = new KeyInfo(element, null); + ki.setSecureValidation(secureValidation); + if (internalKeyResolvers != null) { + int size = internalKeyResolvers.size(); + for (int i = 0; i < size; i++) { + ki.registerInternalKeyResolver(internalKeyResolvers.get(i)); + } + } + return ki; + } catch (XMLSecurityException xse) { + throw new XMLEncryptionException("Error loading Key Info", xse); + } + } + + /** + * @param element + * @return a new EncryptionMethod */ - // - // - // - // - // - // - // - // EncryptionMethod newEncryptionMethod(Element element) { - String algorithm = element.getAttributeNS( - null, EncryptionConstants._ATT_ALGORITHM); - EncryptionMethod result = newEncryptionMethod(algorithm); + String encAlgorithm = element.getAttributeNS(null, EncryptionConstants._ATT_ALGORITHM); + EncryptionMethod result = newEncryptionMethod(encAlgorithm); Element keySizeElement = (Element) element.getElementsByTagNameNS( @@ -2533,92 +2350,83 @@ public class XMLCipher { EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_OAEPPARAMS).item(0); if (null != oaepParamsElement) { - result.setOAEPparams( - oaepParamsElement.getNodeValue().getBytes()); + try { + String oaepParams = oaepParamsElement.getFirstChild().getNodeValue(); + result.setOAEPparams(Base64.decode(oaepParams.getBytes("UTF-8"))); + } catch(UnsupportedEncodingException e) { + throw new RuntimeException("UTF-8 not supported", e); + } catch (Base64DecodingException e) { + throw new RuntimeException("BASE-64 decoding error", e); + } + } + + Element digestElement = + (Element) element.getElementsByTagNameNS( + Constants.SignatureSpecNS, Constants._TAG_DIGESTMETHOD).item(0); + if (digestElement != null) { + String digestAlgorithm = digestElement.getAttributeNS(null, "Algorithm"); + result.setDigestAlgorithm(digestAlgorithm); + } + + Element mgfElement = + (Element) element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpec11NS, EncryptionConstants._TAG_MGF).item(0); + if (mgfElement != null && !XMLCipher.RSA_OAEP.equals(algorithm)) { + String mgfAlgorithm = mgfElement.getAttributeNS(null, "Algorithm"); + result.setMGFAlgorithm(mgfAlgorithm); } // TODO: Make this mess work // - return (result); + return result; } /** * @param element - * @return - * + * @return a new EncryptionProperties */ - // - // - // - // - // - // - // EncryptionProperties newEncryptionProperties(Element element) { EncryptionProperties result = newEncryptionProperties(); - result.setId(element.getAttributeNS( - null, EncryptionConstants._ATT_ID)); + result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID)); NodeList encryptionPropertyList = element.getElementsByTagNameNS( EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_ENCRYPTIONPROPERTY); - for(int i = 0; i < encryptionPropertyList.getLength(); i++) { + for (int i = 0; i < encryptionPropertyList.getLength(); i++) { Node n = encryptionPropertyList.item(i); if (null != n) { - result.addEncryptionProperty( - newEncryptionProperty((Element) n)); + result.addEncryptionProperty(newEncryptionProperty((Element) n)); } } - return (result); + return result; } /** * @param element - * @return - * + * @return a new EncryptionProperty */ - // - // - // - // - // - // - // - // - // EncryptionProperty newEncryptionProperty(Element element) { EncryptionProperty result = newEncryptionProperty(); - result.setTarget( - element.getAttributeNS(null, EncryptionConstants._ATT_TARGET)); - result.setId(element.getAttributeNS( - null, EncryptionConstants._ATT_ID)); + result.setTarget(element.getAttributeNS(null, EncryptionConstants._ATT_TARGET)); + result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID)); // TODO: Make this lot work... // // TODO: Make this work... // - return (result); + return result; } /** * @param element - * @return - * + * @return a new ReferenceList */ - // - // - // - // - // - // - // - // ReferenceList newReferenceList(Element element) { int type = 0; if (null != element.getElementsByTagNameNS( @@ -2629,84 +2437,38 @@ public class XMLCipher { EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_KEYREFERENCE).item(0)) { type = ReferenceList.KEY_REFERENCE; - } else { - // complain } ReferenceList result = new ReferenceListImpl(type); NodeList list = null; switch (type) { case ReferenceList.DATA_REFERENCE: - list = element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_DATAREFERENCE); + list = + element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_DATAREFERENCE); for (int i = 0; i < list.getLength() ; i++) { String uri = ((Element) list.item(i)).getAttribute("URI"); result.add(result.newDataReference(uri)); } break; case ReferenceList.KEY_REFERENCE: - list = element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_KEYREFERENCE); + list = + element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_KEYREFERENCE); for (int i = 0; i < list.getLength() ; i++) { String uri = ((Element) list.item(i)).getAttribute("URI"); result.add(result.newKeyReference(uri)); } } - return (result); - } - - /** - * @param element - * @return - * - */ - Transforms newTransforms(Element element) { - return (null); - } - - /** - * @param agreementMethod - * @return - * - */ - Element toElement(AgreementMethod agreementMethod) { - return ((AgreementMethodImpl) agreementMethod).toElement(); - } - - /** - * @param cipherData - * @return - * - */ - Element toElement(CipherData cipherData) { - return ((CipherDataImpl) cipherData).toElement(); - } - - /** - * @param cipherReference - * @return - * - */ - Element toElement(CipherReference cipherReference) { - return ((CipherReferenceImpl) cipherReference).toElement(); - } - - /** - * @param cipherValue - * @return - * - */ - Element toElement(CipherValue cipherValue) { - return ((CipherValueImpl) cipherValue).toElement(); + return result; } /** * @param encryptedData - * @return - * + * @return the XML Element form of that EncryptedData */ Element toElement(EncryptedData encryptedData) { return ((EncryptedDataImpl) encryptedData).toElement(); @@ -2714,64 +2476,20 @@ public class XMLCipher { /** * @param encryptedKey - * @return - * + * @return the XML Element form of that EncryptedKey */ Element toElement(EncryptedKey encryptedKey) { return ((EncryptedKeyImpl) encryptedKey).toElement(); } /** - * @param encryptionMethod - * @return - * + * @param referenceList + * @return the XML Element form of that ReferenceList */ - Element toElement(EncryptionMethod encryptionMethod) { - return ((EncryptionMethodImpl) encryptionMethod).toElement(); - } - - /** - * @param encryptionProperties - * @return - * - */ - Element toElement(EncryptionProperties encryptionProperties) { - return ((EncryptionPropertiesImpl) encryptionProperties).toElement(); - } - - /** - * @param encryptionProperty - * @return - * - */ - Element toElement(EncryptionProperty encryptionProperty) { - return ((EncryptionPropertyImpl) encryptionProperty).toElement(); - } - Element toElement(ReferenceList referenceList) { return ((ReferenceListImpl) referenceList).toElement(); } - /** - * @param transforms - * @return - * - */ - Element toElement(Transforms transforms) { - return ((TransformsImpl) transforms).toElement(); - } - - // - // - // - // - // - // - // - // - // - // - // private class AgreementMethodImpl implements AgreementMethod { private byte[] kaNonce = null; private List agreementMethodInformation = null; @@ -2787,15 +2505,16 @@ public class XMLCipher { URI tmpAlgorithm = null; try { tmpAlgorithm = new URI(algorithm); - } catch (URI.MalformedURIException fmue) { - //complain? + } catch (URISyntaxException ex) { + throw (IllegalArgumentException) + new IllegalArgumentException().initCause(ex); } algorithmURI = tmpAlgorithm.toString(); } /** @inheritDoc */ public byte[] getKANonce() { - return (kaNonce); + return kaNonce; } /** @inheritDoc */ @@ -2805,7 +2524,7 @@ public class XMLCipher { /** @inheritDoc */ public Iterator getAgreementMethodInformation() { - return (agreementMethodInformation.iterator()); + return agreementMethodInformation.iterator(); } /** @inheritDoc */ @@ -2820,7 +2539,7 @@ public class XMLCipher { /** @inheritDoc */ public KeyInfo getOriginatorKeyInfo() { - return (originatorKeyInfo); + return originatorKeyInfo; } /** @inheritDoc */ @@ -2830,7 +2549,7 @@ public class XMLCipher { /** @inheritDoc */ public KeyInfo getRecipientKeyInfo() { - return (recipientKeyInfo); + return recipientKeyInfo; } /** @inheritDoc */ @@ -2840,70 +2559,10 @@ public class XMLCipher { /** @inheritDoc */ public String getAlgorithm() { - return (algorithmURI); - } - - /** @param algorithm*/ - public void setAlgorithm(String algorithm) { - URI tmpAlgorithm = null; - try { - tmpAlgorithm = new URI(algorithm); - } catch (URI.MalformedURIException mfue) { - //complain - } - algorithmURI = tmpAlgorithm.toString(); - } - - // - // - // - // - // - // - // - // - // - // - // - Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_AGREEMENTMETHOD); - result.setAttributeNS( - null, EncryptionConstants._ATT_ALGORITHM, algorithmURI); - if (null != kaNonce) { - result.appendChild( - ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_KA_NONCE)).appendChild( - _contextDocument.createTextNode(new String(kaNonce))); - } - if (!agreementMethodInformation.isEmpty()) { - Iterator itr = agreementMethodInformation.iterator(); - while (itr.hasNext()) { - result.appendChild(itr.next()); - } - } - if (null != originatorKeyInfo) { - result.appendChild(originatorKeyInfo.getElement()); - } - if (null != recipientKeyInfo) { - result.appendChild(recipientKeyInfo.getElement()); - } - - return (result); + return algorithmURI; } } - // - // - // - // - // - // - // private class CipherDataImpl implements CipherData { private static final String valueMessage = "Data type is reference type."; @@ -2922,16 +2581,16 @@ public class XMLCipher { /** @inheritDoc */ public CipherValue getCipherValue() { - return (cipherValue); + return cipherValue; } /** @inheritDoc */ - public void setCipherValue(CipherValue value) throws - XMLEncryptionException { + public void setCipherValue(CipherValue value) throws XMLEncryptionException { if (cipherType == REFERENCE_TYPE) { - throw new XMLEncryptionException("empty", - new UnsupportedOperationException(valueMessage)); + throw new XMLEncryptionException( + "empty", new UnsupportedOperationException(valueMessage) + ); } cipherValue = value; @@ -2939,15 +2598,16 @@ public class XMLCipher { /** @inheritDoc */ public CipherReference getCipherReference() { - return (cipherReference); + return cipherReference; } /** @inheritDoc */ public void setCipherReference(CipherReference reference) throws - XMLEncryptionException { + XMLEncryptionException { if (cipherType == VALUE_TYPE) { - throw new XMLEncryptionException("empty", - new UnsupportedOperationException(referenceMessage)); + throw new XMLEncryptionException( + "empty", new UnsupportedOperationException(referenceMessage) + ); } cipherReference = reference; @@ -2955,77 +2615,59 @@ public class XMLCipher { /** @inheritDoc */ public int getDataType() { - return (cipherType); + return cipherType; } - // - // - // - // - // - // - // Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERDATA); + Element result = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_CIPHERDATA + ); if (cipherType == VALUE_TYPE) { - result.appendChild( - ((CipherValueImpl) cipherValue).toElement()); + result.appendChild(((CipherValueImpl) cipherValue).toElement()); } else if (cipherType == REFERENCE_TYPE) { - result.appendChild( - ((CipherReferenceImpl) cipherReference).toElement()); - } else { - // complain + result.appendChild(((CipherReferenceImpl) cipherReference).toElement()); } - return (result); + return result; } } - // - // - // - // - // - // - // private class CipherReferenceImpl implements CipherReference { private String referenceURI = null; private Transforms referenceTransforms = null; - private Attr referenceNode = null; + private Attr referenceNode = null; /** * @param uri */ public CipherReferenceImpl(String uri) { - /* Don't check validity of URI as may be "" */ + /* Don't check validity of URI as may be "" */ referenceURI = uri; - referenceNode = null; + referenceNode = null; } - /** - * @param uri - */ - public CipherReferenceImpl(Attr uri) { - referenceURI = uri.getNodeValue(); - referenceNode = uri; - } + /** + * @param uri + */ + public CipherReferenceImpl(Attr uri) { + referenceURI = uri.getNodeValue(); + referenceNode = uri; + } /** @inheritDoc */ public String getURI() { - return (referenceURI); + return referenceURI; } /** @inheritDoc */ - public Attr getURIAsAttr() { - return (referenceNode); - } + public Attr getURIAsAttr() { + return referenceNode; + } /** @inheritDoc */ public Transforms getTransforms() { - return (referenceTransforms); + return referenceTransforms; } /** @inheritDoc */ @@ -3033,91 +2675,53 @@ public class XMLCipher { referenceTransforms = transforms; } - // - // - // - // - // - // - // Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERREFERENCE); - result.setAttributeNS( - null, EncryptionConstants._ATT_URI, referenceURI); + Element result = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_CIPHERREFERENCE + ); + result.setAttributeNS(null, EncryptionConstants._ATT_URI, referenceURI); if (null != referenceTransforms) { - result.appendChild( - ((TransformsImpl) referenceTransforms).toElement()); + result.appendChild(((TransformsImpl) referenceTransforms).toElement()); } - return (result); + return result; } } private class CipherValueImpl implements CipherValue { - private String cipherValue = null; - - // public CipherValueImpl(byte[] value) { - // cipherValue = value; - // } + private String cipherValue = null; /** * @param value */ public CipherValueImpl(String value) { - // cipherValue = value.getBytes(); - cipherValue = value; + cipherValue = value; } /** @inheritDoc */ - public String getValue() { - return (cipherValue); + public String getValue() { + return cipherValue; } - // public void setValue(byte[] value) { - // public void setValue(String value) { - // cipherValue = value; - // } - /** @inheritDoc */ + /** @inheritDoc */ public void setValue(String value) { - // cipherValue = value.getBytes(); - cipherValue = value; + cipherValue = value; } Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERVALUE); - result.appendChild(_contextDocument.createTextNode( - cipherValue)); + Element result = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_CIPHERVALUE + ); + result.appendChild(contextDocument.createTextNode(cipherValue)); - return (result); + return result; } } - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - private class EncryptedDataImpl extends EncryptedTypeImpl implements - EncryptedData { + private class EncryptedDataImpl extends EncryptedTypeImpl implements EncryptedData { + /** * @param data */ @@ -3125,94 +2729,49 @@ public class XMLCipher { super(data); } - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTEDDATA); + Element result = + ElementProxy.createElementForFamily( + contextDocument, EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_ENCRYPTEDDATA + ); if (null != super.getId()) { - result.setAttributeNS( - null, EncryptionConstants._ATT_ID, super.getId()); + result.setAttributeNS(null, EncryptionConstants._ATT_ID, super.getId()); } if (null != super.getType()) { - result.setAttributeNS( - null, EncryptionConstants._ATT_TYPE, super.getType()); + result.setAttributeNS(null, EncryptionConstants._ATT_TYPE, super.getType()); } if (null != super.getMimeType()) { result.setAttributeNS( - null, EncryptionConstants._ATT_MIMETYPE, - super.getMimeType()); + null, EncryptionConstants._ATT_MIMETYPE, super.getMimeType() + ); } if (null != super.getEncoding()) { result.setAttributeNS( - null, EncryptionConstants._ATT_ENCODING, - super.getEncoding()); + null, EncryptionConstants._ATT_ENCODING, super.getEncoding() + ); } if (null != super.getEncryptionMethod()) { - result.appendChild(((EncryptionMethodImpl) - super.getEncryptionMethod()).toElement()); + result.appendChild( + ((EncryptionMethodImpl)super.getEncryptionMethod()).toElement() + ); } if (null != super.getKeyInfo()) { - result.appendChild(super.getKeyInfo().getElement()); + result.appendChild(super.getKeyInfo().getElement().cloneNode(true)); } - result.appendChild( - ((CipherDataImpl) super.getCipherData()).toElement()); + result.appendChild(((CipherDataImpl) super.getCipherData()).toElement()); if (null != super.getEncryptionProperties()) { result.appendChild(((EncryptionPropertiesImpl) super.getEncryptionProperties()).toElement()); } - return (result); + return result; } } - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - private class EncryptedKeyImpl extends EncryptedTypeImpl implements - EncryptedKey { + private class EncryptedKeyImpl extends EncryptedTypeImpl implements EncryptedKey { private String keyRecipient = null; private ReferenceList referenceList = null; private String carriedName = null; @@ -3226,7 +2785,7 @@ public class XMLCipher { /** @inheritDoc */ public String getRecipient() { - return (keyRecipient); + return keyRecipient; } /** @inheritDoc */ @@ -3236,7 +2795,7 @@ public class XMLCipher { /** @inheritDoc */ public ReferenceList getReferenceList() { - return (referenceList); + return referenceList; } /** @inheritDoc */ @@ -3246,7 +2805,7 @@ public class XMLCipher { /** @inheritDoc */ public String getCarriedName() { - return (carriedName); + return carriedName; } /** @inheritDoc */ @@ -3254,84 +2813,60 @@ public class XMLCipher { carriedName = name; } - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTEDKEY); + Element result = + ElementProxy.createElementForFamily( + contextDocument, EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_ENCRYPTEDKEY + ); if (null != super.getId()) { - result.setAttributeNS( - null, EncryptionConstants._ATT_ID, super.getId()); + result.setAttributeNS(null, EncryptionConstants._ATT_ID, super.getId()); } if (null != super.getType()) { - result.setAttributeNS( - null, EncryptionConstants._ATT_TYPE, super.getType()); + result.setAttributeNS(null, EncryptionConstants._ATT_TYPE, super.getType()); } if (null != super.getMimeType()) { - result.setAttributeNS(null, - EncryptionConstants._ATT_MIMETYPE, super.getMimeType()); + result.setAttributeNS( + null, EncryptionConstants._ATT_MIMETYPE, super.getMimeType() + ); } if (null != super.getEncoding()) { - result.setAttributeNS(null, Constants._ATT_ENCODING, - super.getEncoding()); + result.setAttributeNS(null, Constants._ATT_ENCODING, super.getEncoding()); } if (null != getRecipient()) { - result.setAttributeNS(null, - EncryptionConstants._ATT_RECIPIENT, getRecipient()); + result.setAttributeNS( + null, EncryptionConstants._ATT_RECIPIENT, getRecipient() + ); } if (null != super.getEncryptionMethod()) { result.appendChild(((EncryptionMethodImpl) super.getEncryptionMethod()).toElement()); } if (null != super.getKeyInfo()) { - result.appendChild(super.getKeyInfo().getElement()); + result.appendChild(super.getKeyInfo().getElement().cloneNode(true)); } - result.appendChild( - ((CipherDataImpl) super.getCipherData()).toElement()); + result.appendChild(((CipherDataImpl) super.getCipherData()).toElement()); if (null != super.getEncryptionProperties()) { result.appendChild(((EncryptionPropertiesImpl) super.getEncryptionProperties()).toElement()); } if (referenceList != null && !referenceList.isEmpty()) { - result.appendChild(((ReferenceListImpl) - getReferenceList()).toElement()); + result.appendChild(((ReferenceListImpl)getReferenceList()).toElement()); } if (null != carriedName) { - Element element = ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CARRIEDKEYNAME); - Node node = _contextDocument.createTextNode(carriedName); + Element element = + ElementProxy.createElementForFamily( + contextDocument, + EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_CARRIEDKEYNAME + ); + Node node = contextDocument.createTextNode(carriedName); element.appendChild(node); result.appendChild(element); } - return (result); + return result; } } @@ -3345,16 +2880,22 @@ public class XMLCipher { private CipherData cipherData = null; private EncryptionProperties encryptionProperties = null; + /** + * Constructor. + * @param data + */ protected EncryptedTypeImpl(CipherData data) { cipherData = data; } + /** * - * @return + * @return the Id */ public String getId() { - return (id); + return id; } + /** * * @param id @@ -3362,13 +2903,15 @@ public class XMLCipher { public void setId(String id) { this.id = id; } + /** * - * @return + * @return the type */ public String getType() { - return (type); + return type; } + /** * * @param type @@ -3380,18 +2923,20 @@ public class XMLCipher { URI tmpType = null; try { tmpType = new URI(type); - } catch (URI.MalformedURIException mfue) { - // complain + } catch (URISyntaxException ex) { + throw (IllegalArgumentException) + new IllegalArgumentException().initCause(ex); } this.type = tmpType.toString(); } } + /** * - * @return + * @return the MimeType */ public String getMimeType() { - return (mimeType); + return mimeType; } /** * @@ -3400,13 +2945,15 @@ public class XMLCipher { public void setMimeType(String type) { mimeType = type; } + /** * - * @return + * @return the encoding */ public String getEncoding() { - return (encoding); + return encoding; } + /** * * @param encoding @@ -3418,19 +2965,22 @@ public class XMLCipher { URI tmpEncoding = null; try { tmpEncoding = new URI(encoding); - } catch (URI.MalformedURIException mfue) { - // complain + } catch (URISyntaxException ex) { + throw (IllegalArgumentException) + new IllegalArgumentException().initCause(ex); } this.encoding = tmpEncoding.toString(); } } + /** * - * @return + * @return the EncryptionMethod */ public EncryptionMethod getEncryptionMethod() { - return (encryptionMethod); + return encryptionMethod; } + /** * * @param method @@ -3438,13 +2988,15 @@ public class XMLCipher { public void setEncryptionMethod(EncryptionMethod method) { encryptionMethod = method; } + /** * - * @return + * @return the KeyInfo */ public KeyInfo getKeyInfo() { - return (keyInfo); + return keyInfo; } + /** * * @param info @@ -3452,217 +3004,235 @@ public class XMLCipher { public void setKeyInfo(KeyInfo info) { keyInfo = info; } + /** * - * @return + * @return the CipherData */ public CipherData getCipherData() { - return (cipherData); + return cipherData; } + /** * - * @return + * @return the EncryptionProperties */ public EncryptionProperties getEncryptionProperties() { - return (encryptionProperties); + return encryptionProperties; } + /** * * @param properties */ - public void setEncryptionProperties( - EncryptionProperties properties) { + public void setEncryptionProperties(EncryptionProperties properties) { encryptionProperties = properties; } } - // - // - // - // - // - // - // - // private class EncryptionMethodImpl implements EncryptionMethod { private String algorithm = null; private int keySize = Integer.MIN_VALUE; private byte[] oaepParams = null; private List encryptionMethodInformation = null; + private String digestAlgorithm = null; + private String mgfAlgorithm = null; + /** - * + * Constructor. * @param algorithm */ public EncryptionMethodImpl(String algorithm) { URI tmpAlgorithm = null; try { tmpAlgorithm = new URI(algorithm); - } catch (URI.MalformedURIException mfue) { - // complain + } catch (URISyntaxException ex) { + throw (IllegalArgumentException) + new IllegalArgumentException().initCause(ex); } this.algorithm = tmpAlgorithm.toString(); encryptionMethodInformation = new LinkedList(); } + /** @inheritDoc */ public String getAlgorithm() { - return (algorithm); + return algorithm; } + /** @inheritDoc */ public int getKeySize() { - return (keySize); + return keySize; } + /** @inheritDoc */ public void setKeySize(int size) { keySize = size; } + /** @inheritDoc */ public byte[] getOAEPparams() { - return (oaepParams); + return oaepParams; } + /** @inheritDoc */ public void setOAEPparams(byte[] params) { oaepParams = params; } + + /** @inheritDoc */ + public void setDigestAlgorithm(String digestAlgorithm) { + this.digestAlgorithm = digestAlgorithm; + } + + /** @inheritDoc */ + public String getDigestAlgorithm() { + return digestAlgorithm; + } + + /** @inheritDoc */ + public void setMGFAlgorithm(String mgfAlgorithm) { + this.mgfAlgorithm = mgfAlgorithm; + } + + /** @inheritDoc */ + public String getMGFAlgorithm() { + return mgfAlgorithm; + } + /** @inheritDoc */ public Iterator getEncryptionMethodInformation() { - return (encryptionMethodInformation.iterator()); + return encryptionMethodInformation.iterator(); } + /** @inheritDoc */ public void addEncryptionMethodInformation(Element info) { encryptionMethodInformation.add(info); } + /** @inheritDoc */ public void removeEncryptionMethodInformation(Element info) { encryptionMethodInformation.remove(info); } - // - // - // - // - // - // - // - // Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTIONMETHOD); - result.setAttributeNS(null, EncryptionConstants._ATT_ALGORITHM, - algorithm); + Element result = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_ENCRYPTIONMETHOD + ); + result.setAttributeNS(null, EncryptionConstants._ATT_ALGORITHM, algorithm); if (keySize > 0) { result.appendChild( - ElementProxy.createElementForFamily(_contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_KEYSIZE).appendChild( - _contextDocument.createTextNode( - String.valueOf(keySize)))); + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_KEYSIZE + ).appendChild(contextDocument.createTextNode(String.valueOf(keySize)))); } if (null != oaepParams) { - result.appendChild( - ElementProxy.createElementForFamily(_contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_OAEPPARAMS).appendChild( - _contextDocument.createTextNode( - new String(oaepParams)))); + Element oaepElement = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_OAEPPARAMS + ); + oaepElement.appendChild(contextDocument.createTextNode(Base64.encode(oaepParams))); + result.appendChild(oaepElement); } - if (!encryptionMethodInformation.isEmpty()) { - Iterator itr = encryptionMethodInformation.iterator(); + if (digestAlgorithm != null) { + Element digestElement = + XMLUtils.createElementInSignatureSpace(contextDocument, Constants._TAG_DIGESTMETHOD); + digestElement.setAttributeNS(null, "Algorithm", digestAlgorithm); + result.appendChild(digestElement); + } + if (mgfAlgorithm != null) { + Element mgfElement = + XMLUtils.createElementInEncryption11Space( + contextDocument, EncryptionConstants._TAG_MGF + ); + mgfElement.setAttributeNS(null, "Algorithm", mgfAlgorithm); + mgfElement.setAttributeNS( + Constants.NamespaceSpecNS, + "xmlns:" + ElementProxy.getDefaultPrefix(EncryptionConstants.EncryptionSpec11NS), + EncryptionConstants.EncryptionSpec11NS + ); + result.appendChild(mgfElement); + } + Iterator itr = encryptionMethodInformation.iterator(); + while (itr.hasNext()) { result.appendChild(itr.next()); } - return (result); + return result; } } - // - // - // - // - // - // - // private class EncryptionPropertiesImpl implements EncryptionProperties { private String id = null; private List encryptionProperties = null; + /** - * - * + * Constructor. */ public EncryptionPropertiesImpl() { encryptionProperties = new LinkedList(); } + /** @inheritDoc */ public String getId() { - return (id); + return id; } + /** @inheritDoc */ public void setId(String id) { this.id = id; } + /** @inheritDoc */ public Iterator getEncryptionProperties() { - return (encryptionProperties.iterator()); + return encryptionProperties.iterator(); } + /** @inheritDoc */ public void addEncryptionProperty(EncryptionProperty property) { encryptionProperties.add(property); } + /** @inheritDoc */ public void removeEncryptionProperty(EncryptionProperty property) { encryptionProperties.remove(property); } - // - // - // - // - // - // - // Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTIONPROPERTIES); + Element result = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_ENCRYPTIONPROPERTIES + ); if (null != id) { result.setAttributeNS(null, EncryptionConstants._ATT_ID, id); } Iterator itr = getEncryptionProperties(); while (itr.hasNext()) { - result.appendChild(((EncryptionPropertyImpl) - itr.next()).toElement()); + result.appendChild(((EncryptionPropertyImpl)itr.next()).toElement()); } - return (result); + return result; } } - // - // - // - // - // - // - // - // - // private class EncryptionPropertyImpl implements EncryptionProperty { private String target = null; private String id = null; - private HashMap attributeMap = new HashMap(); + private Map attributeMap = new HashMap(); private List encryptionInformation = null; /** - * - * + * Constructor. */ public EncryptionPropertyImpl() { encryptionInformation = new LinkedList(); } + /** @inheritDoc */ public String getTarget() { - return (target); + return target; } + /** @inheritDoc */ public void setTarget(String target) { if (target == null || target.length() == 0) { @@ -3670,163 +3240,144 @@ public class XMLCipher { } else if (target.startsWith("#")) { /* * This is a same document URI reference. Do not parse, - * because com.sun.org.apache.xml.internal.utils.URI considers this an - * illegal URI because it has no scheme. + * because it has no scheme. */ this.target = target; } else { URI tmpTarget = null; try { tmpTarget = new URI(target); - } catch (URI.MalformedURIException mfue) { - // complain + } catch (URISyntaxException ex) { + throw (IllegalArgumentException) + new IllegalArgumentException().initCause(ex); } this.target = tmpTarget.toString(); } } + /** @inheritDoc */ public String getId() { - return (id); + return id; } + /** @inheritDoc */ public void setId(String id) { this.id = id; } + /** @inheritDoc */ public String getAttribute(String attribute) { return attributeMap.get(attribute); } + /** @inheritDoc */ public void setAttribute(String attribute, String value) { attributeMap.put(attribute, value); } + /** @inheritDoc */ public Iterator getEncryptionInformation() { - return (encryptionInformation.iterator()); + return encryptionInformation.iterator(); } + /** @inheritDoc */ public void addEncryptionInformation(Element info) { encryptionInformation.add(info); } + /** @inheritDoc */ public void removeEncryptionInformation(Element info) { encryptionInformation.remove(info); } - // - // - // - // - // - // - // - // - // Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTIONPROPERTY); + Element result = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_ENCRYPTIONPROPERTY + ); if (null != target) { - result.setAttributeNS(null, EncryptionConstants._ATT_TARGET, - target); + result.setAttributeNS(null, EncryptionConstants._ATT_TARGET, target); } if (null != id) { - result.setAttributeNS(null, EncryptionConstants._ATT_ID, - id); + result.setAttributeNS(null, EncryptionConstants._ATT_ID, id); } // TODO: figure out the anyAttribyte stuff... // TODO: figure out the any stuff... - return (result); + return result; } } - // - // - // - // - // - private class TransformsImpl extends - com.sun.org.apache.xml.internal.security.transforms.Transforms - implements Transforms { + private class TransformsImpl extends com.sun.org.apache.xml.internal.security.transforms.Transforms + implements Transforms { - /** - * Construct Transforms - */ - - public TransformsImpl() { - super(_contextDocument); - } - /** - * - * @param doc - */ - public TransformsImpl(Document doc) { - if (doc == null) { - throw new RuntimeException("Document is null"); - } - - this._doc = doc; - this._constructionElement = createElementForFamilyLocal(this._doc, - this.getBaseNamespace(), this.getBaseLocalName()); - } - /** - * - * @param element - * @throws XMLSignatureException - * @throws InvalidTransformException - * @throws XMLSecurityException - * @throws TransformationException - */ - public TransformsImpl(Element element) - throws XMLSignatureException, - InvalidTransformException, - XMLSecurityException, - TransformationException { - - super(element, ""); - - } + /** + * Construct Transforms + */ + public TransformsImpl() { + super(contextDocument); + } /** * - * @return + * @param doc */ - public Element toElement() { + public TransformsImpl(Document doc) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } - if (_doc == null) - _doc = _contextDocument; + this.doc = doc; + this.constructionElement = + createElementForFamilyLocal( + this.doc, this.getBaseNamespace(), this.getBaseLocalName() + ); + } - return getElement(); - } + /** + * + * @param element + * @throws XMLSignatureException + * @throws InvalidTransformException + * @throws XMLSecurityException + * @throws TransformationException + */ + public TransformsImpl(Element element) + throws XMLSignatureException, InvalidTransformException, + XMLSecurityException, TransformationException { + super(element, ""); + } + + /** + * + * @return the XML Element form of that Transforms + */ + public Element toElement() { + if (doc == null) { + doc = contextDocument; + } + + return getElement(); + } /** @inheritDoc */ - public com.sun.org.apache.xml.internal.security.transforms.Transforms getDSTransforms() { - return (this); - } + public com.sun.org.apache.xml.internal.security.transforms.Transforms getDSTransforms() { + return this; + } - - // Over-ride the namespace + // Over-ride the namespace /** @inheritDoc */ - public String getBaseNamespace() { - return EncryptionConstants.EncryptionSpecNS; - } - + public String getBaseNamespace() { + return EncryptionConstants.EncryptionSpecNS; + } } - // - // - // - // - // - // - // - // private class ReferenceListImpl implements ReferenceList { private Class sentry; private List references; + /** - * + * Constructor. * @param type */ public ReferenceListImpl(int type) { @@ -3839,13 +3390,15 @@ public class XMLCipher { } references = new LinkedList(); } + /** @inheritDoc */ public void add(Reference reference) { if (!reference.getClass().equals(sentry)) { throw new IllegalArgumentException(); } - references.add(reference); + references.add(reference); } + /** @inheritDoc */ public void remove(Reference reference) { if (!reference.getClass().equals(sentry)) { @@ -3853,39 +3406,45 @@ public class XMLCipher { } references.remove(reference); } + /** @inheritDoc */ public int size() { - return (references.size()); + return references.size(); } + /** @inheritDoc */ public boolean isEmpty() { - return (references.isEmpty()); + return references.isEmpty(); } + /** @inheritDoc */ public Iterator getReferences() { - return (references.iterator()); + return references.iterator(); } Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_REFERENCELIST); + Element result = + ElementProxy.createElementForFamily( + contextDocument, + EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_REFERENCELIST + ); Iterator eachReference = references.iterator(); while (eachReference.hasNext()) { Reference reference = eachReference.next(); - result.appendChild( - ((ReferenceImpl) reference).toElement()); + result.appendChild(((ReferenceImpl) reference).toElement()); } - return (result); + return result; } + /** @inheritDoc */ public Reference newDataReference(String uri) { - return (new DataReference(uri)); + return new DataReference(uri); } + /** @inheritDoc */ public Reference newKeyReference(String uri) { - return (new KeyReference(uri)); + return new KeyReference(uri); } /** @@ -3898,68 +3457,81 @@ public class XMLCipher { private String uri; private List referenceInformation; - ReferenceImpl(String _uri) { - this.uri = _uri; + ReferenceImpl(String uri) { + this.uri = uri; referenceInformation = new LinkedList(); } + + /** @inheritDoc */ + public abstract String getType(); + /** @inheritDoc */ public String getURI() { - return (uri); + return uri; } + /** @inheritDoc */ public Iterator getElementRetrievalInformation() { - return (referenceInformation.iterator()); + return referenceInformation.iterator(); } + /** @inheritDoc */ - public void setURI(String _uri) { - this.uri = _uri; + public void setURI(String uri) { + this.uri = uri; } + /** @inheritDoc */ public void removeElementRetrievalInformation(Element node) { referenceInformation.remove(node); } + /** @inheritDoc */ public void addElementRetrievalInformation(Element node) { referenceInformation.add(node); } - /** - * - * @return - */ - public abstract Element toElement(); - Element toElement(String tagName) { - Element result = ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - tagName); + /** + * @return the XML Element form of that Reference + */ + public Element toElement() { + String tagName = getType(); + Element result = + ElementProxy.createElementForFamily( + contextDocument, + EncryptionConstants.EncryptionSpecNS, + tagName + ); result.setAttribute(EncryptionConstants._ATT_URI, uri); // TODO: Need to martial referenceInformation // Figure out how to make this work.. // - return (result); + return result; } } private class DataReference extends ReferenceImpl { + DataReference(String uri) { super(uri); } + /** @inheritDoc */ - public Element toElement() { - return super.toElement(EncryptionConstants._TAG_DATAREFERENCE); + public String getType() { + return EncryptionConstants._TAG_DATAREFERENCE; } } private class KeyReference extends ReferenceImpl { + KeyReference(String uri) { - super (uri); + super(uri); } + /** @inheritDoc */ - public Element toElement() { - return super.toElement(EncryptionConstants._TAG_KEYREFERENCE); + public String getType() { + return EncryptionConstants._TAG_KEYREFERENCE; } } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java index 65b9a604b66..583042680d1 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java @@ -2,23 +2,24 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.encryption; import java.io.IOException; @@ -32,7 +33,6 @@ import com.sun.org.apache.xml.internal.security.transforms.TransformationExcepti import org.w3c.dom.Attr; import com.sun.org.apache.xml.internal.security.utils.Base64; - /** * XMLCipherInput is used to wrap input passed into the * XMLCipher encryption operations. @@ -50,77 +50,79 @@ import com.sun.org.apache.xml.internal.security.utils.Base64; public class XMLCipherInput { private static java.util.logging.Logger logger = - java.util.logging.Logger.getLogger(XMLCipher.class.getName()); + java.util.logging.Logger.getLogger(XMLCipherInput.class.getName()); - /** The data we are working with */ - private CipherData _cipherData; + /** The data we are working with */ + private CipherData cipherData; - /** MODES */ - private int _mode; + /** MODES */ + private int mode; - /** - * Constructor for processing encrypted octets - * - * @param data The CipherData object to read the bytes from - * @throws XMLEncryptionException {@link XMLEncryptionException} - */ - - public XMLCipherInput(CipherData data) throws XMLEncryptionException { - - _cipherData = data; - _mode = XMLCipher.DECRYPT_MODE; - if (_cipherData == null) { - throw new XMLEncryptionException("CipherData is null"); - } + private boolean secureValidation; + /** + * Constructor for processing encrypted octets + * + * @param data The CipherData object to read the bytes from + * @throws XMLEncryptionException {@link XMLEncryptionException} + */ + public XMLCipherInput(CipherData data) throws XMLEncryptionException { + cipherData = data; + mode = XMLCipher.DECRYPT_MODE; + if (cipherData == null) { + throw new XMLEncryptionException("CipherData is null"); } + } - /** - * Constructor for processing encrypted octets - * - * @param input The EncryptedType object to read - * the bytes from. - * @throws XMLEncryptionException {@link XMLEncryptionException} - */ - - public XMLCipherInput(EncryptedType input) throws XMLEncryptionException { - - _cipherData = ((input == null) ? null : input.getCipherData()); - _mode = XMLCipher.DECRYPT_MODE; - if (_cipherData == null) { - throw new XMLEncryptionException("CipherData is null"); - } - + /** + * Constructor for processing encrypted octets + * + * @param input The EncryptedType object to read + * the bytes from. + * @throws XMLEncryptionException {@link XMLEncryptionException} + */ + public XMLCipherInput(EncryptedType input) throws XMLEncryptionException { + cipherData = ((input == null) ? null : input.getCipherData()); + mode = XMLCipher.DECRYPT_MODE; + if (cipherData == null) { + throw new XMLEncryptionException("CipherData is null"); } + } - /** - * Dereferences the input and returns it as a single byte array. - * - * @throws XMLEncryptionException + /** + * Set whether secure validation is enabled or not. The default is false. + */ + public void setSecureValidation(boolean secureValidation) { + this.secureValidation = secureValidation; + } + + /** + * Dereferences the input and returns it as a single byte array. + * + * @throws XMLEncryptionException * @return The decripted bytes. - */ - - public byte[] getBytes() throws XMLEncryptionException { - - if (_mode == XMLCipher.DECRYPT_MODE) { - return getDecryptBytes(); - } - return null; + */ + public byte[] getBytes() throws XMLEncryptionException { + if (mode == XMLCipher.DECRYPT_MODE) { + return getDecryptBytes(); } + return null; + } /** * Internal method to get bytes in decryption mode - * @return the decripted bytes + * @return the decrypted bytes * @throws XMLEncryptionException */ private byte[] getDecryptBytes() throws XMLEncryptionException { - String base64EncodedEncryptedOctets = null; - if (_cipherData.getDataType() == CipherData.REFERENCE_TYPE) { + if (cipherData.getDataType() == CipherData.REFERENCE_TYPE) { // Fun time! - logger.log(java.util.logging.Level.FINE, "Found a reference type CipherData"); - CipherReference cr = _cipherData.getCipherReference(); + if (logger.isLoggable(java.util.logging.Level.FINE)) { + logger.log(java.util.logging.Level.FINE, "Found a reference type CipherData"); + } + CipherReference cr = cipherData.getCipherReference(); // Need to wrap the uri in an Attribute node so that we can // Pass to the resource resolvers @@ -130,25 +132,32 @@ public class XMLCipherInput { try { ResourceResolver resolver = - ResourceResolver.getInstance(uriAttr, null); - input = resolver.resolve(uriAttr, null); + ResourceResolver.getInstance(uriAttr, null, secureValidation); + input = resolver.resolve(uriAttr, null, secureValidation); } catch (ResourceResolverException ex) { throw new XMLEncryptionException("empty", ex); } if (input != null) { - logger.log(java.util.logging.Level.FINE, "Managed to resolve URI \"" + cr.getURI() + "\""); + if (logger.isLoggable(java.util.logging.Level.FINE)) { + logger.log(java.util.logging.Level.FINE, "Managed to resolve URI \"" + cr.getURI() + "\""); + } } else { - logger.log(java.util.logging.Level.FINE, "Failed to resolve URI \"" + cr.getURI() + "\""); + if (logger.isLoggable(java.util.logging.Level.FINE)) { + logger.log(java.util.logging.Level.FINE, "Failed to resolve URI \"" + cr.getURI() + "\""); + } } // Lets see if there are any transforms Transforms transforms = cr.getTransforms(); if (transforms != null) { - logger.log(java.util.logging.Level.FINE, "Have transforms in cipher reference"); + if (logger.isLoggable(java.util.logging.Level.FINE)) { + logger.log(java.util.logging.Level.FINE, "Have transforms in cipher reference"); + } try { com.sun.org.apache.xml.internal.security.transforms.Transforms dsTransforms = transforms.getDSTransforms(); + dsTransforms.setSecureValidation(secureValidation); input = dsTransforms.performTransforms(input); } catch (TransformationException ex) { throw new XMLEncryptionException("empty", ex); @@ -163,23 +172,21 @@ public class XMLCipherInput { throw new XMLEncryptionException("empty", ex); } - // retrieve the cipher text - } else if (_cipherData.getDataType() == CipherData.VALUE_TYPE) { - base64EncodedEncryptedOctets = - _cipherData.getCipherValue().getValue(); + // retrieve the cipher text + } else if (cipherData.getDataType() == CipherData.VALUE_TYPE) { + base64EncodedEncryptedOctets = cipherData.getCipherValue().getValue(); } else { throw new XMLEncryptionException("CipherData.getDataType() returned unexpected value"); } - logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets); + if (logger.isLoggable(java.util.logging.Level.FINE)) { + logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets); + } - byte[] encryptedBytes = null; try { - encryptedBytes = Base64.decode(base64EncodedEncryptedOctets); + return Base64.decode(base64EncodedEncryptedOctets); } catch (Base64DecodingException bde) { throw new XMLEncryptionException("empty", bde); } - - return (encryptedBytes); } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java index e25e1fa2a61..1c74f02060d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java @@ -2,104 +2,85 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.encryption; - /** * Constants */ public interface XMLCipherParameters { - /** */ - public static final String AES_128 = + String AES_128 = "http://www.w3.org/2001/04/xmlenc#aes128-cbc"; - /** */ - public static final String AES_256 = + String AES_256 = "http://www.w3.org/2001/04/xmlenc#aes256-cbc"; - /** */ - public static final String AES_192 = + String AES_192 = "http://www.w3.org/2001/04/xmlenc#aes192-cbc"; - /** */ - public static final String RSA_1_5 = + String RSA_1_5 = "http://www.w3.org/2001/04/xmlenc#rsa-1_5"; - /** */ - public static final String RSA_OAEP = + String RSA_OAEP = "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"; - /** */ - public static final String DIFFIE_HELLMAN = + String DIFFIE_HELLMAN = "http://www.w3.org/2001/04/xmlenc#dh"; - /** */ - public static final String TRIPLEDES_KEYWRAP = + String TRIPLEDES_KEYWRAP = "http://www.w3.org/2001/04/xmlenc#kw-tripledes"; - /** */ - public static final String AES_128_KEYWRAP = + String AES_128_KEYWRAP = "http://www.w3.org/2001/04/xmlenc#kw-aes128"; - /** */ - public static final String AES_256_KEYWRAP = + String AES_256_KEYWRAP = "http://www.w3.org/2001/04/xmlenc#kw-aes256"; - /** */ - public static final String AES_192_KEYWRAP = + String AES_192_KEYWRAP = "http://www.w3.org/2001/04/xmlenc#kw-aes192"; - /** */ - public static final String SHA1 = + String SHA1 = "http://www.w3.org/2000/09/xmldsig#sha1"; - /** */ - public static final String SHA256 = + String SHA256 = "http://www.w3.org/2001/04/xmlenc#sha256"; - /** */ - public static final String SHA512 = + String SHA512 = "http://www.w3.org/2001/04/xmlenc#sha512"; - /** */ - public static final String RIPEMD_160 = + String RIPEMD_160 = "http://www.w3.org/2001/04/xmlenc#ripemd160"; - /** */ - public static final String XML_DSIG = + String XML_DSIG = "http://www.w3.org/2000/09/xmldsig#"; - /** */ - public static final String N14C_XML = + String N14C_XML = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; - /** */ - public static final String N14C_XML_CMMNTS = + String N14C_XML_CMMNTS = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; - /** */ - public static final String EXCL_XML_N14C = + String EXCL_XML_N14C = "http://www.w3.org/2001/10/xml-exc-c14n#"; - /** */ - public static final String EXCL_XML_N14C_CMMNTS = + String EXCL_XML_N14C_CMMNTS = "http://www.w3.org/2001/10/xml-exc-c14n#WithComments"; } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java index 0c913145058..8d027a2d893 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.encryption; @@ -26,49 +28,53 @@ import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; * */ public class XMLEncryptionException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; - /** + /** * - * - */ - public XMLEncryptionException() { - super(); - } - /** - * - * @param _msgID - */ - public XMLEncryptionException(String _msgID) { - super(_msgID); - } - /** - * - * @param _msgID - * @param exArgs - */ - public XMLEncryptionException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } - /** - * - * @param _msgID - * @param _originalException - */ - public XMLEncryptionException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } - /** - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public XMLEncryptionException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + */ + private static final long serialVersionUID = 1L; + + /** + * + * + */ + public XMLEncryptionException() { + super(); + } + + /** + * + * @param msgID + */ + public XMLEncryptionException(String msgID) { + super(msgID); + } + + /** + * + * @param msgID + * @param exArgs + */ + public XMLEncryptionException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } + + /** + * + * @param msgID + * @param originalException + */ + public XMLEncryptionException(String msgID, Exception originalException) { + super(msgID, originalException); + + } + + /** + * + * @param msgID + * @param exArgs + * @param originalException + */ + public XMLEncryptionException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java index bbdbaefa27d..1dcb10b9ec6 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java @@ -2,88 +2,80 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.exceptions; - - -/** - * - * - * - * - * @author Christian Geuer-Pollmann - * - */ public class AlgorithmAlreadyRegisteredException extends XMLSecurityException { + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * Constructor AlgorithmAlreadyRegisteredException + * + */ + public AlgorithmAlreadyRegisteredException() { + super(); + } - /** - * Constructor AlgorithmAlreadyRegisteredException - * - */ - public AlgorithmAlreadyRegisteredException() { - super(); - } + /** + * Constructor AlgorithmAlreadyRegisteredException + * + * @param msgID + */ + public AlgorithmAlreadyRegisteredException(String msgID) { + super(msgID); + } - /** - * Constructor AlgorithmAlreadyRegisteredException - * - * @param _msgID - */ - public AlgorithmAlreadyRegisteredException(String _msgID) { - super(_msgID); - } + /** + * Constructor AlgorithmAlreadyRegisteredException + * + * @param msgID + * @param exArgs + */ + public AlgorithmAlreadyRegisteredException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor AlgorithmAlreadyRegisteredException - * - * @param _msgID - * @param exArgs - */ - public AlgorithmAlreadyRegisteredException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor AlgorithmAlreadyRegisteredException + * + * @param msgID + * @param originalException + */ + public AlgorithmAlreadyRegisteredException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor AlgorithmAlreadyRegisteredException - * - * @param _msgID - * @param _originalException - */ - public AlgorithmAlreadyRegisteredException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor AlgorithmAlreadyRegisteredException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public AlgorithmAlreadyRegisteredException( + String msgID, Object exArgs[], Exception originalException + ) { + super(msgID, exArgs, originalException); + } - /** - * Constructor AlgorithmAlreadyRegisteredException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public AlgorithmAlreadyRegisteredException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java index bf039a2602e..0b982c0b241 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.exceptions; - - /** * This Exception is thrown if decoding of Base64 data fails. * @@ -29,58 +29,54 @@ package com.sun.org.apache.xml.internal.security.exceptions; */ public class Base64DecodingException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - /** - * Constructor Base64DecodingException - * - */ - public Base64DecodingException() { - super(); - } + /** + * Constructor Base64DecodingException + * + */ + public Base64DecodingException() { + super(); + } - /** - * Constructor Base64DecodingException - * - * @param _msgID - */ - public Base64DecodingException(String _msgID) { - super(_msgID); - } + /** + * Constructor Base64DecodingException + * + * @param msgID + */ + public Base64DecodingException(String msgID) { + super(msgID); + } - /** - * Constructor Base64DecodingException - * - * @param _msgID - * @param exArgs - */ - public Base64DecodingException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor Base64DecodingException + * + * @param msgID + * @param exArgs + */ + public Base64DecodingException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor Base64DecodingException - * - * @param _msgID - * @param _originalException - */ - public Base64DecodingException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor Base64DecodingException + * + * @param msgID + * @param originalException + */ + public Base64DecodingException(String msgID, Exception originalException) { + super(msgID, originalException); + } + + /** + * Constructor Base64DecodingException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public Base64DecodingException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } - /** - * Constructor Base64DecodingException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public Base64DecodingException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java index 4a4be909ab2..63cb4572e49 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.exceptions; - - import java.io.PrintStream; import java.io.PrintWriter; import java.text.MessageFormat; @@ -29,7 +29,6 @@ import java.text.MessageFormat; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.I18n; - /** * The mother of all Exceptions in this bundle. It allows exceptions to have * their messages translated to the different locales. @@ -64,186 +63,154 @@ import com.sun.org.apache.xml.internal.security.utils.I18n; */ public class XMLSecurityException extends Exception { + /** + * + */ + private static final long serialVersionUID = 1L; + /** Field msgID */ + protected String msgID; - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * Constructor XMLSecurityException + * + */ + public XMLSecurityException() { + super("Missing message string"); - /** Field originalException */ - protected Exception originalException = null; + this.msgID = null; + } - /** Field msgID */ - protected String msgID; + /** + * Constructor XMLSecurityException + * + * @param msgID + */ + public XMLSecurityException(String msgID) { + super(I18n.getExceptionMessage(msgID)); - /** - * Constructor XMLSecurityException - * - */ - public XMLSecurityException() { + this.msgID = msgID; + } - super("Missing message string"); + /** + * Constructor XMLSecurityException + * + * @param msgID + * @param exArgs + */ + public XMLSecurityException(String msgID, Object exArgs[]) { - this.msgID = null; - this.originalException = null; - } + super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs)); - /** - * Constructor XMLSecurityException - * - * @param _msgID - */ - public XMLSecurityException(String _msgID) { + this.msgID = msgID; + } - super(I18n.getExceptionMessage(_msgID)); + /** + * Constructor XMLSecurityException + * + * @param originalException + */ + public XMLSecurityException(Exception originalException) { - this.msgID = _msgID; - this.originalException = null; - } + super("Missing message ID to locate message string in resource bundle \"" + + Constants.exceptionMessagesResourceBundleBase + + "\". Original Exception was a " + + originalException.getClass().getName() + " and message " + + originalException.getMessage(), originalException); + } - /** - * Constructor XMLSecurityException - * - * @param _msgID - * @param exArgs - */ - public XMLSecurityException(String _msgID, Object exArgs[]) { + /** + * Constructor XMLSecurityException + * + * @param msgID + * @param originalException + */ + public XMLSecurityException(String msgID, Exception originalException) { + super(I18n.getExceptionMessage(msgID, originalException), originalException); - super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs)); + this.msgID = msgID; + } - this.msgID = _msgID; - this.originalException = null; - } + /** + * Constructor XMLSecurityException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public XMLSecurityException(String msgID, Object exArgs[], Exception originalException) { + super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs), originalException); - /** - * Constructor XMLSecurityException - * - * @param _originalException - */ - public XMLSecurityException(Exception _originalException) { + this.msgID = msgID; + } - super("Missing message ID to locate message string in resource bundle \"" - + Constants.exceptionMessagesResourceBundleBase - + "\". Original Exception was a " - + _originalException.getClass().getName() + " and message " - + _originalException.getMessage()); + /** + * Method getMsgID + * + * @return the messageId + */ + public String getMsgID() { + if (msgID == null) { + return "Missing message ID"; + } + return msgID; + } - this.originalException = _originalException; - } + /** @inheritDoc */ + public String toString() { + String s = this.getClass().getName(); + String message = super.getLocalizedMessage(); - /** - * Constructor XMLSecurityException - * - * @param _msgID - * @param _originalException - */ - public XMLSecurityException(String _msgID, Exception _originalException) { + if (message != null) { + message = s + ": " + message; + } else { + message = s; + } - super(I18n.getExceptionMessage(_msgID, _originalException)); + if (super.getCause() != null) { + message = message + "\nOriginal Exception was " + super.getCause().toString(); + } - this.msgID = _msgID; - this.originalException = _originalException; - } + return message; + } - /** - * Constructor XMLSecurityException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public XMLSecurityException(String _msgID, Object exArgs[], - Exception _originalException) { + /** + * Method printStackTrace + * + */ + public void printStackTrace() { + synchronized (System.err) { + super.printStackTrace(System.err); + } + } - super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs)); + /** + * Method printStackTrace + * + * @param printwriter + */ + public void printStackTrace(PrintWriter printwriter) { + super.printStackTrace(printwriter); + } - this.msgID = _msgID; - this.originalException = _originalException; - } + /** + * Method printStackTrace + * + * @param printstream + */ + public void printStackTrace(PrintStream printstream) { + super.printStackTrace(printstream); + } - /** - * Method getMsgID - * - * @return the messageId - */ - public String getMsgID() { - - if (msgID == null) { - return "Missing message ID"; - } - return msgID; - } - - /** @inheritDoc */ - public String toString() { - - String s = this.getClass().getName(); - String message = super.getLocalizedMessage(); - - if (message != null) { - message = s + ": " + message; - } else { - message = s; - } - - if (originalException != null) { - message = message + "\nOriginal Exception was " - + originalException.toString(); - } - - return message; - } - - /** - * Method printStackTrace - * - */ - public void printStackTrace() { - - synchronized (System.err) { - super.printStackTrace(System.err); - - if (this.originalException != null) { - this.originalException.printStackTrace(System.err); - } - } - } - - /** - * Method printStackTrace - * - * @param printwriter - */ - public void printStackTrace(PrintWriter printwriter) { - - super.printStackTrace(printwriter); - - if (this.originalException != null) { - this.originalException.printStackTrace(printwriter); - } - } - - /** - * Method printStackTrace - * - * @param printstream - */ - public void printStackTrace(PrintStream printstream) { - - super.printStackTrace(printstream); - - if (this.originalException != null) { - this.originalException.printStackTrace(printstream); - } - } - - /** - * Method getOriginalException - * - * @return the original exception - */ - public Exception getOriginalException() { - return originalException; - } + /** + * Method getOriginalException + * + * @return the original exception + */ + public Exception getOriginalException() { + if (this.getCause() instanceof Exception) { + return (Exception)this.getCause(); + } + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java index 69a803b04c9..06cb920dabe 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java @@ -1,3 +1,25 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 com.sun.org.apache.xml.internal.security.exceptions; import java.io.PrintStream; @@ -39,186 +61,152 @@ import com.sun.org.apache.xml.internal.security.utils.I18n; * * @author Christian Geuer-Pollmann */ -public class XMLSecurityRuntimeException - extends RuntimeException { - /** - * - */ +public class XMLSecurityRuntimeException extends RuntimeException { + private static final long serialVersionUID = 1L; - /** Field originalException */ - protected Exception originalException = null; + /** Field msgID */ + protected String msgID; - /** Field msgID */ - protected String msgID; + /** + * Constructor XMLSecurityRuntimeException + * + */ + public XMLSecurityRuntimeException() { + super("Missing message string"); - /** - * Constructor XMLSecurityRuntimeException - * - */ - public XMLSecurityRuntimeException() { + this.msgID = null; + } - super("Missing message string"); + /** + * Constructor XMLSecurityRuntimeException + * + * @param msgID + */ + public XMLSecurityRuntimeException(String msgID) { + super(I18n.getExceptionMessage(msgID)); - this.msgID = null; - this.originalException = null; - } + this.msgID = msgID; + } - /** - * Constructor XMLSecurityRuntimeException - * - * @param _msgID - */ - public XMLSecurityRuntimeException(String _msgID) { + /** + * Constructor XMLSecurityRuntimeException + * + * @param msgID + * @param exArgs + */ + public XMLSecurityRuntimeException(String msgID, Object exArgs[]) { + super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs)); - super(I18n.getExceptionMessage(_msgID)); + this.msgID = msgID; + } - this.msgID = _msgID; - this.originalException = null; - } + /** + * Constructor XMLSecurityRuntimeException + * + * @param originalException + */ + public XMLSecurityRuntimeException(Exception originalException) { + super("Missing message ID to locate message string in resource bundle \"" + + Constants.exceptionMessagesResourceBundleBase + + "\". Original Exception was a " + + originalException.getClass().getName() + " and message " + + originalException.getMessage(), originalException); + } - /** - * Constructor XMLSecurityRuntimeException - * - * @param _msgID - * @param exArgs - */ - public XMLSecurityRuntimeException(String _msgID, Object exArgs[]) { + /** + * Constructor XMLSecurityRuntimeException + * + * @param msgID + * @param originalException + */ + public XMLSecurityRuntimeException(String msgID, Exception originalException) { + super(I18n.getExceptionMessage(msgID, originalException), originalException); - super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs)); + this.msgID = msgID; + } - this.msgID = _msgID; - this.originalException = null; - } + /** + * Constructor XMLSecurityRuntimeException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public XMLSecurityRuntimeException(String msgID, Object exArgs[], Exception originalException) { + super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs)); - /** - * Constructor XMLSecurityRuntimeException - * - * @param _originalException - */ - public XMLSecurityRuntimeException(Exception _originalException) { + this.msgID = msgID; + } - super("Missing message ID to locate message string in resource bundle \"" - + Constants.exceptionMessagesResourceBundleBase - + "\". Original Exception was a " - + _originalException.getClass().getName() + " and message " - + _originalException.getMessage()); + /** + * Method getMsgID + * + * @return the messageId + */ + public String getMsgID() { + if (msgID == null) { + return "Missing message ID"; + } + return msgID; + } - this.originalException = _originalException; - } + /** @inheritDoc */ + public String toString() { + String s = this.getClass().getName(); + String message = super.getLocalizedMessage(); - /** - * Constructor XMLSecurityRuntimeException - * - * @param _msgID - * @param _originalException - */ - public XMLSecurityRuntimeException(String _msgID, Exception _originalException) { + if (message != null) { + message = s + ": " + message; + } else { + message = s; + } - super(I18n.getExceptionMessage(_msgID, _originalException)); + if (this.getCause() != null) { + message = message + "\nOriginal Exception was " + this.getCause().toString(); + } - this.msgID = _msgID; - this.originalException = _originalException; - } + return message; + } - /** - * Constructor XMLSecurityRuntimeException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public XMLSecurityRuntimeException(String _msgID, Object exArgs[], - Exception _originalException) { + /** + * Method printStackTrace + * + */ + public void printStackTrace() { + synchronized (System.err) { + super.printStackTrace(System.err); + } + } - super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs)); + /** + * Method printStackTrace + * + * @param printwriter + */ + public void printStackTrace(PrintWriter printwriter) { + super.printStackTrace(printwriter); + } - this.msgID = _msgID; - this.originalException = _originalException; - } + /** + * Method printStackTrace + * + * @param printstream + */ + public void printStackTrace(PrintStream printstream) { + super.printStackTrace(printstream); + } - /** - * Method getMsgID - * - * @return the messageId - */ - public String getMsgID() { + /** + * Method getOriginalException + * + * @return the original exception + */ + public Exception getOriginalException() { + if (this.getCause() instanceof Exception) { + return (Exception)this.getCause(); + } + return null; + } - if (msgID == null) { - return "Missing message ID"; - } - return msgID; - } - - /** @inheritDoc */ - public String toString() { - - String s = this.getClass().getName(); - String message = super.getLocalizedMessage(); - - if (message != null) { - message = s + ": " + message; - } else { - message = s; - } - - if (originalException != null) { - message = message + "\nOriginal Exception was " - + originalException.toString(); - } - - return message; - } - - /** - * Method printStackTrace - * - */ - public void printStackTrace() { - - synchronized (System.err) { - super.printStackTrace(System.err); - - if (this.originalException != null) { - this.originalException.printStackTrace(System.err); - } - } - } - - /** - * Method printStackTrace - * - * @param printwriter - */ - public void printStackTrace(PrintWriter printwriter) { - - super.printStackTrace(printwriter); - - if (this.originalException != null) { - this.originalException.printStackTrace(printwriter); - } - } - - /** - * Method printStackTrace - * - * @param printstream - */ - public void printStackTrace(PrintStream printstream) { - - super.printStackTrace(printstream); - - if (this.originalException != null) { - this.originalException.printStackTrace(printstream); - } - } - - /** - * Method getOriginalException - * - * @return the original exception - */ - public Exception getOriginalException() { - return originalException; - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java index 6477d9bba2c..ad807c2d862 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java @@ -2,89 +2,83 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +public class ContentHandlerAlreadyRegisteredException extends XMLSecurityException { -/** - * - * @author $Author: mullan $ - */ -public class ContentHandlerAlreadyRegisteredException - extends XMLSecurityException { + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * Constructor ContentHandlerAlreadyRegisteredException + * + */ + public ContentHandlerAlreadyRegisteredException() { + super(); + } - /** - * Constructor ContentHandlerAlreadyRegisteredException - * - */ - public ContentHandlerAlreadyRegisteredException() { - super(); - } + /** + * Constructor ContentHandlerAlreadyRegisteredException + * + * @param msgID + */ + public ContentHandlerAlreadyRegisteredException(String msgID) { + super(msgID); + } - /** - * Constructor ContentHandlerAlreadyRegisteredException - * - * @param _msgID - */ - public ContentHandlerAlreadyRegisteredException(String _msgID) { - super(_msgID); - } + /** + * Constructor ContentHandlerAlreadyRegisteredException + * + * @param msgID + * @param exArgs + */ + public ContentHandlerAlreadyRegisteredException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor ContentHandlerAlreadyRegisteredException - * - * @param _msgID - * @param exArgs - */ - public ContentHandlerAlreadyRegisteredException(String _msgID, - Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor ContentHandlerAlreadyRegisteredException + * + * @param msgID + * @param originalException + */ + public ContentHandlerAlreadyRegisteredException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor ContentHandlerAlreadyRegisteredException - * - * @param _msgID - * @param _originalException - */ - public ContentHandlerAlreadyRegisteredException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor ContentHandlerAlreadyRegisteredException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public ContentHandlerAlreadyRegisteredException( + String msgID, Object exArgs[], Exception originalException + ) { + super(msgID, exArgs, originalException); + } - /** - * Constructor ContentHandlerAlreadyRegisteredException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public ContentHandlerAlreadyRegisteredException(String _msgID, - Object exArgs[], Exception _originalException) { - super(_msgID, exArgs, _originalException); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java index 3c273dea7ac..6716d80d899 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java @@ -2,30 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys; - - +import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.X509Certificate; import java.util.ArrayList; -import java.util.Collections; import java.util.Iterator; import java.util.List; @@ -35,6 +35,8 @@ import com.sun.org.apache.xml.internal.security.encryption.EncryptedKey; import com.sun.org.apache.xml.internal.security.encryption.XMLCipher; import com.sun.org.apache.xml.internal.security.encryption.XMLEncryptionException; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.keys.content.DEREncodedKeyValue; +import com.sun.org.apache.xml.internal.security.keys.content.KeyInfoReference; import com.sun.org.apache.xml.internal.security.keys.content.KeyName; import com.sun.org.apache.xml.internal.security.keys.content.KeyValue; import com.sun.org.apache.xml.internal.security.keys.content.MgmtData; @@ -49,9 +51,8 @@ import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverExce import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; import com.sun.org.apache.xml.internal.security.transforms.Transforms; -import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants; import com.sun.org.apache.xml.internal.security.utils.Constants; -import com.sun.org.apache.xml.internal.security.utils.IdResolver; +import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Attr; @@ -60,7 +61,6 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; - /** * This class stand for KeyInfo Element that may contain keys, names, * certificates and other public key management information, @@ -91,639 +91,769 @@ import org.w3c.dom.NodeList; * The containsXXX() methods return whether the KeyInfo * contains the corresponding type. * - * @author $Author: mullan $ */ public class KeyInfo extends SignatureElementProxy { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(KeyInfo.class.getName()); - List x509Datas=null; - List encryptedKeys=null; - static final List nullList; + // We need at least one StorageResolver otherwise + // the KeyResolvers would not be called. + // The default StorageResolver is null. + + private List x509Datas = null; + private List encryptedKeys = null; + + private static final List nullList; static { List list = new ArrayList(1); list.add(null); - nullList = Collections.unmodifiableList(list); + nullList = java.util.Collections.unmodifiableList(list); } - /** - * Constructor KeyInfo - * @param doc - */ - public KeyInfo(Document doc) { - - super(doc); - - XMLUtils.addReturnToElement(this._constructionElement); - - } - - /** - * Constructor KeyInfo - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public KeyInfo(Element element, String BaseURI) throws XMLSecurityException { - super(element, BaseURI); - - Attr attr = element.getAttributeNodeNS(null, "Id"); - if (attr != null) { - element.setIdAttributeNode(attr, true); - } - } - - /** - * Sets the Id attribute - * - * @param Id ID - */ - public void setId(String Id) { - - if (Id != null) { - setLocalIdAttribute(Constants._ATT_ID, Id); - } - } - - /** - * Returns the Id attribute - * - * @return the Id attribute - */ - public String getId() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ID); - } - - /** - * Method addKeyName - * - * @param keynameString - */ - public void addKeyName(String keynameString) { - this.add(new KeyName(this._doc, keynameString)); - } - - /** - * Method add - * - * @param keyname - */ - public void add(KeyName keyname) { - - this._constructionElement.appendChild(keyname.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addKeyValue - * - * @param pk - */ - public void addKeyValue(PublicKey pk) { - this.add(new KeyValue(this._doc, pk)); - } - - /** - * Method addKeyValue - * - * @param unknownKeyValueElement - */ - public void addKeyValue(Element unknownKeyValueElement) { - this.add(new KeyValue(this._doc, unknownKeyValueElement)); - } - - /** - * Method add - * - * @param dsakeyvalue - */ - public void add(DSAKeyValue dsakeyvalue) { - this.add(new KeyValue(this._doc, dsakeyvalue)); - } - - /** - * Method add - * - * @param rsakeyvalue - */ - public void add(RSAKeyValue rsakeyvalue) { - this.add(new KeyValue(this._doc, rsakeyvalue)); - } - - /** - * Method add - * - * @param pk - */ - public void add(PublicKey pk) { - this.add(new KeyValue(this._doc, pk)); - } - - /** - * Method add - * - * @param keyvalue - */ - public void add(KeyValue keyvalue) { - this._constructionElement.appendChild(keyvalue.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addMgmtData - * - * @param mgmtdata - */ - public void addMgmtData(String mgmtdata) { - this.add(new MgmtData(this._doc, mgmtdata)); - } - - /** - * Method add - * - * @param mgmtdata - */ - public void add(MgmtData mgmtdata) { - this._constructionElement.appendChild(mgmtdata.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addPGPData - * - * @param pgpdata - */ - public void add(PGPData pgpdata) { - this._constructionElement.appendChild(pgpdata.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addRetrievalMethod - * - * @param URI - * @param transforms - * @param Type - */ - public void addRetrievalMethod(String URI, Transforms transforms, - String Type) { - this.add(new RetrievalMethod(this._doc, URI, transforms, Type)); - } - - /** - * Method add - * - * @param retrievalmethod - */ - public void add(RetrievalMethod retrievalmethod) { - this._constructionElement.appendChild(retrievalmethod.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method add - * - * @param spkidata - */ - public void add(SPKIData spkidata) { - this._constructionElement.appendChild(spkidata.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addX509Data - * - * @param x509data - */ - public void add(X509Data x509data) { - if (x509Datas==null) - x509Datas=new ArrayList(); - x509Datas.add(x509data); - this._constructionElement.appendChild(x509data.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addEncryptedKey - * - * @param encryptedKey - * @throws XMLEncryptionException - */ - - public void add(EncryptedKey encryptedKey) - throws XMLEncryptionException { - if (encryptedKeys==null) - encryptedKeys=new ArrayList(); - encryptedKeys.add(encryptedKey); - XMLCipher cipher = XMLCipher.getInstance(); - this._constructionElement.appendChild(cipher.martial(encryptedKey)); - } - - /** - * Method addUnknownElement - * - * @param element - */ - public void addUnknownElement(Element element) { - this._constructionElement.appendChild(element); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method lengthKeyName - * - * @return the number of the KeyName tags - */ - public int lengthKeyName() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_KEYNAME); - } - - /** - * Method lengthKeyValue - * - *@return the number of the KeyValue tags - */ - public int lengthKeyValue() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_KEYVALUE); - } - - /** - * Method lengthMgmtData - * - *@return the number of the MgmtData tags - */ - public int lengthMgmtData() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_MGMTDATA); - } - - /** - * Method lengthPGPData - * - *@return the number of the PGPDat. tags - */ - public int lengthPGPData() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_PGPDATA); - } - - /** - * Method lengthRetrievalMethod - * - *@return the number of the RetrievalMethod tags - */ - public int lengthRetrievalMethod() { - return this.length(Constants.SignatureSpecNS, - Constants._TAG_RETRIEVALMETHOD); - } - - /** - * Method lengthSPKIData - * - *@return the number of the SPKIData tags - */ - public int lengthSPKIData() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_SPKIDATA); - } - - /** - * Method lengthX509Data - * - *@return the number of the X509Data tags - */ - public int lengthX509Data() { - if (x509Datas!=null) { - return x509Datas.size(); - } - return this.length(Constants.SignatureSpecNS, Constants._TAG_X509DATA); - } - - /** - * Method lengthUnknownElement - * NOTE posibly buggy. - *@return the number of the UnknownElement tags - */ - public int lengthUnknownElement() { - - int res = 0; - NodeList nl = this._constructionElement.getChildNodes(); - - for (int i = 0; i < nl.getLength(); i++) { - Node current = nl.item(i); - - /** - * $todo$ using this method, we don't see unknown Elements - * from Signature NS; revisit - */ - if ((current.getNodeType() == Node.ELEMENT_NODE) - && current.getNamespaceURI() - .equals(Constants.SignatureSpecNS)) { - res++; - } - } - - return res; - } - - /** - * Method itemKeyName - * - * @param i - * @return the asked KeyName element, null if the index is too big - * @throws XMLSecurityException - */ - public KeyName itemKeyName(int i) throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_KEYNAME,i); - - if (e != null) { - return new KeyName(e, this._baseURI); - } - return null; - } - - /** - * Method itemKeyValue - * - * @param i - * @return the asked KeyValue element, null if the index is too big - * @throws XMLSecurityException - */ - public KeyValue itemKeyValue(int i) throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_KEYVALUE,i); - - if (e != null) { - return new KeyValue(e, this._baseURI); - } - return null; - } - - /** - * Method itemMgmtData - * - * @param i - *@return the asked MgmtData element, null if the index is too big - * @throws XMLSecurityException - */ - public MgmtData itemMgmtData(int i) throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_MGMTDATA,i); - - if (e != null) { - return new MgmtData(e, this._baseURI); - } - return null; - } - - /** - * Method itemPGPData - * - * @param i - *@return the asked PGPData element, null if the index is too big - * @throws XMLSecurityException - */ - public PGPData itemPGPData(int i) throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_PGPDATA,i); - - if (e != null) { - return new PGPData(e, this._baseURI); - } - return null; - } - - /** - * Method itemRetrievalMethod - * - * @param i - *@return the asked RetrievalMethod element, null if the index is too big - * @throws XMLSecurityException - */ - public RetrievalMethod itemRetrievalMethod(int i) - throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_RETRIEVALMETHOD,i); - - if (e != null) { - return new RetrievalMethod(e, this._baseURI); - } - return null; - } - - /** - * Method itemSPKIData - * - * @param i - *@return the asked SPKIData element, null if the index is too big - * @throws XMLSecurityException - */ - public SPKIData itemSPKIData(int i) throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_SPKIDATA,i); - - if (e != null) { - return new SPKIData(e, this._baseURI); - } - return null; - } - - /** - * Method itemX509Data - *@return the asked X509Data element, null if the index is too big - * @param i - * - * @throws XMLSecurityException - */ - public X509Data itemX509Data(int i) throws XMLSecurityException { - if (x509Datas!=null) { - return x509Datas.get(i); - } - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_X509DATA,i); - - if (e != null) { - return new X509Data(e, this._baseURI); - } - return null; - } - - /** - * Method itemEncryptedKey - * - * @param i - * @return the asked EncryptedKey element, null if the index is too big - * @throws XMLSecurityException - */ - - public EncryptedKey itemEncryptedKey(int i) throws XMLSecurityException { - if (encryptedKeys!=null) { - return encryptedKeys.get(i); - } - Element e = - XMLUtils.selectXencNode(this._constructionElement.getFirstChild(), - EncryptionConstants._TAG_ENCRYPTEDKEY,i); - - if (e != null) { - XMLCipher cipher = XMLCipher.getInstance(); - cipher.init(XMLCipher.UNWRAP_MODE, null); - return cipher.loadEncryptedKey(e); - } - return null; - } - - /** - * Method itemUnknownElement - * - * @param i index - * @return the element number of the unknown elemens - */ - public Element itemUnknownElement(int i) { - - NodeList nl = this._constructionElement.getChildNodes(); - int res = 0; - - for (int j = 0; j < nl.getLength(); j++) { - Node current = nl.item(j); - - /** - * $todo$ using this method, we don't see unknown Elements - * from Signature NS; revisit - */ - if ((current.getNodeType() == Node.ELEMENT_NODE) - && current.getNamespaceURI() - .equals(Constants.SignatureSpecNS)) { - res++; - - if (res == i) { - return (Element) current; - } - } - } - - return null; - } - - /** - * Method isEmpty - * - * @return true if the element has no descedants. - */ - public boolean isEmpty() { - return this._constructionElement.getFirstChild()==null; - } - - /** - * Method containsKeyName - * - * @return If the KeyInfo contains a KeyName node - */ - public boolean containsKeyName() { - return this.lengthKeyName() > 0; - } - - /** - * Method containsKeyValue - * - * @return If the KeyInfo contains a KeyValue node - */ - public boolean containsKeyValue() { - return this.lengthKeyValue() > 0; - } - - /** - * Method containsMgmtData - * - * @return If the KeyInfo contains a MgmtData node - */ - public boolean containsMgmtData() { - return this.lengthMgmtData() > 0; - } - - /** - * Method containsPGPData - * - * @return If the KeyInfo contains a PGPData node - */ - public boolean containsPGPData() { - return this.lengthPGPData() > 0; - } - - /** - * Method containsRetrievalMethod - * - * @return If the KeyInfo contains a RetrievalMethod node - */ - public boolean containsRetrievalMethod() { - return this.lengthRetrievalMethod() > 0; - } - - /** - * Method containsSPKIData - * - * @return If the KeyInfo contains a SPKIData node - */ - public boolean containsSPKIData() { - return this.lengthSPKIData() > 0; - } - - /** - * Method containsUnknownElement - * - * @return If the KeyInfo contains a UnknownElement node - */ - public boolean containsUnknownElement() { - return this.lengthUnknownElement() > 0; - } - - /** - * Method containsX509Data - * - * @return If the KeyInfo contains a X509Data node - */ - public boolean containsX509Data() { - return this.lengthX509Data() > 0; - } - - /** - * This method returns the public key. - * - * @return If the KeyInfo contains a PublicKey node - * @throws KeyResolverException - */ - - public PublicKey getPublicKey() throws KeyResolverException { - - PublicKey pk = this.getPublicKeyFromInternalResolvers(); - - if (pk != null) { - log.log(java.util.logging.Level.FINE, "I could find a key using the per-KeyInfo key resolvers"); - - return pk; - } - log.log(java.util.logging.Level.FINE, "I couldn't find a key using the per-KeyInfo key resolvers"); - - pk = this.getPublicKeyFromStaticResolvers(); - - if (pk != null) { - log.log(java.util.logging.Level.FINE, "I could find a key using the system-wide key resolvers"); - - return pk; - } - log.log(java.util.logging.Level.FINE, "I couldn't find a key using the system-wide key resolvers"); - - return null; - } + /** Field storageResolvers */ + private List storageResolvers = nullList; /** - * Searches the library wide keyresolvers for public keys + * Stores the individual (per-KeyInfo) {@link KeyResolverSpi}s + */ + private List internalKeyResolvers = new ArrayList(); + + private boolean secureValidation; + + /** + * Constructor KeyInfo + * @param doc + */ + public KeyInfo(Document doc) { + super(doc); + + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Constructor KeyInfo + * + * @param element + * @param baseURI + * @throws XMLSecurityException + */ + public KeyInfo(Element element, String baseURI) throws XMLSecurityException { + super(element, baseURI); + + Attr attr = element.getAttributeNodeNS(null, "Id"); + if (attr != null) { + element.setIdAttributeNode(attr, true); + } + } + + /** + * Set whether secure processing is enabled or not. The default is false. + */ + public void setSecureValidation(boolean secureValidation) { + this.secureValidation = secureValidation; + } + + /** + * Sets the Id attribute + * + * @param Id ID + */ + public void setId(String id) { + if (id != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id); + this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true); + } + } + + /** + * Returns the Id attribute + * + * @return the Id attribute + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } + + /** + * Method addKeyName + * + * @param keynameString + */ + public void addKeyName(String keynameString) { + this.add(new KeyName(this.doc, keynameString)); + } + + /** + * Method add + * + * @param keyname + */ + public void add(KeyName keyname) { + this.constructionElement.appendChild(keyname.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addKeyValue + * + * @param pk + */ + public void addKeyValue(PublicKey pk) { + this.add(new KeyValue(this.doc, pk)); + } + + /** + * Method addKeyValue + * + * @param unknownKeyValueElement + */ + public void addKeyValue(Element unknownKeyValueElement) { + this.add(new KeyValue(this.doc, unknownKeyValueElement)); + } + + /** + * Method add + * + * @param dsakeyvalue + */ + public void add(DSAKeyValue dsakeyvalue) { + this.add(new KeyValue(this.doc, dsakeyvalue)); + } + + /** + * Method add + * + * @param rsakeyvalue + */ + public void add(RSAKeyValue rsakeyvalue) { + this.add(new KeyValue(this.doc, rsakeyvalue)); + } + + /** + * Method add + * + * @param pk + */ + public void add(PublicKey pk) { + this.add(new KeyValue(this.doc, pk)); + } + + /** + * Method add + * + * @param keyvalue + */ + public void add(KeyValue keyvalue) { + this.constructionElement.appendChild(keyvalue.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addMgmtData + * + * @param mgmtdata + */ + public void addMgmtData(String mgmtdata) { + this.add(new MgmtData(this.doc, mgmtdata)); + } + + /** + * Method add + * + * @param mgmtdata + */ + public void add(MgmtData mgmtdata) { + this.constructionElement.appendChild(mgmtdata.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addPGPData + * + * @param pgpdata + */ + public void add(PGPData pgpdata) { + this.constructionElement.appendChild(pgpdata.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addRetrievalMethod + * + * @param uri + * @param transforms + * @param Type + */ + public void addRetrievalMethod(String uri, Transforms transforms, String Type) { + this.add(new RetrievalMethod(this.doc, uri, transforms, Type)); + } + + /** + * Method add + * + * @param retrievalmethod + */ + public void add(RetrievalMethod retrievalmethod) { + this.constructionElement.appendChild(retrievalmethod.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method add + * + * @param spkidata + */ + public void add(SPKIData spkidata) { + this.constructionElement.appendChild(spkidata.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addX509Data + * + * @param x509data + */ + public void add(X509Data x509data) { + if (x509Datas == null) { + x509Datas = new ArrayList(); + } + x509Datas.add(x509data); + this.constructionElement.appendChild(x509data.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addEncryptedKey + * + * @param encryptedKey + * @throws XMLEncryptionException + */ + + public void add(EncryptedKey encryptedKey) throws XMLEncryptionException { + if (encryptedKeys == null) { + encryptedKeys = new ArrayList(); + } + encryptedKeys.add(encryptedKey); + XMLCipher cipher = XMLCipher.getInstance(); + this.constructionElement.appendChild(cipher.martial(encryptedKey)); + } + + /** + * Method addDEREncodedKeyValue + * + * @param pk + * @throws XMLSecurityException + */ + public void addDEREncodedKeyValue(PublicKey pk) throws XMLSecurityException { + this.add(new DEREncodedKeyValue(this.doc, pk)); + } + + /** + * Method add + * + * @param derEncodedKeyValue + */ + public void add(DEREncodedKeyValue derEncodedKeyValue) { + this.constructionElement.appendChild(derEncodedKeyValue.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addKeyInfoReference + * + * @param URI + * @throws XMLSecurityException + */ + public void addKeyInfoReference(String URI) throws XMLSecurityException { + this.add(new KeyInfoReference(this.doc, URI)); + } + + /** + * Method add + * + * @param keyInfoReference + */ + public void add(KeyInfoReference keyInfoReference) { + this.constructionElement.appendChild(keyInfoReference.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addUnknownElement + * + * @param element + */ + public void addUnknownElement(Element element) { + this.constructionElement.appendChild(element); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method lengthKeyName + * + * @return the number of the KeyName tags + */ + public int lengthKeyName() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_KEYNAME); + } + + /** + * Method lengthKeyValue + * + *@return the number of the KeyValue tags + */ + public int lengthKeyValue() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_KEYVALUE); + } + + /** + * Method lengthMgmtData + * + *@return the number of the MgmtData tags + */ + public int lengthMgmtData() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_MGMTDATA); + } + + /** + * Method lengthPGPData + * + *@return the number of the PGPDat. tags + */ + public int lengthPGPData() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_PGPDATA); + } + + /** + * Method lengthRetrievalMethod + * + *@return the number of the RetrievalMethod tags + */ + public int lengthRetrievalMethod() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_RETRIEVALMETHOD); + } + + /** + * Method lengthSPKIData + * + *@return the number of the SPKIData tags + */ + public int lengthSPKIData() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_SPKIDATA); + } + + /** + * Method lengthX509Data + * + *@return the number of the X509Data tags + */ + public int lengthX509Data() { + if (x509Datas != null) { + return x509Datas.size(); + } + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509DATA); + } + + /** + * Method lengthDEREncodedKeyValue + * + *@return the number of the DEREncodedKeyValue tags + */ + public int lengthDEREncodedKeyValue() { + return this.length(Constants.SignatureSpec11NS, Constants._TAG_DERENCODEDKEYVALUE); + } + + /** + * Method lengthKeyInfoReference + * + *@return the number of the KeyInfoReference tags + */ + public int lengthKeyInfoReference() { + return this.length(Constants.SignatureSpec11NS, Constants._TAG_KEYINFOREFERENCE); + } + + /** + * Method lengthUnknownElement + * NOTE possibly buggy. + * @return the number of the UnknownElement tags + */ + public int lengthUnknownElement() { + int res = 0; + NodeList nl = this.constructionElement.getChildNodes(); + + for (int i = 0; i < nl.getLength(); i++) { + Node current = nl.item(i); + + /** + * $todo$ using this method, we don't see unknown Elements + * from Signature NS; revisit + */ + if ((current.getNodeType() == Node.ELEMENT_NODE) + && current.getNamespaceURI().equals(Constants.SignatureSpecNS)) { + res++; + } + } + + return res; + } + + /** + * Method itemKeyName + * + * @param i + * @return the asked KeyName element, null if the index is too big + * @throws XMLSecurityException + */ + public KeyName itemKeyName(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_KEYNAME, i); + + if (e != null) { + return new KeyName(e, this.baseURI); + } + return null; + } + + /** + * Method itemKeyValue + * + * @param i + * @return the asked KeyValue element, null if the index is too big + * @throws XMLSecurityException + */ + public KeyValue itemKeyValue(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_KEYVALUE, i); + + if (e != null) { + return new KeyValue(e, this.baseURI); + } + return null; + } + + /** + * Method itemMgmtData + * + * @param i + * @return the asked MgmtData element, null if the index is too big + * @throws XMLSecurityException + */ + public MgmtData itemMgmtData(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_MGMTDATA, i); + + if (e != null) { + return new MgmtData(e, this.baseURI); + } + return null; + } + + /** + * Method itemPGPData + * + * @param i + * @return the asked PGPData element, null if the index is too big + * @throws XMLSecurityException + */ + public PGPData itemPGPData(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_PGPDATA, i); + + if (e != null) { + return new PGPData(e, this.baseURI); + } + return null; + } + + /** + * Method itemRetrievalMethod + * + * @param i + *@return the asked RetrievalMethod element, null if the index is too big + * @throws XMLSecurityException + */ + public RetrievalMethod itemRetrievalMethod(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_RETRIEVALMETHOD, i); + + if (e != null) { + return new RetrievalMethod(e, this.baseURI); + } + return null; + } + + /** + * Method itemSPKIData + * + * @param i + * @return the asked SPKIData element, null if the index is too big + * @throws XMLSecurityException + */ + public SPKIData itemSPKIData(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_SPKIDATA, i); + + if (e != null) { + return new SPKIData(e, this.baseURI); + } + return null; + } + + /** + * Method itemX509Data + * + * @param i + * @return the asked X509Data element, null if the index is too big + * @throws XMLSecurityException + */ + public X509Data itemX509Data(int i) throws XMLSecurityException { + if (x509Datas != null) { + return x509Datas.get(i); + } + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509DATA, i); + + if (e != null) { + return new X509Data(e, this.baseURI); + } + return null; + } + + /** + * Method itemEncryptedKey + * + * @param i + * @return the asked EncryptedKey element, null if the index is too big + * @throws XMLSecurityException + */ + public EncryptedKey itemEncryptedKey(int i) throws XMLSecurityException { + if (encryptedKeys != null) { + return encryptedKeys.get(i); + } + Element e = + XMLUtils.selectXencNode( + this.constructionElement.getFirstChild(), EncryptionConstants._TAG_ENCRYPTEDKEY, i); + + if (e != null) { + XMLCipher cipher = XMLCipher.getInstance(); + cipher.init(XMLCipher.UNWRAP_MODE, null); + return cipher.loadEncryptedKey(e); + } + return null; + } + + /** + * Method itemDEREncodedKeyValue + * + * @param i + * @return the asked DEREncodedKeyValue element, null if the index is too big + * @throws XMLSecurityException + */ + public DEREncodedKeyValue itemDEREncodedKeyValue(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDs11Node( + this.constructionElement.getFirstChild(), Constants._TAG_DERENCODEDKEYVALUE, i); + + if (e != null) { + return new DEREncodedKeyValue(e, this.baseURI); + } + return null; + } + + /** + * Method itemKeyInfoReference + * + * @param i + * @return the asked KeyInfoReference element, null if the index is too big + * @throws XMLSecurityException + */ + public KeyInfoReference itemKeyInfoReference(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDs11Node( + this.constructionElement.getFirstChild(), Constants._TAG_KEYINFOREFERENCE, i); + + if (e != null) { + return new KeyInfoReference(e, this.baseURI); + } + return null; + } + + /** + * Method itemUnknownElement + * + * @param i index + * @return the element number of the unknown elements + */ + public Element itemUnknownElement(int i) { + NodeList nl = this.constructionElement.getChildNodes(); + int res = 0; + + for (int j = 0; j < nl.getLength(); j++) { + Node current = nl.item(j); + + /** + * $todo$ using this method, we don't see unknown Elements + * from Signature NS; revisit + */ + if ((current.getNodeType() == Node.ELEMENT_NODE) + && current.getNamespaceURI().equals(Constants.SignatureSpecNS)) { + res++; + + if (res == i) { + return (Element) current; + } + } + } + + return null; + } + + /** + * Method isEmpty + * + * @return true if the element has no descendants. + */ + public boolean isEmpty() { + return this.constructionElement.getFirstChild() == null; + } + + /** + * Method containsKeyName + * + * @return If the KeyInfo contains a KeyName node + */ + public boolean containsKeyName() { + return this.lengthKeyName() > 0; + } + + /** + * Method containsKeyValue + * + * @return If the KeyInfo contains a KeyValue node + */ + public boolean containsKeyValue() { + return this.lengthKeyValue() > 0; + } + + /** + * Method containsMgmtData + * + * @return If the KeyInfo contains a MgmtData node + */ + public boolean containsMgmtData() { + return this.lengthMgmtData() > 0; + } + + /** + * Method containsPGPData + * + * @return If the KeyInfo contains a PGPData node + */ + public boolean containsPGPData() { + return this.lengthPGPData() > 0; + } + + /** + * Method containsRetrievalMethod + * + * @return If the KeyInfo contains a RetrievalMethod node + */ + public boolean containsRetrievalMethod() { + return this.lengthRetrievalMethod() > 0; + } + + /** + * Method containsSPKIData + * + * @return If the KeyInfo contains a SPKIData node + */ + public boolean containsSPKIData() { + return this.lengthSPKIData() > 0; + } + + /** + * Method containsUnknownElement + * + * @return If the KeyInfo contains a UnknownElement node + */ + public boolean containsUnknownElement() { + return this.lengthUnknownElement() > 0; + } + + /** + * Method containsX509Data + * + * @return If the KeyInfo contains a X509Data node + */ + public boolean containsX509Data() { + return this.lengthX509Data() > 0; + } + + /** + * Method containsDEREncodedKeyValue + * + * @return If the KeyInfo contains a DEREncodedKeyValue node + */ + public boolean containsDEREncodedKeyValue() { + return this.lengthDEREncodedKeyValue() > 0; + } + + /** + * Method containsKeyInfoReference + * + * @return If the KeyInfo contains a KeyInfoReference node + */ + public boolean containsKeyInfoReference() { + return this.lengthKeyInfoReference() > 0; + } + + /** + * This method returns the public key. + * + * @return If the KeyInfo contains a PublicKey node + * @throws KeyResolverException + */ + public PublicKey getPublicKey() throws KeyResolverException { + PublicKey pk = this.getPublicKeyFromInternalResolvers(); + + if (pk != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a key using the per-KeyInfo key resolvers"); + } + + return pk; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a key using the per-KeyInfo key resolvers"); + } + + pk = this.getPublicKeyFromStaticResolvers(); + + if (pk != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a key using the system-wide key resolvers"); + } + + return pk; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a key using the system-wide key resolvers"); + } + + return null; + } + + /** + * Searches the library wide KeyResolvers for public keys * * @return The public key contained in this Node. * @throws KeyResolverException @@ -732,11 +862,12 @@ public class KeyInfo extends SignatureElementProxy { Iterator it = KeyResolver.iterator(); while (it.hasNext()) { KeyResolverSpi keyResolver = it.next(); - Node currentChild = this._constructionElement.getFirstChild(); + keyResolver.setSecureValidation(secureValidation); + Node currentChild = this.constructionElement.getFirstChild(); String uri = this.getBaseURI(); while (currentChild != null) { if (currentChild.getNodeType() == Node.ELEMENT_NODE) { - for (StorageResolver storage : _storageResolvers) { + for (StorageResolver storage : storageResolvers) { PublicKey pk = keyResolver.engineLookupAndResolvePublicKey( (Element) currentChild, uri, storage @@ -753,78 +884,77 @@ public class KeyInfo extends SignatureElementProxy { return null; } - /** - * Searches the per-KeyInfo keyresolvers for public keys - * - * @return The publick contained in this Node. - * @throws KeyResolverException - */ - PublicKey getPublicKeyFromInternalResolvers() throws KeyResolverException { - int length=lengthInternalKeyResolver(); - int storageLength=this._storageResolvers.size(); - for (int i = 0; i < length; i++) { - KeyResolverSpi keyResolver = this.itemInternalKeyResolver(i); - if (log.isLoggable(java.util.logging.Level.FINE)) + /** + * Searches the per-KeyInfo KeyResolvers for public keys + * + * @return The public key contained in this Node. + * @throws KeyResolverException + */ + PublicKey getPublicKeyFromInternalResolvers() throws KeyResolverException { + for (KeyResolverSpi keyResolver : internalKeyResolvers) { + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName()); - - Node currentChild=this._constructionElement.getFirstChild(); - String uri=this.getBaseURI(); - while (currentChild!=null) { - if (currentChild.getNodeType() == Node.ELEMENT_NODE) { - for (int k = 0; k < storageLength; k++) { - StorageResolver storage = - this._storageResolvers.get(k); - PublicKey pk = keyResolver - .engineLookupAndResolvePublicKey((Element) currentChild, uri, storage); - - if (pk != null) { - return pk; - } - } } - currentChild=currentChild.getNextSibling(); - } - } + keyResolver.setSecureValidation(secureValidation); + Node currentChild = this.constructionElement.getFirstChild(); + String uri = this.getBaseURI(); + while (currentChild != null) { + if (currentChild.getNodeType() == Node.ELEMENT_NODE) { + for (StorageResolver storage : storageResolvers) { + PublicKey pk = + keyResolver.engineLookupAndResolvePublicKey( + (Element) currentChild, uri, storage + ); - return null; - } + if (pk != null) { + return pk; + } + } + } + currentChild = currentChild.getNextSibling(); + } + } - /** - * Method getX509Certificate - * - * @return The certificate contined in this KeyInfo - * @throws KeyResolverException - */ - public X509Certificate getX509Certificate() throws KeyResolverException { + return null; + } - // First search using the individual resolvers from the user - X509Certificate cert = this.getX509CertificateFromInternalResolvers(); + /** + * Method getX509Certificate + * + * @return The certificate contained in this KeyInfo + * @throws KeyResolverException + */ + public X509Certificate getX509Certificate() throws KeyResolverException { + // First search using the individual resolvers from the user + X509Certificate cert = this.getX509CertificateFromInternalResolvers(); - if (cert != null) { - log.log(java.util.logging.Level.FINE, - "I could find a X509Certificate using the per-KeyInfo key resolvers"); + if (cert != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a X509Certificate using the per-KeyInfo key resolvers"); + } - return cert; - } - log.log(java.util.logging.Level.FINE, - "I couldn't find a X509Certificate using the per-KeyInfo key resolvers"); + return cert; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a X509Certificate using the per-KeyInfo key resolvers"); + } + // Then use the system-wide Resolvers + cert = this.getX509CertificateFromStaticResolvers(); - // Then use the system-wide Resolvers - cert = this.getX509CertificateFromStaticResolvers(); + if (cert != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a X509Certificate using the system-wide key resolvers"); + } - if (cert != null) { - log.log(java.util.logging.Level.FINE, - "I could find a X509Certificate using the system-wide key resolvers"); + return cert; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a X509Certificate using the system-wide key resolvers"); + } - return cert; - } - log.log(java.util.logging.Level.FINE, - "I couldn't find a X509Certificate using the system-wide key resolvers"); - - - return null; - } + return null; + } /** * This method uses each System-wide {@link KeyResolver} to search the @@ -846,6 +976,7 @@ public class KeyInfo extends SignatureElementProxy { Iterator it = KeyResolver.iterator(); while (it.hasNext()) { KeyResolverSpi keyResolver = it.next(); + keyResolver.setSecureValidation(secureValidation); X509Certificate cert = applyCurrentResolver(uri, keyResolver); if (cert != null) { return cert; @@ -857,10 +988,10 @@ public class KeyInfo extends SignatureElementProxy { private X509Certificate applyCurrentResolver( String uri, KeyResolverSpi keyResolver ) throws KeyResolverException { - Node currentChild = this._constructionElement.getFirstChild(); + Node currentChild = this.constructionElement.getFirstChild(); while (currentChild != null) { if (currentChild.getNodeType() == Node.ELEMENT_NODE) { - for (StorageResolver storage : _storageResolvers) { + for (StorageResolver storage : storageResolvers) { X509Certificate cert = keyResolver.engineLookupResolveX509Certificate( (Element) currentChild, uri, storage @@ -879,7 +1010,7 @@ public class KeyInfo extends SignatureElementProxy { /** * Method getX509CertificateFromInternalResolvers * - * @return The certificate contined in this KeyInfo + * @return The certificate contained in this KeyInfo * @throws KeyResolverException */ X509Certificate getX509CertificateFromInternalResolvers() @@ -891,10 +1022,11 @@ public class KeyInfo extends SignatureElementProxy { ); } String uri = this.getBaseURI(); - for (KeyResolverSpi keyResolver : _internalKeyResolvers) { + for (KeyResolverSpi keyResolver : internalKeyResolvers) { if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName()); } + keyResolver.setSecureValidation(secureValidation); X509Certificate cert = applyCurrentResolver(uri, keyResolver); if (cert != null) { return cert; @@ -904,189 +1036,252 @@ public class KeyInfo extends SignatureElementProxy { return null; } - /** - * This method returns a secret (symmetric) key. This is for XML Encryption. - * @return the secret key contained in this KeyInfo - * @throws KeyResolverException - */ - public SecretKey getSecretKey() throws KeyResolverException { - SecretKey sk = this.getSecretKeyFromInternalResolvers(); + /** + * This method returns a secret (symmetric) key. This is for XML Encryption. + * @return the secret key contained in this KeyInfo + * @throws KeyResolverException + */ + public SecretKey getSecretKey() throws KeyResolverException { + SecretKey sk = this.getSecretKeyFromInternalResolvers(); - if (sk != null) { - log.log(java.util.logging.Level.FINE, "I could find a secret key using the per-KeyInfo key resolvers"); - - return sk; - } - log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the per-KeyInfo key resolvers"); - - - sk = this.getSecretKeyFromStaticResolvers(); - - if (sk != null) { - log.log(java.util.logging.Level.FINE, "I could find a secret key using the system-wide key resolvers"); - - return sk; - } - log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the system-wide key resolvers"); - - - return null; - } - - /** - * Searches the library wide keyresolvers for Secret keys - * - * @return the secret key contained in this KeyInfo - * @throws KeyResolverException - */ - - SecretKey getSecretKeyFromStaticResolvers() throws KeyResolverException { - final int length=KeyResolver.length(); - int storageLength=this._storageResolvers.size(); - Iterator it = KeyResolver.iterator(); - for (int i = 0; i < length; i++) { - KeyResolverSpi keyResolver = it.next(); - - Node currentChild=this._constructionElement.getFirstChild(); - String uri=this.getBaseURI(); - while (currentChild!=null) { - if (currentChild.getNodeType() == Node.ELEMENT_NODE) { - for (int k = 0; k < storageLength; k++) { - StorageResolver storage = - this._storageResolvers.get(k); - - SecretKey sk = - keyResolver.engineLookupAndResolveSecretKey((Element) currentChild, - uri, - storage); - - if (sk != null) { - return sk; - } - } + if (sk != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a secret key using the per-KeyInfo key resolvers"); } - currentChild=currentChild.getNextSibling(); - } - } - return null; - } - /** - * Searches the per-KeyInfo keyresolvers for secret keys - * - * @return the secret key contained in this KeyInfo - * @throws KeyResolverException - */ + return sk; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the per-KeyInfo key resolvers"); + } - SecretKey getSecretKeyFromInternalResolvers() throws KeyResolverException { - int storageLength=this._storageResolvers.size(); - for (int i = 0; i < this.lengthInternalKeyResolver(); i++) { - KeyResolverSpi keyResolver = this.itemInternalKeyResolver(i); - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName()); + sk = this.getSecretKeyFromStaticResolvers(); - Node currentChild=this._constructionElement.getFirstChild(); - String uri=this.getBaseURI(); - while (currentChild!=null) { - if (currentChild.getNodeType() == Node.ELEMENT_NODE) { - for (int k = 0; k < storageLength; k++) { - StorageResolver storage = - this._storageResolvers.get(k); + if (sk != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a secret key using the system-wide key resolvers"); + } - SecretKey sk = keyResolver - .engineLookupAndResolveSecretKey((Element) currentChild, uri, storage); + return sk; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the system-wide key resolvers"); + } - if (sk != null) { - return sk; - } + return null; + } + + /** + * Searches the library wide KeyResolvers for Secret keys + * + * @return the secret key contained in this KeyInfo + * @throws KeyResolverException + */ + SecretKey getSecretKeyFromStaticResolvers() throws KeyResolverException { + Iterator it = KeyResolver.iterator(); + while (it.hasNext()) { + KeyResolverSpi keyResolver = it.next(); + keyResolver.setSecureValidation(secureValidation); + + Node currentChild = this.constructionElement.getFirstChild(); + String uri = this.getBaseURI(); + while (currentChild != null) { + if (currentChild.getNodeType() == Node.ELEMENT_NODE) { + for (StorageResolver storage : storageResolvers) { + SecretKey sk = + keyResolver.engineLookupAndResolveSecretKey( + (Element) currentChild, uri, storage + ); + + if (sk != null) { + return sk; + } + } } - } - currentChild=currentChild.getNextSibling(); - } - } + currentChild = currentChild.getNextSibling(); + } + } + return null; + } - return null; - } + /** + * Searches the per-KeyInfo KeyResolvers for secret keys + * + * @return the secret key contained in this KeyInfo + * @throws KeyResolverException + */ - /** - * Stores the individual (per-KeyInfo) {@link KeyResolver}s - */ - List _internalKeyResolvers = new ArrayList(); + SecretKey getSecretKeyFromInternalResolvers() throws KeyResolverException { + for (KeyResolverSpi keyResolver : internalKeyResolvers) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName()); + } + keyResolver.setSecureValidation(secureValidation); + Node currentChild = this.constructionElement.getFirstChild(); + String uri = this.getBaseURI(); + while (currentChild != null) { + if (currentChild.getNodeType() == Node.ELEMENT_NODE) { + for (StorageResolver storage : storageResolvers) { + SecretKey sk = + keyResolver.engineLookupAndResolveSecretKey( + (Element) currentChild, uri, storage + ); - /** - * This method is used to add a custom {@link KeyResolverSpi} to a KeyInfo - * object. - * - * @param realKeyResolver - */ - public void registerInternalKeyResolver(KeyResolverSpi realKeyResolver) { - if (_internalKeyResolvers==null) { - _internalKeyResolvers=new ArrayList(); - } - this._internalKeyResolvers.add(realKeyResolver); - } + if (sk != null) { + return sk; + } + } + } + currentChild = currentChild.getNextSibling(); + } + } - /** - * Method lengthInternalKeyResolver - * @return the length of the key - */ - int lengthInternalKeyResolver() { - if (_internalKeyResolvers==null) - return 0; - return this._internalKeyResolvers.size(); - } + return null; + } - /** - * Method itemInternalKeyResolver - * - * @param i the index - * @return the KeyResolverSpi for the index. - */ - KeyResolverSpi itemInternalKeyResolver(int i) { - return this._internalKeyResolvers.get(i); - } + /** + * This method returns a private key. This is for Key Transport in XML Encryption. + * @return the private key contained in this KeyInfo + * @throws KeyResolverException + */ + public PrivateKey getPrivateKey() throws KeyResolverException { + PrivateKey pk = this.getPrivateKeyFromInternalResolvers(); - /** Field _storageResolvers */ - private List _storageResolvers = nullList; + if (pk != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a private key using the per-KeyInfo key resolvers"); + } + return pk; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the per-KeyInfo key resolvers"); + } - /** - * Method addStorageResolver - * - * @param storageResolver - */ - public void addStorageResolver(StorageResolver storageResolver) { - if (_storageResolvers == nullList ){ - _storageResolvers=new ArrayList(); - } - this._storageResolvers.add(storageResolver); + pk = this.getPrivateKeyFromStaticResolvers(); + if (pk != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a private key using the system-wide key resolvers"); + } + return pk; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a private key using the system-wide key resolvers"); + } - } + return null; + } - //J- - static boolean _alreadyInitialized = false; - /** init the keyinfo (Still needed?)*/ - public static void init() { + /** + * Searches the library wide KeyResolvers for Private keys + * + * @return the private key contained in this KeyInfo + * @throws KeyResolverException + */ + PrivateKey getPrivateKeyFromStaticResolvers() throws KeyResolverException { + Iterator it = KeyResolver.iterator(); + while (it.hasNext()) { + KeyResolverSpi keyResolver = it.next(); + keyResolver.setSecureValidation(secureValidation); - if (!KeyInfo._alreadyInitialized) { - if (KeyInfo.log == null) { + Node currentChild = this.constructionElement.getFirstChild(); + String uri = this.getBaseURI(); + while (currentChild != null) { + if (currentChild.getNodeType() == Node.ELEMENT_NODE) { + // not using StorageResolvers at the moment + // since they cannot return private keys + PrivateKey pk = + keyResolver.engineLookupAndResolvePrivateKey( + (Element) currentChild, uri, null + ); - /** - * $todo$ why the hell does the static initialization from the - * start not work ? - */ - KeyInfo.log = - java.util.logging.Logger.getLogger(KeyInfo.class.getName()); + if (pk != null) { + return pk; + } + } + currentChild = currentChild.getNextSibling(); + } + } + return null; + } - log.log(java.util.logging.Level.SEVERE, "Had to assign log in the init() function"); - } + /** + * Searches the per-KeyInfo KeyResolvers for private keys + * + * @return the private key contained in this KeyInfo + * @throws KeyResolverException + */ + PrivateKey getPrivateKeyFromInternalResolvers() throws KeyResolverException { + for (KeyResolverSpi keyResolver : internalKeyResolvers) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName()); + } + keyResolver.setSecureValidation(secureValidation); + Node currentChild = this.constructionElement.getFirstChild(); + String uri = this.getBaseURI(); + while (currentChild != null) { + if (currentChild.getNodeType() == Node.ELEMENT_NODE) { + // not using StorageResolvers at the moment + // since they cannot return private keys + PrivateKey pk = + keyResolver.engineLookupAndResolvePrivateKey( + (Element) currentChild, uri, null + ); - // KeyInfo._contentHandlerHash = new HashMap(10); - KeyInfo._alreadyInitialized = true; - } - } + if (pk != null) { + return pk; + } + } + currentChild = currentChild.getNextSibling(); + } + } - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_KEYINFO; - } + return null; + } + + /** + * This method is used to add a custom {@link KeyResolverSpi} to a KeyInfo + * object. + * + * @param realKeyResolver + */ + public void registerInternalKeyResolver(KeyResolverSpi realKeyResolver) { + this.internalKeyResolvers.add(realKeyResolver); + } + + /** + * Method lengthInternalKeyResolver + * @return the length of the key + */ + int lengthInternalKeyResolver() { + return this.internalKeyResolvers.size(); + } + + /** + * Method itemInternalKeyResolver + * + * @param i the index + * @return the KeyResolverSpi for the index. + */ + KeyResolverSpi itemInternalKeyResolver(int i) { + return this.internalKeyResolvers.get(i); + } + + /** + * Method addStorageResolver + * + * @param storageResolver + */ + public void addStorageResolver(StorageResolver storageResolver) { + if (storageResolvers == nullList) { + // Replace the default null StorageResolver + storageResolvers = new ArrayList(); + } + this.storageResolvers.add(storageResolver); + } + + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_KEYINFO; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java index 67ce204efba..8613c8197b7 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys; - - import java.io.PrintStream; import java.security.PublicKey; @@ -31,57 +31,53 @@ import com.sun.org.apache.xml.internal.security.keys.content.KeyValue; import com.sun.org.apache.xml.internal.security.keys.content.MgmtData; import com.sun.org.apache.xml.internal.security.keys.content.X509Data; - /** * Utility class for for com.sun.org.apache.xml.internal.security.keys package. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class KeyUtils { - private KeyUtils() { - // no instantiation - } + private KeyUtils() { + // no instantiation + } - /** - * Method prinoutKeyInfo - * - * @param ki - * @param os - * @throws XMLSecurityException - */ - public static void prinoutKeyInfo(KeyInfo ki, PrintStream os) - throws XMLSecurityException { + /** + * Method prinoutKeyInfo + * + * @param ki + * @param os + * @throws XMLSecurityException + */ + public static void prinoutKeyInfo(KeyInfo ki, PrintStream os) + throws XMLSecurityException { - for (int i = 0; i < ki.lengthKeyName(); i++) { - KeyName x = ki.itemKeyName(i); + for (int i = 0; i < ki.lengthKeyName(); i++) { + KeyName x = ki.itemKeyName(i); - os.println("KeyName(" + i + ")=\"" + x.getKeyName() + "\""); - } + os.println("KeyName(" + i + ")=\"" + x.getKeyName() + "\""); + } - for (int i = 0; i < ki.lengthKeyValue(); i++) { - KeyValue x = ki.itemKeyValue(i); - PublicKey pk = x.getPublicKey(); + for (int i = 0; i < ki.lengthKeyValue(); i++) { + KeyValue x = ki.itemKeyValue(i); + PublicKey pk = x.getPublicKey(); - os.println("KeyValue Nr. " + i); - os.println(pk); - } + os.println("KeyValue Nr. " + i); + os.println(pk); + } - for (int i = 0; i < ki.lengthMgmtData(); i++) { - MgmtData x = ki.itemMgmtData(i); + for (int i = 0; i < ki.lengthMgmtData(); i++) { + MgmtData x = ki.itemMgmtData(i); - os.println("MgmtData(" + i + ")=\"" + x.getMgmtData() + "\""); - } + os.println("MgmtData(" + i + ")=\"" + x.getMgmtData() + "\""); + } - for (int i = 0; i < ki.lengthX509Data(); i++) { - X509Data x = ki.itemX509Data(i); + for (int i = 0; i < ki.lengthX509Data(); i++) { + X509Data x = ki.itemX509Data(i); - os.println("X509Data(" + i + ")=\"" + (x.containsCertificate() - ? "Certificate " - : "") + (x - .containsIssuerSerial() - ? "IssuerSerial " - : "") + "\""); - } - } + os.println("X509Data(" + i + ")=\"" + (x.containsCertificate() + ? "Certificate " : "") + (x.containsIssuerSerial() + ? "IssuerSerial " : "") + "\""); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java new file mode 100644 index 00000000000..0144025216a --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java @@ -0,0 +1,158 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 com.sun.org.apache.xml.internal.security.keys.content; + +import java.security.KeyFactory; +import java.security.NoSuchAlgorithmException; +import java.security.PublicKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.X509EncodedKeySpec; + +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.Signature11ElementProxy; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * Provides content model support for the dsig11:DEREncodedKeyvalue element. + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public class DEREncodedKeyValue extends Signature11ElementProxy implements KeyInfoContent { + + /** JCA algorithm key types supported by this implementation. */ + public static final String supportedKeyTypes[] = { "RSA", "DSA", "EC"}; + + /** + * Constructor DEREncodedKeyValue + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public DEREncodedKeyValue(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } + + /** + * Constructor DEREncodedKeyValue + * + * @param doc + * @param publicKey + * @throws XMLSecurityException + */ + public DEREncodedKeyValue(Document doc, PublicKey publicKey) throws XMLSecurityException { + super(doc); + + this.addBase64Text(getEncodedDER(publicKey)); + } + + /** + * Constructor DEREncodedKeyValue + * + * @param doc + * @param base64EncodedKey + */ + public DEREncodedKeyValue(Document doc, byte[] encodedKey) { + super(doc); + + this.addBase64Text(encodedKey); + } + + /** + * Sets the Id attribute + * + * @param Id ID + */ + public void setId(String id) { + if (id != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id); + this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true); + } else { + this.constructionElement.removeAttributeNS(null, Constants._ATT_ID); + } + } + + /** + * Returns the Id attribute + * + * @return the Id attribute + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_DERENCODEDKEYVALUE; + } + + /** + * Method getPublicKey + * + * @return the public key + * @throws XMLSecurityException + */ + public PublicKey getPublicKey() throws XMLSecurityException { + byte[] encodedKey = getBytesFromTextChild(); + + // Iterate over the supported key types until one produces a public key. + for (String keyType : supportedKeyTypes) { + try { + KeyFactory keyFactory = KeyFactory.getInstance(keyType); + X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey); + PublicKey publicKey = keyFactory.generatePublic(keySpec); + if (publicKey != null) { + return publicKey; + } + } catch (NoSuchAlgorithmException e) { + // Do nothing, try the next type + } catch (InvalidKeySpecException e) { + // Do nothing, try the next type + } + } + throw new XMLSecurityException("DEREncodedKeyValue.UnsupportedEncodedKey"); + } + + /** + * Method getEncodedDER + * + * @return the public key + * @throws XMLSecurityException + */ + protected byte[] getEncodedDER(PublicKey publicKey) throws XMLSecurityException { + try { + KeyFactory keyFactory = KeyFactory.getInstance(publicKey.getAlgorithm()); + X509EncodedKeySpec keySpec = keyFactory.getKeySpec(publicKey, X509EncodedKeySpec.class); + return keySpec.getEncoded(); + } catch (NoSuchAlgorithmException e) { + Object exArgs[] = { publicKey.getAlgorithm(), publicKey.getFormat(), publicKey.getClass().getName() }; + throw new XMLSecurityException("DEREncodedKeyValue.UnsupportedPublicKey", exArgs, e); + } catch (InvalidKeySpecException e) { + Object exArgs[] = { publicKey.getAlgorithm(), publicKey.getFormat(), publicKey.getClass().getName() }; + throw new XMLSecurityException("DEREncodedKeyValue.UnsupportedPublicKey", exArgs, e); + } + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java index 4d5a7a6b975..e753f1bb4ce 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java @@ -2,32 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.content; - - - - /** - * Empty interface just to identify Elements that can be cildren of ds:KeyInfo. + * Empty interface just to identify Elements that can be children of ds:KeyInfo. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public interface KeyInfoContent { } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoReference.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoReference.java new file mode 100644 index 00000000000..f52f4a98e54 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoReference.java @@ -0,0 +1,107 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 com.sun.org.apache.xml.internal.security.keys.content; + +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.Signature11ElementProxy; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * Provides content model support for the dsig11:KeyInfoReference element. + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public class KeyInfoReference extends Signature11ElementProxy implements KeyInfoContent { + + /** + * Constructor RetrievalMethod + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public KeyInfoReference(Element element, String baseURI) throws XMLSecurityException { + super(element, baseURI); + } + + /** + * Constructor RetrievalMethod + * + * @param doc + * @param URI + */ + public KeyInfoReference(Document doc, String URI) { + super(doc); + + this.constructionElement.setAttributeNS(null, Constants._ATT_URI, URI); + } + + /** + * Method getURIAttr + * + * @return the URI attribute + */ + public Attr getURIAttr() { + return this.constructionElement.getAttributeNodeNS(null, Constants._ATT_URI); + } + + /** + * Method getURI + * + * @return URI string + */ + public String getURI() { + return this.getURIAttr().getNodeValue(); + } + + /** + * Sets the Id attribute + * + * @param Id ID + */ + public void setId(String id) { + if (id != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id); + this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true); + } else { + this.constructionElement.removeAttributeNS(null, Constants._ATT_ID); + } + } + + /** + * Returns the Id attribute + * + * @return the Id attribute + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_KEYINFOREFERENCE; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java index 6794ea67586..fbe2e0c1faf 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.content; @@ -27,46 +29,44 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; /** - * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class KeyName extends SignatureElementProxy implements KeyInfoContent { - /** - * Constructor KeyName - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public KeyName(Element element, String BaseURI) throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor KeyName + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public KeyName(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } - /** - * Constructor KeyName - * - * @param doc - * @param keyName - */ - public KeyName(Document doc, String keyName) { + /** + * Constructor KeyName + * + * @param doc + * @param keyName + */ + public KeyName(Document doc, String keyName) { + super(doc); - super(doc); + this.addText(keyName); + } - this.addText(keyName); - } + /** + * Method getKeyName + * + * @return key name + */ + public String getKeyName() { + return this.getTextFromTextChild(); + } - /** - * Method getKeyName - * - * @return key name - */ - public String getKeyName() { - return this.getTextFromTextChild(); - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_KEYNAME; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_KEYNAME; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java index 0d3ee810d23..db7a6836d56 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.content; @@ -39,7 +41,7 @@ import org.w3c.dom.Element; * keys values represented as PCDATA or element types from an external * namespace. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { @@ -50,12 +52,11 @@ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { * @param dsaKeyValue */ public KeyValue(Document doc, DSAKeyValue dsaKeyValue) { - super(doc); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(dsaKeyValue.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(dsaKeyValue.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); } /** @@ -65,12 +66,11 @@ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { * @param rsaKeyValue */ public KeyValue(Document doc, RSAKeyValue rsaKeyValue) { - super(doc); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(rsaKeyValue.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(rsaKeyValue.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); } /** @@ -80,12 +80,11 @@ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { * @param unknownKeyValue */ public KeyValue(Document doc, Element unknownKeyValue) { - super(doc); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(unknownKeyValue); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(unknownKeyValue); + XMLUtils.addReturnToElement(this.constructionElement); } /** @@ -95,21 +94,20 @@ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { * @param pk */ public KeyValue(Document doc, PublicKey pk) { - super(doc); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); if (pk instanceof java.security.interfaces.DSAPublicKey) { - DSAKeyValue dsa = new DSAKeyValue(this._doc, pk); + DSAKeyValue dsa = new DSAKeyValue(this.doc, pk); - this._constructionElement.appendChild(dsa.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); + this.constructionElement.appendChild(dsa.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); } else if (pk instanceof java.security.interfaces.RSAPublicKey) { - RSAKeyValue rsa = new RSAKeyValue(this._doc, pk); + RSAKeyValue rsa = new RSAKeyValue(this.doc, pk); - this._constructionElement.appendChild(rsa.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); + this.constructionElement.appendChild(rsa.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); } } @@ -120,8 +118,7 @@ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { * @param BaseURI * @throws XMLSecurityException */ - public KeyValue(Element element, String BaseURI) - throws XMLSecurityException { + public KeyValue(Element element, String BaseURI) throws XMLSecurityException { super(element, BaseURI); } @@ -132,22 +129,21 @@ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { * @throws XMLSecurityException */ public PublicKey getPublicKey() throws XMLSecurityException { - - Element rsa = XMLUtils.selectDsNode - (this._constructionElement.getFirstChild(), - Constants._TAG_RSAKEYVALUE,0); + Element rsa = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_RSAKEYVALUE, 0); if (rsa != null) { - RSAKeyValue kv = new RSAKeyValue(rsa, this._baseURI); + RSAKeyValue kv = new RSAKeyValue(rsa, this.baseURI); return kv.getPublicKey(); } - Element dsa = XMLUtils.selectDsNode - (this._constructionElement.getFirstChild(), - Constants._TAG_DSAKEYVALUE,0); + Element dsa = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_DSAKEYVALUE, 0); if (dsa != null) { - DSAKeyValue kv = new DSAKeyValue(dsa, this._baseURI); + DSAKeyValue kv = new DSAKeyValue(dsa, this.baseURI); return kv.getPublicKey(); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java index 185e3557170..c037ee77f7d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.content; @@ -27,47 +29,45 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; /** - * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class MgmtData extends SignatureElementProxy implements KeyInfoContent { - /** - * Constructor MgmtData - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public MgmtData(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor MgmtData + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public MgmtData(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } - /** - * Constructor MgmtData - * - * @param doc - * @param mgmtData - */ - public MgmtData(Document doc, String mgmtData) { + /** + * Constructor MgmtData + * + * @param doc + * @param mgmtData + */ + public MgmtData(Document doc, String mgmtData) { + super(doc); - super(doc); + this.addText(mgmtData); + } - this.addText(mgmtData); - } + /** + * Method getMgmtData + * + * @return the managment data + */ + public String getMgmtData() { + return this.getTextFromTextChild(); + } - /** - * Method getMgmtData - * - * @return the managment data - */ - public String getMgmtData() { - return this.getTextFromTextChild(); - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_MGMTDATA; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_MGMTDATA; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java index 010c907a8d9..e4dbbf4b091 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.content; @@ -26,25 +28,24 @@ import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import org.w3c.dom.Element; /** - * - * @author $Author: mullan $ + * @author $Author: coheigea $ * $todo$ Implement */ public class PGPData extends SignatureElementProxy implements KeyInfoContent { - /** - * Constructor PGPData - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public PGPData(Element element, String BaseURI) throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor PGPData + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public PGPData(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_PGPDATA; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_PGPDATA; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java index 3c4956b7787..5ee9041f7b1 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.content; @@ -30,118 +32,104 @@ import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; -/** - * - * @author $Author: mullan $ - */ -public class RetrievalMethod extends SignatureElementProxy - implements KeyInfoContent { +public class RetrievalMethod extends SignatureElementProxy implements KeyInfoContent { - //J- /** DSA retrieval */ - public static final String TYPE_DSA = Constants.SignatureSpecNS + "DSAKeyValue"; - /** RSA retrieval */ - public static final String TYPE_RSA = Constants.SignatureSpecNS + "RSAKeyValue"; - /** PGP retrieval */ - public static final String TYPE_PGP = Constants.SignatureSpecNS + "PGPData"; - /** SPKI retrieval */ - public static final String TYPE_SPKI = Constants.SignatureSpecNS + "SPKIData"; - /** MGMT retrieval */ - public static final String TYPE_MGMT = Constants.SignatureSpecNS + "MgmtData"; - /** X509 retrieval */ - public static final String TYPE_X509 = Constants.SignatureSpecNS + "X509Data"; - /** RAWX509 retrieval */ - public static final String TYPE_RAWX509 = Constants.SignatureSpecNS + "rawX509Certificate"; - //J+ + public static final String TYPE_DSA = Constants.SignatureSpecNS + "DSAKeyValue"; + /** RSA retrieval */ + public static final String TYPE_RSA = Constants.SignatureSpecNS + "RSAKeyValue"; + /** PGP retrieval */ + public static final String TYPE_PGP = Constants.SignatureSpecNS + "PGPData"; + /** SPKI retrieval */ + public static final String TYPE_SPKI = Constants.SignatureSpecNS + "SPKIData"; + /** MGMT retrieval */ + public static final String TYPE_MGMT = Constants.SignatureSpecNS + "MgmtData"; + /** X509 retrieval */ + public static final String TYPE_X509 = Constants.SignatureSpecNS + "X509Data"; + /** RAWX509 retrieval */ + public static final String TYPE_RAWX509 = Constants.SignatureSpecNS + "rawX509Certificate"; - /** - * Constructor RetrievalMethod - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public RetrievalMethod(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor RetrievalMethod + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public RetrievalMethod(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } - /** - * Constructor RetrievalMethod - * - * @param doc - * @param URI - * @param transforms - * @param Type - */ - public RetrievalMethod(Document doc, String URI, Transforms transforms, - String Type) { + /** + * Constructor RetrievalMethod + * + * @param doc + * @param URI + * @param transforms + * @param Type + */ + public RetrievalMethod(Document doc, String URI, Transforms transforms, String Type) { + super(doc); - super(doc); + this.constructionElement.setAttributeNS(null, Constants._ATT_URI, URI); - this._constructionElement.setAttributeNS(null, Constants._ATT_URI, URI); + if (Type != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_TYPE, Type); + } - if (Type != null) { - this._constructionElement.setAttributeNS(null, Constants._ATT_TYPE, Type); - } + if (transforms != null) { + this.constructionElement.appendChild(transforms.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + } - if (transforms != null) { - this._constructionElement.appendChild(transforms.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - } + /** + * Method getURIAttr + * + * @return the URI attribute + */ + public Attr getURIAttr() { + return this.constructionElement.getAttributeNodeNS(null, Constants._ATT_URI); + } - /** - * Method getURIAttr - * - * @return the URI attribute - */ - public Attr getURIAttr() { - return this._constructionElement.getAttributeNodeNS(null, Constants._ATT_URI); - } + /** + * Method getURI + * + * @return URI string + */ + public String getURI() { + return this.getURIAttr().getNodeValue(); + } - /** - * Method getURI - * - * - * @return URI string - */ - public String getURI() { - return this.getURIAttr().getNodeValue(); - } + /** @return the type*/ + public String getType() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_TYPE); + } - /** @return the type*/ - public String getType() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_TYPE); - } + /** + * Method getTransforms + * + * @throws XMLSecurityException + * @return the transformations + */ + public Transforms getTransforms() throws XMLSecurityException { + try { + Element transformsElem = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_TRANSFORMS, 0); - /** - * Method getTransforms - * - * - * @throws XMLSecurityException - * @return the transforamitons - */ - public Transforms getTransforms() throws XMLSecurityException { + if (transformsElem != null) { + return new Transforms(transformsElem, this.baseURI); + } - try { - Element transformsElem = - XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants - ._TAG_TRANSFORMS, 0); + return null; + } catch (XMLSignatureException ex) { + throw new XMLSecurityException("empty", ex); + } + } - if (transformsElem != null) { - return new Transforms(transformsElem, this._baseURI); - } - - return null; - } catch (XMLSignatureException ex) { - throw new XMLSecurityException("empty", ex); - } - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_RETRIEVALMETHOD; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_RETRIEVALMETHOD; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java index 95cef8d5491..0177f9bcc12 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.content; @@ -26,26 +28,25 @@ import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import org.w3c.dom.Element; /** - * - * @author $Author: mullan $ + * @author $Author: coheigea $ * $todo$ implement */ public class SPKIData extends SignatureElementProxy implements KeyInfoContent { - /** - * Constructor SPKIData - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public SPKIData(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor SPKIData + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public SPKIData(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_SPKIDATA; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_SPKIDATA; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java index 199b1dcb020..55a2a0edd40 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java @@ -2,32 +2,33 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.content; - - import java.math.BigInteger; import java.security.cert.X509Certificate; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509CRL; import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Digest; import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509IssuerSerial; import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI; import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SubjectName; @@ -38,447 +39,501 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; - -/** - * - * @author $Author: mullan $ - */ public class X509Data extends SignatureElementProxy implements KeyInfoContent { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(X509Data.class.getName()); - /** - * Constructor X509Data - * - * @param doc - */ - public X509Data(Document doc) { + /** + * Constructor X509Data + * + * @param doc + */ + public X509Data(Document doc) { + super(doc); - super(doc); + XMLUtils.addReturnToElement(this.constructionElement); + } - XMLUtils.addReturnToElement(this._constructionElement); - } + /** + * Constructor X509Data + * + * @param element + * @param baseURI + * @throws XMLSecurityException + */ + public X509Data(Element element, String baseURI) throws XMLSecurityException { + super(element, baseURI); - /** - * Constructor X509Data - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public X509Data(Element element, String BaseURI) - throws XMLSecurityException { + Node sibling = this.constructionElement.getFirstChild(); + while (sibling != null) { + if (sibling.getNodeType() != Node.ELEMENT_NODE) { + sibling = sibling.getNextSibling(); + continue; + } + return; + } + /* No Elements found */ + Object exArgs[] = { "Elements", Constants._TAG_X509DATA }; + throw new XMLSecurityException("xml.WrongContent", exArgs); + } - super(element, BaseURI); - Node sibling=this._constructionElement.getFirstChild(); - while (sibling!=null) { - if (sibling.getNodeType()!=Node.ELEMENT_NODE) { - sibling=sibling.getNextSibling(); - continue; - } - return; - } - /* No Elements found */ - Object exArgs[] = { "Elements", Constants._TAG_X509DATA }; - throw new XMLSecurityException("xml.WrongContent", exArgs); - } + /** + * Method addIssuerSerial + * + * @param X509IssuerName + * @param X509SerialNumber + */ + public void addIssuerSerial(String X509IssuerName, BigInteger X509SerialNumber) { + this.add(new XMLX509IssuerSerial(this.doc, X509IssuerName, X509SerialNumber)); + } - /** - * Method addIssuerSerial - * - * @param X509IssuerName - * @param X509SerialNumber - */ - public void addIssuerSerial(String X509IssuerName, - BigInteger X509SerialNumber) { - this.add(new XMLX509IssuerSerial(this._doc, X509IssuerName, - X509SerialNumber)); - } + /** + * Method addIssuerSerial + * + * @param X509IssuerName + * @param X509SerialNumber + */ + public void addIssuerSerial(String X509IssuerName, String X509SerialNumber) { + this.add(new XMLX509IssuerSerial(this.doc, X509IssuerName, X509SerialNumber)); + } - /** - * Method addIssuerSerial - * - * @param X509IssuerName - * @param X509SerialNumber - */ - public void addIssuerSerial(String X509IssuerName, String X509SerialNumber) { - this.add(new XMLX509IssuerSerial(this._doc, X509IssuerName, - X509SerialNumber)); - } + /** + * Method addIssuerSerial + * + * @param X509IssuerName + * @param X509SerialNumber + */ + public void addIssuerSerial(String X509IssuerName, int X509SerialNumber) { + this.add(new XMLX509IssuerSerial(this.doc, X509IssuerName, X509SerialNumber)); + } - /** - * Method addIssuerSerial - * - * @param X509IssuerName - * @param X509SerialNumber - */ - public void addIssuerSerial(String X509IssuerName, int X509SerialNumber) { - this.add(new XMLX509IssuerSerial(this._doc, X509IssuerName, - X509SerialNumber)); - } + /** + * Method add + * + * @param xmlX509IssuerSerial + */ + public void add(XMLX509IssuerSerial xmlX509IssuerSerial) { - /** - * Method add - * - * @param xmlX509IssuerSerial - */ - public void add(XMLX509IssuerSerial xmlX509IssuerSerial) { + this.constructionElement.appendChild(xmlX509IssuerSerial.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } - this._constructionElement - .appendChild(xmlX509IssuerSerial.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } + /** + * Method addSKI + * + * @param skiBytes + */ + public void addSKI(byte[] skiBytes) { + this.add(new XMLX509SKI(this.doc, skiBytes)); + } - /** - * Method addSKI - * - * @param skiBytes - */ - public void addSKI(byte[] skiBytes) { - this.add(new XMLX509SKI(this._doc, skiBytes)); - } + /** + * Method addSKI + * + * @param x509certificate + * @throws XMLSecurityException + */ + public void addSKI(X509Certificate x509certificate) + throws XMLSecurityException { + this.add(new XMLX509SKI(this.doc, x509certificate)); + } - /** - * Method addSKI - * - * @param x509certificate - * @throws XMLSecurityException - */ - public void addSKI(X509Certificate x509certificate) - throws XMLSecurityException { - this.add(new XMLX509SKI(this._doc, x509certificate)); - } + /** + * Method add + * + * @param xmlX509SKI + */ + public void add(XMLX509SKI xmlX509SKI) { + this.constructionElement.appendChild(xmlX509SKI.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * Method add - * - * @param xmlX509SKI - */ - public void add(XMLX509SKI xmlX509SKI) { - this._constructionElement.appendChild(xmlX509SKI.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } + /** + * Method addSubjectName + * + * @param subjectName + */ + public void addSubjectName(String subjectName) { + this.add(new XMLX509SubjectName(this.doc, subjectName)); + } - /** - * Method addSubjectName - * - * @param subjectName - */ - public void addSubjectName(String subjectName) { - this.add(new XMLX509SubjectName(this._doc, subjectName)); - } + /** + * Method addSubjectName + * + * @param x509certificate + */ + public void addSubjectName(X509Certificate x509certificate) { + this.add(new XMLX509SubjectName(this.doc, x509certificate)); + } - /** - * Method addSubjectName - * - * @param x509certificate - */ - public void addSubjectName(X509Certificate x509certificate) { - this.add(new XMLX509SubjectName(this._doc, x509certificate)); - } + /** + * Method add + * + * @param xmlX509SubjectName + */ + public void add(XMLX509SubjectName xmlX509SubjectName) { + this.constructionElement.appendChild(xmlX509SubjectName.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * Method add - * - * @param xmlX509SubjectName - */ - public void add(XMLX509SubjectName xmlX509SubjectName) { - this._constructionElement.appendChild(xmlX509SubjectName.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } + /** + * Method addCertificate + * + * @param x509certificate + * @throws XMLSecurityException + */ + public void addCertificate(X509Certificate x509certificate) + throws XMLSecurityException { + this.add(new XMLX509Certificate(this.doc, x509certificate)); + } - /** - * Method addCertificate - * - * @param x509certificate - * @throws XMLSecurityException - */ - public void addCertificate(X509Certificate x509certificate) - throws XMLSecurityException { - this.add(new XMLX509Certificate(this._doc, x509certificate)); - } + /** + * Method addCertificate + * + * @param x509certificateBytes + */ + public void addCertificate(byte[] x509certificateBytes) { + this.add(new XMLX509Certificate(this.doc, x509certificateBytes)); + } - /** - * Method addCertificate - * - * @param x509certificateBytes - */ - public void addCertificate(byte[] x509certificateBytes) { - this.add(new XMLX509Certificate(this._doc, x509certificateBytes)); - } + /** + * Method add + * + * @param xmlX509Certificate + */ + public void add(XMLX509Certificate xmlX509Certificate) { + this.constructionElement.appendChild(xmlX509Certificate.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * Method add - * - * @param xmlX509Certificate - */ - public void add(XMLX509Certificate xmlX509Certificate) { - this._constructionElement.appendChild(xmlX509Certificate.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } + /** + * Method addCRL + * + * @param crlBytes + */ + public void addCRL(byte[] crlBytes) { + this.add(new XMLX509CRL(this.doc, crlBytes)); + } - /** - * Method addCRL - * - * @param crlBytes - */ - public void addCRL(byte[] crlBytes) { - this.add(new XMLX509CRL(this._doc, crlBytes)); - } + /** + * Method add + * + * @param xmlX509CRL + */ + public void add(XMLX509CRL xmlX509CRL) { + this.constructionElement.appendChild(xmlX509CRL.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * Method add - * - * @param xmlX509CRL - */ - public void add(XMLX509CRL xmlX509CRL) { - this._constructionElement.appendChild(xmlX509CRL.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } + /** + * Method addDigest + * + * @param x509certificate + * @param algorithmURI + * @throws XMLSecurityException + */ + public void addDigest(X509Certificate x509certificate, String algorithmURI) + throws XMLSecurityException { + this.add(new XMLX509Digest(this.doc, x509certificate, algorithmURI)); + } - /** - * Method addUnknownElement - * - * @param element - */ - public void addUnknownElement(Element element) { - this._constructionElement.appendChild(element); - XMLUtils.addReturnToElement(this._constructionElement); - } + /** + * Method addDigest + * + * @param x509CertificateDigestByes + * @param algorithmURI + */ + public void addDigest(byte[] x509certificateDigestBytes, String algorithmURI) { + this.add(new XMLX509Digest(this.doc, x509certificateDigestBytes, algorithmURI)); + } - /** - * Method lengthIssuerSerial - * - * @return the number of IssuerSerial elements in this X509Data - */ - public int lengthIssuerSerial() { - return this.length(Constants.SignatureSpecNS, - Constants._TAG_X509ISSUERSERIAL); - } + /** + * Method add + * + * @param XMLX509Digest + */ + public void add(XMLX509Digest xmlX509Digest) { + this.constructionElement.appendChild(xmlX509Digest.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * Method lengthSKI - * - * @return the number of SKI elements in this X509Data - */ - public int lengthSKI() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_X509SKI); - } + /** + * Method addUnknownElement + * + * @param element + */ + public void addUnknownElement(Element element) { + this.constructionElement.appendChild(element); + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * Method lengthSubjectName - * - * @return the number of SubjectName elements in this X509Data - */ - public int lengthSubjectName() { - return this.length(Constants.SignatureSpecNS, - Constants._TAG_X509SUBJECTNAME); - } + /** + * Method lengthIssuerSerial + * + * @return the number of IssuerSerial elements in this X509Data + */ + public int lengthIssuerSerial() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509ISSUERSERIAL); + } - /** - * Method lengthCertificate - * - * @return the number of Certificate elements in this X509Data - */ - public int lengthCertificate() { - return this.length(Constants.SignatureSpecNS, - Constants._TAG_X509CERTIFICATE); - } + /** + * Method lengthSKI + * + * @return the number of SKI elements in this X509Data + */ + public int lengthSKI() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509SKI); + } - /** - * Method lengthCRL - * - * @return the number of CRL elements in this X509Data - */ - public int lengthCRL() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_X509CRL); - } + /** + * Method lengthSubjectName + * + * @return the number of SubjectName elements in this X509Data + */ + public int lengthSubjectName() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509SUBJECTNAME); + } - /** - * Method lengthUnknownElement - * - * @return the number of UnknownElement elements in this X509Data - */ - public int lengthUnknownElement() { + /** + * Method lengthCertificate + * + * @return the number of Certificate elements in this X509Data + */ + public int lengthCertificate() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509CERTIFICATE); + } - int result = 0; - Node n=this._constructionElement.getFirstChild(); - while (n!=null){ + /** + * Method lengthCRL + * + * @return the number of CRL elements in this X509Data + */ + public int lengthCRL() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509CRL); + } - if ((n.getNodeType() == Node.ELEMENT_NODE) - &&!n.getNamespaceURI().equals(Constants.SignatureSpecNS)) { - result += 1; - } - n=n.getNextSibling(); - } + /** + * Method lengthDigest + * + * @return the number of X509Digest elements in this X509Data + */ + public int lengthDigest() { + return this.length(Constants.SignatureSpec11NS, Constants._TAG_X509DIGEST); + } - return result; - } + /** + * Method lengthUnknownElement + * + * @return the number of UnknownElement elements in this X509Data + */ + public int lengthUnknownElement() { + int result = 0; + Node n = this.constructionElement.getFirstChild(); + while (n != null){ + if ((n.getNodeType() == Node.ELEMENT_NODE) + && !n.getNamespaceURI().equals(Constants.SignatureSpecNS)) { + result++; + } + n = n.getNextSibling(); + } - /** - * Method itemIssuerSerial - * - * @param i - * @return the X509IssuerSerial, null if not present - * @throws XMLSecurityException - */ - public XMLX509IssuerSerial itemIssuerSerial(int i) - throws XMLSecurityException { + return result; + } - Element e = - XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_X509ISSUERSERIAL,i); + /** + * Method itemIssuerSerial + * + * @param i + * @return the X509IssuerSerial, null if not present + * @throws XMLSecurityException + */ + public XMLX509IssuerSerial itemIssuerSerial(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509ISSUERSERIAL, i); - if (e != null) { - return new XMLX509IssuerSerial(e, this._baseURI); - } - return null; - } + if (e != null) { + return new XMLX509IssuerSerial(e, this.baseURI); + } + return null; + } - /** - * Method itemSKI - * - * @param i - * @return the X509SKI, null if not present - * @throws XMLSecurityException - */ - public XMLX509SKI itemSKI(int i) throws XMLSecurityException { + /** + * Method itemSKI + * + * @param i + * @return the X509SKI, null if not present + * @throws XMLSecurityException + */ + public XMLX509SKI itemSKI(int i) throws XMLSecurityException { - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_X509SKI,i); + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509SKI, i); - if (e != null) { - return new XMLX509SKI(e, this._baseURI); - } - return null; - } + if (e != null) { + return new XMLX509SKI(e, this.baseURI); + } + return null; + } - /** - * Method itemSubjectName - * - * @param i - * @return the X509SubjectName, null if not present - * @throws XMLSecurityException - */ - public XMLX509SubjectName itemSubjectName(int i) - throws XMLSecurityException { + /** + * Method itemSubjectName + * + * @param i + * @return the X509SubjectName, null if not present + * @throws XMLSecurityException + */ + public XMLX509SubjectName itemSubjectName(int i) throws XMLSecurityException { - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_X509SUBJECTNAME,i); + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509SUBJECTNAME, i); - if (e != null) { - return new XMLX509SubjectName(e, this._baseURI); - } - return null; - } + if (e != null) { + return new XMLX509SubjectName(e, this.baseURI); + } + return null; + } - /** - * Method itemCertificate - * - * @param i - * @return the X509Certifacte, null if not present - * @throws XMLSecurityException - */ - public XMLX509Certificate itemCertificate(int i) - throws XMLSecurityException { + /** + * Method itemCertificate + * + * @param i + * @return the X509Certifacte, null if not present + * @throws XMLSecurityException + */ + public XMLX509Certificate itemCertificate(int i) throws XMLSecurityException { - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_X509CERTIFICATE,i); + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509CERTIFICATE, i); - if (e != null) { - return new XMLX509Certificate(e, this._baseURI); - } - return null; - } + if (e != null) { + return new XMLX509Certificate(e, this.baseURI); + } + return null; + } - /** - * Method itemCRL - * - * @param i - * @return the X509CRL, null if not present - * @throws XMLSecurityException - */ - public XMLX509CRL itemCRL(int i) throws XMLSecurityException { + /** + * Method itemCRL + * + * @param i + * @return the X509CRL, null if not present + * @throws XMLSecurityException + */ + public XMLX509CRL itemCRL(int i) throws XMLSecurityException { - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_X509CRL,i); + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509CRL, i); - if (e != null) { - return new XMLX509CRL(e, this._baseURI); - } - return null; - } + if (e != null) { + return new XMLX509CRL(e, this.baseURI); + } + return null; + } - /** - * Method itemUnknownElement - * - * @param i - * @return the Unknown Element at i - * TODO implement - **/ - public Element itemUnknownElement(int i) { - log.log(java.util.logging.Level.FINE, "itemUnknownElement not implemented:"+i); - return null; - } + /** + * Method itemDigest + * + * @param i + * @return the X509Digest, null if not present + * @throws XMLSecurityException + */ + public XMLX509Digest itemDigest(int i) throws XMLSecurityException { - /** - * Method containsIssuerSerial - * - * @return true if this X509Data contains a IssuerSerial - */ - public boolean containsIssuerSerial() { - return this.lengthIssuerSerial() > 0; - } + Element e = + XMLUtils.selectDs11Node( + this.constructionElement.getFirstChild(), Constants._TAG_X509DIGEST, i); - /** - * Method containsSKI - * - * @return true if this X509Data contains a SKI - */ - public boolean containsSKI() { - return this.lengthSKI() > 0; - } + if (e != null) { + return new XMLX509Digest(e, this.baseURI); + } + return null; + } - /** - * Method containsSubjectName - * - * @return true if this X509Data contains a SubjectName - */ - public boolean containsSubjectName() { - return this.lengthSubjectName() > 0; - } + /** + * Method itemUnknownElement + * + * @param i + * @return the Unknown Element at i + * TODO implement + **/ + public Element itemUnknownElement(int i) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "itemUnknownElement not implemented:" + i); + } + return null; + } - /** - * Method containsCertificate - * - * @return true if this X509Data contains a Certificate - */ - public boolean containsCertificate() { - return this.lengthCertificate() > 0; - } + /** + * Method containsIssuerSerial + * + * @return true if this X509Data contains a IssuerSerial + */ + public boolean containsIssuerSerial() { + return this.lengthIssuerSerial() > 0; + } - /** - * Method containsCRL - * - * @return true if this X509Data contains a CRL - */ - public boolean containsCRL() { - return this.lengthCRL() > 0; - } + /** + * Method containsSKI + * + * @return true if this X509Data contains a SKI + */ + public boolean containsSKI() { + return this.lengthSKI() > 0; + } - /** - * Method containsUnknownElement - * - * @return true if this X509Data contains an UnknownElement - */ - public boolean containsUnknownElement() { - return this.lengthUnknownElement() > 0; - } + /** + * Method containsSubjectName + * + * @return true if this X509Data contains a SubjectName + */ + public boolean containsSubjectName() { + return this.lengthSubjectName() > 0; + } - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_X509DATA; - } + /** + * Method containsCertificate + * + * @return true if this X509Data contains a Certificate + */ + public boolean containsCertificate() { + return this.lengthCertificate() > 0; + } + + /** + * Method containsDigest + * + * @return true if this X509Data contains an X509Digest + */ + public boolean containsDigest() { + return this.lengthDigest() > 0; + } + + /** + * Method containsCRL + * + * @return true if this X509Data contains a CRL + */ + public boolean containsCRL() { + return this.lengthCRL() > 0; + } + + /** + * Method containsUnknownElement + * + * @return true if this X509Data contains an UnknownElement + */ + public boolean containsUnknownElement() { + return this.lengthUnknownElement() > 0; + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_X509DATA; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java index ef735c3dad6..2cfa51fc28c 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.content.keyvalues; @@ -37,104 +39,93 @@ import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; -/** - * - * @author $Author: mullan $ - */ -public class DSAKeyValue extends SignatureElementProxy - implements KeyValueContent { +public class DSAKeyValue extends SignatureElementProxy implements KeyValueContent { - /** - * Constructor DSAKeyValue - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public DSAKeyValue(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor DSAKeyValue + * + * @param element + * @param baseURI + * @throws XMLSecurityException + */ + public DSAKeyValue(Element element, String baseURI) throws XMLSecurityException { + super(element, baseURI); + } - /** - * Constructor DSAKeyValue - * - * @param doc - * @param P - * @param Q - * @param G - * @param Y - */ - public DSAKeyValue(Document doc, BigInteger P, BigInteger Q, BigInteger G, - BigInteger Y) { + /** + * Constructor DSAKeyValue + * + * @param doc + * @param P + * @param Q + * @param G + * @param Y + */ + public DSAKeyValue(Document doc, BigInteger P, BigInteger Q, BigInteger G, BigInteger Y) { + super(doc); - super(doc); + XMLUtils.addReturnToElement(this.constructionElement); + this.addBigIntegerElement(P, Constants._TAG_P); + this.addBigIntegerElement(Q, Constants._TAG_Q); + this.addBigIntegerElement(G, Constants._TAG_G); + this.addBigIntegerElement(Y, Constants._TAG_Y); + } - XMLUtils.addReturnToElement(this._constructionElement); - this.addBigIntegerElement(P, Constants._TAG_P); - this.addBigIntegerElement(Q, Constants._TAG_Q); - this.addBigIntegerElement(G, Constants._TAG_G); - this.addBigIntegerElement(Y, Constants._TAG_Y); - } + /** + * Constructor DSAKeyValue + * + * @param doc + * @param key + * @throws IllegalArgumentException + */ + public DSAKeyValue(Document doc, Key key) throws IllegalArgumentException { + super(doc); - /** - * Constructor DSAKeyValue - * - * @param doc - * @param key - * @throws IllegalArgumentException - */ - public DSAKeyValue(Document doc, Key key) throws IllegalArgumentException { + XMLUtils.addReturnToElement(this.constructionElement); - super(doc); + if (key instanceof java.security.interfaces.DSAPublicKey) { + this.addBigIntegerElement(((DSAPublicKey) key).getParams().getP(), Constants._TAG_P); + this.addBigIntegerElement(((DSAPublicKey) key).getParams().getQ(), Constants._TAG_Q); + this.addBigIntegerElement(((DSAPublicKey) key).getParams().getG(), Constants._TAG_G); + this.addBigIntegerElement(((DSAPublicKey) key).getY(), Constants._TAG_Y); + } else { + Object exArgs[] = { Constants._TAG_DSAKEYVALUE, key.getClass().getName() }; - XMLUtils.addReturnToElement(this._constructionElement); + throw new IllegalArgumentException(I18n.translate("KeyValue.IllegalArgument", exArgs)); + } + } - if (key instanceof java.security.interfaces.DSAPublicKey) { - this.addBigIntegerElement(((DSAPublicKey) key).getParams().getP(), - Constants._TAG_P); - this.addBigIntegerElement(((DSAPublicKey) key).getParams().getQ(), - Constants._TAG_Q); - this.addBigIntegerElement(((DSAPublicKey) key).getParams().getG(), - Constants._TAG_G); - this.addBigIntegerElement(((DSAPublicKey) key).getY(), - Constants._TAG_Y); - } else { - Object exArgs[] = { Constants._TAG_DSAKEYVALUE, - key.getClass().getName() }; + /** @inheritDoc */ + public PublicKey getPublicKey() throws XMLSecurityException { + try { + DSAPublicKeySpec pkspec = + new DSAPublicKeySpec( + this.getBigIntegerFromChildElement( + Constants._TAG_Y, Constants.SignatureSpecNS + ), + this.getBigIntegerFromChildElement( + Constants._TAG_P, Constants.SignatureSpecNS + ), + this.getBigIntegerFromChildElement( + Constants._TAG_Q, Constants.SignatureSpecNS + ), + this.getBigIntegerFromChildElement( + Constants._TAG_G, Constants.SignatureSpecNS + ) + ); + KeyFactory dsaFactory = KeyFactory.getInstance("DSA"); + PublicKey pk = dsaFactory.generatePublic(pkspec); - throw new IllegalArgumentException(I18n - .translate("KeyValue.IllegalArgument", exArgs)); - } - } + return pk; + } catch (NoSuchAlgorithmException ex) { + throw new XMLSecurityException("empty", ex); + } catch (InvalidKeySpecException ex) { + throw new XMLSecurityException("empty", ex); + } + } - /** @inheritDoc */ - public PublicKey getPublicKey() throws XMLSecurityException { - - try { - DSAPublicKeySpec pkspec = - new DSAPublicKeySpec(this - .getBigIntegerFromChildElement(Constants._TAG_Y, Constants - .SignatureSpecNS), this - .getBigIntegerFromChildElement(Constants._TAG_P, Constants - .SignatureSpecNS), this - .getBigIntegerFromChildElement(Constants._TAG_Q, Constants - .SignatureSpecNS), this - .getBigIntegerFromChildElement(Constants - ._TAG_G, Constants.SignatureSpecNS)); - KeyFactory dsaFactory = KeyFactory.getInstance("DSA"); - PublicKey pk = dsaFactory.generatePublic(pkspec); - - return pk; - } catch (NoSuchAlgorithmException ex) { - throw new XMLSecurityException("empty", ex); - } catch (InvalidKeySpecException ex) { - throw new XMLSecurityException("empty", ex); - } - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_DSAKEYVALUE; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_DSAKEYVALUE; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java index 31e761443c5..d5ebe5b6937 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java @@ -2,46 +2,38 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.content.keyvalues; - - import java.security.PublicKey; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; -/** - * - * - * - * - * @author $Author: mullan $ - * - */ public interface KeyValueContent { - /** - * Method getPublicKey - * - * @return the public key - * @throws XMLSecurityException - */ - public PublicKey getPublicKey() - throws XMLSecurityException; + /** + * Method getPublicKey + * + * @return the public key + * @throws XMLSecurityException + */ + PublicKey getPublicKey() throws XMLSecurityException; + } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java index 71b23cda593..a12b8b45bd9 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.content.keyvalues; @@ -37,93 +39,86 @@ import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; -/** - * - * @author $Author: mullan $ - */ -public class RSAKeyValue extends SignatureElementProxy - implements KeyValueContent { +public class RSAKeyValue extends SignatureElementProxy implements KeyValueContent { - /** - * Constructor RSAKeyValue - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public RSAKeyValue(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor RSAKeyValue + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public RSAKeyValue(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } - /** - * Constructor RSAKeyValue - * - * @param doc - * @param modulus - * @param exponent - */ - public RSAKeyValue(Document doc, BigInteger modulus, BigInteger exponent) { + /** + * Constructor RSAKeyValue + * + * @param doc + * @param modulus + * @param exponent + */ + public RSAKeyValue(Document doc, BigInteger modulus, BigInteger exponent) { + super(doc); - super(doc); + XMLUtils.addReturnToElement(this.constructionElement); + this.addBigIntegerElement(modulus, Constants._TAG_MODULUS); + this.addBigIntegerElement(exponent, Constants._TAG_EXPONENT); + } - XMLUtils.addReturnToElement(this._constructionElement); - this.addBigIntegerElement(modulus, Constants._TAG_MODULUS); - this.addBigIntegerElement(exponent, Constants._TAG_EXPONENT); - } + /** + * Constructor RSAKeyValue + * + * @param doc + * @param key + * @throws IllegalArgumentException + */ + public RSAKeyValue(Document doc, Key key) throws IllegalArgumentException { + super(doc); - /** - * Constructor RSAKeyValue - * - * @param doc - * @param key - * @throws IllegalArgumentException - */ - public RSAKeyValue(Document doc, Key key) throws IllegalArgumentException { + XMLUtils.addReturnToElement(this.constructionElement); - super(doc); + if (key instanceof java.security.interfaces.RSAPublicKey ) { + this.addBigIntegerElement( + ((RSAPublicKey) key).getModulus(), Constants._TAG_MODULUS + ); + this.addBigIntegerElement( + ((RSAPublicKey) key).getPublicExponent(), Constants._TAG_EXPONENT + ); + } else { + Object exArgs[] = { Constants._TAG_RSAKEYVALUE, key.getClass().getName() }; - XMLUtils.addReturnToElement(this._constructionElement); + throw new IllegalArgumentException(I18n.translate("KeyValue.IllegalArgument", exArgs)); + } + } - if (key instanceof java.security.interfaces.RSAPublicKey ) { - this.addBigIntegerElement(((RSAPublicKey) key).getModulus(), - Constants._TAG_MODULUS); - this.addBigIntegerElement(((RSAPublicKey) key).getPublicExponent(), - Constants._TAG_EXPONENT); - } else { - Object exArgs[] = { Constants._TAG_RSAKEYVALUE, - key.getClass().getName() }; + /** @inheritDoc */ + public PublicKey getPublicKey() throws XMLSecurityException { + try { + KeyFactory rsaFactory = KeyFactory.getInstance("RSA"); - throw new IllegalArgumentException(I18n - .translate("KeyValue.IllegalArgument", exArgs)); - } - } + RSAPublicKeySpec rsaKeyspec = + new RSAPublicKeySpec( + this.getBigIntegerFromChildElement( + Constants._TAG_MODULUS, Constants.SignatureSpecNS + ), + this.getBigIntegerFromChildElement( + Constants._TAG_EXPONENT, Constants.SignatureSpecNS + ) + ); + PublicKey pk = rsaFactory.generatePublic(rsaKeyspec); - /** @inheritDoc */ - public PublicKey getPublicKey() throws XMLSecurityException { + return pk; + } catch (NoSuchAlgorithmException ex) { + throw new XMLSecurityException("empty", ex); + } catch (InvalidKeySpecException ex) { + throw new XMLSecurityException("empty", ex); + } + } - try { - KeyFactory rsaFactory = KeyFactory.getInstance("RSA"); - - // KeyFactory rsaFactory = KeyFactory.getInstance(JCE_RSA); - RSAPublicKeySpec rsaKeyspec = - new RSAPublicKeySpec(this - .getBigIntegerFromChildElement(Constants._TAG_MODULUS, Constants - .SignatureSpecNS), this - .getBigIntegerFromChildElement(Constants - ._TAG_EXPONENT, Constants.SignatureSpecNS)); - PublicKey pk = rsaFactory.generatePublic(rsaKeyspec); - - return pk; - } catch (NoSuchAlgorithmException ex) { - throw new XMLSecurityException("empty", ex); - } catch (InvalidKeySpecException ex) { - throw new XMLSecurityException("empty", ex); - } - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_RSAKEYVALUE; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_RSAKEYVALUE; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java index b68c444dc08..0046c71d05c 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.content.x509; @@ -26,51 +28,43 @@ import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import org.w3c.dom.Document; import org.w3c.dom.Element; -/** - * - * @author $Author: mullan $ - * - */ -public class XMLX509CRL extends SignatureElementProxy - implements XMLX509DataContent { +public class XMLX509CRL extends SignatureElementProxy implements XMLX509DataContent { - /** - * Constructor XMLX509CRL - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public XMLX509CRL(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor XMLX509CRL + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public XMLX509CRL(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } - /** - * Constructor X509CRL - * - * @param doc - * @param crlBytes - */ - public XMLX509CRL(Document doc, byte[] crlBytes) { + /** + * Constructor X509CRL + * + * @param doc + * @param crlBytes + */ + public XMLX509CRL(Document doc, byte[] crlBytes) { + super(doc); - super(doc); + this.addBase64Text(crlBytes); + } - this.addBase64Text(crlBytes); - } + /** + * Method getCRLBytes + * + * @return the CRL bytes + * @throws XMLSecurityException + */ + public byte[] getCRLBytes() throws XMLSecurityException { + return this.getBytesFromTextChild(); + } - /** - * Method getCRLBytes - * - * @return the CRL bytes - * @throws XMLSecurityException - */ - public byte[] getCRLBytes() throws XMLSecurityException { - return this.getBytesFromTextChild(); - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_X509CRL; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_X509CRL; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java index 630d9ccc279..1a5931ff5d8 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.content.x509; @@ -25,6 +27,7 @@ import java.security.PublicKey; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; +import java.util.Arrays; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.utils.Constants; @@ -32,135 +35,134 @@ import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import org.w3c.dom.Document; import org.w3c.dom.Element; -/** - * - * @author $Author: mullan $ - */ -public class XMLX509Certificate extends SignatureElementProxy - implements XMLX509DataContent { +public class XMLX509Certificate extends SignatureElementProxy implements XMLX509DataContent { - /** Field JCA_CERT_ID */ - public static final String JCA_CERT_ID = "X.509"; + /** Field JCA_CERT_ID */ + public static final String JCA_CERT_ID = "X.509"; - /** - * Constructor X509Certificate - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public XMLX509Certificate(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor X509Certificate + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public XMLX509Certificate(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } - /** - * Constructor X509Certificate - * - * @param doc - * @param certificateBytes - */ - public XMLX509Certificate(Document doc, byte[] certificateBytes) { + /** + * Constructor X509Certificate + * + * @param doc + * @param certificateBytes + */ + public XMLX509Certificate(Document doc, byte[] certificateBytes) { + super(doc); - super(doc); + this.addBase64Text(certificateBytes); + } - this.addBase64Text(certificateBytes); - } + /** + * Constructor XMLX509Certificate + * + * @param doc + * @param x509certificate + * @throws XMLSecurityException + */ + public XMLX509Certificate(Document doc, X509Certificate x509certificate) + throws XMLSecurityException { + super(doc); - /** - * Constructor XMLX509Certificate - * - * @param doc - * @param x509certificate - * @throws XMLSecurityException - */ - public XMLX509Certificate(Document doc, X509Certificate x509certificate) - throws XMLSecurityException { + try { + this.addBase64Text(x509certificate.getEncoded()); + } catch (java.security.cert.CertificateEncodingException ex) { + throw new XMLSecurityException("empty", ex); + } + } - super(doc); + /** + * Method getCertificateBytes + * + * @return the certificate bytes + * @throws XMLSecurityException + */ + public byte[] getCertificateBytes() throws XMLSecurityException { + return this.getBytesFromTextChild(); + } - try { - this.addBase64Text(x509certificate.getEncoded()); - } catch (java.security.cert.CertificateEncodingException ex) { - throw new XMLSecurityException("empty", ex); - } - } + /** + * Method getX509Certificate + * + * @return the x509 certificate + * @throws XMLSecurityException + */ + public X509Certificate getX509Certificate() throws XMLSecurityException { + try { + byte certbytes[] = this.getCertificateBytes(); + CertificateFactory certFact = + CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID); + X509Certificate cert = + (X509Certificate) certFact.generateCertificate( + new ByteArrayInputStream(certbytes) + ); - /** - * Method getCertificateBytes - * - * @return the certificate bytes - * @throws XMLSecurityException - */ - public byte[] getCertificateBytes() throws XMLSecurityException { - return this.getBytesFromTextChild(); - } + if (cert != null) { + return cert; + } - /** - * Method getX509Certificate - * - * @return the x509 certificate - * @throws XMLSecurityException - */ - public X509Certificate getX509Certificate() throws XMLSecurityException { + return null; + } catch (CertificateException ex) { + throw new XMLSecurityException("empty", ex); + } + } - try { - byte certbytes[] = this.getCertificateBytes(); - CertificateFactory certFact = - CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID); - X509Certificate cert = - (X509Certificate) certFact - .generateCertificate(new ByteArrayInputStream(certbytes)); + /** + * Method getPublicKey + * + * @return the publickey + * @throws XMLSecurityException + */ + public PublicKey getPublicKey() throws XMLSecurityException { + X509Certificate cert = this.getX509Certificate(); - if (cert != null) { - return cert; - } + if (cert != null) { + return cert.getPublicKey(); + } - return null; - } catch (CertificateException ex) { - throw new XMLSecurityException("empty", ex); - } - } - - /** - * Method getPublicKey - * - * @return teh publickey - * @throws XMLSecurityException - */ - public PublicKey getPublicKey() throws XMLSecurityException { - - X509Certificate cert = this.getX509Certificate(); - - if (cert != null) { - return cert.getPublicKey(); - } - - return null; - } + return null; + } /** @inheritDoc */ public boolean equals(Object obj) { - - if (obj == null) { - return false; - } - if (!this.getClass().getName().equals(obj.getClass().getName())) { + if (!(obj instanceof XMLX509Certificate)) { return false; } XMLX509Certificate other = (XMLX509Certificate) obj; try { - - /** $todo$ or should be create X509Certificates and use the equals() from the Certs */ - return java.security.MessageDigest.isEqual - (other.getCertificateBytes(), this.getCertificateBytes()); + return Arrays.equals(other.getCertificateBytes(), this.getCertificateBytes()); } catch (XMLSecurityException ex) { return false; } } - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_X509CERTIFICATE; - } + public int hashCode() { + int result = 17; + try { + byte[] bytes = getCertificateBytes(); + for (int i = 0; i < bytes.length; i++) { + result = 31 * result + bytes[i]; + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + } + return result; + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_X509CERTIFICATE; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java index 02bf9f82d39..2171572d3ab 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java @@ -2,32 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.content.x509; - - - - /** * Just used for tagging contents that are allowed inside a ds:X509Data Element. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public interface XMLX509DataContent { } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Digest.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Digest.java new file mode 100644 index 00000000000..57acc678bd9 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Digest.java @@ -0,0 +1,139 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 com.sun.org.apache.xml.internal.security.keys.content.x509; + +import java.security.MessageDigest; +import java.security.cert.X509Certificate; + +import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper; +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.Signature11ElementProxy; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * Provides content model support for the dsig11:X509Digest element. + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public class XMLX509Digest extends Signature11ElementProxy implements XMLX509DataContent { + + /** + * Constructor XMLX509Digest + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public XMLX509Digest(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } + + /** + * Constructor XMLX509Digest + * + * @param doc + * @param digestBytes + * @param algorithmURI + */ + public XMLX509Digest(Document doc, byte[] digestBytes, String algorithmURI) { + super(doc); + this.addBase64Text(digestBytes); + this.constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI); + } + + /** + * Constructor XMLX509Digest + * + * @param doc + * @param x509certificate + * @param algorithmURI + * @throws XMLSecurityException + */ + public XMLX509Digest(Document doc, X509Certificate x509certificate, String algorithmURI) throws XMLSecurityException { + super(doc); + this.addBase64Text(getDigestBytesFromCert(x509certificate, algorithmURI)); + this.constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI); + } + + /** + * Method getAlgorithmAttr + * + * @return the Algorithm attribute + */ + public Attr getAlgorithmAttr() { + return this.constructionElement.getAttributeNodeNS(null, Constants._ATT_ALGORITHM); + } + + /** + * Method getAlgorithm + * + * @return Algorithm string + */ + public String getAlgorithm() { + return this.getAlgorithmAttr().getNodeValue(); + } + + /** + * Method getDigestBytes + * + * @return the digestbytes + * @throws XMLSecurityException + */ + public byte[] getDigestBytes() throws XMLSecurityException { + return this.getBytesFromTextChild(); + } + + /** + * Method getDigestBytesFromCert + * + * @param cert + * @param algorithmURI + * @return digest bytes from the given certificate + * + * @throws XMLSecurityException + */ + public static byte[] getDigestBytesFromCert(X509Certificate cert, String algorithmURI) throws XMLSecurityException { + String jcaDigestAlgorithm = JCEMapper.translateURItoJCEID(algorithmURI); + if (jcaDigestAlgorithm == null) { + Object exArgs[] = { algorithmURI }; + throw new XMLSecurityException("XMLX509Digest.UnknownDigestAlgorithm", exArgs); + } + + try { + MessageDigest md = MessageDigest.getInstance(jcaDigestAlgorithm); + return md.digest(cert.getEncoded()); + } catch (Exception e) { + Object exArgs[] = { jcaDigestAlgorithm }; + throw new XMLSecurityException("XMLX509Digest.FailedDigest", exArgs); + } + + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_X509DIGEST; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java index 1d16b2b622f..cf3274377cb 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.content.x509; @@ -31,17 +33,11 @@ import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; -/** - * - * @author $Author: mullan $ - */ -public class XMLX509IssuerSerial extends SignatureElementProxy - implements XMLX509DataContent { +public class XMLX509IssuerSerial extends SignatureElementProxy implements XMLX509DataContent { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - XMLX509IssuerSerial.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(XMLX509IssuerSerial.class.getName()); /** * Constructor XMLX509IssuerSerial @@ -50,8 +46,7 @@ public class XMLX509IssuerSerial extends SignatureElementProxy * @param baseURI * @throws XMLSecurityException */ - public XMLX509IssuerSerial(Element element, String baseURI) - throws XMLSecurityException { + public XMLX509IssuerSerial(Element element, String baseURI) throws XMLSecurityException { super(element, baseURI); } @@ -62,11 +57,9 @@ public class XMLX509IssuerSerial extends SignatureElementProxy * @param x509IssuerName * @param x509SerialNumber */ - public XMLX509IssuerSerial(Document doc, String x509IssuerName, - BigInteger x509SerialNumber) { - + public XMLX509IssuerSerial(Document doc, String x509IssuerName, BigInteger x509SerialNumber) { super(doc); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); addTextElement(x509IssuerName, Constants._TAG_X509ISSUERNAME); addTextElement(x509SerialNumber.toString(), Constants._TAG_X509SERIALNUMBER); } @@ -78,8 +71,7 @@ public class XMLX509IssuerSerial extends SignatureElementProxy * @param x509IssuerName * @param x509SerialNumber */ - public XMLX509IssuerSerial(Document doc, String x509IssuerName, - String x509SerialNumber) { + public XMLX509IssuerSerial(Document doc, String x509IssuerName, String x509SerialNumber) { this(doc, x509IssuerName, new BigInteger(x509SerialNumber)); } @@ -90,10 +82,8 @@ public class XMLX509IssuerSerial extends SignatureElementProxy * @param x509IssuerName * @param x509SerialNumber */ - public XMLX509IssuerSerial(Document doc, String x509IssuerName, - int x509SerialNumber) { - this(doc, x509IssuerName, - new BigInteger(Integer.toString(x509SerialNumber))); + public XMLX509IssuerSerial(Document doc, String x509IssuerName, int x509SerialNumber) { + this(doc, x509IssuerName, new BigInteger(Integer.toString(x509SerialNumber))); } /** @@ -103,10 +93,11 @@ public class XMLX509IssuerSerial extends SignatureElementProxy * @param x509certificate */ public XMLX509IssuerSerial(Document doc, X509Certificate x509certificate) { - - this(doc, - RFC2253Parser.normalize(x509certificate.getIssuerDN().getName()), - x509certificate.getSerialNumber()); + this( + doc, + x509certificate.getIssuerX500Principal().getName(), + x509certificate.getSerialNumber() + ); } /** @@ -115,11 +106,11 @@ public class XMLX509IssuerSerial extends SignatureElementProxy * @return the serial number */ public BigInteger getSerialNumber() { - - String text = this.getTextFromChildElement - (Constants._TAG_X509SERIALNUMBER, Constants.SignatureSpecNS); - if (log.isLoggable(java.util.logging.Level.FINE)) + String text = + this.getTextFromChildElement(Constants._TAG_X509SERIALNUMBER, Constants.SignatureSpecNS); + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "X509SerialNumber text: " + text); + } return new BigInteger(text); } @@ -139,27 +130,28 @@ public class XMLX509IssuerSerial extends SignatureElementProxy * @return the issuer name */ public String getIssuerName() { - - return RFC2253Parser - .normalize(this - .getTextFromChildElement(Constants._TAG_X509ISSUERNAME, - Constants.SignatureSpecNS)); + return RFC2253Parser.normalize( + this.getTextFromChildElement(Constants._TAG_X509ISSUERNAME, Constants.SignatureSpecNS) + ); } /** @inheritDoc */ public boolean equals(Object obj) { - - if (obj == null) { - return false; - } - if (!this.getClass().getName().equals(obj.getClass().getName())) { + if (!(obj instanceof XMLX509IssuerSerial)) { return false; } XMLX509IssuerSerial other = (XMLX509IssuerSerial) obj; return this.getSerialNumber().equals(other.getSerialNumber()) - && this.getIssuerName().equals(other.getIssuerName()); + && this.getIssuerName().equals(other.getIssuerName()); + } + + public int hashCode() { + int result = 17; + result = 31 * result + getSerialNumber().hashCode(); + result = 31 * result + getIssuerName().hashCode(); + return result; } /** @inheritDoc */ diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java index fbbb17e6a54..e4617daead9 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java @@ -2,30 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.content.x509; -import java.io.IOException; -import java.io.ByteArrayInputStream; -import java.io.InputStream; import java.security.cert.X509Certificate; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; +import java.util.Arrays; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.utils.Base64; @@ -37,14 +35,13 @@ import org.w3c.dom.Element; /** * Handles SubjectKeyIdentifier (SKI) for X.509v3. * - * @author $Author: mullan $ - * @see Interface X509Extension + * @see + * Interface X509Extension */ -public class XMLX509SKI extends SignatureElementProxy - implements XMLX509DataContent { +public class XMLX509SKI extends SignatureElementProxy implements XMLX509DataContent { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(XMLX509SKI.class.getName()); /** @@ -53,7 +50,7 @@ public class XMLX509SKI extends SignatureElementProxy * distinct keys used by the same subject to be differentiated * (e.g., as key updating occurs). *
- * A key identifer shall be unique with respect to all key identifiers + * A key identifier shall be unique with respect to all key identifiers * for the subject with which it is used. This extension is always non-critical. */ public static final String SKI_OID = "2.5.29.14"; @@ -77,7 +74,7 @@ public class XMLX509SKI extends SignatureElementProxy * @throws XMLSecurityException */ public XMLX509SKI(Document doc, X509Certificate x509certificate) - throws XMLSecurityException { + throws XMLSecurityException { super(doc); this.addBase64Text(XMLX509SKI.getSKIBytesFromCert(x509certificate)); } @@ -89,8 +86,7 @@ public class XMLX509SKI extends SignatureElementProxy * @param BaseURI * @throws XMLSecurityException */ - public XMLX509SKI(Element element, String BaseURI) - throws XMLSecurityException { + public XMLX509SKI(Element element, String BaseURI) throws XMLSecurityException { super(element, BaseURI); } @@ -117,9 +113,8 @@ public class XMLX509SKI extends SignatureElementProxy throws XMLSecurityException { if (cert.getVersion() < 3) { - Object exArgs[] = { new Integer(cert.getVersion()) }; - throw new XMLSecurityException("certificate.noSki.lowVersion", - exArgs); + Object exArgs[] = { Integer.valueOf(cert.getVersion()) }; + throw new XMLSecurityException("certificate.noSki.lowVersion", exArgs); } /* @@ -137,7 +132,7 @@ public class XMLX509SKI extends SignatureElementProxy * Strip away first four bytes from the extensionValue * The first two bytes are the tag and length of the extensionValue * OCTET STRING, and the next two bytes are the tag and length of - * the skid OCTET STRING. + * the ski OCTET STRING. */ byte skidValue[] = new byte[extensionValue.length - 4]; @@ -152,23 +147,35 @@ public class XMLX509SKI extends SignatureElementProxy /** @inheritDoc */ public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!this.getClass().getName().equals(obj.getClass().getName())) { + if (!(obj instanceof XMLX509SKI)) { return false; } XMLX509SKI other = (XMLX509SKI) obj; try { - return java.security.MessageDigest.isEqual(other.getSKIBytes(), - this.getSKIBytes()); + return Arrays.equals(other.getSKIBytes(), this.getSKIBytes()); } catch (XMLSecurityException ex) { return false; } } + public int hashCode() { + int result = 17; + try { + byte[] bytes = getSKIBytes(); + for (int i = 0; i < bytes.length; i++) { + result = 31 * result + bytes[i]; + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + } + return result; + + } + /** @inheritDoc */ public String getBaseLocalName() { return Constants._TAG_X509SKI; diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java index 8d51da2e2fd..c183abbf8af 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.content.x509; @@ -30,65 +32,57 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; /** - * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ -public class XMLX509SubjectName extends SignatureElementProxy - implements XMLX509DataContent { +public class XMLX509SubjectName extends SignatureElementProxy implements XMLX509DataContent { - /** - * Constructor X509SubjectName - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public XMLX509SubjectName(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor X509SubjectName + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public XMLX509SubjectName(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } - /** - * Constructor X509SubjectName - * - * @param doc - * @param X509SubjectNameString - */ - public XMLX509SubjectName(Document doc, String X509SubjectNameString) { + /** + * Constructor X509SubjectName + * + * @param doc + * @param X509SubjectNameString + */ + public XMLX509SubjectName(Document doc, String X509SubjectNameString) { + super(doc); - super(doc); + this.addText(X509SubjectNameString); + } - this.addText(X509SubjectNameString); - } + /** + * Constructor XMLX509SubjectName + * + * @param doc + * @param x509certificate + */ + public XMLX509SubjectName(Document doc, X509Certificate x509certificate) { + this(doc, x509certificate.getSubjectX500Principal().getName()); + } - /** - * Constructor XMLX509SubjectName - * - * @param doc - * @param x509certificate - */ - public XMLX509SubjectName(Document doc, X509Certificate x509certificate) { - this(doc, - RFC2253Parser.normalize(x509certificate.getSubjectDN().getName())); - } - - /** - * Method getSubjectName - * - * - * @return the subject name - */ - public String getSubjectName() { - return RFC2253Parser.normalize(this.getTextFromTextChild()); - } + /** + * Method getSubjectName + * + * + * @return the subject name + */ + public String getSubjectName() { + return RFC2253Parser.normalize(this.getTextFromTextChild()); + } /** @inheritDoc */ public boolean equals(Object obj) { - if (obj == null) { - return false; - } - - if (!this.getClass().getName().equals(obj.getClass().getName())) { + if (!(obj instanceof XMLX509SubjectName)) { return false; } @@ -97,10 +91,16 @@ public class XMLX509SubjectName extends SignatureElementProxy String thisSubject = this.getSubjectName(); return thisSubject.equals(otherSubject); - } + } - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_X509SUBJECTNAME; - } + public int hashCode() { + int result = 17; + result = 31 * result + this.getSubjectName().hashCode(); + return result; + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_X509SUBJECTNAME; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java index 3b3508005cb..614a34f41e6 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java @@ -2,88 +2,80 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.keyresolver; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - -/** - * - * - * @author $Author: mullan $ - */ public class InvalidKeyResolverException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor InvalidKeyResolverException - * - */ - public InvalidKeyResolverException() { - super(); - } + /** + * Constructor InvalidKeyResolverException + * + */ + public InvalidKeyResolverException() { + super(); + } - /** - * Constructor InvalidKeyResolverException - * - * @param _msgID - */ - public InvalidKeyResolverException(String _msgID) { - super(_msgID); - } + /** + * Constructor InvalidKeyResolverException + * + * @param msgID + */ + public InvalidKeyResolverException(String msgID) { + super(msgID); + } - /** - * Constructor InvalidKeyResolverException - * - * @param _msgID - * @param exArgs - */ - public InvalidKeyResolverException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor InvalidKeyResolverException + * + * @param msgID + * @param exArgs + */ + public InvalidKeyResolverException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor InvalidKeyResolverException - * - * @param _msgID - * @param _originalException - */ - public InvalidKeyResolverException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor InvalidKeyResolverException + * + * @param msgID + * @param originalException + */ + public InvalidKeyResolverException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor InvalidKeyResolverException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public InvalidKeyResolverException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * Constructor InvalidKeyResolverException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public InvalidKeyResolverException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java index 00c60165f8a..fe541ff044f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java @@ -31,10 +31,13 @@ import java.util.concurrent.CopyOnWriteArrayList; import javax.crypto.SecretKey; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.DEREncodedKeyValueResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.DSAKeyValueResolver; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.KeyInfoReferenceResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.RSAKeyValueResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.RetrievalMethodResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509CertificateResolver; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509DigestResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509IssuerSerialResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SKIResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SubjectNameResolver; @@ -277,6 +280,9 @@ public class KeyResolver { keyResolverList.add(new KeyResolver(new RetrievalMethodResolver())); keyResolverList.add(new KeyResolver(new X509SubjectNameResolver())); keyResolverList.add(new KeyResolver(new X509IssuerSerialResolver())); + keyResolverList.add(new KeyResolver(new DEREncodedKeyValueResolver())); + keyResolverList.add(new KeyResolver(new KeyInfoReferenceResolver())); + keyResolverList.add(new KeyResolver(new X509DigestResolver())); resolverVector.addAll(keyResolverList); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java index f0069949b2f..028a0e9dec2 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java @@ -2,90 +2,80 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.keyresolver; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - -/** - * - * - * - * - * @author $Author: mullan $ - * - */ public class KeyResolverException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor KeyResolverException - * - */ - public KeyResolverException() { - super(); - } + /** + * Constructor KeyResolverException + * + */ + public KeyResolverException() { + super(); + } - /** - * Constructor KeyResolverException - * - * @param _msgID - */ - public KeyResolverException(String _msgID) { - super(_msgID); - } + /** + * Constructor KeyResolverException + * + * @param msgID + */ + public KeyResolverException(String msgID) { + super(msgID); + } - /** - * Constructor KeyResolverException - * - * @param _msgID - * @param exArgs - */ - public KeyResolverException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor KeyResolverException + * + * @param msgID + * @param exArgs + */ + public KeyResolverException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor KeyResolverException - * - * @param _msgID - * @param _originalException - */ - public KeyResolverException(String _msgID, Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor KeyResolverException + * + * @param msgID + * @param originalException + */ + public KeyResolverException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor KeyResolverException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public KeyResolverException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * Constructor KeyResolverException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public KeyResolverException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java index 3e5c82ccfe5..78622d79336 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java @@ -2,24 +2,27 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.keyresolver; +import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.X509Certificate; import java.util.HashMap; @@ -30,78 +33,89 @@ import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; import org.w3c.dom.Element; /** - * This class is abstract class for a child KeyInfo Elemnet. + * This class is an abstract class for a child KeyInfo Element. * - * If you want your KeyResolver, at first you must extend this class, and register + * If you want the your KeyResolver, at firstly you must extend this class, and register * as following in config.xml *

  *  <KeyResolver URI="http://www.w3.org/2000/09/xmldsig#KeyValue"
  *   JAVACLASS="MyPackage.MyKeyValueImpl"//gt;
  * 
- * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public abstract class KeyResolverSpi { - /** - * This method helps the {@link com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver} to decide whether a - * {@link com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi} is able to perform the requested action. - * - * @param element - * @param BaseURI - * @param storage - * @return - */ - public boolean engineCanResolve(Element element, String BaseURI, - StorageResolver storage) { - throw new UnsupportedOperationException(); - } - /** - * Method engineResolvePublicKey - * - * @param element - * @param BaseURI - * @param storage - * @return resolved public key from the registered from the element. - * - * @throws KeyResolverException - */ - public PublicKey engineResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - throw new UnsupportedOperationException(); + /** Field properties */ + protected java.util.Map properties = null; + + protected boolean globalResolver = false; + + protected boolean secureValidation; + + /** + * Set whether secure validation is enabled or not. The default is false. + */ + public void setSecureValidation(boolean secureValidation) { + this.secureValidation = secureValidation; + } + + /** + * This method returns whether the KeyResolverSpi is able to perform the requested action. + * + * @param element + * @param baseURI + * @param storage + * @return whether the KeyResolverSpi is able to perform the requested action. + */ + public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + throw new UnsupportedOperationException(); + } + + /** + * Method engineResolvePublicKey + * + * @param element + * @param baseURI + * @param storage + * @return resolved public key from the registered from the element. + * + * @throws KeyResolverException + */ + public PublicKey engineResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + throw new UnsupportedOperationException(); }; - /** - * Method engineResolvePublicKey - * - * @param element - * @param BaseURI - * @param storage - * @return resolved public key from the registered from the element. - * - * @throws KeyResolverException - */ + /** + * Method engineLookupAndResolvePublicKey + * + * @param element + * @param baseURI + * @param storage + * @return resolved public key from the registered from the element. + * + * @throws KeyResolverException + */ public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { KeyResolverSpi tmp = cloneIfNeeded(); - if (!tmp.engineCanResolve(element, BaseURI, storage)) - return null; - return tmp.engineResolvePublicKey(element, BaseURI, storage); + if (!tmp.engineCanResolve(element, baseURI, storage)) { + return null; + } + return tmp.engineResolvePublicKey(element, baseURI, storage); } private KeyResolverSpi cloneIfNeeded() throws KeyResolverException { - KeyResolverSpi tmp=this; + KeyResolverSpi tmp = this; if (globalResolver) { - try { - tmp = (KeyResolverSpi) getClass().newInstance(); - } catch (InstantiationException e) { - throw new KeyResolverException("",e); - } catch (IllegalAccessException e) { - throw new KeyResolverException("",e); - } + try { + tmp = getClass().newInstance(); + } catch (InstantiationException e) { + throw new KeyResolverException("", e); + } catch (IllegalAccessException e) { + throw new KeyResolverException("", e); + } } return tmp; } @@ -110,116 +124,138 @@ public abstract class KeyResolverSpi { * Method engineResolveCertificate * * @param element - * @param BaseURI + * @param baseURI * @param storage * @return resolved X509Certificate key from the registered from the elements * * @throws KeyResolverException */ public X509Certificate engineResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException{ - throw new UnsupportedOperationException(); + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException{ + throw new UnsupportedOperationException(); }; - /** - * Method engineResolveCertificate - * - * @param element - * @param BaseURI - * @param storage - * @return resolved X509Certificate key from the registered from the elements - * - * @throws KeyResolverException - */ + /** + * Method engineLookupResolveX509Certificate + * + * @param element + * @param baseURI + * @param storage + * @return resolved X509Certificate key from the registered from the elements + * + * @throws KeyResolverException + */ public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { KeyResolverSpi tmp = cloneIfNeeded(); - if (!tmp.engineCanResolve(element, BaseURI, storage)) - return null; - return tmp.engineResolveX509Certificate(element, BaseURI, storage); + if (!tmp.engineCanResolve(element, baseURI, storage)) { + return null; + } + return tmp.engineResolveX509Certificate(element, baseURI, storage); } /** * Method engineResolveSecretKey * * @param element - * @param BaseURI + * @param baseURI * @param storage * @return resolved SecretKey key from the registered from the elements * * @throws KeyResolverException */ public SecretKey engineResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException{ - throw new UnsupportedOperationException(); + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException{ + throw new UnsupportedOperationException(); }; - /** - * Method engineResolveSecretKey - * - * @param element - * @param BaseURI - * @param storage - * @return resolved SecretKey key from the registered from the elements - * - * @throws KeyResolverException - */ - public SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - KeyResolverSpi tmp = cloneIfNeeded(); - if (!tmp.engineCanResolve(element, BaseURI, storage)) - return null; - return tmp.engineResolveSecretKey(element, BaseURI, storage); - } + /** + * Method engineLookupAndResolveSecretKey + * + * @param element + * @param baseURI + * @param storage + * @return resolved SecretKey key from the registered from the elements + * + * @throws KeyResolverException + */ + public SecretKey engineLookupAndResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + KeyResolverSpi tmp = cloneIfNeeded(); + if (!tmp.engineCanResolve(element, baseURI, storage)) { + return null; + } + return tmp.engineResolveSecretKey(element, baseURI, storage); + } - /** Field _properties */ - protected java.util.Map _properties = null; + /** + * Method engineLookupAndResolvePrivateKey + * + * @param element + * @param baseURI + * @param storage + * @return resolved PrivateKey key from the registered from the elements + * + * @throws KeyResolverException + */ + public PrivateKey engineLookupAndResolvePrivateKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + // This method was added later, it has no equivalent + // engineResolvePrivateKey() in the old API. + // We cannot throw UnsupportedOperationException because + // KeyResolverSpi implementations who don't know about + // this method would stop the search too early. + return null; + } - protected boolean globalResolver=false; + /** + * Method engineSetProperty + * + * @param key + * @param value + */ + public void engineSetProperty(String key, String value) { + if (properties == null) { + properties = new HashMap(); + } + properties.put(key, value); + } - /** - * Method engineSetProperty - * - * @param key - * @param value - */ - public void engineSetProperty(String key, String value) { - if (_properties==null) - _properties=new HashMap(); - this._properties.put(key, value); - } + /** + * Method engineGetProperty + * + * @param key + * @return obtain the property appointed by key + */ + public String engineGetProperty(String key) { + if (properties == null) { + return null; + } - /** - * Method engineGetProperty - * - * @param key - * @return obtain the property appointed by key - */ - public String engineGetProperty(String key) { - if (_properties==null) - return null; + return properties.get(key); + } - return this._properties.get(key); - } + /** + * Method understandsProperty + * + * @param propertyToTest + * @return true if understood the property + */ + public boolean understandsProperty(String propertyToTest) { + if (properties == null) { + return false; + } - /** - * Method understandsProperty - * - * @param propertyToTest - * @return true if understood the property - */ - public boolean understandsProperty(String propertyToTest) { - if (_properties==null) - return false; + return properties.get(propertyToTest) != null; + } - return this._properties.get(propertyToTest)!=null; - } - public void setGlobalResolver(boolean globalResolver) { + public void setGlobalResolver(boolean globalResolver) { this.globalResolver = globalResolver; - } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java new file mode 100644 index 00000000000..dbd2e084f0c --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java @@ -0,0 +1,83 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.X509Certificate; + +import javax.crypto.SecretKey; + +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.keys.content.DEREncodedKeyValue; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import org.w3c.dom.Element; + +/** + * KeyResolverSpi implementation which resolves public keys from a + * dsig11:DEREncodedKeyValue element. + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public class DEREncodedKeyValueResolver extends KeyResolverSpi { + + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(DEREncodedKeyValueResolver.class.getName()); + + /** {@inheritDoc}. */ + public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + return XMLUtils.elementIsInSignature11Space(element, Constants._TAG_DERENCODEDKEYVALUE); + } + + /** {@inheritDoc}. */ + public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + DEREncodedKeyValue derKeyValue = new DEREncodedKeyValue(element, baseURI); + return derKeyValue.getPublicKey(); + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** {@inheritDoc}. */ + public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + return null; + } + + /** {@inheritDoc}. */ + public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + return null; + } + + /** {@inheritDoc}. */ + public PrivateKey engineLookupAndResolvePrivateKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + return null; + } + + + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java index 20bf7bad777..784d5fc874d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java @@ -2,30 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; import java.security.cert.X509Certificate; - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.keys.content.keyvalues.DSAKeyValue; import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; @@ -34,66 +33,70 @@ import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - -/** - * - * @author $Author: mullan $ - */ public class DSAKeyValueResolver extends KeyResolverSpi { - /** - * Method engineResolvePublicKey - * - * @param element - * @param BaseURI - * @param storage - * @return null if no {@link PublicKey} could be obtained - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) { - if (element == null) { - return null; - } - Element dsaKeyElement=null; - boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_KEYVALUE); - if (isKeyValue) { - dsaKeyElement = - XMLUtils.selectDsNode(element.getFirstChild(),Constants._TAG_DSAKEYVALUE,0); - } else if (XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_DSAKEYVALUE)) { - // this trick is needed to allow the RetrievalMethodResolver to eat a - // ds:DSAKeyValue directly (without KeyValue) - dsaKeyElement = element; + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(DSAKeyValueResolver.class.getName()); + + + /** + * Method engineResolvePublicKey + * + * @param element + * @param BaseURI + * @param storage + * @return null if no {@link PublicKey} could be obtained + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String BaseURI, StorageResolver storage + ) { + if (element == null) { + return null; + } + Element dsaKeyElement = null; + boolean isKeyValue = + XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYVALUE); + if (isKeyValue) { + dsaKeyElement = + XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_DSAKEYVALUE, 0); + } else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_DSAKEYVALUE)) { + // this trick is needed to allow the RetrievalMethodResolver to eat a + // ds:DSAKeyValue directly (without KeyValue) + dsaKeyElement = element; + } + + if (dsaKeyElement == null) { + return null; + } + + try { + DSAKeyValue dsaKeyValue = new DSAKeyValue(dsaKeyElement, BaseURI); + PublicKey pk = dsaKeyValue.getPublicKey(); + + return pk; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); } + //do nothing + } - if (dsaKeyElement == null) { - return null; - } - - try { - DSAKeyValue dsaKeyValue = new DSAKeyValue(dsaKeyElement, - BaseURI); - PublicKey pk = dsaKeyValue.getPublicKey(); - - return pk; - } catch (XMLSecurityException ex) { - //do nothing - } - - return null; - } + return null; + } - /** @inheritDoc */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) { - return null; - } + /** @inheritDoc */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } - /** @inheritDoc */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage){ - return null; - } + /** @inheritDoc */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java index 6adc050e893..a1be10b977f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java @@ -2,39 +2,43 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; import java.security.Key; import java.security.PublicKey; import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; import javax.crypto.SecretKey; import com.sun.org.apache.xml.internal.security.encryption.EncryptedKey; import com.sun.org.apache.xml.internal.security.encryption.XMLCipher; +import com.sun.org.apache.xml.internal.security.encryption.XMLEncryptionException; import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - /** * The EncryptedKeyResolver is not a generic resolver. It can * only be for specific instantiations, as the key being unwrapped will @@ -47,78 +51,100 @@ import org.w3c.dom.Element; * * @author Berin Lautenbach */ - public class EncryptedKeyResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - RSAKeyValueResolver.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(EncryptedKeyResolver.class.getName()); + private Key kek; + private String algorithm; + private List internalKeyResolvers; - Key _kek; - String _algorithm; - - /** - * Constructor for use when a KEK needs to be derived from a KeyInfo - * list - * @param algorithm - */ - public EncryptedKeyResolver(String algorithm) { - _kek = null; - _algorithm=algorithm; - } - - /** - * Constructor used for when a KEK has been set - * @param algorithm - * @param kek - */ - - public EncryptedKeyResolver(String algorithm, Key kek) { - _algorithm = algorithm; - _kek = kek; + /** + * Constructor for use when a KEK needs to be derived from a KeyInfo + * list + * @param algorithm + */ + public EncryptedKeyResolver(String algorithm) { + kek = null; + this.algorithm = algorithm; + } + /** + * Constructor used for when a KEK has been set + * @param algorithm + * @param kek + */ + public EncryptedKeyResolver(String algorithm, Key kek) { + this.algorithm = algorithm; + this.kek = kek; + } + + /** + * This method is used to add a custom {@link KeyResolverSpi} to help + * resolve the KEK. + * + * @param realKeyResolver + */ + public void registerInternalKeyResolver(KeyResolverSpi realKeyResolver) { + if (internalKeyResolvers == null) { + internalKeyResolvers = new ArrayList(); } + internalKeyResolvers.add(realKeyResolver); + } /** @inheritDoc */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) { + public PublicKey engineLookupAndResolvePublicKey( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } - return null; - } + /** @inheritDoc */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } - /** @inheritDoc */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) { - return null; - } + /** @inheritDoc */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String BaseURI, StorageResolver storage + ) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "EncryptedKeyResolver - Can I resolve " + element.getTagName()); + } - /** @inheritDoc */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) { - SecretKey key=null; - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "EncryptedKeyResolver - Can I resolve " + element.getTagName()); + if (element == null) { + return null; + } - if (element == null) { - return null; - } + SecretKey key = null; + boolean isEncryptedKey = + XMLUtils.elementIsInEncryptionSpace(element, EncryptionConstants._TAG_ENCRYPTEDKEY); + if (isEncryptedKey) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Passed an Encrypted Key"); + } + try { + XMLCipher cipher = XMLCipher.getInstance(); + cipher.init(XMLCipher.UNWRAP_MODE, kek); + if (internalKeyResolvers != null) { + int size = internalKeyResolvers.size(); + for (int i = 0; i < size; i++) { + cipher.registerInternalKeyResolver(internalKeyResolvers.get(i)); + } + } + EncryptedKey ek = cipher.loadEncryptedKey(element); + key = (SecretKey) cipher.decryptKey(ek, algorithm); + } catch (XMLEncryptionException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + } + } - boolean isEncryptedKey = XMLUtils.elementIsInEncryptionSpace(element, - EncryptionConstants._TAG_ENCRYPTEDKEY); - - if (isEncryptedKey) { - log.log(java.util.logging.Level.FINE, "Passed an Encrypted Key"); - try { - XMLCipher cipher = XMLCipher.getInstance(); - cipher.init(XMLCipher.UNWRAP_MODE, _kek); - EncryptedKey ek = cipher.loadEncryptedKey(element); - key = (SecretKey) cipher.decryptKey(ek, _algorithm); - } - catch (Exception e) {} - } - - return key; - } + return key; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java new file mode 100644 index 00000000000..0e63715e2df --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java @@ -0,0 +1,290 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.X509Certificate; + +import javax.crypto.SecretKey; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.keys.KeyInfo; +import com.sun.org.apache.xml.internal.security.keys.content.KeyInfoReference; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** + * KeyResolverSpi implementation which resolves public keys, private keys, secret keys, and X.509 certificates from a + * dsig11:KeyInfoReference element. + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public class KeyInfoReferenceResolver extends KeyResolverSpi { + + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(KeyInfoReferenceResolver.class.getName()); + + /** {@inheritDoc}. */ + public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + return XMLUtils.elementIsInSignature11Space(element, Constants._TAG_KEYINFOREFERENCE); + } + + /** {@inheritDoc}. */ + public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage); + if (referent != null) { + return referent.getPublicKey(); + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** {@inheritDoc}. */ + public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage); + if (referent != null) { + return referent.getX509Certificate(); + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** {@inheritDoc}. */ + public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage); + if (referent != null) { + return referent.getSecretKey(); + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** {@inheritDoc}. */ + public PrivateKey engineLookupAndResolvePrivateKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage); + if (referent != null) { + return referent.getPrivateKey(); + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** + * Resolve the KeyInfoReference Element's URI attribute into a KeyInfo instance. + * + * @param element + * @param baseURI + * @param storage + * @return the KeyInfo which is referred to by this KeyInfoReference, or null if can not be resolved + * @throws XMLSecurityException + */ + private KeyInfo resolveReferentKeyInfo(Element element, String baseURI, StorageResolver storage) throws XMLSecurityException { + KeyInfoReference reference = new KeyInfoReference(element, baseURI); + Attr uriAttr = reference.getURIAttr(); + + XMLSignatureInput resource = resolveInput(uriAttr, baseURI, secureValidation); + + Element referentElement = null; + try { + referentElement = obtainReferenceElement(resource); + } catch (Exception e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + return null; + } + + if (referentElement == null) { + log.log(java.util.logging.Level.FINE, "De-reference of KeyInfoReference URI returned null: " + uriAttr.getValue()); + return null; + } + + validateReference(referentElement); + + KeyInfo referent = new KeyInfo(referentElement, baseURI); + referent.addStorageResolver(storage); + return referent; + } + + /** + * Validate the Element referred to by the KeyInfoReference. + * + * @param referentElement + * + * @throws XMLSecurityException + */ + private void validateReference(Element referentElement) throws XMLSecurityException { + if (!XMLUtils.elementIsInSignatureSpace(referentElement, Constants._TAG_KEYINFO)) { + Object exArgs[] = { new QName(referentElement.getNamespaceURI(), referentElement.getLocalName()) }; + throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.WrongType", exArgs); + } + + KeyInfo referent = new KeyInfo(referentElement, ""); + if (referent.containsKeyInfoReference()) { + if (secureValidation) { + throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.ReferenceWithSecure"); + } else { + // Don't support chains of references at this time. If do support in the future, this is where the code + // would go to validate that don't have a cycle, resulting in an infinite loop. This may be unrealistic + // to implement, and/or very expensive given remote URI references. + throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.ReferenceWithoutSecure"); + } + } + + } + + /** + * Resolve the XML signature input represented by the specified URI. + * + * @param uri + * @param baseURI + * @param secureValidation + * @return + * @throws XMLSecurityException + */ + private XMLSignatureInput resolveInput(Attr uri, String baseURI, boolean secureValidation) + throws XMLSecurityException { + ResourceResolver resRes = ResourceResolver.getInstance(uri, baseURI, secureValidation); + XMLSignatureInput resource = resRes.resolve(uri, baseURI, secureValidation); + return resource; + } + + /** + * Resolve the Element effectively represented by the XML signature input source. + * + * @param resource + * @return + * @throws CanonicalizationException + * @throws ParserConfigurationException + * @throws IOException + * @throws SAXException + * @throws KeyResolverException + */ + private Element obtainReferenceElement(XMLSignatureInput resource) + throws CanonicalizationException, ParserConfigurationException, + IOException, SAXException, KeyResolverException { + + Element e; + if (resource.isElement()){ + e = (Element) resource.getSubNode(); + } else if (resource.isNodeSet()) { + log.log(java.util.logging.Level.FINE, "De-reference of KeyInfoReference returned an unsupported NodeSet"); + return null; + } else { + // Retrieved resource is a byte stream + byte inputBytes[] = resource.getBytes(); + e = getDocFromBytes(inputBytes); + } + return e; + } + + /** + * Parses a byte array and returns the parsed Element. + * + * @param bytes + * @return the Document Element after parsing bytes + * @throws KeyResolverException if something goes wrong + */ + private Element getDocFromBytes(byte[] bytes) throws KeyResolverException { + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document doc = db.parse(new ByteArrayInputStream(bytes)); + return doc.getDocumentElement(); + } catch (SAXException ex) { + throw new KeyResolverException("empty", ex); + } catch (IOException ex) { + throw new KeyResolverException("empty", ex); + } catch (ParserConfigurationException ex) { + throw new KeyResolverException("empty", ex); + } + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java new file mode 100644 index 00000000000..708cda45049 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java @@ -0,0 +1,353 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.security.Key; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.Certificate; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Enumeration; +import javax.crypto.SecretKey; +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.keys.content.X509Data; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509IssuerSerial; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SubjectName; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import org.w3c.dom.Element; + +/** + * Resolves a PrivateKey within a KeyStore based on the KeyInfo hints. + * For X509Data hints, the certificate associated with the private key entry must match. + * For a KeyName hint, the KeyName must match the alias of a PrivateKey entry within the KeyStore. + */ +public class PrivateKeyResolver extends KeyResolverSpi { + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(PrivateKeyResolver.class.getName()); + + private KeyStore keyStore; + private char[] password; + + /** + * Constructor. + */ + public PrivateKeyResolver(KeyStore keyStore, char[] password) { + this.keyStore = keyStore; + this.password = password; + } + + /** + * This method returns whether the KeyResolverSpi is able to perform the requested action. + * + * @param element + * @param BaseURI + * @param storage + * @return whether the KeyResolverSpi is able to perform the requested action. + */ + public boolean engineCanResolve(Element element, String BaseURI, StorageResolver storage) { + if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA) + || XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + return true; + } + + return false; + } + + /** + * Method engineLookupAndResolvePublicKey + * + * @param element + * @param BaseURI + * @param storage + * @return null if no {@link PublicKey} could be obtained + * @throws KeyResolverException + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String BaseURI, StorageResolver storage + ) throws KeyResolverException { + return null; + } + + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param BaseURI + * @param storage + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String BaseURI, StorageResolver storage + ) throws KeyResolverException { + return null; + } + + /** + * Method engineResolveSecretKey + * + * @param element + * @param BaseURI + * @param storage + * @return resolved SecretKey key or null if no {@link SecretKey} could be obtained + * + * @throws KeyResolverException + */ + public SecretKey engineResolveSecretKey( + Element element, String BaseURI, StorageResolver storage + ) throws KeyResolverException { + return null; + } + + /** + * Method engineResolvePrivateKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * @return resolved PrivateKey key or null if no {@link PrivateKey} could be obtained + * @throws KeyResolverException + */ + public PrivateKey engineLookupAndResolvePrivateKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + + if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) { + PrivateKey privKey = resolveX509Data(element, baseURI); + if (privKey != null) { + return privKey; + } + } else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + log.log(java.util.logging.Level.FINE, "Can I resolve KeyName?"); + String keyName = element.getFirstChild().getNodeValue(); + + try { + Key key = keyStore.getKey(keyName, password); + if (key instanceof PrivateKey) { + return (PrivateKey) key; + } + } catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + } + } + + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } + + private PrivateKey resolveX509Data(Element element, String baseURI) { + log.log(java.util.logging.Level.FINE, "Can I resolve X509Data?"); + + try { + X509Data x509Data = new X509Data(element, baseURI); + + int len = x509Data.lengthSKI(); + for (int i = 0; i < len; i++) { + XMLX509SKI x509SKI = x509Data.itemSKI(i); + PrivateKey privKey = resolveX509SKI(x509SKI); + if (privKey != null) { + return privKey; + } + } + + len = x509Data.lengthIssuerSerial(); + for (int i = 0; i < len; i++) { + XMLX509IssuerSerial x509Serial = x509Data.itemIssuerSerial(i); + PrivateKey privKey = resolveX509IssuerSerial(x509Serial); + if (privKey != null) { + return privKey; + } + } + + len = x509Data.lengthSubjectName(); + for (int i = 0; i < len; i++) { + XMLX509SubjectName x509SubjectName = x509Data.itemSubjectName(i); + PrivateKey privKey = resolveX509SubjectName(x509SubjectName); + if (privKey != null) { + return privKey; + } + } + + len = x509Data.lengthCertificate(); + for (int i = 0; i < len; i++) { + XMLX509Certificate x509Cert = x509Data.itemCertificate(i); + PrivateKey privKey = resolveX509Certificate(x509Cert); + if (privKey != null) { + return privKey; + } + } + } catch (XMLSecurityException e) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } catch (KeyStoreException e) { + log.log(java.util.logging.Level.FINE, "KeyStoreException", e); + } + + return null; + } + + /* + * Search for a private key entry in the KeyStore with the same Subject Key Identifier + */ + private PrivateKey resolveX509SKI(XMLX509SKI x509SKI) throws XMLSecurityException, KeyStoreException { + log.log(java.util.logging.Level.FINE, "Can I resolve X509SKI?"); + + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (keyStore.isKeyEntry(alias)) { + + Certificate cert = keyStore.getCertificate(alias); + if (cert instanceof X509Certificate) { + XMLX509SKI certSKI = new XMLX509SKI(x509SKI.getDocument(), (X509Certificate) cert); + + if (certSKI.equals(x509SKI)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + + try { + Key key = keyStore.getKey(alias, password); + if (key instanceof PrivateKey) { + return (PrivateKey) key; + } + } catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + // Keep searching + } + } + } + } + } + + return null; + } + + /* + * Search for a private key entry in the KeyStore with the same Issuer/Serial Number pair. + */ + private PrivateKey resolveX509IssuerSerial(XMLX509IssuerSerial x509Serial) throws KeyStoreException { + log.log(java.util.logging.Level.FINE, "Can I resolve X509IssuerSerial?"); + + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (keyStore.isKeyEntry(alias)) { + + Certificate cert = keyStore.getCertificate(alias); + if (cert instanceof X509Certificate) { + XMLX509IssuerSerial certSerial = + new XMLX509IssuerSerial(x509Serial.getDocument(), (X509Certificate) cert); + + if (certSerial.equals(x509Serial)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + + try { + Key key = keyStore.getKey(alias, password); + if (key instanceof PrivateKey) { + return (PrivateKey) key; + } + } catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + // Keep searching + } + } + } + } + } + + return null; + } + + /* + * Search for a private key entry in the KeyStore with the same Subject Name. + */ + private PrivateKey resolveX509SubjectName(XMLX509SubjectName x509SubjectName) throws KeyStoreException { + log.log(java.util.logging.Level.FINE, "Can I resolve X509SubjectName?"); + + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (keyStore.isKeyEntry(alias)) { + + Certificate cert = keyStore.getCertificate(alias); + if (cert instanceof X509Certificate) { + XMLX509SubjectName certSN = + new XMLX509SubjectName(x509SubjectName.getDocument(), (X509Certificate) cert); + + if (certSN.equals(x509SubjectName)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + + try { + Key key = keyStore.getKey(alias, password); + if (key instanceof PrivateKey) { + return (PrivateKey) key; + } + } catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + // Keep searching + } + } + } + } + } + + return null; + } + + /* + * Search for a private key entry in the KeyStore with the same Certificate. + */ + private PrivateKey resolveX509Certificate( + XMLX509Certificate x509Cert + ) throws XMLSecurityException, KeyStoreException { + log.log(java.util.logging.Level.FINE, "Can I resolve X509Certificate?"); + byte[] x509CertBytes = x509Cert.getCertificateBytes(); + + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (keyStore.isKeyEntry(alias)) { + + Certificate cert = keyStore.getCertificate(alias); + if (cert instanceof X509Certificate) { + byte[] certBytes = null; + + try { + certBytes = cert.getEncoded(); + } catch (CertificateEncodingException e1) { + } + + if (certBytes != null && Arrays.equals(certBytes, x509CertBytes)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + + try { + Key key = keyStore.getKey(alias, password); + if (key instanceof PrivateKey) { + return (PrivateKey) key; + } + } + catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + // Keep searching + } + } + } + } + } + + return null; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java index fb38e872590..b493f98182d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; import java.security.cert.X509Certificate; @@ -34,69 +34,63 @@ import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - -/** - * - * @author $Author: mullan $ - */ public class RSAKeyValueResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - RSAKeyValueResolver.class.getName()); - - /** Field _rsaKeyElement */ + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(RSAKeyValueResolver.class.getName()); - /** @inheritDoc */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); - if (element == null) { - return null; - } + /** @inheritDoc */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String BaseURI, StorageResolver storage + ) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + if (element == null) { + return null; + } - boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_KEYVALUE); - Element rsaKeyElement=null; - if (isKeyValue) { - rsaKeyElement = XMLUtils.selectDsNode(element.getFirstChild(), - Constants._TAG_RSAKEYVALUE, 0); - } else if (XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_RSAKEYVALUE)) { - // this trick is needed to allow the RetrievalMethodResolver to eat a - // ds:RSAKeyValue directly (without KeyValue) - rsaKeyElement = element; - } + boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYVALUE); + Element rsaKeyElement = null; + if (isKeyValue) { + rsaKeyElement = + XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_RSAKEYVALUE, 0); + } else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RSAKEYVALUE)) { + // this trick is needed to allow the RetrievalMethodResolver to eat a + // ds:RSAKeyValue directly (without KeyValue) + rsaKeyElement = element; + } + if (rsaKeyElement == null) { + return null; + } - if (rsaKeyElement == null) { - return null; - } + try { + RSAKeyValue rsaKeyValue = new RSAKeyValue(rsaKeyElement, BaseURI); - try { - RSAKeyValue rsaKeyValue = new RSAKeyValue(rsaKeyElement, - BaseURI); + return rsaKeyValue.getPublicKey(); + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } + } - return rsaKeyValue.getPublicKey(); - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); - } + return null; + } - return null; - } + /** @inheritDoc */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } - /** @inheritDoc */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) { - return null; - } - - /** @inheritDoc */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) { - return null; - } + /** @inheritDoc */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java index 4ba848a681d..e5159c084b6 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.io.ByteArrayInputStream; import java.io.IOException; import java.security.PublicKey; @@ -35,6 +35,8 @@ import java.util.ListIterator; import java.util.Set; import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; @@ -51,11 +53,11 @@ import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver; import org.w3c.dom.Attr; +import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.SAXException; - /** * The RetrievalMethodResolver can retrieve public keys and certificates from * other locations. The location is specified using the ds:RetrievalMethod @@ -65,252 +67,325 @@ import org.xml.sax.SAXException; * RetrievalMethodResolver cannot handle itself, resolving of the extracted * element is delegated back to the KeyResolver mechanism. * - * @author $Author: mullan $ modified by Dave Garcia + * @author $Author: raul $ modified by Dave Garcia */ public class RetrievalMethodResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - RetrievalMethodResolver.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(RetrievalMethodResolver.class.getName()); - /** - * Method engineResolvePublicKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - { - if (!XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_RETRIEVALMETHOD)) { - return null; - } - - try { - //Create a retrieval method over the given element - RetrievalMethod rm = new RetrievalMethod(element, BaseURI); - String type = rm.getType(); - XMLSignatureInput resource=resolveInput(rm,BaseURI); - if (RetrievalMethod.TYPE_RAWX509.equals(type)) { - //a raw certificate, direct parsing is done! - X509Certificate cert=getRawCertificate(resource); - if (cert != null) { - return cert.getPublicKey(); - } - return null; - }; - Element e = obtainRefrenceElement(resource); - return resolveKey(e,BaseURI,storage); - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); - } catch (CertificateException ex) { - log.log(java.util.logging.Level.FINE, "CertificateException", ex); - } catch (IOException ex) { - log.log(java.util.logging.Level.FINE, "IOException", ex); - } catch (ParserConfigurationException e) { - log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e); - } catch (SAXException e) { - log.log(java.util.logging.Level.FINE, "SAXException", e); - } - return null; - } - - static private Element obtainRefrenceElement(XMLSignatureInput resource) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException, KeyResolverException { - Element e; - if (resource.isElement()){ - e=(Element) resource.getSubNode(); - } else if (resource.isNodeSet()) { - //Retrieved resource is a nodeSet - e=getDocumentElement(resource.getNodeSet()); - } else { - //Retrieved resource is an inputStream - byte inputBytes[] = resource.getBytes(); - e = getDocFromBytes(inputBytes); - //otherwise, we parse the resource, create an Element and delegate - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "we have to parse " + inputBytes.length + " bytes"); - } - return e; - } - - /** - * Method engineResolveX509Certificate - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - { - if (!XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_RETRIEVALMETHOD)) { - return null; - } - - try { - RetrievalMethod rm = new RetrievalMethod(element, BaseURI); - String type = rm.getType(); - XMLSignatureInput resource=resolveInput(rm,BaseURI); - if (RetrievalMethod.TYPE_RAWX509.equals(type)) { - X509Certificate cert=getRawCertificate(resource); - return cert; - } - Element e = obtainRefrenceElement(resource); - return resolveCertificate(e,BaseURI,storage); - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); - } catch (CertificateException ex) { - log.log(java.util.logging.Level.FINE, "CertificateException", ex); - } catch (IOException ex) { - log.log(java.util.logging.Level.FINE, "IOException", ex); - } catch (ParserConfigurationException e) { - log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e); - } catch (SAXException e) { - log.log(java.util.logging.Level.FINE, "SAXException", e); - } - return null; - } - - /** - * Retrieves a x509Certificate from the given information - * @param e - * @param BaseURI - * @param storage - * @return - * @throws KeyResolverException - */ - static private X509Certificate resolveCertificate(Element e,String BaseURI,StorageResolver storage) throws KeyResolverException{ - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}"+ e.getLocalName() + " Element"); - //An element has been provided - if (e != null) { - return KeyResolver.getX509Certificate(e,BaseURI, storage); - } - return null; - } - - /** - * Retrieves a x509Certificate from the given information - * @param e - * @param BaseURI - * @param storage - * @return - * @throws KeyResolverException - */ - static private PublicKey resolveKey(Element e,String BaseURI,StorageResolver storage) throws KeyResolverException{ - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}"+ e.getLocalName() + " Element"); - //An element has been provided - if (e != null) { - return KeyResolver.getPublicKey(e,BaseURI, storage); - } - return null; - } - - static private X509Certificate getRawCertificate(XMLSignatureInput resource) throws CanonicalizationException, IOException, CertificateException{ - byte inputBytes[] = resource.getBytes(); - // if the resource stores a raw certificate, we have to handle it - CertificateFactory certFact =CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID); - X509Certificate cert =(X509Certificate) certFact.generateCertificate(new ByteArrayInputStream(inputBytes)); - return cert; - } - /** - * Resolves the input from the given retrieval method - * @return - * @throws XMLSecurityException - */ - static private XMLSignatureInput resolveInput(RetrievalMethod rm,String BaseURI) throws XMLSecurityException{ - Attr uri = rm.getURIAttr(); - //Apply the trnasforms - Transforms transforms = rm.getTransforms(); - ResourceResolver resRes = ResourceResolver.getInstance(uri, BaseURI); - if (resRes != null) { - XMLSignatureInput resource = resRes.resolve(uri, BaseURI); - if (transforms != null) { - log.log(java.util.logging.Level.FINE, "We have Transforms"); - resource = transforms.performTransforms(resource); - } - return resource; - } - return null; - } - - /** - * Parses a byte array and returns the parsed Element. - * - * @param bytes - * @return the Document Element after parsing bytes - * @throws KeyResolverException if something goes wrong - */ - static Element getDocFromBytes(byte[] bytes) throws KeyResolverException { - try { - javax.xml.parsers.DocumentBuilderFactory dbf =javax.xml.parsers.DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); - javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); - org.w3c.dom.Document doc = - db.parse(new java.io.ByteArrayInputStream(bytes)); - return doc.getDocumentElement(); - } catch (org.xml.sax.SAXException ex) { - throw new KeyResolverException("empty", ex); - } catch (java.io.IOException ex) { - throw new KeyResolverException("empty", ex); - } catch (javax.xml.parsers.ParserConfigurationException ex) { - throw new KeyResolverException("empty", ex); - } - } - - /** - * Method engineResolveSecretKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - { - return null; - } - - static Element getDocumentElement(Set set) { - Iterator it=set.iterator(); - Element e=null; - while (it.hasNext()) { - Node currentNode=it.next(); - if (currentNode != null && currentNode.getNodeType() == Node.ELEMENT_NODE) { - e=(Element)currentNode; - break; - } - - } - List parents=new ArrayList(10); - - //Obtain all the parents of the elemnt - while (e != null) { - parents.add(e); - Node n=e.getParentNode(); - if (n == null || n.getNodeType() != Node.ELEMENT_NODE) { - break; - } - e=(Element)n; - } - //Visit them in reverse order. - ListIterator it2=parents.listIterator(parents.size()-1); - Element ele=null; - while (it2.hasPrevious()) { - ele=it2.previous(); - if (set.contains(ele)) { - return ele; - } + /** + * Method engineResolvePublicKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) { + if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RETRIEVALMETHOD)) { + return null; } + + try { + // Create a retrieval method over the given element + RetrievalMethod rm = new RetrievalMethod(element, baseURI); + String type = rm.getType(); + XMLSignatureInput resource = resolveInput(rm, baseURI, secureValidation); + if (RetrievalMethod.TYPE_RAWX509.equals(type)) { + // a raw certificate, direct parsing is done! + X509Certificate cert = getRawCertificate(resource); + if (cert != null) { + return cert.getPublicKey(); + } return null; - } + } + Element e = obtainReferenceElement(resource); + + // Check to make sure that the reference is not to another RetrievalMethod + // which points to this element + if (XMLUtils.elementIsInSignatureSpace(e, Constants._TAG_RETRIEVALMETHOD)) { + if (secureValidation) { + String error = "Error: It is forbidden to have one RetrievalMethod " + + "point to another with secure validation"; + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, error); + } + return null; + } + RetrievalMethod rm2 = new RetrievalMethod(e, baseURI); + XMLSignatureInput resource2 = resolveInput(rm2, baseURI, secureValidation); + Element e2 = obtainReferenceElement(resource2); + if (e2 == element) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Error: Can't have RetrievalMethods pointing to each other"); + } + return null; + } + } + + return resolveKey(e, baseURI, storage); + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } + } catch (CertificateException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "CertificateException", ex); + } + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "IOException", ex); + } + } catch (ParserConfigurationException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e); + } + } catch (SAXException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "SAXException", e); + } + } + return null; + } + + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param baseURI + * @param storage + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage) { + if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RETRIEVALMETHOD)) { + return null; + } + + try { + RetrievalMethod rm = new RetrievalMethod(element, baseURI); + String type = rm.getType(); + XMLSignatureInput resource = resolveInput(rm, baseURI, secureValidation); + if (RetrievalMethod.TYPE_RAWX509.equals(type)) { + return getRawCertificate(resource); + } + + Element e = obtainReferenceElement(resource); + + // Check to make sure that the reference is not to another RetrievalMethod + // which points to this element + if (XMLUtils.elementIsInSignatureSpace(e, Constants._TAG_RETRIEVALMETHOD)) { + if (secureValidation) { + String error = "Error: It is forbidden to have one RetrievalMethod " + + "point to another with secure validation"; + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, error); + } + return null; + } + RetrievalMethod rm2 = new RetrievalMethod(e, baseURI); + XMLSignatureInput resource2 = resolveInput(rm2, baseURI, secureValidation); + Element e2 = obtainReferenceElement(resource2); + if (e2 == element) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Error: Can't have RetrievalMethods pointing to each other"); + } + return null; + } + } + + return resolveCertificate(e, baseURI, storage); + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } + } catch (CertificateException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "CertificateException", ex); + } + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "IOException", ex); + } + } catch (ParserConfigurationException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e); + } + } catch (SAXException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "SAXException", e); + } + } + return null; + } + + /** + * Retrieves a x509Certificate from the given information + * @param e + * @param baseURI + * @param storage + * @return + * @throws KeyResolverException + */ + private static X509Certificate resolveCertificate( + Element e, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}" + + e.getLocalName() + " Element"); + } + // An element has been provided + if (e != null) { + return KeyResolver.getX509Certificate(e, baseURI, storage); + } + return null; + } + + /** + * Retrieves a PublicKey from the given information + * @param e + * @param baseURI + * @param storage + * @return + * @throws KeyResolverException + */ + private static PublicKey resolveKey( + Element e, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}" + + e.getLocalName() + " Element"); + } + // An element has been provided + if (e != null) { + return KeyResolver.getPublicKey(e, baseURI, storage); + } + return null; + } + + private static Element obtainReferenceElement(XMLSignatureInput resource) + throws CanonicalizationException, ParserConfigurationException, + IOException, SAXException, KeyResolverException { + Element e; + if (resource.isElement()){ + e = (Element) resource.getSubNode(); + } else if (resource.isNodeSet()) { + // Retrieved resource is a nodeSet + e = getDocumentElement(resource.getNodeSet()); + } else { + // Retrieved resource is an inputStream + byte inputBytes[] = resource.getBytes(); + e = getDocFromBytes(inputBytes); + // otherwise, we parse the resource, create an Element and delegate + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "we have to parse " + inputBytes.length + " bytes"); + } + } + return e; + } + + private static X509Certificate getRawCertificate(XMLSignatureInput resource) + throws CanonicalizationException, IOException, CertificateException { + byte inputBytes[] = resource.getBytes(); + // if the resource stores a raw certificate, we have to handle it + CertificateFactory certFact = + CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID); + X509Certificate cert = (X509Certificate) + certFact.generateCertificate(new ByteArrayInputStream(inputBytes)); + return cert; + } + + /** + * Resolves the input from the given retrieval method + * @return + * @throws XMLSecurityException + */ + private static XMLSignatureInput resolveInput( + RetrievalMethod rm, String baseURI, boolean secureValidation + ) throws XMLSecurityException { + Attr uri = rm.getURIAttr(); + // Apply the transforms + Transforms transforms = rm.getTransforms(); + ResourceResolver resRes = ResourceResolver.getInstance(uri, baseURI, secureValidation); + XMLSignatureInput resource = resRes.resolve(uri, baseURI, secureValidation); + if (transforms != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "We have Transforms"); + } + resource = transforms.performTransforms(resource); + } + return resource; + } + + /** + * Parses a byte array and returns the parsed Element. + * + * @param bytes + * @return the Document Element after parsing bytes + * @throws KeyResolverException if something goes wrong + */ + private static Element getDocFromBytes(byte[] bytes) throws KeyResolverException { + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document doc = db.parse(new ByteArrayInputStream(bytes)); + return doc.getDocumentElement(); + } catch (SAXException ex) { + throw new KeyResolverException("empty", ex); + } catch (IOException ex) { + throw new KeyResolverException("empty", ex); + } catch (ParserConfigurationException ex) { + throw new KeyResolverException("empty", ex); + } + } + + /** + * Method engineResolveSecretKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) { + return null; + } + + private static Element getDocumentElement(Set set) { + Iterator it = set.iterator(); + Element e = null; + while (it.hasNext()) { + Node currentNode = it.next(); + if (currentNode != null && Node.ELEMENT_NODE == currentNode.getNodeType()) { + e = (Element) currentNode; + break; + } + } + List parents = new ArrayList(); + + // Obtain all the parents of the elemnt + while (e != null) { + parents.add(e); + Node n = e.getParentNode(); + if (n == null || Node.ELEMENT_NODE != n.getNodeType()) { + break; + } + e = (Element) n; + } + // Visit them in reverse order. + ListIterator it2 = parents.listIterator(parents.size()-1); + Element ele = null; + while (it2.hasPrevious()) { + ele = (Element) it2.previous(); + if (set.contains(ele)) { + return ele; + } + } + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java new file mode 100644 index 00000000000..a5e239f2662 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java @@ -0,0 +1,129 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.security.Key; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.X509Certificate; +import javax.crypto.SecretKey; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import org.w3c.dom.Element; + +/** + * Resolves a SecretKey within a KeyStore based on the KeyName. + * The KeyName is the key entry alias within the KeyStore. + */ +public class SecretKeyResolver extends KeyResolverSpi +{ + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(SecretKeyResolver.class.getName()); + + private KeyStore keyStore; + private char[] password; + + /** + * Constructor. + */ + public SecretKeyResolver(KeyStore keyStore, char[] password) { + this.keyStore = keyStore; + this.password = password; + } + + /** + * This method returns whether the KeyResolverSpi is able to perform the requested action. + * + * @param element + * @param baseURI + * @param storage + * @return whether the KeyResolverSpi is able to perform the requested action. + */ + public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + return XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME); + } + + /** + * Method engineLookupAndResolvePublicKey + * + * @param element + * @param baseURI + * @param storage + * @return null if no {@link PublicKey} could be obtained + * @throws KeyResolverException + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + return null; + } + + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + return null; + } + + /** + * Method engineResolveSecretKey + * + * @param element + * @param baseURI + * @param storage + * @return resolved SecretKey key or null if no {@link SecretKey} could be obtained + * + * @throws KeyResolverException + */ + public SecretKey engineResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + + if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + String keyName = element.getFirstChild().getNodeValue(); + try { + Key key = keyStore.getKey(keyName, password); + if (key instanceof SecretKey) { + return (SecretKey) key; + } + } catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + } + } + + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } + + /** + * Method engineResolvePrivateKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * @return resolved PrivateKey key or null if no {@link PrivateKey} could be obtained + * @throws KeyResolverException + */ + public PrivateKey engineLookupAndResolvePrivateKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + return null; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java new file mode 100644 index 00000000000..4b23ef1e207 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java @@ -0,0 +1,172 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.X509Certificate; +import javax.crypto.SecretKey; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import org.w3c.dom.Element; + +/** + * Resolves a single Key based on the KeyName. + */ +public class SingleKeyResolver extends KeyResolverSpi +{ + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(SingleKeyResolver.class.getName()); + + private String keyName; + private PublicKey publicKey; + private PrivateKey privateKey; + private SecretKey secretKey; + + /** + * Constructor. + * @param keyName + * @param publicKey + */ + public SingleKeyResolver(String keyName, PublicKey publicKey) { + this.keyName = keyName; + this.publicKey = publicKey; + } + + /** + * Constructor. + * @param keyName + * @param privateKey + */ + public SingleKeyResolver(String keyName, PrivateKey privateKey) { + this.keyName = keyName; + this.privateKey = privateKey; + } + + /** + * Constructor. + * @param keyName + * @param secretKey + */ + public SingleKeyResolver(String keyName, SecretKey secretKey) { + this.keyName = keyName; + this.secretKey = secretKey; + } + + /** + * This method returns whether the KeyResolverSpi is able to perform the requested action. + * + * @param element + * @param BaseURI + * @param storage + * @return whether the KeyResolverSpi is able to perform the requested action. + */ + public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + return XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME); + } + + /** + * Method engineLookupAndResolvePublicKey + * + * @param element + * @param baseURI + * @param storage + * @return null if no {@link PublicKey} could be obtained + * @throws KeyResolverException + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + + if (publicKey != null + && XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + String name = element.getFirstChild().getNodeValue(); + if (keyName.equals(name)) { + return publicKey; + } + } + + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } + + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + return null; + } + + /** + * Method engineResolveSecretKey + * + * @param element + * @param baseURI + * @param storage + * @return resolved SecretKey key or null if no {@link SecretKey} could be obtained + * + * @throws KeyResolverException + */ + public SecretKey engineResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + + if (secretKey != null + && XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + String name = element.getFirstChild().getNodeValue(); + if (keyName.equals(name)) { + return secretKey; + } + } + + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } + + /** + * Method engineResolvePrivateKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * @return resolved PrivateKey key or null if no {@link PrivateKey} could be obtained + * @throws KeyResolverException + */ + public PrivateKey engineLookupAndResolvePrivateKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + + if (privateKey != null + && XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + String name = element.getFirstChild().getNodeValue(); + if (keyName.equals(name)) { + return privateKey; + } + } + + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java index 06a49c6708e..06511c37c29 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java @@ -2,30 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; import java.security.cert.X509Certificate; - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate; import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; @@ -35,96 +34,93 @@ import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - /** * Resolves Certificates which are directly contained inside a * ds:X509Certificate Element. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class X509CertificateResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(X509CertificateResolver.class.getName()); + /** + * Method engineResolvePublicKey + * @inheritDoc + * @param element + * @param BaseURI + * @param storage + * + * @throws KeyResolverException + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String BaseURI, StorageResolver storage + ) throws KeyResolverException { + X509Certificate cert = + this.engineLookupResolveX509Certificate(element, BaseURI, storage); - /** - * Method engineResolvePublicKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - * @throws KeyResolverException - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { + if (cert != null) { + return cert.getPublicKey(); + } - X509Certificate cert = this.engineLookupResolveX509Certificate(element, - BaseURI, storage); + return null; + } - if (cert != null) { - return cert.getPublicKey(); - } + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param BaseURI + * @param storage + * + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String BaseURI, StorageResolver storage + ) throws KeyResolverException { - return null; - } - - /** - * Method engineResolveX509Certificate - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - * @throws KeyResolverException - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - - try { - Element[] els=XMLUtils.selectDsNodes(element.getFirstChild(), - Constants._TAG_X509CERTIFICATE); - if ((els == null) || (els.length == 0)) { - Element el=XMLUtils.selectDsNode(element.getFirstChild(), - Constants._TAG_X509DATA,0); - if (el!=null) { - return engineLookupResolveX509Certificate(el, BaseURI, storage); - } - return null; - } - - // populate Object array - for (int i = 0; i < els.length; i++) { - XMLX509Certificate xmlCert=new XMLX509Certificate(els[i], BaseURI); - X509Certificate cert = xmlCert.getX509Certificate(); - if (cert!=null) { - return cert; + try { + Element[] els = + XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509CERTIFICATE); + if ((els == null) || (els.length == 0)) { + Element el = + XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_X509DATA, 0); + if (el != null) { + return engineLookupResolveX509Certificate(el, BaseURI, storage); + } + return null; } - } - return null; - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); - throw new KeyResolverException("generic.EmptyMessage", ex); - } - } + // populate Object array + for (int i = 0; i < els.length; i++) { + XMLX509Certificate xmlCert = new XMLX509Certificate(els[i], BaseURI); + X509Certificate cert = xmlCert.getX509Certificate(); + if (cert != null) { + return cert; + } + } + return null; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } + throw new KeyResolverException("generic.EmptyMessage", ex); + } + } - /** - * Method engineResolveSecretKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - { - return null; - } + /** + * Method engineResolveSecretKey + * @inheritDoc + * @param element + * @param BaseURI + * @param storage + */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java new file mode 100644 index 00000000000..c1b44e68a86 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java @@ -0,0 +1,164 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.security.PublicKey; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Iterator; + +import javax.crypto.SecretKey; + +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.keys.content.X509Data; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Digest; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import org.w3c.dom.Element; + +/** + * KeyResolverSpi implementation which resolves public keys and X.509 certificates from a + * dsig11:X509Digest element. + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public class X509DigestResolver extends KeyResolverSpi { + + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(X509DigestResolver.class.getName()); + + /** {@inheritDoc}. */ + public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) { + try { + X509Data x509Data = new X509Data(element, baseURI); + return x509Data.containsDigest(); + } catch (XMLSecurityException e) { + return false; + } + } else { + return false; + } + } + + /** {@inheritDoc}. */ + public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + X509Certificate cert = this.engineLookupResolveX509Certificate(element, baseURI, storage); + + if (cert != null) { + return cert.getPublicKey(); + } + + return null; + } + + /** {@inheritDoc}. */ + public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + return resolveCertificate(element, baseURI, storage); + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** {@inheritDoc}. */ + public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + return null; + } + + /** + * Resolves from the storage resolver the actual certificate represented by the digest. + * + * @param element + * @param baseURI + * @param storage + * @return + * @throws XMLSecurityException + */ + private X509Certificate resolveCertificate(Element element, String baseURI, StorageResolver storage) + throws XMLSecurityException { + + XMLX509Digest x509Digests[] = null; + + Element x509childNodes[] = XMLUtils.selectDs11Nodes(element.getFirstChild(), Constants._TAG_X509DIGEST); + + if (x509childNodes == null || x509childNodes.length <= 0) { + return null; + } + + try { + checkStorage(storage); + + x509Digests = new XMLX509Digest[x509childNodes.length]; + + for (int i = 0; i < x509childNodes.length; i++) { + x509Digests[i] = new XMLX509Digest(x509childNodes[i], baseURI); + } + + Iterator storageIterator = storage.getIterator(); + while (storageIterator.hasNext()) { + X509Certificate cert = (X509Certificate) storageIterator.next(); + + for (int i = 0; i < x509Digests.length; i++) { + XMLX509Digest keyInfoDigest = x509Digests[i]; + byte[] certDigestBytes = XMLX509Digest.getDigestBytesFromCert(cert, keyInfoDigest.getAlgorithm()); + + if (Arrays.equals(keyInfoDigest.getDigestBytes(), certDigestBytes)) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found certificate with: " + cert.getSubjectX500Principal().getName()); + } + return cert; + } + + } + } + + } catch (XMLSecurityException ex) { + throw new KeyResolverException("empty", ex); + } + + return null; + } + + /** + * Method checkSrorage + * + * @param storage + * @throws KeyResolverException + */ + private void checkStorage(StorageResolver storage) throws KeyResolverException { + if (storage == null) { + Object exArgs[] = { Constants._TAG_X509DIGEST }; + KeyResolverException ex = new KeyResolverException("KeyResolver.needStorageResolver", exArgs); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "", ex); + } + throw ex; + } + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java index 8f717e71689..1d00692bd03 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java @@ -2,28 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; +import java.security.cert.Certificate; import java.security.cert.X509Certificate; +import java.util.Iterator; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.keys.content.X509Data; @@ -35,114 +37,114 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import com.sun.org.apache.xml.internal.security.utils.Constants; import org.w3c.dom.Element; - -/** - * - * @author $Author: mullan $ - */ public class X509IssuerSerialResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - X509IssuerSerialResolver.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(X509IssuerSerialResolver.class.getName()); - /** @inheritDoc */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { + /** @inheritDoc */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { - X509Certificate cert = this.engineLookupResolveX509Certificate(element, - BaseURI, storage); + X509Certificate cert = + this.engineLookupResolveX509Certificate(element, baseURI, storage); - if (cert != null) { - return cert.getPublicKey(); - } + if (cert != null) { + return cert.getPublicKey(); + } - return null; - } + return null; + } - /** @inheritDoc */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); - - X509Data x509data = null; - try { - x509data = new X509Data(element, BaseURI); - } catch (XMLSignatureException ex) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } - - if (x509data == null) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } - - if (!x509data.containsIssuerSerial()) { - return null; - } - try { - if (storage == null) { - Object exArgs[] = { Constants._TAG_X509ISSUERSERIAL }; - KeyResolverException ex = - new KeyResolverException("KeyResolver.needStorageResolver", - exArgs); - - log.log(java.util.logging.Level.INFO, "", ex); - throw ex; - } - - int noOfISS = x509data.lengthIssuerSerial(); - - while (storage.hasNext()) { - X509Certificate cert = storage.next(); - XMLX509IssuerSerial certSerial = new XMLX509IssuerSerial(element.getOwnerDocument(), cert); + /** @inheritDoc */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + X509Data x509data = null; + try { + x509data = new X509Data(element, baseURI); + } catch (XMLSignatureException ex) { if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Found Certificate Issuer: " - + certSerial.getIssuerName()); - log.log(java.util.logging.Level.FINE, "Found Certificate Serial: " - + certSerial.getSerialNumber().toString()); + log.log(java.util.logging.Level.FINE, "I can't"); + } + return null; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I can't"); + } + return null; + } + + if (!x509data.containsIssuerSerial()) { + return null; + } + try { + if (storage == null) { + Object exArgs[] = { Constants._TAG_X509ISSUERSERIAL }; + KeyResolverException ex = + new KeyResolverException("KeyResolver.needStorageResolver", exArgs); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "", ex); + } + throw ex; } - for (int i=0; i storageIterator = storage.getIterator(); + while (storageIterator.hasNext()) { + X509Certificate cert = (X509Certificate)storageIterator.next(); + XMLX509IssuerSerial certSerial = new XMLX509IssuerSerial(element.getOwnerDocument(), cert); - if (certSerial.equals(xmliss)) { - log.log(java.util.logging.Level.FINE, "match !!! "); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found Certificate Issuer: " + certSerial.getIssuerName()); + log.log(java.util.logging.Level.FINE, "Found Certificate Serial: " + certSerial.getSerialNumber().toString()); + } - return cert; - } - log.log(java.util.logging.Level.FINE, "no match..."); + for (int i = 0; i < noOfISS; i++) { + XMLX509IssuerSerial xmliss = x509data.itemIssuerSerial(i); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found Element Issuer: " + + xmliss.getIssuerName()); + log.log(java.util.logging.Level.FINE, "Found Element Serial: " + + xmliss.getSerialNumber().toString()); + } + + if (certSerial.equals(xmliss)) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + } + return cert; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "no match..."); + } + } } - } - return null; - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + return null; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } - throw new KeyResolverException("generic.EmptyMessage", ex); - } - } + throw new KeyResolverException("generic.EmptyMessage", ex); + } + } - /** @inheritDoc */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) { - return null; - } + /** @inheritDoc */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) { + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java index ac90842059e..8dd381e59ba 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java @@ -2,28 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; +import java.security.cert.Certificate; import java.security.cert.X509Certificate; +import java.util.Iterator; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; @@ -35,124 +37,121 @@ import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - -/** - * - * - * @author $Author: mullan $ - */ public class X509SKIResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(X509SKIResolver.class.getName()); - /** - * Method engineResolvePublicKey - * - * @param element - * @param BaseURI - * @param storage - * @return null if no {@link PublicKey} could be obtained - * @throws KeyResolverException - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { + /** + * Method engineResolvePublicKey + * + * @param element + * @param baseURI + * @param storage + * @return null if no {@link PublicKey} could be obtained + * @throws KeyResolverException + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { - X509Certificate cert = this.engineLookupResolveX509Certificate(element, - BaseURI, storage); + X509Certificate cert = + this.engineLookupResolveX509Certificate(element, baseURI, storage); - if (cert != null) { - return cert.getPublicKey(); - } + if (cert != null) { + return cert.getPublicKey(); + } - return null; - } + return null; + } - /** - * Method engineResolveX509Certificate - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - * @throws KeyResolverException - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); - } - if (!XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_X509DATA)) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } - /** Field _x509childObject[] */ - XMLX509SKI x509childObject[] = null; - - Element x509childNodes[] = null; - x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), - Constants._TAG_X509SKI); - - if (!((x509childNodes != null) - && (x509childNodes.length > 0))) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } - try { - if (storage == null) { - Object exArgs[] = { Constants._TAG_X509SKI }; - KeyResolverException ex = - new KeyResolverException("KeyResolver.needStorageResolver", - exArgs); - - log.log(java.util.logging.Level.INFO, "", ex); - - throw ex; - } - - x509childObject = new XMLX509SKI[x509childNodes.length]; - - for (int i = 0; i < x509childNodes.length; i++) { - x509childObject[i] = - new XMLX509SKI(x509childNodes[i], BaseURI); - } - - while (storage.hasNext()) { - X509Certificate cert = storage.next(); - XMLX509SKI certSKI = new XMLX509SKI(element.getOwnerDocument(), cert); - - for (int i = 0; i < x509childObject.length; i++) { - if (certSKI.equals(x509childObject[i])) { - log.log(java.util.logging.Level.FINE, "Return PublicKey from " - + cert.getSubjectDN().getName()); - - return cert; - } + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I can't"); } - } - } catch (XMLSecurityException ex) { - throw new KeyResolverException("empty", ex); - } + return null; + } + /** Field _x509childObject[] */ + XMLX509SKI x509childObject[] = null; - return null; - } + Element x509childNodes[] = null; + x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SKI); - /** - * Method engineResolveSecretKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - { - return null; - } + if (!((x509childNodes != null) && (x509childNodes.length > 0))) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I can't"); + } + return null; + } + try { + if (storage == null) { + Object exArgs[] = { Constants._TAG_X509SKI }; + KeyResolverException ex = + new KeyResolverException("KeyResolver.needStorageResolver", exArgs); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "", ex); + } + + throw ex; + } + + x509childObject = new XMLX509SKI[x509childNodes.length]; + + for (int i = 0; i < x509childNodes.length; i++) { + x509childObject[i] = new XMLX509SKI(x509childNodes[i], baseURI); + } + + Iterator storageIterator = storage.getIterator(); + while (storageIterator.hasNext()) { + X509Certificate cert = (X509Certificate)storageIterator.next(); + XMLX509SKI certSKI = new XMLX509SKI(element.getOwnerDocument(), cert); + + for (int i = 0; i < x509childObject.length; i++) { + if (certSKI.equals(x509childObject[i])) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Return PublicKey from " + cert.getSubjectX500Principal().getName()); + } + + return cert; + } + } + } + } catch (XMLSecurityException ex) { + throw new KeyResolverException("empty", ex); + } + + return null; + } + + /** + * Method engineResolveSecretKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * + */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) { + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java index 05e82226c4c..dc2ca4abd5a 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java @@ -2,28 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; +import java.security.cert.Certificate; import java.security.cert.X509Certificate; +import java.util.Iterator; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; @@ -35,133 +37,140 @@ import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - -/** - * - * @author $Author: mullan $ - */ public class X509SubjectNameResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - X509SubjectNameResolver.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(X509SubjectNameResolver.class.getName()); - /** - * Method engineResolvePublicKey - * - * @param element - * @param BaseURI - * @param storage - * @return null if no {@link PublicKey} could be obtained - * @throws KeyResolverException - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { + /** + * Method engineResolvePublicKey + * + * @param element + * @param BaseURI + * @param storage + * @return null if no {@link PublicKey} could be obtained + * @throws KeyResolverException + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { - X509Certificate cert = this.engineLookupResolveX509Certificate(element, - BaseURI, storage); + X509Certificate cert = + this.engineLookupResolveX509Certificate(element, baseURI, storage); - if (cert != null) { - return cert.getPublicKey(); - } + if (cert != null) { + return cert.getPublicKey(); + } - return null; - } + return null; + } - /** - * Method engineResolveX509Certificate - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - * @throws KeyResolverException - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); - Element[] x509childNodes = null; - XMLX509SubjectName x509childObject[] = null; + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + Element[] x509childNodes = null; + XMLX509SubjectName x509childObject[] = null; - if (!XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_X509DATA) ) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } - x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), - Constants._TAG_X509SUBJECTNAME); + if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I can't"); + } + return null; + } + x509childNodes = + XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SUBJECTNAME); if (!((x509childNodes != null) - && (x509childNodes.length > 0))) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; + && (x509childNodes.length > 0))) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I can't"); + } + return null; + } + + try { + if (storage == null) { + Object exArgs[] = { Constants._TAG_X509SUBJECTNAME }; + KeyResolverException ex = + new KeyResolverException("KeyResolver.needStorageResolver", exArgs); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "", ex); + } + + throw ex; } - try { - if (storage == null) { - Object exArgs[] = { Constants._TAG_X509SUBJECTNAME }; - KeyResolverException ex = - new KeyResolverException("KeyResolver.needStorageResolver", - exArgs); + x509childObject = new XMLX509SubjectName[x509childNodes.length]; - log.log(java.util.logging.Level.INFO, "", ex); - - throw ex; - } - - x509childObject = - new XMLX509SubjectName[x509childNodes.length]; - - for (int i = 0; i < x509childNodes.length; i++) { - x509childObject[i] = - new XMLX509SubjectName(x509childNodes[i], - BaseURI); - } - - while (storage.hasNext()) { - X509Certificate cert = storage.next(); - XMLX509SubjectName certSN = - new XMLX509SubjectName(element.getOwnerDocument(), cert); - - log.log(java.util.logging.Level.FINE, "Found Certificate SN: " + certSN.getSubjectName()); - - for (int i = 0; i < x509childObject.length; i++) { - log.log(java.util.logging.Level.FINE, "Found Element SN: " - + x509childObject[i].getSubjectName()); - - if (certSN.equals(x509childObject[i])) { - log.log(java.util.logging.Level.FINE, "match !!! "); - - return cert; - } - log.log(java.util.logging.Level.FINE, "no match..."); + for (int i = 0; i < x509childNodes.length; i++) { + x509childObject[i] = new XMLX509SubjectName(x509childNodes[i], baseURI); } - } - return null; - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + Iterator storageIterator = storage.getIterator(); + while (storageIterator.hasNext()) { + X509Certificate cert = (X509Certificate)storageIterator.next(); + XMLX509SubjectName certSN = + new XMLX509SubjectName(element.getOwnerDocument(), cert); - throw new KeyResolverException("generic.EmptyMessage", ex); - } - } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found Certificate SN: " + certSN.getSubjectName()); + } - /** - * Method engineResolveSecretKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - { - return null; - } + for (int i = 0; i < x509childObject.length; i++) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found Element SN: " + + x509childObject[i].getSubjectName()); + } + + if (certSN.equals(x509childObject[i])) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + } + + return cert; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "no match..."); + } + } + } + + return null; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } + + throw new KeyResolverException("generic.EmptyMessage", ex); + } + } + + /** + * Method engineResolveSecretKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * + */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) { + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java index 7b11e848e8f..88392495d33 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java @@ -2,197 +2,187 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.storage; import java.security.KeyStore; +import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.NoSuchElementException; import com.sun.org.apache.xml.internal.security.keys.storage.implementations.KeyStoreResolver; import com.sun.org.apache.xml.internal.security.keys.storage.implementations.SingleCertificateResolver; - /** * This class collects customized resolvers for Certificates. - * - * @author $Author: mullan $ */ public class StorageResolver { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(StorageResolver.class.getName()); - /** Field _storageResolvers */ - List _storageResolvers = null; + /** Field storageResolvers */ + private List storageResolvers = null; - /** Field _iterator */ - Iterator _iterator = null; + /** + * Constructor StorageResolver + * + */ + public StorageResolver() {} - /** - * Constructor StorageResolver - * - */ - public StorageResolver() {} + /** + * Constructor StorageResolver + * + * @param resolver + */ + public StorageResolver(StorageResolverSpi resolver) { + this.add(resolver); + } - /** - * Constructor StorageResolver - * - * @param resolver - */ - public StorageResolver(StorageResolverSpi resolver) { - this.add(resolver); - } + /** + * Method addResolver + * + * @param resolver + */ + public void add(StorageResolverSpi resolver) { + if (storageResolvers == null) { + storageResolvers = new ArrayList(); + } + this.storageResolvers.add(resolver); + } - /** - * Method addResolver - * - * @param resolver - */ - public void add(StorageResolverSpi resolver) { - if (_storageResolvers==null) - _storageResolvers=new ArrayList(); - this._storageResolvers.add(resolver); + /** + * Constructor StorageResolver + * + * @param keyStore + */ + public StorageResolver(KeyStore keyStore) { + this.add(keyStore); + } - this._iterator = null; - } + /** + * Method addKeyStore + * + * @param keyStore + */ + public void add(KeyStore keyStore) { + try { + this.add(new KeyStoreResolver(keyStore)); + } catch (StorageResolverException ex) { + log.log(java.util.logging.Level.SEVERE, "Could not add KeyStore because of: ", ex); + } + } - /** - * Constructor StorageResolver - * - * @param keyStore - */ - public StorageResolver(KeyStore keyStore) { - this.add(keyStore); - } + /** + * Constructor StorageResolver + * + * @param x509certificate + */ + public StorageResolver(X509Certificate x509certificate) { + this.add(x509certificate); + } - /** - * Method addKeyStore - * - * @param keyStore - */ - public void add(KeyStore keyStore) { + /** + * Method addCertificate + * + * @param x509certificate + */ + public void add(X509Certificate x509certificate) { + this.add(new SingleCertificateResolver(x509certificate)); + } - try { - this.add(new KeyStoreResolver(keyStore)); - } catch (StorageResolverException ex) { - log.log(java.util.logging.Level.SEVERE, "Could not add KeyStore because of: ", ex); - } - } + /** + * Method getIterator + * @return the iterator for the resolvers. + */ + public Iterator getIterator() { + return new StorageResolverIterator(this.storageResolvers.iterator()); + } - /** - * Constructor StorageResolver - * - * @param x509certificate - */ - public StorageResolver(X509Certificate x509certificate) { - this.add(x509certificate); - } + /** + * Class StorageResolverIterator + * This iterates over all the Certificates found in all the resolvers. + */ + static class StorageResolverIterator implements Iterator { - /** - * Method addCertificate - * - * @param x509certificate - */ - public void add(X509Certificate x509certificate) { - this.add(new SingleCertificateResolver(x509certificate)); - } + /** Field resolvers */ + Iterator resolvers = null; - /** - * Method getIterator - * @return the iterator for the resolvers. - * - */ - public Iterator getIterator() { + /** Field currentResolver */ + Iterator currentResolver = null; - if (this._iterator == null) { - if (_storageResolvers==null) - _storageResolvers=new ArrayList(); - this._iterator = new StorageResolverIterator(this._storageResolvers.iterator()); - } + /** + * Constructor StorageResolverIterator + * + * @param resolvers + */ + public StorageResolverIterator(Iterator resolvers) { + this.resolvers = resolvers; + currentResolver = findNextResolver(); + } - return this._iterator; - } + /** @inheritDoc */ + public boolean hasNext() { + if (currentResolver == null) { + return false; + } - /** - * Method hasNext - * - * @return true if there is more elements. - */ - public boolean hasNext() { + if (currentResolver.hasNext()) { + return true; + } - if (this._iterator == null) { - if (_storageResolvers==null) - _storageResolvers=new ArrayList(); - this._iterator = new StorageResolverIterator(this._storageResolvers.iterator()); - } + currentResolver = findNextResolver(); + return (currentResolver != null); + } - return this._iterator.hasNext(); - } + /** @inheritDoc */ + public Certificate next() { + if (hasNext()) { + return currentResolver.next(); + } - /** - * Method next - * - * @return the next element - */ - public X509Certificate next() { - return (X509Certificate) this._iterator.next(); - } + throw new NoSuchElementException(); + } - /** - * Class StorageResolverIterator - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - static class StorageResolverIterator implements Iterator { + /** + * Method remove + */ + public void remove() { + throw new UnsupportedOperationException("Can't remove keys from KeyStore"); + } - /** Field _resolvers */ - Iterator _resolvers = null; + // Find the next storage with at least one element and return its Iterator + private Iterator findNextResolver() { + while (resolvers.hasNext()) { + StorageResolverSpi resolverSpi = resolvers.next(); + Iterator iter = resolverSpi.getIterator(); + if (iter.hasNext()) { + return iter; + } + } - /** - * Constructor FilesystemIterator - * - * @param resolvers - */ - public StorageResolverIterator(Iterator resolvers) { - this._resolvers = resolvers; - } - - /** @inheritDoc */ - public boolean hasNext() { - return _resolvers.hasNext(); - } - - /** @inheritDoc */ - public Object next() { - return _resolvers.next(); - } - - /** - * Method remove - */ - public void remove() { - throw new UnsupportedOperationException( - "Can't remove keys from KeyStore"); - } - } + return null; + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java index 29dff030f78..af8af531aab 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java @@ -2,86 +2,82 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.storage; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; -/** - * - * @author $Author: mullan $ - */ public class StorageResolverException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor StorageResolverException - * - */ - public StorageResolverException() { - super(); - } + /** + * Constructor StorageResolverException + * + */ + public StorageResolverException() { + super(); + } - /** - * Constructor StorageResolverException - * - * @param _msgID - */ - public StorageResolverException(String _msgID) { - super(_msgID); - } + /** + * Constructor StorageResolverException + * + * @param msgID + */ + public StorageResolverException(String msgID) { + super(msgID); + } - /** - * Constructor StorageResolverException - * - * @param _msgID - * @param exArgs - */ - public StorageResolverException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor StorageResolverException + * + * @param msgID + * @param exArgs + */ + public StorageResolverException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor StorageResolverException - * - * @param _msgID - * @param _originalException - */ - public StorageResolverException(String _msgID, Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor StorageResolverException + * + * @param msgID + * @param originalException + */ + public StorageResolverException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor StorageResolverException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public StorageResolverException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * Constructor StorageResolverException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public StorageResolverException(String msgID, Object exArgs[], + Exception originalException) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java index 07211253d22..7cc075a36f9 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java @@ -2,39 +2,35 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.storage; - - +import java.security.cert.Certificate; import java.util.Iterator; - -/** - * - * @author $Author: mullan $ - */ public abstract class StorageResolverSpi { - /** - * Method getIterator - * - * @return the iterator for the storage - */ - public abstract Iterator getIterator(); + /** + * Method getIterator + * + * @return the iterator for the storage + */ + public abstract Iterator getIterator(); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java index 3b38e4a2572..6d7057e1e45 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.storage.implementations; @@ -24,6 +26,7 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; +import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateFactory; @@ -39,188 +42,188 @@ import com.sun.org.apache.xml.internal.security.utils.Base64; /** * This {@link StorageResolverSpi} makes all raw (binary) {@link X509Certificate}s - * which reside as files in a single directory available to the {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}. - * - * @author $Author: mullan $ + * which reside as files in a single directory available to the + * {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}. */ public class CertsInFilesystemDirectoryResolver extends StorageResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger( - CertsInFilesystemDirectoryResolver.class.getName()); + CertsInFilesystemDirectoryResolver.class.getName() + ); - /** Field _merlinsCertificatesDir */ - String _merlinsCertificatesDir = null; + /** Field merlinsCertificatesDir */ + private String merlinsCertificatesDir = null; - /** Field _certs */ - private List _certs = new ArrayList(); + /** Field certs */ + private List certs = new ArrayList(); - /** Field _iterator */ - Iterator _iterator = null; + /** + * @param directoryName + * @throws StorageResolverException + */ + public CertsInFilesystemDirectoryResolver(String directoryName) + throws StorageResolverException { + this.merlinsCertificatesDir = directoryName; - /** - * - * - * @param directoryName - * @throws StorageResolverException - */ - public CertsInFilesystemDirectoryResolver(String directoryName) - throws StorageResolverException { + this.readCertsFromHarddrive(); + } - this._merlinsCertificatesDir = directoryName; + /** + * Method readCertsFromHarddrive + * + * @throws StorageResolverException + */ + private void readCertsFromHarddrive() throws StorageResolverException { - this.readCertsFromHarddrive(); + File certDir = new File(this.merlinsCertificatesDir); + List al = new ArrayList(); + String[] names = certDir.list(); - this._iterator = new FilesystemIterator(this._certs); - } + for (int i = 0; i < names.length; i++) { + String currentFileName = names[i]; - /** - * Method readCertsFromHarddrive - * - * @throws StorageResolverException - */ - private void readCertsFromHarddrive() throws StorageResolverException { + if (currentFileName.endsWith(".crt")) { + al.add(names[i]); + } + } - File certDir = new File(this._merlinsCertificatesDir); - ArrayList al = new ArrayList(); - String[] names = certDir.list(); + CertificateFactory cf = null; - for (int i = 0; i < names.length; i++) { - String currentFileName = names[i]; + try { + cf = CertificateFactory.getInstance("X.509"); + } catch (CertificateException ex) { + throw new StorageResolverException("empty", ex); + } - if (currentFileName.endsWith(".crt")) { - al.add(names[i]); - } - } + if (cf == null) { + throw new StorageResolverException("empty"); + } - CertificateFactory cf = null; + for (int i = 0; i < al.size(); i++) { + String filename = certDir.getAbsolutePath() + File.separator + al.get(i); + File file = new File(filename); + boolean added = false; + String dn = null; - try { - cf = CertificateFactory.getInstance("X.509"); - } catch (CertificateException ex) { - throw new StorageResolverException("empty", ex); - } + FileInputStream fis = null; + try { + fis = new FileInputStream(file); + X509Certificate cert = + (X509Certificate) cf.generateCertificate(fis); - if (cf == null) { - throw new StorageResolverException("empty"); - } + //add to ArrayList + cert.checkValidity(); + this.certs.add(cert); - for (int i = 0; i < al.size(); i++) { - String filename = certDir.getAbsolutePath() + File.separator - + al.get(i); - File file = new File(filename); - boolean added = false; - String dn = null; + dn = cert.getSubjectX500Principal().getName(); + added = true; + } catch (FileNotFoundException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + } + } catch (CertificateNotYetValidException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + } + } catch (CertificateExpiredException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + } + } catch (CertificateException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + } + } finally { + try { + if (fis != null) { + fis.close(); + } + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + } + } + } - try { - FileInputStream fis = new FileInputStream(file); - X509Certificate cert = - (X509Certificate) cf.generateCertificate(fis); - - fis.close(); - - //add to ArrayList - cert.checkValidity(); - this._certs.add(cert); - - dn = cert.getSubjectDN().getName(); - added = true; - } catch (FileNotFoundException ex) { - log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); - } catch (IOException ex) { - log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); - } catch (CertificateNotYetValidException ex) { - log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); - } catch (CertificateExpiredException ex) { - log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); - } catch (CertificateException ex) { - log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); - } - - if (added) { - if (log.isLoggable(java.util.logging.Level.FINE)) + if (added && log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Added certificate: " + dn); - } - } - } + } + } + } - /** @inheritDoc */ - public Iterator getIterator() { - return this._iterator; - } + /** @inheritDoc */ + public Iterator getIterator() { + return new FilesystemIterator(this.certs); + } - /** - * Class FilesystemIterator - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - private static class FilesystemIterator implements Iterator { + /** + * Class FilesystemIterator + */ + private static class FilesystemIterator implements Iterator { - /** Field _certs */ - List _certs = null; + /** Field certs */ + List certs = null; - /** Field _i */ - int _i; + /** Field i */ + int i; - /** - * Constructor FilesystemIterator - * - * @param certs - */ - public FilesystemIterator(List certs) { - this._certs = certs; - this._i = 0; - } + /** + * Constructor FilesystemIterator + * + * @param certs + */ + public FilesystemIterator(List certs) { + this.certs = certs; + this.i = 0; + } - /** @inheritDoc */ - public boolean hasNext() { - return (this._i < this._certs.size()); - } + /** @inheritDoc */ + public boolean hasNext() { + return (this.i < this.certs.size()); + } - /** @inheritDoc */ - public X509Certificate next() { - return this._certs.get(this._i++); - } + /** @inheritDoc */ + public Certificate next() { + return this.certs.get(this.i++); + } - /** - * Method remove - * - */ - public void remove() { - throw new UnsupportedOperationException( - "Can't remove keys from KeyStore"); - } - } + /** + * Method remove + * + */ + public void remove() { + throw new UnsupportedOperationException("Can't remove keys from KeyStore"); + } + } - /** - * Method main - * - * @param unused - * @throws Exception - */ - public static void main(String unused[]) throws Exception { + /** + * Method main + * + * @param unused + * @throws Exception + */ + public static void main(String unused[]) throws Exception { - CertsInFilesystemDirectoryResolver krs = - new CertsInFilesystemDirectoryResolver( - "data/ie/baltimore/merlin-examples/merlin-xmldsig-eighteen/certs"); + CertsInFilesystemDirectoryResolver krs = + new CertsInFilesystemDirectoryResolver( + "data/ie/baltimore/merlin-examples/merlin-xmldsig-eighteen/certs"); - for (Iterator i = krs.getIterator(); i.hasNext(); ) { - X509Certificate cert = i.next(); - byte[] ski = - com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI - .getSKIBytesFromCert(cert); + for (Iterator i = krs.getIterator(); i.hasNext(); ) { + X509Certificate cert = (X509Certificate) i.next(); + byte[] ski = + com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI.getSKIBytesFromCert(cert); - System.out.println(); - System.out.println("Base64(SKI())= \"" - + Base64.encode(ski) + "\""); - System.out.println("cert.getSerialNumber()= \"" - + cert.getSerialNumber().toString() + "\""); - System.out.println("cert.getSubjectDN().getName()= \"" - + cert.getSubjectDN().getName() + "\""); - System.out.println("cert.getIssuerDN().getName()= \"" - + cert.getIssuerDN().getName() + "\""); - } - } + System.out.println(); + System.out.println("Base64(SKI())= \"" + + Base64.encode(ski) + "\""); + System.out.println("cert.getSerialNumber()= \"" + + cert.getSerialNumber().toString() + "\""); + System.out.println("cert.getSubjectX500Principal().getName()= \"" + + cert.getSubjectX500Principal().getName() + "\""); + System.out.println("cert.getIssuerX500Principal().getName()= \"" + + cert.getIssuerX500Principal().getName() + "\""); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java index 2a5662101b8..1e325d121ee 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java @@ -2,147 +2,152 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.storage.implementations; import java.security.KeyStore; import java.security.KeyStoreException; -import java.security.cert.X509Certificate; +import java.security.cert.Certificate; import java.util.Enumeration; import java.util.Iterator; +import java.util.NoSuchElementException; import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverException; import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverSpi; - /** * Makes the Certificates from a JAVA {@link KeyStore} object available to the * {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}. - * - * @author $Author: mullan $ */ public class KeyStoreResolver extends StorageResolverSpi { - /** Field _keyStore */ - KeyStore _keyStore = null; + /** Field keyStore */ + private KeyStore keyStore = null; - /** Field _iterator */ - Iterator _iterator = null; - - /** - * Constructor KeyStoreResolver - * - * @param keyStore is the keystore which contains the Certificates - * @throws StorageResolverException - */ - public KeyStoreResolver(KeyStore keyStore) throws StorageResolverException { - this._keyStore = keyStore; - this._iterator = new KeyStoreIterator(this._keyStore); - } - - /** @inheritDoc */ - public Iterator getIterator() { - return this._iterator; - } - - /** - * Class KeyStoreIterator - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - static class KeyStoreIterator implements Iterator { - - /** Field _keyStore */ - KeyStore _keyStore = null; - - /** Field _aliases */ - Enumeration _aliases = null; - - /** - * Constructor KeyStoreIterator - * - * @param keyStore - * @throws StorageResolverException - */ - public KeyStoreIterator(KeyStore keyStore) - throws StorageResolverException { - - try { - this._keyStore = keyStore; - this._aliases = this._keyStore.aliases(); - } catch (KeyStoreException ex) { + /** + * Constructor KeyStoreResolver + * + * @param keyStore is the keystore which contains the Certificates + * @throws StorageResolverException + */ + public KeyStoreResolver(KeyStore keyStore) throws StorageResolverException { + this.keyStore = keyStore; + // Do a quick check on the keystore + try { + keyStore.aliases(); + } catch (KeyStoreException ex) { throw new StorageResolverException("generic.EmptyMessage", ex); - } - } + } + } - /** @inheritDoc */ - public boolean hasNext() { - return this._aliases.hasMoreElements(); - } + /** @inheritDoc */ + public Iterator getIterator() { + return new KeyStoreIterator(this.keyStore); + } - /** @inheritDoc */ - @SuppressWarnings("unchecked") - public X509Certificate next() { + /** + * Class KeyStoreIterator + */ + static class KeyStoreIterator implements Iterator { - String alias = this._aliases.nextElement(); + /** Field keyStore */ + KeyStore keyStore = null; + + /** Field aliases */ + Enumeration aliases = null; + + /** Field nextCert */ + Certificate nextCert = null; + + /** + * Constructor KeyStoreIterator + * + * @param keyStore + */ + public KeyStoreIterator(KeyStore keyStore) { + try { + this.keyStore = keyStore; + this.aliases = this.keyStore.aliases(); + } catch (KeyStoreException ex) { + // empty Enumeration + this.aliases = new Enumeration() { + public boolean hasMoreElements() { + return false; + } + public String nextElement() { + return null; + } + }; + } + } + + /** @inheritDoc */ + public boolean hasNext() { + if (nextCert == null) { + nextCert = findNextCert(); + } + + return (nextCert != null); + } + + /** @inheritDoc */ + public Certificate next() { + if (nextCert == null) { + // maybe caller did not call hasNext() + nextCert = findNextCert(); + + if (nextCert == null) { + throw new NoSuchElementException(); + } + } + + Certificate ret = nextCert; + nextCert = null; + return ret; + } + + /** + * Method remove + */ + public void remove() { + throw new UnsupportedOperationException("Can't remove keys from KeyStore"); + } + + // Find the next entry that contains a certificate and return it. + // In particular, this skips over entries containing symmetric keys. + private Certificate findNextCert() { + while (this.aliases.hasMoreElements()) { + String alias = this.aliases.nextElement(); + try { + Certificate cert = this.keyStore.getCertificate(alias); + if (cert != null) { + return cert; + } + } catch (KeyStoreException ex) { + return null; + } + } - try { - return (X509Certificate)this._keyStore.getCertificate(alias); - } catch (KeyStoreException ex) { return null; - } - } + } - /** - * Method remove - * - */ - public void remove() { - throw new UnsupportedOperationException( - "Can't remove keys from KeyStore"); - } - } + } - /** - * Method main - * - * @param unused - * @throws Exception - */ - public static void main(String unused[]) throws Exception { - - KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - - ks.load( - new java.io.FileInputStream( - "data/com/sun/org/apache/xml/internal/security/samples/input/keystore.jks"), - "xmlsecurity".toCharArray()); - - KeyStoreResolver krs = new KeyStoreResolver(ks); - - for (Iterator i = krs.getIterator(); i.hasNext(); ) { - X509Certificate cert = i.next(); - byte[] ski = - com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI - .getSKIBytesFromCert(cert); - - System.out.println(com.sun.org.apache.xml.internal.security.utils.Base64.encode(ski)); - } - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java index 3048bb123ac..e007051fb10 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java @@ -2,102 +2,93 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.keys.storage.implementations; +import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.Iterator; +import java.util.NoSuchElementException; import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverSpi; - /** * This {@link StorageResolverSpi} makes a single {@link X509Certificate} * available to the {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}. - * - * @author $Author: mullan $ */ public class SingleCertificateResolver extends StorageResolverSpi { - /** Field _certificate */ - X509Certificate _certificate = null; + /** Field certificate */ + private X509Certificate certificate = null; - /** Field _iterator */ - Iterator _iterator = null; + /** + * @param x509cert the single {@link X509Certificate} + */ + public SingleCertificateResolver(X509Certificate x509cert) { + this.certificate = x509cert; + } - /** - * - * - * @param x509cert the single {@link X509Certificate} - */ - public SingleCertificateResolver(X509Certificate x509cert) { - this._certificate = x509cert; - this._iterator = new InternalIterator(this._certificate); - } + /** @inheritDoc */ + public Iterator getIterator() { + return new InternalIterator(this.certificate); + } - /** @inheritDoc */ - public Iterator getIterator() { - return this._iterator; - } + /** + * Class InternalIterator + */ + static class InternalIterator implements Iterator { - /** - * Class InternalIterator - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - static class InternalIterator implements Iterator { + /** Field alreadyReturned */ + boolean alreadyReturned = false; - /** Field _alreadyReturned */ - boolean _alreadyReturned = false; + /** Field certificate */ + X509Certificate certificate = null; - /** Field _certificate */ - X509Certificate _certificate = null; + /** + * Constructor InternalIterator + * + * @param x509cert + */ + public InternalIterator(X509Certificate x509cert) { + this.certificate = x509cert; + } - /** - * Constructor InternalIterator - * - * @param x509cert - */ - public InternalIterator(X509Certificate x509cert) { - this._certificate = x509cert; - } + /** @inheritDoc */ + public boolean hasNext() { + return !this.alreadyReturned; + } - /** @inheritDoc */ - public boolean hasNext() { - return (!this._alreadyReturned); - } + /** @inheritDoc */ + public Certificate next() { + if (this.alreadyReturned) { + throw new NoSuchElementException(); + } + this.alreadyReturned = true; + return this.certificate; + } - /** @inheritDoc */ - public X509Certificate next() { - - this._alreadyReturned = true; - - return this._certificate; - } - - /** - * Method remove - * - */ - public void remove() { - throw new UnsupportedOperationException( - "Can't remove keys from KeyStore"); - } - } + /** + * Method remove + */ + public void remove() { + throw new UnsupportedOperationException("Can't remove keys from KeyStore"); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml index aea1595741b..55c396c012e 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml @@ -52,9 +52,6 @@ - - @@ -78,6 +75,12 @@ JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA512" /> + + + @@ -97,7 +100,7 @@ Description="MD5 message digest from RFC 1321" AlgorithmClass="MessageDigest" RequirementLevel="NOT RECOMMENDED" - SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt" + SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt" JCEName="MD5"/> + SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt" + JCEName="SHA1withECDSA"/> + + + + + + @@ -260,7 +284,31 @@ KeyLength="256" RequiredKey="AES" JCEName="AES/CBC/ISO10126Padding"/> + + + + + + + JCEName="RSA/ECB/OAEPPadding"/> + + - - - - + @@ -330,32 +378,8 @@ + DESCRIPTION="A simple resolver for requests of XPointer fragments" /> - - - - - - - - - - diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/log4j.properties b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/log4j.properties deleted file mode 100644 index e67ae2c79ef..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/log4j.properties +++ /dev/null @@ -1,36 +0,0 @@ -# ------------------------------------------------------------------------ -# -# Logging Configuration -# -# ------------------------------------------------------------------------ -# -log4j.rootLogger=DEBUG, LOGTXT - -######################################################################## -# -# Logging based on packages -# -######################################################################## -log4j.logger.com.sun.org.apache.xml.internal.security=DEBUG, LOGTXT -log4j.logger.com.sun.org.apache.xml.internal.security.test.AllTests=DEBUG, LOGTXT - -######################################################################## -# -# Logfile definitions -# -######################################################################## -#Console Log -log4j.appender.Console=org.apache.log4j.ConsoleAppender -log4j.appender.Console.Threshold=DEBUG -log4j.appender.Console.layout=org.apache.log4j.PatternLayout -log4j.appender.Console.layout.ConversionPattern=%-5p %C{1}:%L - %m\n -log4j.appender.Console.Target=System.err - -#LOGTXT Log -log4j.appender.LOGTXT=org.apache.log4j.FileAppender -log4j.appender.LOGTXT.File=log.txt -log4j.appender.LOGTXT.Append=true -log4j.appender.LOGTXT.Threshold=DEBUG -log4j.appender.LOGTXT.layout=org.apache.log4j.PatternLayout -log4j.appender.LOGTXT.layout.ConversionPattern=%-5p %C{1}:%L - %m\n - diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties index c285aa0f87d..746361d2923 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties @@ -5,6 +5,7 @@ algorithm.extendsWrongClass = Kann URI {0} nicht f algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures. algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures. algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs. +algorithms.HMACOutputLengthMin = HMACOutputLength must not be less than {0} algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms algorithms.NoSuchAlgorithm = Der Algorithmus {0} ist nicht verfügbar. Original Nachricht war: {1} algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm @@ -88,8 +89,13 @@ prefix.AlreadyAssigned = Sie binden den Prefix {0} an den Namespace {1} aber er signature.Canonicalizer.UnknownCanonicalizer = Unbekannter Canonicalizer. Kein Handler installiert für URI {0} signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first +signature.Reference.ForbiddenResolver = It is forbidden to access resolver {0} when secure validation is enabled +signature.signatureAlgorithm = It is forbidden to use algorithm {0} when secure validation is enabled signature.signaturePropertyHasNoTarget = Das Target Attribut der SignatureProperty muss gesetzt sein +signature.tooManyReferences = {0} references are contained in the Manifest, maximum {1} are allowed with secure validation +signature.tooManyTransforms = {0} transforms are contained in the Reference, maximum {1} are allowed with secure validation signature.Transform.ErrorDuringTransform = Während der Transformation {0} trat eine {1} auf. +signature.Transform.ForbiddenTransform = Transform {0} is forbidden when secure validation is enabled signature.Transform.NotYetImplemented = Transform {0} noch nicht implementiert signature.Transform.NullPointerTransform = Null pointer als URI übergeben. Programmierfehler? signature.Transform.UnknownTransform = Unbekannte Transformation. Kein Handler installiert für URI {0} @@ -103,6 +109,7 @@ signature.Verification.InvalidDigestOrReference = Ung signature.Verification.keyStore = Öffnen des KeyStore fehlgeschlagen signature.Verification.MissingID = Cannot resolve element with ID {0} signature.Verification.MissingResources = Kann die externe Resource {0} nicht auflösen +signature.Verification.MultipleIDs = Multiple Elements with the same ID {0} were detected signature.Verification.NoSignatureElement = Input Dokument enthält kein {0} Element mit dem Namespace {1} signature.Verification.Reference.NoInput = Die Reference für den URI {0} hat keinen XMLSignatureInput erhalten. signature.Verification.SignatureError = Signatur Fehler diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties index f15104e94b5..a01124ee85f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties @@ -1,126 +1,131 @@ -algorithm.alreadyRegistered = URI {0} already assigned to class {1} -algorithm.classDoesNotExist = Cannot register URI {0} to class {1} because this class does not exist in CLASSPATH -algorithm.ClassDoesNotExist = Class {0} does not exist -algorithm.extendsWrongClass = Cannot register URI {0} to class {1} because it does not extend {2} -algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures. -algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures. -algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs. -algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms -algorithms.NoSuchAlgorithm = The requested algorithm {0} does not exist. Original Message was: {1} -algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm -algorithms.NoSuchProvider = The specified Provider {0} does not exist. Original Message was: {1} -algorithms.operationOnlyVerification = A public key can only used for verification of a signature. -algorithms.WrongKeyForThisOperation = Sorry, you supplied the wrong key type for this operation! You supplied a {0} but a {1} is needed. -attributeValueIllegal = The attribute {0} has value {1} but must be {2} -c14n.Canonicalizer.Exception = Exception during Canonicalization: Original Message was {0} -c14n.Canonicalizer.IllegalNode = Illegal node type {0}, node name was {1} -c14n.Canonicalizer.NoSuchCanonicalizer = No canonicalizer found with URI {0} -c14n.Canonicalizer.ParserConfigurationException = ParserConfigurationException during Canonicalization: Original Message was {0} -c14n.Canonicalizer.RelativeNamespace = Element {0} has a relative namespace: {1}="{2}" -c14n.Canonicalizer.SAXException = SAXException during Canonicalization: Original Message was {0} -c14n.Canonicalizer.TraversalNotSupported = This DOM document does not support Traversal {0} -c14n.Canonicalizer.UnsupportedEncoding = Unsupported encoding {0} -c14n.Canonicalizer.UnsupportedOperation = This canonicalizer does not support this operation -c14n.XMLUtils.circumventBug2650forgotten = The tree has not been prepared for canonicalization using XMLUtils#circumventBug2650(Document) -certificate.noSki.lowVersion = Certificate cannot contain a SubjectKeyIdentifier because it is only X509v{0} -certificate.noSki.notOctetString = Certificates SubjectKeyIdentifier is not a OctetString -certificate.noSki.null = Certificate does not contain a SubjectKeyIdentifier -defaultNamespaceCannotBeSetHere = Default namespace cannot be set here -ElementProxy.nullElement = Cannot create an ElementProxy from a null argument -empty = {0} -encryption.algorithmCannotBeUsedForEncryptedData = encryption.algorithmCannotBeUsedForEncryptedData {0} -encryption.algorithmCannotEatInitParams = encryption.algorithmCannotEatInitParams -encryption.algorithmCannotEncryptDecrypt = encryption.algorithmCannotEncryptDecrypt -encryption.algorithmCannotWrapUnWrap = encryption.algorithmCannotWrapUnWrap -encryption.ExplicitKeySizeMismatch = The xenc:KeySize element requests a key size of {0} bit but the algorithm implements {1} bit -encryption.nonceLongerThanDecryptedPlaintext = The given nonce is longer than the available plaintext. I Cannot strip away this. -encryption.RSAOAEP.dataHashWrong = data hash wrong -encryption.RSAOAEP.dataStartWrong = data wrong start {0} -encryption.RSAOAEP.dataTooShort = data too short -encryption.RSAPKCS15.blockTruncated = block truncated -encryption.RSAPKCS15.noDataInBlock = no data in block -encryption.RSAPKCS15.unknownBlockType = unknown block type -encryption.nokey = No Key Encryption Key loaded and cannot determine using key resolvers -endorsed.jdk1.4.0 = Since it seems that nobody reads our installation notes, we must do it in the exception messages. Hope you read them. You did NOT use the endorsed mechanism from JDK 1.4 properly; look at how to solve this problem. -errorMessages.InvalidDigestValueException = INVALID signature -- check reference resolution. -errorMessages.InvalidSignatureValueException = INVALID signature -- core validation failed. -errorMessages.IOException = Other file I/O and similar exceptions. -errorMessages.MissingKeyFailureException = Cannot verify because of missing public key. Provide it via addResource and try again. -errorMessages.MissingResourceFailureException = Cannot verify because of unresolved references. Provide it via addResource and try again. -errorMessages.NoSuchAlgorithmException = Unknown Algorithm {0} -errorMessages.NotYetImplementedException = Functionality not yet there. -errorMessages.XMLSignatureException = Verification failed for some other reason. -decoding.divisible.four = It should be divisible by four -decoding.general = Error while decoding -FileKeyStorageImpl.addToDefaultFromRemoteNotImplemented = Method addToDefaultFromRemote() not yet implemented. -FileKeyStorageImpl.NoCert.Context = Not found such a X509Certificate including context {0} -FileKeyStorageImpl.NoCert.IssNameSerNo = Not found such a X509Certificate with IssuerName {0} and serial number {1} -FileKeyStorageImpl.NoCert.SubjName = Not found such a X509Certificate including SubjectName {0} -generic.dontHaveConstructionElement = I do not have a construction Element -generic.EmptyMessage = {0} -generic.NotYetImplemented = {0} Not YET implemented ;-(( -java.security.InvalidKeyException = Invalid key -java.security.NoSuchProviderException = Unknown or unsupported provider -java.security.UnknownKeyType = Unknown or unsupported key type {0} -KeyInfo.needKeyResolver = More than one keyResovler have to be registered -KeyInfo.nokey = Cannot get key from {0} -KeyInfo.noKey = Cannot get the public key -KeyInfo.wrongNumberOfObject = Need {0} keyObjects -KeyInfo.wrongUse = This object was made for getting {0} -keyResolver.alreadyRegistered = {1} class has already been registered for {0} -KeyResolver.needStorageResolver = Need a StorageResolver to retrieve a Certificate from a {0} -KeyResoverSpiImpl.cannotGetCert = Cannot get the Certificate that include or in {1} in implement class {0} -KeyResoverSpiImpl.elementGeneration = Cannot make {1} element in implement class {0} -KeyResoverSpiImpl.getPoublicKey = Cannot get the public key from implement class {0} -KeyResoverSpiImpl.InvalidElement = Cannot set (2) Element in implement class {0} -KeyResoverSpiImpl.keyStore = KeyStorage error in implement class {0} -KeyResoverSpiImpl.need.Element = {1} type of Element is needed in implement class {0} -KeyResoverSpiImpl.wrongCRLElement = Cannot make CRL from {1} in implement class {0} -KeyResoverSpiImpl.wrongKeyObject = Need {1} type of KeyObject for generation Element in implement class{0} -KeyResoverSpiImpl.wrongNumberOfObject = Need {1} keyObject in implement class {0} -KeyStore.alreadyRegistered = {0} Class has already been registered for {1} -KeyStore.register = {1} type class register error in class {0} -KeyStore.registerStore.register = Registeration error for type {0} -KeyValue.IllegalArgument = Cannot create a {0} from {1} -namespacePrefixAlreadyUsedByOtherURI = Namespace prefix {0} already used by other URI {1} -notYetInitialized = The module {0} is not yet initialized -prefix.AlreadyAssigned = You want to assign {0} as prefix for namespace {1} but it is already assigned for {2} -signature.Canonicalizer.UnknownCanonicalizer = Unknown canonicalizer. No handler installed for URI {0} -signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature -signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first -signature.Reference.ForbiddenResolver = It is forbidden to access resolver {0} when secure validation is enabled -signature.signatureAlgorithm = It is forbidden to use algorithm {0} when secure validation is enabled -signature.signaturePropertyHasNoTarget = The Target attribute of the SignatureProperty must be set -signature.Transform.ErrorDuringTransform = A {1} was thrown during the {0} transform -signature.Transform.NotYetImplemented = Transform {0} not yet implemented -signature.Transform.NullPointerTransform = Null pointer as URI. Programming bug? -signature.Transform.UnknownTransform = Unknown transformation. No handler installed for URI {0} -signature.Transform.node = Current Node: {0} -signature.Transform.nodeAndType = Current Node: {0}, type: {1} -signature.Util.BignumNonPositive = bigInteger.signum() must be positive -signature.Util.NonTextNode = Not a text node -signature.Util.TooManyChilds = Too many childs of Type {0} in {1} -signature.Verification.certificateError = Certificate error -signature.Verification.IndexOutOfBounds = Index {0} illegal. We only have {1} References -signature.Verification.internalError = Internal error -signature.Verification.InvalidDigestOrReference = Invalid digest of reference {0} -signature.Verification.keyStore = KeyStore error -signature.Verification.MissingID = Cannot resolve element with ID {0} -signature.Verification.MissingResources = Cannot resolve external resource {0} -signature.Verification.MultipleIDs = Multiple Elements with the same ID {0} were detected -signature.Verification.NoSignatureElement = Input document contains no {0} Element in namespace {1} -signature.Verification.Reference.NoInput = The Reference for URI {0} has no XMLSignatureInput -signature.Verification.SignatureError = Signature error -signature.XMLSignatureInput.MissingConstuctor = Cannot construct a XMLSignatureInput from class {0} -signature.XMLSignatureInput.SerializeDOM = Input initialized with DOM Element. Use Canonicalization to serialize it -signature.XMLSignatureInput.nodesetReference = Unable to convert to nodeset the reference -transform.Init.IllegalContextArgument = Invalid context argument of class {0}. Must be String, org.w3c.dom.NodeList or java.io.InputStream. -transform.init.NotInitialized = -transform.init.wrongURI = Initialized with wrong URI. How could this happen? We implement {0} but {1} was used during initialization -utils.Base64.IllegalBitlength = Illegal byte length; Data to be decoded must be a multiple of 4 -Base64Decoding = Error while decoding -utils.resolver.noClass = Could not find a resolver for URI {0} and Base {1} -xml.WrongContent = Cannot find {0} in {1} -xml.WrongElement = Cannot create a {0} from a {1} element -xpath.funcHere.documentsDiffer = The XPath is not in the same document as the context node -xpath.funcHere.noXPathContext = Try to evaluate an XPath which uses the here() function but XPath is not inside an ds:XPath Element. XPath was : {0} +algorithm.alreadyRegistered = URI {0} already assigned to class {1} +algorithm.classDoesNotExist = Cannot register URI {0} to class {1} because this class does not exist in CLASSPATH +algorithm.ClassDoesNotExist = Class {0} does not exist +algorithm.extendsWrongClass = Cannot register URI {0} to class {1} because it does not extend {2} +algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures. +algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures. +algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs. +algorithms.HMACOutputLengthMin = HMACOutputLength must not be less than {0} +algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms +algorithms.NoSuchAlgorithm = The requested algorithm {0} does not exist. Original Message was: {1} +algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm +algorithms.NoSuchProvider = The specified Provider {0} does not exist. Original Message was: {1} +algorithms.operationOnlyVerification = A public key can only used for verification of a signature. +algorithms.WrongKeyForThisOperation = Sorry, you supplied the wrong key type for this operation! You supplied a {0} but a {1} is needed. +attributeValueIllegal = The attribute {0} has value {1} but must be {2} +c14n.Canonicalizer.Exception = Exception during Canonicalization: Original Message was {0} +c14n.Canonicalizer.IllegalNode = Illegal node type {0}, node name was {1} +c14n.Canonicalizer.NoSuchCanonicalizer = No canonicalizer found with URI {0} +c14n.Canonicalizer.ParserConfigurationException = ParserConfigurationException during Canonicalization: Original Message was {0} +c14n.Canonicalizer.RelativeNamespace = Element {0} has a relative namespace: {1}="{2}" +c14n.Canonicalizer.SAXException = SAXException during Canonicalization: Original Message was {0} +c14n.Canonicalizer.TraversalNotSupported = This DOM document does not support Traversal {0} +c14n.Canonicalizer.UnsupportedEncoding = Unsupported encoding {0} +c14n.Canonicalizer.UnsupportedOperation = This canonicalizer does not support this operation +c14n.XMLUtils.circumventBug2650forgotten = The tree has not been prepared for canonicalization using XMLUtils#circumventBug2650(Document) +certificate.noSki.lowVersion = Certificate cannot contain a SubjectKeyIdentifier because it is only X509v{0} +certificate.noSki.notOctetString = Certificates SubjectKeyIdentifier is not a OctetString +certificate.noSki.null = Certificate does not contain a SubjectKeyIdentifier +defaultNamespaceCannotBeSetHere = Default namespace cannot be set here +ElementProxy.nullElement = Cannot create an ElementProxy from a null argument +empty = {0} +encryption.algorithmCannotBeUsedForEncryptedData = encryption.algorithmCannotBeUsedForEncryptedData {0} +encryption.algorithmCannotEatInitParams = encryption.algorithmCannotEatInitParams +encryption.algorithmCannotEncryptDecrypt = encryption.algorithmCannotEncryptDecrypt +encryption.algorithmCannotWrapUnWrap = encryption.algorithmCannotWrapUnWrap +encryption.ExplicitKeySizeMismatch = The xenc:KeySize element requests a key size of {0} bit but the algorithm implements {1} bit +encryption.nonceLongerThanDecryptedPlaintext = The given nonce is longer than the available plaintext. I Cannot strip away this. +encryption.RSAOAEP.dataHashWrong = data hash wrong +encryption.RSAOAEP.dataStartWrong = data wrong start {0} +encryption.RSAOAEP.dataTooShort = data too short +encryption.RSAPKCS15.blockTruncated = block truncated +encryption.RSAPKCS15.noDataInBlock = no data in block +encryption.RSAPKCS15.unknownBlockType = unknown block type +encryption.nokey = No Key Encryption Key loaded and cannot determine using key resolvers +endorsed.jdk1.4.0 = Since it seems that nobody reads our installation notes, we must do it in the exception messages. Hope you read them. You did NOT use the endorsed mechanism from JDK 1.4 properly; look at how to solve this problem. +errorMessages.InvalidDigestValueException = INVALID signature -- check reference resolution. +errorMessages.InvalidSignatureValueException = INVALID signature -- core validation failed. +errorMessages.IOException = Other file I/O and similar exceptions. +errorMessages.MissingKeyFailureException = Cannot verify because of missing public key. Provide it via addResource and try again. +errorMessages.MissingResourceFailureException = Cannot verify because of unresolved references. Provide it via addResource and try again. +errorMessages.NoSuchAlgorithmException = Unknown Algorithm {0} +errorMessages.NotYetImplementedException = Functionality not yet there. +errorMessages.XMLSignatureException = Verification failed for some other reason. +decoding.divisible.four = It should be divisible by four +decoding.general = Error while decoding +FileKeyStorageImpl.addToDefaultFromRemoteNotImplemented = Method addToDefaultFromRemote() not yet implemented. +FileKeyStorageImpl.NoCert.Context = Not found such a X509Certificate including context {0} +FileKeyStorageImpl.NoCert.IssNameSerNo = Not found such a X509Certificate with IssuerName {0} and serial number {1} +FileKeyStorageImpl.NoCert.SubjName = Not found such a X509Certificate including SubjectName {0} +generic.dontHaveConstructionElement = I do not have a construction Element +generic.EmptyMessage = {0} +generic.NotYetImplemented = {0} Not YET implemented ;-(( +java.security.InvalidKeyException = Invalid key +java.security.NoSuchProviderException = Unknown or unsupported provider +java.security.UnknownKeyType = Unknown or unsupported key type {0} +KeyInfo.needKeyResolver = More than one keyResovler have to be registered +KeyInfo.nokey = Cannot get key from {0} +KeyInfo.noKey = Cannot get the public key +KeyInfo.wrongNumberOfObject = Need {0} keyObjects +KeyInfo.wrongUse = This object was made for getting {0} +keyResolver.alreadyRegistered = {1} class has already been registered for {0} +KeyResolver.needStorageResolver = Need a StorageResolver to retrieve a Certificate from a {0} +KeyResoverSpiImpl.cannotGetCert = Cannot get the Certificate that include or in {1} in implement class {0} +KeyResoverSpiImpl.elementGeneration = Cannot make {1} element in implement class {0} +KeyResoverSpiImpl.getPoublicKey = Cannot get the public key from implement class {0} +KeyResoverSpiImpl.InvalidElement = Cannot set (2) Element in implement class {0} +KeyResoverSpiImpl.keyStore = KeyStorage error in implement class {0} +KeyResoverSpiImpl.need.Element = {1} type of Element is needed in implement class {0} +KeyResoverSpiImpl.wrongCRLElement = Cannot make CRL from {1} in implement class {0} +KeyResoverSpiImpl.wrongKeyObject = Need {1} type of KeyObject for generation Element in implement class{0} +KeyResoverSpiImpl.wrongNumberOfObject = Need {1} keyObject in implement class {0} +KeyStore.alreadyRegistered = {0} Class has already been registered for {1} +KeyStore.register = {1} type class register error in class {0} +KeyStore.registerStore.register = Registeration error for type {0} +KeyValue.IllegalArgument = Cannot create a {0} from {1} +namespacePrefixAlreadyUsedByOtherURI = Namespace prefix {0} already used by other URI {1} +notYetInitialized = The module {0} is not yet initialized +prefix.AlreadyAssigned = You want to assign {0} as prefix for namespace {1} but it is already assigned for {2} +signature.Canonicalizer.UnknownCanonicalizer = Unknown canonicalizer. No handler installed for URI {0} +signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature +signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first +signature.Reference.ForbiddenResolver = It is forbidden to access resolver {0} when secure validation is enabled +signature.signatureAlgorithm = It is forbidden to use algorithm {0} when secure validation is enabled +signature.signaturePropertyHasNoTarget = The Target attribute of the SignatureProperty must be set +signature.tooManyReferences = {0} references are contained in the Manifest, maximum {1} are allowed with secure validation +signature.tooManyTransforms = {0} transforms are contained in the Reference, maximum {1} are allowed with secure validation +signature.Transform.ErrorDuringTransform = A {1} was thrown during the {0} transform +signature.Transform.ForbiddenTransform = Transform {0} is forbidden when secure validation is enabled +signature.Transform.NotYetImplemented = Transform {0} not yet implemented +signature.Transform.NullPointerTransform = Null pointer as URI. Programming bug? +signature.Transform.UnknownTransform = Unknown transformation. No handler installed for URI {0} +signature.Transform.node = Current Node: {0} +signature.Transform.nodeAndType = Current Node: {0}, type: {1} +signature.Util.BignumNonPositive = bigInteger.signum() must be positive +signature.Util.NonTextNode = Not a text node +signature.Util.TooManyChilds = Too many childs of Type {0} in {1} +signature.Verification.certificateError = Certificate error +signature.Verification.IndexOutOfBounds = Index {0} illegal. We only have {1} References +signature.Verification.internalError = Internal error +signature.Verification.InvalidDigestOrReference = Invalid digest of reference {0} +signature.Verification.keyStore = KeyStore error +signature.Verification.MissingID = Cannot resolve element with ID {0} +signature.Verification.MissingResources = Cannot resolve external resource {0} +signature.Verification.MultipleIDs = Multiple Elements with the same ID {0} were detected +signature.Verification.NoSignatureElement = Input document contains no {0} Element in namespace {1} +signature.Verification.Reference.NoInput = The Reference for URI {0} has no XMLSignatureInput +signature.Verification.SignatureError = Signature error +signature.XMLSignatureInput.MissingConstuctor = Cannot construct a XMLSignatureInput from class {0} +signature.XMLSignatureInput.SerializeDOM = Input initialized with DOM Element. Use Canonicalization to serialize it +signature.XMLSignatureInput.nodesetReference = Unable to convert to nodeset the reference +transform.Init.IllegalContextArgument = Invalid context argument of class {0}. Must be String, org.w3c.dom.NodeList or java.io.InputStream. +transform.init.NotInitialized = +transform.init.wrongURI = Initialized with wrong URI. How could this happen? We implement {0} but {1} was used during initialization +transform.envelopedSignatureTransformNotInSignatureElement = Enveloped Transform cannot find Signature element +utils.Base64.IllegalBitlength = Illegal byte length; Data to be decoded must be a multiple of 4 +Base64Decoding = Error while decoding +utils.resolver.noClass = Could not find a resolver for URI {0} and Base {1} +xml.WrongContent = Cannot find {0} in {1} +xml.WrongElement = Cannot create a {0} from a {1} element +xpath.funcHere.documentsDiffer = The XPath is not in the same document as the context node +xpath.funcHere.noXPathContext = Try to evaluate an XPath which uses the here() function but XPath is not inside an ds:XPath Element. XPath was : {0} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java index 57da56c5cb2..7801315c02d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java @@ -2,85 +2,85 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.signature; - - /** - * Raised when the computed hash value doesn't match the given DigestValue. Additional human readable info is passed to the constructor -- this being the benefit of raising an exception or returning a value. + * Raised when the computed hash value doesn't match the given DigestValue. + * Additional human readable info is passed to the constructor -- this being the benefit + * of raising an exception or returning a value. * * @author Christian Geuer-Pollmann */ public class InvalidDigestValueException extends XMLSignatureException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor InvalidDigestValueException - * - */ - public InvalidDigestValueException() { - super(); - } + /** + * Constructor InvalidDigestValueException + * + */ + public InvalidDigestValueException() { + super(); + } - /** - * Constructor InvalidDigestValueException - * - * @param _msgID - */ - public InvalidDigestValueException(String _msgID) { - super(_msgID); - } + /** + * Constructor InvalidDigestValueException + * + * @param msgID + */ + public InvalidDigestValueException(String msgID) { + super(msgID); + } - /** - * Constructor InvalidDigestValueException - * - * @param _msgID - * @param exArgs - */ - public InvalidDigestValueException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor InvalidDigestValueException + * + * @param msgID + * @param exArgs + */ + public InvalidDigestValueException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor InvalidDigestValueException - * - * @param _msgID - * @param _originalException - */ - public InvalidDigestValueException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor InvalidDigestValueException + * + * @param msgID + * @param originalException + */ + public InvalidDigestValueException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor InvalidDigestValueException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public InvalidDigestValueException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * Constructor InvalidDigestValueException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public InvalidDigestValueException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java index 397c1293492..a216ebb4d17 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.signature; - - /** * Raised if testing the signature value over DigestValue fails because of invalid signature. * @@ -30,58 +30,56 @@ package com.sun.org.apache.xml.internal.security.signature; */ public class InvalidSignatureValueException extends XMLSignatureException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor InvalidSignatureValueException - * - */ - public InvalidSignatureValueException() { - super(); - } + /** + * Constructor InvalidSignatureValueException + * + */ + public InvalidSignatureValueException() { + super(); + } - /** - * Constructor InvalidSignatureValueException - * - * @param _msgID - */ - public InvalidSignatureValueException(String _msgID) { - super(_msgID); - } + /** + * Constructor InvalidSignatureValueException + * + * @param msgID + */ + public InvalidSignatureValueException(String msgID) { + super(msgID); + } - /** - * Constructor InvalidSignatureValueException - * - * @param _msgID - * @param exArgs - */ - public InvalidSignatureValueException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor InvalidSignatureValueException + * + * @param msgID + * @param exArgs + */ + public InvalidSignatureValueException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor InvalidSignatureValueException - * - * @param _msgID - * @param _originalException - */ - public InvalidSignatureValueException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor InvalidSignatureValueException + * + * @param msgID + * @param originalException + */ + public InvalidSignatureValueException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor InvalidSignatureValueException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public InvalidSignatureValueException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * Constructor InvalidSignatureValueException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public InvalidSignatureValueException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java index 351dee5edaf..01d76effdff 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java @@ -2,33 +2,33 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.signature; - - import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; -import java.util.Set; import java.util.Map; +import java.util.Set; import javax.xml.parsers.ParserConfigurationException; @@ -38,7 +38,6 @@ import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.transforms.Transforms; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.I18n; -import com.sun.org.apache.xml.internal.security.utils.IdResolver; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver; @@ -50,523 +49,561 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.SAXException; - - /** * Handles <ds:Manifest> elements. *

This element holds the Reference elements

- * @author $author: $ */ public class Manifest extends SignatureElementProxy { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** + * The maximum number of references per Manifest, if secure validation is enabled. + */ + public static final int MAXIMUM_REFERENCE_COUNT = 30; + + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(Manifest.class.getName()); - /** Field _references */ - List _references; - Element[] _referencesEl; + /** Field references */ + private List references; + private Element[] referencesEl; - /** Field verificationResults[] */ - private boolean verificationResults[] = null; + /** Field verificationResults[] */ + private boolean verificationResults[] = null; - /** Field _resolverProperties */ - Map _resolverProperties = null; + /** Field resolverProperties */ + private Map resolverProperties = null; - /** Field _perManifestResolvers */ - List _perManifestResolvers = null; + /** Field perManifestResolvers */ + private List perManifestResolvers = null; - /** - * Consturts {@link Manifest} - * - * @param doc the {@link Document} in which XMLsignature is placed - */ - public Manifest(Document doc) { + private boolean secureValidation; - super(doc); + /** + * Constructs {@link Manifest} + * + * @param doc the {@link Document} in which XMLsignature is placed + */ + public Manifest(Document doc) { + super(doc); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); - this._references = new ArrayList(); - } + this.references = new ArrayList(); + } - /** - * Constructor Manifest - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public Manifest(Element element, String BaseURI) - throws XMLSecurityException { + /** + * Constructor Manifest + * + * @param element + * @param baseURI + * @throws XMLSecurityException + */ + public Manifest(Element element, String baseURI) throws XMLSecurityException { + this(element, baseURI, false); - super(element, BaseURI); + } + /** + * Constructor Manifest + * + * @param element + * @param baseURI + * @param secureValidation + * @throws XMLSecurityException + */ + public Manifest( + Element element, String baseURI, boolean secureValidation + ) throws XMLSecurityException { + super(element, baseURI); - Attr attr = element.getAttributeNodeNS(null, "Id"); - if (attr != null) { - element.setIdAttributeNode(attr, true); - } - - // check out Reference children - this._referencesEl = XMLUtils.selectDsNodes(this._constructionElement.getFirstChild(), - Constants._TAG_REFERENCE); - int le = this._referencesEl.length; - { - if (le == 0) { + Attr attr = element.getAttributeNodeNS(null, "Id"); + if (attr != null) { + element.setIdAttributeNode(attr, true); + } + this.secureValidation = secureValidation; + // check out Reference children + this.referencesEl = + XMLUtils.selectDsNodes( + this.constructionElement.getFirstChild(), Constants._TAG_REFERENCE + ); + int le = this.referencesEl.length; + if (le == 0) { // At least one Reference must be present. Bad. - Object exArgs[] = { Constants._TAG_REFERENCE, - Constants._TAG_MANIFEST }; + Object exArgs[] = { Constants._TAG_REFERENCE, Constants._TAG_MANIFEST }; throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, I18n.translate("xml.WrongContent", exArgs)); - } - } + } - // create Vector - this._references = new ArrayList(le); + if (secureValidation && le > MAXIMUM_REFERENCE_COUNT) { + Object exArgs[] = { le, MAXIMUM_REFERENCE_COUNT }; - for (int i = 0; i < le; i++) { - Element refElem = this._referencesEl[i]; - Attr refAttr = refElem.getAttributeNodeNS(null, "Id"); - if (refAttr != null) { - refElem.setIdAttributeNode(refAttr, true); - } - this._references.add(null); - } - } + throw new XMLSecurityException("signature.tooManyReferences", exArgs); + } - /** - * This addDocument method is used to add a new resource to the - * signed info. A {@link com.sun.org.apache.xml.internal.security.signature.Reference} is built - * from the supplied values. - * - * @param BaseURI the URI of the resource where the XML instance was stored - * @param referenceURI URI attribute in Reference for specifing where data is - * @param transforms com.sun.org.apache.xml.internal.security.signature.Transforms object with an ordered list of transformations to be performed. - * @param digestURI The digest algorthim URI to be used. - * @param ReferenceId - * @param ReferenceType - * @throws XMLSignatureException - */ - public void addDocument( - String BaseURI, String referenceURI, Transforms transforms, String digestURI, String ReferenceId, String ReferenceType) - throws XMLSignatureException { + // create List + this.references = new ArrayList(le); - // the this._doc is handed implicitly by the this.getOwnerDocument() - Reference ref = new Reference(this._doc, BaseURI, referenceURI, this, - transforms, digestURI); + for (int i = 0; i < le; i++) { + Element refElem = referencesEl[i]; + Attr refAttr = refElem.getAttributeNodeNS(null, "Id"); + if (refAttr != null) { + refElem.setIdAttributeNode(refAttr, true); + } + this.references.add(null); + } + } - if (ReferenceId != null) { - ref.setId(ReferenceId); - } + /** + * This addDocument method is used to add a new resource to the + * signed info. A {@link com.sun.org.apache.xml.internal.security.signature.Reference} is built + * from the supplied values. + * + * @param baseURI the URI of the resource where the XML instance was stored + * @param referenceURI URI attribute in Reference for specifying + * where data is + * @param transforms com.sun.org.apache.xml.internal.security.signature.Transforms object with an ordered + * list of transformations to be performed. + * @param digestURI The digest algorithm URI to be used. + * @param referenceId + * @param referenceType + * @throws XMLSignatureException + */ + public void addDocument( + String baseURI, String referenceURI, Transforms transforms, + String digestURI, String referenceId, String referenceType + ) throws XMLSignatureException { + // the this.doc is handed implicitly by the this.getOwnerDocument() + Reference ref = + new Reference(this.doc, baseURI, referenceURI, this, transforms, digestURI); - if (ReferenceType != null) { - ref.setType(ReferenceType); - } + if (referenceId != null) { + ref.setId(referenceId); + } - // add Reference object to our cache vector - this._references.add(ref); + if (referenceType != null) { + ref.setType(referenceType); + } - // add the Element of the Reference object to the Manifest/SignedInfo - this._constructionElement.appendChild(ref.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } + // add Reference object to our cache vector + this.references.add(ref); - /** - * The calculation of the DigestValues in the References must be after the - * References are already added to the document and during the signing - * process. This ensures that all neccesary data is in place. - * - * @throws ReferenceNotInitializedException - * @throws XMLSignatureException - */ - public void generateDigestValues() - throws XMLSignatureException, ReferenceNotInitializedException { - - for (int i = 0; i < this.getLength(); i++) { + // add the Element of the Reference object to the Manifest/SignedInfo + this.constructionElement.appendChild(ref.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + /** + * The calculation of the DigestValues in the References must be after the + * References are already added to the document and during the signing + * process. This ensures that all necessary data is in place. + * + * @throws ReferenceNotInitializedException + * @throws XMLSignatureException + */ + public void generateDigestValues() + throws XMLSignatureException, ReferenceNotInitializedException { + for (int i = 0; i < this.getLength(); i++) { // update the cached Reference object, the Element content is automatically updated - Reference currentRef = this._references.get(i); - + Reference currentRef = this.references.get(i); currentRef.generateDigestValue(); - } - } + } + } - /** - * Return the nonnegative number of added references. - * - * @return the number of references - */ - public int getLength() { - return this._references.size(); - } - - /** - * Return the ith reference. Valid i - * values are 0 to {link@ getSize}-1. - * - * @param i Index of the requested {@link Reference} - * @return the ith reference - * @throws XMLSecurityException - */ - public Reference item(int i) throws XMLSecurityException { - - if (this._references.get(i) == null) { + /** + * Return the nonnegative number of added references. + * + * @return the number of references + */ + public int getLength() { + return this.references.size(); + } + /** + * Return the ith reference. Valid i + * values are 0 to {link@ getSize}-1. + * + * @param i Index of the requested {@link Reference} + * @return the ith reference + * @throws XMLSecurityException + */ + public Reference item(int i) throws XMLSecurityException { + if (this.references.get(i) == null) { // not yet constructed, so _we_ have to - Reference ref = new Reference(_referencesEl[i], this._baseURI, this); + Reference ref = + new Reference(referencesEl[i], this.baseURI, this, secureValidation); - this._references.set(i, ref); - } + this.references.set(i, ref); + } - return this._references.get(i); + return this.references.get(i); + } - } + /** + * Sets the Id attribute + * + * @param Id the Id attribute in ds:Manifest + */ + public void setId(String Id) { + if (Id != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ID, Id); + this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true); + } + } - /** - * Sets the Id attribute - * - * @param Id the Id attribute in ds:Manifest - */ - public void setId(String Id) { + /** + * Returns the Id attribute + * + * @return the Id attribute in ds:Manifest + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } - if (Id != null) { - setLocalIdAttribute(Constants._ATT_ID, Id); - } - } + /** + * Used to do a reference + * validation of all enclosed references using the {@link Reference#verify} method. + * + *

This step loops through all {@link Reference}s and does verify the hash + * values. If one or more verifications fail, the method returns + * false. If all verifications are successful, + * it returns true. The results of the individual reference + * validations are available by using the {@link #getVerificationResult(int)} method + * + * @return true if all References verify, false if one or more do not verify. + * @throws MissingResourceFailureException if a {@link Reference} does not verify + * (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException} + * because of an uninitialized {@link XMLSignatureInput} + * @see com.sun.org.apache.xml.internal.security.signature.Reference#verify + * @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify() + * @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException + * @throws XMLSecurityException + */ + public boolean verifyReferences() + throws MissingResourceFailureException, XMLSecurityException { + return this.verifyReferences(false); + } - /** - * Returns the Id attribute - * - * @return the Id attribute in ds:Manifest - */ - public String getId() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ID); - } + /** + * Used to do a reference + * validation of all enclosed references using the {@link Reference#verify} method. + * + *

This step loops through all {@link Reference}s and does verify the hash + * values. If one or more verifications fail, the method returns + * false. If all verifications are successful, + * it returns true. The results of the individual reference + * validations are available by using the {@link #getVerificationResult(int)} method + * + * @param followManifests + * @return true if all References verify, false if one or more do not verify. + * @throws MissingResourceFailureException if a {@link Reference} does not verify + * (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException} + * because of an uninitialized {@link XMLSignatureInput} + * @see com.sun.org.apache.xml.internal.security.signature.Reference#verify + * @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify(boolean) + * @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException + * @throws XMLSecurityException + */ + public boolean verifyReferences(boolean followManifests) + throws MissingResourceFailureException, XMLSecurityException { + if (referencesEl == null) { + this.referencesEl = + XMLUtils.selectDsNodes( + this.constructionElement.getFirstChild(), Constants._TAG_REFERENCE + ); + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "verify " + referencesEl.length + " References"); + log.log(java.util.logging.Level.FINE, "I am " + (followManifests + ? "" : "not") + " requested to follow nested Manifests"); + } + if (referencesEl.length == 0) { + throw new XMLSecurityException("empty"); + } + if (secureValidation && referencesEl.length > MAXIMUM_REFERENCE_COUNT) { + Object exArgs[] = { referencesEl.length, MAXIMUM_REFERENCE_COUNT }; - /** - * Used to do a reference - * validation of all enclosed references using the {@link Reference#verify} method. - * - *

This step loops through all {@link Reference}s and does verify the hash - * values. If one or more verifications fail, the method returns - * false. If all verifications are successful, - * it returns true. The results of the individual reference - * validations are available by using the {@link #getVerificationResult(int)} method - * - * @return true if all References verify, false if one or more do not verify. - * @throws MissingResourceFailureException if a {@link Reference} does not verify (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException} because of an uninitialized {@link XMLSignatureInput} - * @see com.sun.org.apache.xml.internal.security.signature.Reference#verify - * @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify() - * @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException - * @throws XMLSecurityException - */ - public boolean verifyReferences() - throws MissingResourceFailureException, XMLSecurityException { - return this.verifyReferences(false); - } + throw new XMLSecurityException("signature.tooManyReferences", exArgs); + } - /** - * Used to do a reference - * validation of all enclosed references using the {@link Reference#verify} method. - * - *

This step loops through all {@link Reference}s and does verify the hash - * values. If one or more verifications fail, the method returns - * false. If all verifications are successful, - * it returns true. The results of the individual reference - * validations are available by using the {@link #getVerificationResult(int)} method - * - * @param followManifests - * @return true if all References verify, false if one or more do not verify. - * @throws MissingResourceFailureException if a {@link Reference} does not verify (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException} because of an uninitialized {@link XMLSignatureInput} - * @see com.sun.org.apache.xml.internal.security.signature.Reference#verify - * @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify(boolean) - * @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException - * @throws XMLSecurityException - */ - public boolean verifyReferences(boolean followManifests) - throws MissingResourceFailureException, XMLSecurityException { - if (_referencesEl==null) { - this._referencesEl = - XMLUtils.selectDsNodes(this._constructionElement.getFirstChild(), - Constants._TAG_REFERENCE); - } - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "verify " +_referencesEl.length + " References"); - log.log(java.util.logging.Level.FINE, "I am " + (followManifests - ? "" - : "not") + " requested to follow nested Manifests"); - } - boolean verify = true; + this.verificationResults = new boolean[referencesEl.length]; + boolean verify = true; + for (int i = 0; i < this.referencesEl.length; i++) { + Reference currentRef = + new Reference(referencesEl[i], this.baseURI, this, secureValidation); - if (_referencesEl.length==0) { - throw new XMLSecurityException("empty"); - } + this.references.set(i, currentRef); - this.verificationResults = - new boolean[_referencesEl.length]; + // if only one item does not verify, the whole verification fails + try { + boolean currentRefVerified = currentRef.verify(); - for (int i = - 0; i < this._referencesEl.length; i++) { - Reference currentRef = - new Reference(_referencesEl[i], this._baseURI, this); + this.setVerificationResult(i, currentRefVerified); - this._references.set(i, currentRef); + if (!currentRefVerified) { + verify = false; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "The Reference has Type " + currentRef.getType()); + } - /* if only one item does not verify, the whole verification fails */ - try { - boolean currentRefVerified = currentRef.verify(); + // was verification successful till now and do we want to verify the Manifest? + if (verify && followManifests && currentRef.typeIsReferenceToManifest()) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "We have to follow a nested Manifest"); + } - this.setVerificationResult(i, currentRefVerified); + try { + XMLSignatureInput signedManifestNodes = + currentRef.dereferenceURIandPerformTransforms(null); + Set nl = signedManifestNodes.getNodeSet(); + Manifest referencedManifest = null; + Iterator nlIterator = nl.iterator(); - if (!currentRefVerified) { - verify = false; - } - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "The Reference has Type " + currentRef.getType()); + findManifest: while (nlIterator.hasNext()) { + Node n = nlIterator.next(); - // was verification successful till now and do we want to verify the Manifest? - if (verify && followManifests - && currentRef.typeIsReferenceToManifest()) { - log.log(java.util.logging.Level.FINE, "We have to follow a nested Manifest"); - - try { - XMLSignatureInput signedManifestNodes = - currentRef.dereferenceURIandPerformTransforms(null); - Set nl = signedManifestNodes.getNodeSet(); - Manifest referencedManifest = null; - Iterator nlIterator = nl.iterator(); - - findManifest: while (nlIterator.hasNext()) { - Node n = nlIterator.next(); - - if ((n.getNodeType() == Node.ELEMENT_NODE) && ((Element) n) - .getNamespaceURI() - .equals(Constants.SignatureSpecNS) && ((Element) n) - .getLocalName().equals(Constants._TAG_MANIFEST)) { - try { - referencedManifest = - new Manifest((Element) n, - signedManifestNodes.getSourceURI()); - - break findManifest; - } catch (XMLSecurityException ex) { - - // Hm, seems not to be a ds:Manifest + if ((n.getNodeType() == Node.ELEMENT_NODE) + && ((Element) n).getNamespaceURI().equals(Constants.SignatureSpecNS) + && ((Element) n).getLocalName().equals(Constants._TAG_MANIFEST) + ) { + try { + referencedManifest = + new Manifest( + (Element)n, signedManifestNodes.getSourceURI(), secureValidation + ); + break findManifest; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + // Hm, seems not to be a ds:Manifest + } + } } - } - } - if (referencedManifest == null) { + if (referencedManifest == null) { + // The Reference stated that it points to a ds:Manifest + // but we did not find a ds:Manifest in the signed area + throw new MissingResourceFailureException("empty", currentRef); + } - // The Reference stated that it points to a ds:Manifest - // but we did not find a ds:Manifest in the signed area - throw new MissingResourceFailureException("empty", - currentRef); - } + referencedManifest.perManifestResolvers = this.perManifestResolvers; + referencedManifest.resolverProperties = this.resolverProperties; - referencedManifest._perManifestResolvers = - this._perManifestResolvers; - referencedManifest._resolverProperties = - this._resolverProperties; + boolean referencedManifestValid = + referencedManifest.verifyReferences(followManifests); - boolean referencedManifestValid = - referencedManifest.verifyReferences(followManifests); + if (!referencedManifestValid) { + verify = false; - if (!referencedManifestValid) { - verify = false; + log.log(java.util.logging.Level.WARNING, "The nested Manifest was invalid (bad)"); + } else { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "The nested Manifest was valid (good)"); + } + } + } catch (IOException ex) { + throw new ReferenceNotInitializedException("empty", ex); + } catch (ParserConfigurationException ex) { + throw new ReferenceNotInitializedException("empty", ex); + } catch (SAXException ex) { + throw new ReferenceNotInitializedException("empty", ex); + } + } + } catch (ReferenceNotInitializedException ex) { + Object exArgs[] = { currentRef.getURI() }; - log.log(java.util.logging.Level.WARNING, "The nested Manifest was invalid (bad)"); - } else { - log.log(java.util.logging.Level.FINE, "The nested Manifest was valid (good)"); - } - } catch (IOException ex) { - throw new ReferenceNotInitializedException("empty", ex); - } catch (ParserConfigurationException ex) { - throw new ReferenceNotInitializedException("empty", ex); - } catch (SAXException ex) { - throw new ReferenceNotInitializedException("empty", ex); - } + throw new MissingResourceFailureException( + "signature.Verification.Reference.NoInput", exArgs, ex, currentRef + ); } - } catch (ReferenceNotInitializedException ex) { - Object exArgs[] = { currentRef.getURI() }; + } - throw new MissingResourceFailureException( - "signature.Verification.Reference.NoInput", exArgs, ex, - currentRef); - } - } + return verify; + } - return verify; - } + /** + * Method setVerificationResult + * + * @param index + * @param verify + */ + private void setVerificationResult(int index, boolean verify) { + if (this.verificationResults == null) { + this.verificationResults = new boolean[this.getLength()]; + } - /** - * Method setVerificationResult - * - * @param index - * @param verify - */ - private void setVerificationResult(int index, boolean verify) - { + this.verificationResults[index] = verify; + } - if (this.verificationResults == null) { - this.verificationResults = new boolean[this.getLength()]; - } + /** + * After verifying a {@link Manifest} or a {@link SignedInfo} using the + * {@link Manifest#verifyReferences()} or {@link SignedInfo#verify()} methods, + * the individual results can be retrieved with this method. + * + * @param index an index of into a {@link Manifest} or a {@link SignedInfo} + * @return the results of reference validation at the specified index + * @throws XMLSecurityException + */ + public boolean getVerificationResult(int index) throws XMLSecurityException { + if ((index < 0) || (index > this.getLength() - 1)) { + Object exArgs[] = { Integer.toString(index), Integer.toString(this.getLength()) }; + Exception e = + new IndexOutOfBoundsException( + I18n.translate("signature.Verification.IndexOutOfBounds", exArgs) + ); - this.verificationResults[index] = verify; - } + throw new XMLSecurityException("generic.EmptyMessage", e); + } - /** - * After verifying a {@link Manifest} or a {@link SignedInfo} using the - * {@link Manifest#verifyReferences()} or {@link SignedInfo#verify()} methods, - * the individual results can be retrieved with this method. - * - * @param index an index of into a {@link Manifest} or a {@link SignedInfo} - * @return the results of reference validation at the specified index - * @throws XMLSecurityException - */ - public boolean getVerificationResult(int index) throws XMLSecurityException { + if (this.verificationResults == null) { + try { + this.verifyReferences(); + } catch (Exception ex) { + throw new XMLSecurityException("generic.EmptyMessage", ex); + } + } - if ((index < 0) || (index > this.getLength() - 1)) { - Object exArgs[] = { Integer.toString(index), - Integer.toString(this.getLength()) }; - Exception e = - new IndexOutOfBoundsException(I18n - .translate("signature.Verification.IndexOutOfBounds", exArgs)); + return this.verificationResults[index]; + } - throw new XMLSecurityException("generic.EmptyMessage", e); - } + /** + * Adds Resource Resolver for retrieving resources at specified URI attribute + * in reference element + * + * @param resolver {@link ResourceResolver} can provide the implemenatin subclass of + * {@link ResourceResolverSpi} for retrieving resource. + */ + public void addResourceResolver(ResourceResolver resolver) { + if (resolver == null) { + return; + } + if (perManifestResolvers == null) { + perManifestResolvers = new ArrayList(); + } + this.perManifestResolvers.add(resolver); + } - if (this.verificationResults == null) { - try { - this.verifyReferences(); - } catch (Exception ex) { - throw new XMLSecurityException("generic.EmptyMessage", ex); - } - } + /** + * Adds Resource Resolver for retrieving resources at specified URI attribute + * in reference element + * + * @param resolverSpi the implementation subclass of {@link ResourceResolverSpi} for + * retrieving the resource. + */ + public void addResourceResolver(ResourceResolverSpi resolverSpi) { + if (resolverSpi == null) { + return; + } + if (perManifestResolvers == null) { + perManifestResolvers = new ArrayList(); + } + perManifestResolvers.add(new ResourceResolver(resolverSpi)); + } - return this.verificationResults[index]; - } + /** + * Get the Per-Manifest Resolver List + * @return the per-manifest Resolver List + */ + public List getPerManifestResolvers() { + return perManifestResolvers; + } - /** - * Adds Resource Resolver for retrieving resources at specified URI attribute in reference element - * - * @param resolver {@link ResourceResolver} can provide the implemenatin subclass of {@link ResourceResolverSpi} for retrieving resource. - */ - public void addResourceResolver(ResourceResolver resolver) { + /** + * Get the resolver property map + * @return the resolver property map + */ + public Map getResolverProperties() { + return resolverProperties; + } - if (resolver == null) { - return; - } - if (_perManifestResolvers==null) - _perManifestResolvers = new ArrayList(); - this._perManifestResolvers.add(resolver); + /** + * Used to pass parameters like proxy servers etc to the ResourceResolver + * implementation. + * + * @param key the key + * @param value the value + */ + public void setResolverProperty(String key, String value) { + if (resolverProperties == null) { + resolverProperties = new HashMap(10); + } + this.resolverProperties.put(key, value); + } - } + /** + * Returns the value at specified key + * + * @param key the key + * @return the value + */ + public String getResolverProperty(String key) { + return this.resolverProperties.get(key); + } - /** - * Adds Resource Resolver for retrieving resources at specified URI attribute in reference element - * - * @param resolverSpi the implemenatin subclass of {@link ResourceResolverSpi} for retrieving resource. - */ - public void addResourceResolver(ResourceResolverSpi resolverSpi) { + /** + * Method getSignedContentItem + * + * @param i + * @return The signed content of the i reference. + * + * @throws XMLSignatureException + */ + public byte[] getSignedContentItem(int i) throws XMLSignatureException { + try { + return this.getReferencedContentAfterTransformsItem(i).getBytes(); + } catch (IOException ex) { + throw new XMLSignatureException("empty", ex); + } catch (CanonicalizationException ex) { + throw new XMLSignatureException("empty", ex); + } catch (InvalidCanonicalizerException ex) { + throw new XMLSignatureException("empty", ex); + } catch (XMLSecurityException ex) { + throw new XMLSignatureException("empty", ex); + } + } - if (resolverSpi == null) { - return; - } - if (_perManifestResolvers==null) - _perManifestResolvers = new ArrayList(); - this._perManifestResolvers.add(new ResourceResolver(resolverSpi)); + /** + * Method getReferencedContentPriorTransformsItem + * + * @param i + * @return The contents before transformation of the reference i. + * @throws XMLSecurityException + */ + public XMLSignatureInput getReferencedContentBeforeTransformsItem(int i) + throws XMLSecurityException { + return this.item(i).getContentsBeforeTransformation(); + } - } + /** + * Method getReferencedContentAfterTransformsItem + * + * @param i + * @return The contents after transformation of the reference i. + * @throws XMLSecurityException + */ + public XMLSignatureInput getReferencedContentAfterTransformsItem(int i) + throws XMLSecurityException { + return this.item(i).getContentsAfterTransformation(); + } - /** - * Used to pass parameters like proxy servers etc to the ResourceResolver - * implementation. - * - * @param key the key - * @param value the value - */ - public void setResolverProperty(String key, String value) { - if (_resolverProperties==null) { - _resolverProperties=new HashMap(10); - } - this._resolverProperties.put(key, value); - } + /** + * Method getSignedContentLength + * + * @return The number of references contained in this reference. + */ + public int getSignedContentLength() { + return this.getLength(); + } - /** - * Returns the value at specified key - * - * @param key the key - * @return the value - */ - public String getResolverProperty(String key) { - return this._resolverProperties.get(key); - } - - /** - * Method getSignedContentItem - * - * @param i - * @return The signed content of the i reference. - * - * @throws XMLSignatureException - */ - public byte[] getSignedContentItem(int i) throws XMLSignatureException { - - try { - return this.getReferencedContentAfterTransformsItem(i).getBytes(); - } catch (IOException ex) { - throw new XMLSignatureException("empty", ex); - } catch (CanonicalizationException ex) { - throw new XMLSignatureException("empty", ex); - } catch (InvalidCanonicalizerException ex) { - throw new XMLSignatureException("empty", ex); - } catch (XMLSecurityException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** - * Method getReferencedContentPriorTransformsItem - * - * @param i - * @return The contents before transformation of the reference i. - * @throws XMLSecurityException - */ - public XMLSignatureInput getReferencedContentBeforeTransformsItem(int i) - throws XMLSecurityException { - return this.item(i).getContentsBeforeTransformation(); - } - - /** - * Method getReferencedContentAfterTransformsItem - * - * @param i - * @return The contents after transformation of the reference i. - * @throws XMLSecurityException - */ - public XMLSignatureInput getReferencedContentAfterTransformsItem(int i) - throws XMLSecurityException { - return this.item(i).getContentsAfterTransformation(); - } - - /** - * Method getSignedContentLength - * - * @return The nu,ber of references contained in this reference. - */ - public int getSignedContentLength() { - return this.getLength(); - } - - /** - * Method getBaseLocalName - * - * @inheritDoc - */ - public String getBaseLocalName() { - return Constants._TAG_MANIFEST; - } + /** + * Method getBaseLocalName + * + * @inheritDoc + */ + public String getBaseLocalName() { + return Constants._TAG_MANIFEST; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java index 99f76041ee4..7da105d37be 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java @@ -2,28 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.signature; - - - - /** * Thrown by {@link com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify()} when * testing the signature fails because of uninitialized @@ -34,97 +32,93 @@ package com.sun.org.apache.xml.internal.security.signature; */ public class MissingResourceFailureException extends XMLSignatureException { - /** - * - */ - private static final long serialVersionUID = 1L; - /** Field uninitializedReference */ - Reference uninitializedReference = null; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * MissingKeyResourceFailureException constructor. - * @param _msgID - * @param reference - * @see #getReference - */ - public MissingResourceFailureException(String _msgID, Reference reference) { + /** Field uninitializedReference */ + private Reference uninitializedReference = null; - super(_msgID); + /** + * MissingKeyResourceFailureException constructor. + * @param msgID + * @param reference + * @see #getReference + */ + public MissingResourceFailureException(String msgID, Reference reference) { + super(msgID); - this.uninitializedReference = reference; - } + this.uninitializedReference = reference; + } - /** - * Constructor MissingResourceFailureException - * - * @param _msgID - * @param exArgs - * @param reference - * @see #getReference - */ - public MissingResourceFailureException(String _msgID, Object exArgs[], - Reference reference) { + /** + * Constructor MissingResourceFailureException + * + * @param msgID + * @param exArgs + * @param reference + * @see #getReference + */ + public MissingResourceFailureException(String msgID, Object exArgs[], Reference reference) { + super(msgID, exArgs); - super(_msgID, exArgs); + this.uninitializedReference = reference; + } - this.uninitializedReference = reference; - } + /** + * Constructor MissingResourceFailureException + * + * @param msgID + * @param originalException + * @param reference + * @see #getReference + */ + public MissingResourceFailureException( + String msgID, Exception originalException, Reference reference + ) { + super(msgID, originalException); - /** - * Constructor MissingResourceFailureException - * - * @param _msgID - * @param _originalException - * @param reference - * @see #getReference - */ - public MissingResourceFailureException(String _msgID, - Exception _originalException, - Reference reference) { + this.uninitializedReference = reference; + } - super(_msgID, _originalException); + /** + * Constructor MissingResourceFailureException + * + * @param msgID + * @param exArgs + * @param originalException + * @param reference + * @see #getReference + */ + public MissingResourceFailureException( + String msgID, Object exArgs[], Exception originalException, Reference reference + ) { + super(msgID, exArgs, originalException); - this.uninitializedReference = reference; - } + this.uninitializedReference = reference; + } - /** - * Constructor MissingResourceFailureException - * - * @param _msgID - * @param exArgs - * @param _originalException - * @param reference - * @see #getReference - */ - public MissingResourceFailureException(String _msgID, Object exArgs[], - Exception _originalException, - Reference reference) { + /** + * used to set the uninitialized {@link com.sun.org.apache.xml.internal.security.signature.Reference} + * + * @param reference the Reference object + * @see #getReference + */ + public void setReference(Reference reference) { + this.uninitializedReference = reference; + } - super(_msgID, exArgs, _originalException); - - this.uninitializedReference = reference; - } - - /** - * used to set the uninitialized {@link com.sun.org.apache.xml.internal.security.signature.Reference} - * - * @param reference the Reference object - * @see #getReference - */ - public void setReference(Reference reference) { - this.uninitializedReference = reference; - } - - /** - * used to get the uninitialized {@link com.sun.org.apache.xml.internal.security.signature.Reference} - * - * This allows to supply the correct {@link com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput} - * to the {@link com.sun.org.apache.xml.internal.security.signature.Reference} to try again verification. - * - * @return the Reference object - * @see #setReference - */ - public Reference getReference() { - return this.uninitializedReference; - } + /** + * used to get the uninitialized {@link com.sun.org.apache.xml.internal.security.signature.Reference} + * + * This allows to supply the correct {@link com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput} + * to the {@link com.sun.org.apache.xml.internal.security.signature.Reference} to try again verification. + * + * @return the Reference object + * @see #setReference + */ + public Reference getReference() { + return this.uninitializedReference; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java index 2ccf7a06905..6b670c1b274 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.signature; @@ -24,30 +26,30 @@ import org.w3c.dom.Node; /** * An interface to tell to the c14n if a node is included or not in the output - * @author raul - * */ public interface NodeFilter { - /** - * Tells if a node must be outputed in c14n. - * @param n - * @return 1 if the node should be outputed. - * 0 if node must not be outputed, - * -1 if the node and all it's child must not be output. - * - */ - public int isNodeInclude(Node n); - /** - * Tells if a node must be outputed in a c14n. - * The caller must assured that this method is always call - * in document order. The implementations can use this - * restriction to optimize the transformation. - * @param n - * @param level the relative level in the tree - * @return 1 if the node should be outputed. - * 0 if node must not be outputed, - * -1 if the node and all it's child must not be output. - */ - public int isNodeIncludeDO(Node n, int level); + + /** + * Tells if a node must be output in c14n. + * @param n + * @return 1 if the node should be output. + * 0 if node must not be output, + * -1 if the node and all it's child must not be output. + * + */ + int isNodeInclude(Node n); + + /** + * Tells if a node must be output in a c14n. + * The caller must assured that this method is always call + * in document order. The implementations can use this + * restriction to optimize the transformation. + * @param n + * @param level the relative level in the tree + * @return 1 if the node should be output. + * 0 if node must not be output, + * -1 if the node and all it's child must not be output. + */ + int isNodeIncludeDO(Node n, int level); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java index 8bbc4db2a62..bf2473295dc 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java @@ -2,27 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.signature; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.utils.Constants; -import com.sun.org.apache.xml.internal.security.utils.IdResolver; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -38,111 +39,99 @@ import org.w3c.dom.Node; */ public class ObjectContainer extends SignatureElementProxy { - /** - * Constructs {@link ObjectContainer} - * - * @param doc the {@link Document} in which Object element is placed - */ - public ObjectContainer(Document doc) { + /** + * Constructs {@link ObjectContainer} + * + * @param doc the {@link Document} in which Object element is placed + */ + public ObjectContainer(Document doc) { + super(doc); + } - super(doc); - } + /** + * Constructs {@link ObjectContainer} from {@link Element} + * + * @param element is Object element + * @param baseURI the URI of the resource where the XML instance was stored + * @throws XMLSecurityException + */ + public ObjectContainer(Element element, String baseURI) throws XMLSecurityException { + super(element, baseURI); + } - /** - * Constructs {@link ObjectContainer} from {@link Element} - * - * @param element is Object element - * @param BaseURI the URI of the resource where the XML instance was stored - * @throws XMLSecurityException - */ - public ObjectContainer(Element element, String BaseURI) - throws XMLSecurityException { + /** + * Sets the Id attribute + * + * @param Id Id attribute + */ + public void setId(String Id) { + if (Id != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ID, Id); + this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true); + } + } - super(element, BaseURI); - } + /** + * Returns the Id attribute + * + * @return the Id attribute + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } - /** - * Sets the Id attribute - * - * @param Id Id attribute - */ - public void setId(String Id) { + /** + * Sets the MimeType attribute + * + * @param MimeType the MimeType attribute + */ + public void setMimeType(String MimeType) { + if (MimeType != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_MIMETYPE, MimeType); + } + } - if (Id != null) { - setLocalIdAttribute(Constants._ATT_ID, Id); - } - } + /** + * Returns the MimeType attribute + * + * @return the MimeType attribute + */ + public String getMimeType() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_MIMETYPE); + } - /** - * Returns the Id attribute - * - * @return the Id attribute - */ - public String getId() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ID); - } + /** + * Sets the Encoding attribute + * + * @param Encoding the Encoding attribute + */ + public void setEncoding(String Encoding) { + if (Encoding != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ENCODING, Encoding); + } + } - /** - * Sets the MimeType attribute - * - * @param MimeType the MimeType attribute - */ - public void setMimeType(String MimeType) { + /** + * Returns the Encoding attribute + * + * @return the Encoding attribute + */ + public String getEncoding() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ENCODING); + } - if ( (MimeType != null)) { - this._constructionElement.setAttributeNS(null, Constants._ATT_MIMETYPE, - MimeType); - } - } + /** + * Adds child Node + * + * @param node child Node + * @return the new node in the tree. + */ + public Node appendChild(Node node) { + return this.constructionElement.appendChild(node); + } - /** - * Returns the MimeType attribute - * - * @return the MimeType attribute - */ - public String getMimeType() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_MIMETYPE); - } - - /** - * Sets the Encoding attribute - * - * @param Encoding the Encoding attribute - */ - public void setEncoding(String Encoding) { - - if ((Encoding != null)) { - this._constructionElement.setAttributeNS(null, Constants._ATT_ENCODING, - Encoding); - } - } - - /** - * Returns the Encoding attribute - * - * @return the Encoding attribute - */ - public String getEncoding() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ENCODING); - } - - /** - * Adds child Node - * - * @param node child Node - * @return the new node in the tree. - */ - public Node appendChild(Node node) { - - Node result = null; - - result = this._constructionElement.appendChild(node); - - return result; - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_OBJECT; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_OBJECT; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java index 57bb7fa0f77..ece475c983d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java @@ -2,31 +2,32 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.signature; - - import java.io.IOException; import java.io.OutputStream; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.HashSet; +import java.util.Iterator; import java.util.Set; import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm; @@ -34,6 +35,10 @@ import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException; import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceData; +import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceNodeSetData; +import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceOctetStreamData; +import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceSubTreeData; import com.sun.org.apache.xml.internal.security.transforms.InvalidTransformException; import com.sun.org.apache.xml.internal.security.transforms.Transform; import com.sun.org.apache.xml.internal.security.transforms.TransformationException; @@ -42,7 +47,6 @@ import com.sun.org.apache.xml.internal.security.transforms.params.InclusiveNames import com.sun.org.apache.xml.internal.security.utils.Base64; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.DigesterOutputStream; -import com.sun.org.apache.xml.internal.security.utils.IdResolver; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; @@ -54,7 +58,6 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; - /** * Handles <ds:Reference> elements. * @@ -64,17 +67,17 @@ import org.w3c.dom.Text; * *

Create a new reference

*
- * Document _doc;
+ * Document doc;
  * MessageDigestAlgorithm sha1 = MessageDigestAlgorithm.getInstance("http://#sha1");
  * Reference ref = new Reference(new XMLSignatureInput(new FileInputStream("1.gif"),
  *                               "http://localhost/1.gif",
  *                               (Transforms) null, sha1);
- * Element refElem = ref.toElement(_doc);
+ * Element refElem = ref.toElement(doc);
  * 
* *

Verify a reference

*
- * Element refElem = _doc.getElement("Reference"); // PSEUDO
+ * Element refElem = doc.getElement("Reference"); // PSEUDO
  * Reference ref = new Reference(refElem);
  * String url = ref.getURI();
  * ref.setData(new XMLSignatureInput(new FileInputStream(url)));
@@ -103,689 +106,697 @@ import org.w3c.dom.Text;
  */
 public class Reference extends SignatureElementProxy {
 
-   /**
-    * Look up useC14N11 system property. If true, an explicit C14N11 transform
-    * will be added if necessary when generating the signature. See section
-    * 3.1.1 of http://www.w3.org/2007/xmlsec/Drafts/xmldsig-core/ for more info.
-    */
-   private static boolean useC14N11 =
-      AccessController.doPrivileged(new PrivilegedAction() {
-         public Boolean run() {
-            return Boolean.getBoolean
-               ("com.sun.org.apache.xml.internal.security.useC14N11");
-         }
-      });
+    /** Field OBJECT_URI */
+    public static final String OBJECT_URI = Constants.SignatureSpecNS + Constants._TAG_OBJECT;
 
-/*
-   static {
-      try {
-         useC14N11 = Boolean.getBoolean("com.sun.org.apache.xml.internal.security.useC14N11");
-      } catch (Exception e) {
-         // ignore exceptions
-      }
-   }
-*/
+    /** Field MANIFEST_URI */
+    public static final String MANIFEST_URI = Constants.SignatureSpecNS + Constants._TAG_MANIFEST;
 
-   /** Field CacheSignedNodes */
-   public final static boolean CacheSignedNodes = false;
+    /**
+     * The maximum number of transforms per reference, if secure validation is enabled.
+     */
+    public static final int MAXIMUM_TRANSFORM_COUNT = 5;
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
+    private boolean secureValidation;
+
+    /**
+     * Look up useC14N11 system property. If true, an explicit C14N11 transform
+     * will be added if necessary when generating the signature. See section
+     * 3.1.1 of http://www.w3.org/2007/xmlsec/Drafts/xmldsig-core/ for more info.
+     */
+    private static boolean useC14N11 = (
+        AccessController.doPrivileged(new PrivilegedAction() {
+            public Boolean run() {
+                return Boolean.valueOf(Boolean.getBoolean("com.sun.org.apache.xml.internal.security.useC14N11"));
+            }
+        })).booleanValue();
+
+    /** {@link org.apache.commons.logging} logging facility */
+    private static final java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(Reference.class.getName());
 
-   /** Field OBJECT_URI */
-   public static final String OBJECT_URI = Constants.SignatureSpecNS
-                                           + Constants._TAG_OBJECT;
-
-   /** Field MANIFEST_URI */
-   public static final String MANIFEST_URI = Constants.SignatureSpecNS
-                                             + Constants._TAG_MANIFEST;
-   //J-
-   Manifest _manifest = null;
-   XMLSignatureInput _transformsOutput;
-   //J+
-
-private Transforms transforms;
-
-private Element digestMethodElem;
-
-private Element digestValueElement;
-
-   /**
-    * Constructor Reference
-    *
-    * @param doc the {@link Document} in which XMLsignature is placed
-    * @param BaseURI the URI of the resource where the XML instance will be stored
-    * @param ReferenceURI URI indicate where is data which will digested
-    * @param manifest
-    * @param transforms {@link Transforms} applied to data
-    * @param messageDigestAlgorithm {@link MessageDigestAlgorithm Digest algorithm} which is applied to the data
-    * TODO should we throw XMLSignatureException if MessageDigestAlgoURI is wrong?
-    * @throws XMLSignatureException
-    */
-   protected Reference(Document doc, String BaseURI, String ReferenceURI, Manifest manifest, Transforms transforms, String messageDigestAlgorithm)
-           throws XMLSignatureException {
-
-      super(doc);
-
-      XMLUtils.addReturnToElement(this._constructionElement);
-
-      this._baseURI = BaseURI;
-      this._manifest = manifest;
-
-      this.setURI(ReferenceURI);
-
-      // important: The ds:Reference must be added to the associated ds:Manifest
-      //            or ds:SignedInfo _before_ the this.resolverResult() is called.
-      // this._manifest.appendChild(this._constructionElement);
-      // this._manifest.appendChild(this._doc.createTextNode("\n"));
-
-      if (transforms != null) {
-          this.transforms=transforms;
-         this._constructionElement.appendChild(transforms.getElement());
-         XMLUtils.addReturnToElement(this._constructionElement);
-      }
-      {
-         MessageDigestAlgorithm mda =
-            MessageDigestAlgorithm.getInstance(this._doc,
-                                               messageDigestAlgorithm);
-
-         digestMethodElem=mda.getElement();
-         this._constructionElement.appendChild(digestMethodElem);
-         XMLUtils.addReturnToElement(this._constructionElement);
-      }
-      {
-         digestValueElement =
-            XMLUtils.createElementInSignatureSpace(this._doc,
-                                                   Constants._TAG_DIGESTVALUE);
-
-         this._constructionElement.appendChild(digestValueElement);
-         XMLUtils.addReturnToElement(this._constructionElement);
-      }
-   }
-
-
-   /**
-    * Build a {@link Reference} from an {@link Element}
-    *
-    * @param element Reference element
-    * @param BaseURI the URI of the resource where the XML instance was stored
-    * @param manifest is the {@link Manifest} of {@link SignedInfo} in which the Reference occurs. We need this because the Manifest has the individual {@link ResourceResolver}s whcih have been set by the user
-    * @throws XMLSecurityException
-    */
-   protected Reference(Element element, String BaseURI, Manifest manifest)
-           throws XMLSecurityException {
-
-      super(element, BaseURI);
-      this._baseURI=BaseURI;
-      Element el=XMLUtils.getNextElement(element.getFirstChild());
-      if (Constants._TAG_TRANSFORMS.equals(el.getLocalName()) &&
-                  Constants.SignatureSpecNS.equals(el.getNamespaceURI())) {
-          transforms = new Transforms(el,this._baseURI);
-          el=XMLUtils.getNextElement(el.getNextSibling());
-      }
-      digestMethodElem = el;
-      digestValueElement =XMLUtils.getNextElement(digestMethodElem.getNextSibling());;
-      this._manifest = manifest;
-   }
-
-   /**
-    * Returns {@link MessageDigestAlgorithm}
-    *
-    *
-    * @return {@link MessageDigestAlgorithm}
-    *
-    * @throws XMLSignatureException
-    */
-   public MessageDigestAlgorithm getMessageDigestAlgorithm()
-           throws XMLSignatureException {
-
-      if (digestMethodElem == null) {
-         return null;
-      }
-
-      String uri = digestMethodElem.getAttributeNS(null,
-         Constants._ATT_ALGORITHM);
-
-          if (uri == null) {
-                  return null;
-          }
-
-      return MessageDigestAlgorithm.getInstance(this._doc, uri);
-   }
-
-   /**
-    * Sets the URI of this Reference element
-    *
-    * @param URI the URI of this Reference element
-    */
-   public void setURI(String URI) {
-
-      if ( URI != null) {
-         this._constructionElement.setAttributeNS(null, Constants._ATT_URI,
-                                                  URI);
-      }
-   }
-
-   /**
-    * Returns the URI of this Reference element
-    *
-    * @return URI the URI of this Reference element
-    */
-   public String getURI() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_URI);
-   }
-
-   /**
-    * Sets the Id attribute of this Reference element
-    *
-    * @param Id the Id attribute of this Reference element
-    */
-   public void setId(String Id) {
-
-      if ( Id != null ) {
-          setLocalIdAttribute(Constants._ATT_ID, Id);
-      }
-   }
-
-   /**
-    * Returns the Id attribute of this Reference element
-    *
-    * @return Id the Id attribute of this Reference element
-    */
-   public String getId() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
-   }
-
-   /**
-    * Sets the type atttibute of the Reference indicate whether an ds:Object, ds:SignatureProperty, or ds:Manifest element
-    *
-    * @param Type the type attribute of the Reference
-    */
-   public void setType(String Type) {
-
-      if (Type != null) {
-         this._constructionElement.setAttributeNS(null, Constants._ATT_TYPE,
-                                                  Type);
-      }
-   }
-
-   /**
-    * Return the type atttibute of the Reference indicate whether an ds:Object, ds:SignatureProperty, or ds:Manifest element
-    *
-    * @return the type attribute of the Reference
-    */
-   public String getType() {
-      return this._constructionElement.getAttributeNS(null,
-              Constants._ATT_TYPE);
-   }
-
-   /**
-    * Method isReferenceToObject
-    *
-    * This returns true if the Type attribute of the
-    * Refernce element points to a #Object element
-    *
-    * @return true if the Reference type indicates that this Reference points to an Object
-    */
-   public boolean typeIsReferenceToObject() {
-
-      if (Reference.OBJECT_URI.equals(this.getType())) {
-         return true;
-      }
-
-      return false;
-   }
-
-   /**
-    * Method isReferenceToManifest
-    *
-    * This returns true if the Type attribute of the
-    * Refernce element points to a #Manifest element
-    *
-    * @return true if the Reference type indicates that this Reference points to a {@link Manifest}
-    */
-   public boolean typeIsReferenceToManifest() {
-
-      if (Reference.MANIFEST_URI.equals(this.getType())) {
-         return true;
-      }
-
-      return false;
-   }
-
-   /**
-    * Method setDigestValueElement
-    *
-    * @param digestValue
-    */
-   private void setDigestValueElement(byte[] digestValue)
-   {
-         Node n=digestValueElement.getFirstChild();
-         while (n!=null) {
-               digestValueElement.removeChild(n);
-               n = n.getNextSibling();
-         }
-
-         String base64codedValue = Base64.encode(digestValue);
-         Text t = this._doc.createTextNode(base64codedValue);
-
-         digestValueElement.appendChild(t);
-   }
-
-   /**
-    * Method generateDigestValue
-    *
-    * @throws ReferenceNotInitializedException
-    * @throws XMLSignatureException
-    */
-   public void generateDigestValue()
-           throws XMLSignatureException, ReferenceNotInitializedException {
-      this.setDigestValueElement(this.calculateDigest(false));
-   }
-
-   /**
-    * Returns the XMLSignatureInput which is created by de-referencing the URI attribute.
-    * @return the XMLSignatureInput of the source of this reference
-    * @throws ReferenceNotInitializedException If the resolver found any
-    *  problem resolving the reference
-    */
-   public XMLSignatureInput getContentsBeforeTransformation()
-           throws ReferenceNotInitializedException {
-
-      try {
-         Attr URIAttr = this._constructionElement.getAttributeNodeNS(null,
-            Constants._ATT_URI);
-         String URI;
-
-         if (URIAttr == null) {
-            URI = null;
-         } else {
-            URI = URIAttr.getNodeValue();
-         }
-
-         ResourceResolver resolver = ResourceResolver.getInstance(URIAttr,
-            this._baseURI, this._manifest._perManifestResolvers);
-
-         if (resolver == null) {
-            Object exArgs[] = { URI };
-
-            throw new ReferenceNotInitializedException(
-               "signature.Verification.Reference.NoInput", exArgs);
-         }
-
-         resolver.addProperties(this._manifest._resolverProperties);
-
-         XMLSignatureInput input = resolver.resolve(URIAttr, this._baseURI);
-
-
-         return input;
-      }  catch (ResourceResolverException ex) {
-         throw new ReferenceNotInitializedException("empty", ex);
-      } catch (XMLSecurityException ex) {
-         throw new ReferenceNotInitializedException("empty", ex);
-      }
-   }
-
-   /**
-    * Returns the data which is referenced by the URI attribute. This method
-    * only works works after a call to verify.
-    * @return a XMLSignature with a byte array.
-    * @throws ReferenceNotInitializedException
-    *
-    * @deprecated use getContentsBeforeTransformation
-    */
-   @Deprecated
-   public XMLSignatureInput getTransformsInput() throws ReferenceNotInitializedException
-        {
-                XMLSignatureInput input=getContentsBeforeTransformation();
-                XMLSignatureInput result;
-                try {
-                        result = new XMLSignatureInput(input.getBytes());
-                } catch (CanonicalizationException ex) {
-                         throw new ReferenceNotInitializedException("empty", ex);
-                } catch (IOException ex) {
-                         throw new ReferenceNotInitializedException("empty", ex);
-                }
-                result.setSourceURI(input.getSourceURI());
-                return result;
-
-   }
-
-   private XMLSignatureInput getContentsAfterTransformation(XMLSignatureInput input, OutputStream os)
-           throws XMLSignatureException {
-
-      try {
-         Transforms transforms = this.getTransforms();
-         XMLSignatureInput output = null;
-
-         if (transforms != null) {
-            output = transforms.performTransforms(input,os);
-            this._transformsOutput = output;//new XMLSignatureInput(output.getBytes());
-
-            //this._transformsOutput.setSourceURI(output.getSourceURI());
-         } else {
-            output = input;
-         }
-
-         return output;
-      } catch (ResourceResolverException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (CanonicalizationException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (InvalidCanonicalizerException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (TransformationException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (XMLSecurityException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
-
-   /**
-    * Returns the XMLSignatureInput which is the result of the Transforms.
-    * @return a XMLSignatureInput with all transformations applied.
-    * @throws XMLSignatureException
-    */
-   public XMLSignatureInput getContentsAfterTransformation()
-           throws XMLSignatureException {
-
-      XMLSignatureInput input = this.getContentsBeforeTransformation();
-
-      return this.getContentsAfterTransformation(input, null);
-   }
-
-   /**
-    * This method returns the XMLSignatureInput which represents the node set before
-    * some kind of canonicalization is applied for the first time.
-    * @return Gets a the node doing everything till the first c14n is needed
-    *
-    * @throws XMLSignatureException
-    */
-   public XMLSignatureInput getNodesetBeforeFirstCanonicalization()
-           throws XMLSignatureException {
-
-      try {
-         XMLSignatureInput input = this.getContentsBeforeTransformation();
-         XMLSignatureInput output = input;
-         Transforms transforms = this.getTransforms();
-
-         if (transforms != null) {
-            doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
-               Transform t = transforms.item(i);
-               String URI = t.getURI();
-
-               if (URI.equals(Transforms
-                       .TRANSFORM_C14N_EXCL_OMIT_COMMENTS) || URI
-                          .equals(Transforms
-                             .TRANSFORM_C14N_EXCL_WITH_COMMENTS) || URI
-                                .equals(Transforms
-                                   .TRANSFORM_C14N_OMIT_COMMENTS) || URI
-                                      .equals(Transforms
-                                         .TRANSFORM_C14N_WITH_COMMENTS)) {
-
-                  break doTransforms;
-               }
-
-               output = t.performTransform(output, null);
+    private Manifest manifest;
+    private XMLSignatureInput transformsOutput;
+
+    private Transforms transforms;
+
+    private Element digestMethodElem;
+
+    private Element digestValueElement;
+
+    private ReferenceData referenceData;
+
+    /**
+     * Constructor Reference
+     *
+     * @param doc the {@link Document} in which XMLsignature is placed
+     * @param baseURI the URI of the resource where the XML instance will be stored
+     * @param referenceURI URI indicate where is data which will digested
+     * @param manifest
+     * @param transforms {@link Transforms} applied to data
+     * @param messageDigestAlgorithm {@link MessageDigestAlgorithm Digest algorithm} which is
+     * applied to the data
+     * TODO should we throw XMLSignatureException if MessageDigestAlgoURI is wrong?
+     * @throws XMLSignatureException
+     */
+    protected Reference(
+        Document doc, String baseURI, String referenceURI, Manifest manifest,
+        Transforms transforms, String messageDigestAlgorithm
+    ) throws XMLSignatureException {
+        super(doc);
+
+        XMLUtils.addReturnToElement(this.constructionElement);
+
+        this.baseURI = baseURI;
+        this.manifest = manifest;
+
+        this.setURI(referenceURI);
+
+        // important: The ds:Reference must be added to the associated ds:Manifest
+        //            or ds:SignedInfo _before_ the this.resolverResult() is called.
+        // this.manifest.appendChild(this.constructionElement);
+        // this.manifest.appendChild(this.doc.createTextNode("\n"));
+
+        if (transforms != null) {
+            this.transforms=transforms;
+            this.constructionElement.appendChild(transforms.getElement());
+            XMLUtils.addReturnToElement(this.constructionElement);
+        }
+        MessageDigestAlgorithm mda =
+            MessageDigestAlgorithm.getInstance(this.doc, messageDigestAlgorithm);
+
+        digestMethodElem = mda.getElement();
+        this.constructionElement.appendChild(digestMethodElem);
+        XMLUtils.addReturnToElement(this.constructionElement);
+
+        digestValueElement =
+            XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_DIGESTVALUE);
+
+        this.constructionElement.appendChild(digestValueElement);
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
+
+
+    /**
+     * Build a {@link Reference} from an {@link Element}
+     *
+     * @param element Reference element
+     * @param baseURI the URI of the resource where the XML instance was stored
+     * @param manifest is the {@link Manifest} of {@link SignedInfo} in which the Reference occurs.
+     * We need this because the Manifest has the individual {@link ResourceResolver}s which have
+     * been set by the user
+     * @throws XMLSecurityException
+     */
+    protected Reference(Element element, String baseURI, Manifest manifest) throws XMLSecurityException {
+        this(element, baseURI, manifest, false);
+    }
+
+    /**
+     * Build a {@link Reference} from an {@link Element}
+     *
+     * @param element Reference element
+     * @param baseURI the URI of the resource where the XML instance was stored
+     * @param manifest is the {@link Manifest} of {@link SignedInfo} in which the Reference occurs.
+     * @param secureValidation whether secure validation is enabled or not
+     * We need this because the Manifest has the individual {@link ResourceResolver}s which have
+     * been set by the user
+     * @throws XMLSecurityException
+     */
+    protected Reference(Element element, String baseURI, Manifest manifest, boolean secureValidation)
+        throws XMLSecurityException {
+        super(element, baseURI);
+        this.secureValidation = secureValidation;
+        this.baseURI = baseURI;
+        Element el = XMLUtils.getNextElement(element.getFirstChild());
+        if (Constants._TAG_TRANSFORMS.equals(el.getLocalName())
+            && Constants.SignatureSpecNS.equals(el.getNamespaceURI())) {
+            transforms = new Transforms(el, this.baseURI);
+            transforms.setSecureValidation(secureValidation);
+            if (secureValidation && transforms.getLength() > MAXIMUM_TRANSFORM_COUNT) {
+                Object exArgs[] = { transforms.getLength(), MAXIMUM_TRANSFORM_COUNT };
+
+                throw new XMLSecurityException("signature.tooManyTransforms", exArgs);
+            }
+            el = XMLUtils.getNextElement(el.getNextSibling());
+        }
+        digestMethodElem = el;
+        digestValueElement = XMLUtils.getNextElement(digestMethodElem.getNextSibling());
+        this.manifest = manifest;
+    }
+
+    /**
+     * Returns {@link MessageDigestAlgorithm}
+     *
+     *
+     * @return {@link MessageDigestAlgorithm}
+     *
+     * @throws XMLSignatureException
+     */
+    public MessageDigestAlgorithm getMessageDigestAlgorithm() throws XMLSignatureException {
+        if (digestMethodElem == null) {
+            return null;
+        }
+
+        String uri = digestMethodElem.getAttributeNS(null, Constants._ATT_ALGORITHM);
+
+        if (uri == null) {
+            return null;
+        }
+
+        if (secureValidation && MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(uri)) {
+            Object exArgs[] = { uri };
+
+            throw new XMLSignatureException("signature.signatureAlgorithm", exArgs);
+        }
+
+        return MessageDigestAlgorithm.getInstance(this.doc, uri);
+    }
+
+    /**
+     * Sets the URI of this Reference element
+     *
+     * @param uri the URI of this Reference element
+     */
+    public void setURI(String uri) {
+        if (uri != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_URI, uri);
+        }
+    }
+
+    /**
+     * Returns the URI of this Reference element
+     *
+     * @return URI the URI of this Reference element
+     */
+    public String getURI() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_URI);
+    }
+
+    /**
+     * Sets the Id attribute of this Reference element
+     *
+     * @param id the Id attribute of this Reference element
+     */
+    public void setId(String id) {
+        if (id != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
+            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+        }
+    }
+
+    /**
+     * Returns the Id attribute of this Reference element
+     *
+     * @return Id the Id attribute of this Reference element
+     */
+    public String getId() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+    }
+
+    /**
+     * Sets the type atttibute of the Reference indicate whether an
+     * ds:Object, ds:SignatureProperty, or ds:Manifest
+     * element.
+     *
+     * @param type the type attribute of the Reference
+     */
+    public void setType(String type) {
+        if (type != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_TYPE, type);
+        }
+    }
+
+    /**
+     * Return the type atttibute of the Reference indicate whether an
+     * ds:Object, ds:SignatureProperty, or ds:Manifest
+     * element
+     *
+     * @return the type attribute of the Reference
+     */
+    public String getType() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_TYPE);
+    }
+
+    /**
+     * Method isReferenceToObject
+     *
+     * This returns true if the Type attribute of the
+     * Reference element points to a #Object element
+     *
+     * @return true if the Reference type indicates that this Reference points to an
+     * Object
+     */
+    public boolean typeIsReferenceToObject() {
+        if (Reference.OBJECT_URI.equals(this.getType())) {
+            return true;
+        }
+
+        return false;
+    }
+
+    /**
+     * Method isReferenceToManifest
+     *
+     * This returns true if the Type attribute of the
+     * Reference element points to a #Manifest element
+     *
+     * @return true if the Reference type indicates that this Reference points to a
+     * {@link Manifest}
+     */
+    public boolean typeIsReferenceToManifest() {
+        if (Reference.MANIFEST_URI.equals(this.getType())) {
+            return true;
+        }
+
+        return false;
+    }
+
+    /**
+     * Method setDigestValueElement
+     *
+     * @param digestValue
+     */
+    private void setDigestValueElement(byte[] digestValue) {
+        Node n = digestValueElement.getFirstChild();
+        while (n != null) {
+            digestValueElement.removeChild(n);
+            n = n.getNextSibling();
+        }
+
+        String base64codedValue = Base64.encode(digestValue);
+        Text t = this.doc.createTextNode(base64codedValue);
+
+        digestValueElement.appendChild(t);
+    }
+
+    /**
+     * Method generateDigestValue
+     *
+     * @throws ReferenceNotInitializedException
+     * @throws XMLSignatureException
+     */
+    public void generateDigestValue()
+        throws XMLSignatureException, ReferenceNotInitializedException {
+        this.setDigestValueElement(this.calculateDigest(false));
+    }
+
+    /**
+     * Returns the XMLSignatureInput which is created by de-referencing the URI attribute.
+     * @return the XMLSignatureInput of the source of this reference
+     * @throws ReferenceNotInitializedException If the resolver found any
+     * problem resolving the reference
+     */
+    public XMLSignatureInput getContentsBeforeTransformation()
+        throws ReferenceNotInitializedException {
+        try {
+            Attr uriAttr =
+                this.constructionElement.getAttributeNodeNS(null, Constants._ATT_URI);
+
+            ResourceResolver resolver =
+                ResourceResolver.getInstance(
+                    uriAttr, this.baseURI, this.manifest.getPerManifestResolvers(), secureValidation
+                );
+            resolver.addProperties(this.manifest.getResolverProperties());
+
+            return resolver.resolve(uriAttr, this.baseURI, secureValidation);
+        }  catch (ResourceResolverException ex) {
+            throw new ReferenceNotInitializedException("empty", ex);
+        }
+    }
+
+    private XMLSignatureInput getContentsAfterTransformation(
+        XMLSignatureInput input, OutputStream os
+    ) throws XMLSignatureException {
+        try {
+            Transforms transforms = this.getTransforms();
+            XMLSignatureInput output = null;
+
+            if (transforms != null) {
+                output = transforms.performTransforms(input, os);
+                this.transformsOutput = output;//new XMLSignatureInput(output.getBytes());
+
+                //this.transformsOutput.setSourceURI(output.getSourceURI());
+            } else {
+                output = input;
             }
 
+            return output;
+        } catch (ResourceResolverException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (CanonicalizationException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (InvalidCanonicalizerException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (TransformationException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (XMLSecurityException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
+
+    /**
+     * Returns the XMLSignatureInput which is the result of the Transforms.
+     * @return a XMLSignatureInput with all transformations applied.
+     * @throws XMLSignatureException
+     */
+    public XMLSignatureInput getContentsAfterTransformation()
+        throws XMLSignatureException {
+        XMLSignatureInput input = this.getContentsBeforeTransformation();
+        cacheDereferencedElement(input);
+
+        return this.getContentsAfterTransformation(input, null);
+    }
+
+    /**
+     * This method returns the XMLSignatureInput which represents the node set before
+     * some kind of canonicalization is applied for the first time.
+     * @return Gets a the node doing everything till the first c14n is needed
+     *
+     * @throws XMLSignatureException
+     */
+    public XMLSignatureInput getNodesetBeforeFirstCanonicalization()
+        throws XMLSignatureException {
+        try {
+            XMLSignatureInput input = this.getContentsBeforeTransformation();
+            cacheDereferencedElement(input);
+            XMLSignatureInput output = input;
+            Transforms transforms = this.getTransforms();
+
+            if (transforms != null) {
+                doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
+                    Transform t = transforms.item(i);
+                    String uri = t.getURI();
+
+                    if (uri.equals(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS)
+                        || uri.equals(Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS)
+                        || uri.equals(Transforms.TRANSFORM_C14N_OMIT_COMMENTS)
+                        || uri.equals(Transforms.TRANSFORM_C14N_WITH_COMMENTS)) {
+                        break doTransforms;
+                    }
+
+                    output = t.performTransform(output, null);
+                }
+
             output.setSourceURI(input.getSourceURI());
-         }
-         return output;
-      } catch (IOException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (ResourceResolverException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (CanonicalizationException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (InvalidCanonicalizerException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (TransformationException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (XMLSecurityException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+            }
+            return output;
+        } catch (IOException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (ResourceResolverException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (CanonicalizationException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (InvalidCanonicalizerException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (TransformationException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (XMLSecurityException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /**
-    * Method getHTMLRepresentation
-    * @return The HTML of the transformation
-    * @throws XMLSignatureException
-    */
-   public String getHTMLRepresentation() throws XMLSignatureException {
+    /**
+     * Method getHTMLRepresentation
+     * @return The HTML of the transformation
+     * @throws XMLSignatureException
+     */
+    public String getHTMLRepresentation() throws XMLSignatureException {
+        try {
+            XMLSignatureInput nodes = this.getNodesetBeforeFirstCanonicalization();
 
-      try {
-         XMLSignatureInput nodes = this.getNodesetBeforeFirstCanonicalization();
-         Set inclusiveNamespaces = new HashSet();
-
-         {
             Transforms transforms = this.getTransforms();
             Transform c14nTransform = null;
 
             if (transforms != null) {
-               doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
-                  Transform t = transforms.item(i);
-                  String URI = t.getURI();
+                doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
+                    Transform t = transforms.item(i);
+                    String uri = t.getURI();
 
-                  if (URI.equals(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS)
-                          || URI.equals(
-                             Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS)) {
-                     c14nTransform = t;
-
-                     break doTransforms;
-                  }
-               }
+                    if (uri.equals(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS)
+                        || uri.equals(Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS)) {
+                        c14nTransform = t;
+                        break doTransforms;
+                    }
+                }
             }
 
-            if (c14nTransform != null) {
+            Set inclusiveNamespaces = new HashSet();
+            if (c14nTransform != null
+                && (c14nTransform.length(
+                    InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
+                    InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES) == 1)) {
 
-               if (c14nTransform
-                       .length(InclusiveNamespaces
-                          .ExclusiveCanonicalizationNamespace, InclusiveNamespaces
-                          ._TAG_EC_INCLUSIVENAMESPACES) == 1) {
-
-                  // there is one InclusiveNamespaces element
-                  InclusiveNamespaces in = new InclusiveNamespaces(
+                // there is one InclusiveNamespaces element
+                InclusiveNamespaces in =
+                    new InclusiveNamespaces(
                         XMLUtils.selectNode(
-                        c14nTransform.getElement().getFirstChild(),
-                                                InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
-                        InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,0), this.getBaseURI());
+                            c14nTransform.getElement().getFirstChild(),
+                            InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
+                            InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,
+                            0
+                        ), this.getBaseURI());
 
-                  inclusiveNamespaces = InclusiveNamespaces.prefixStr2Set(
-                     in.getInclusiveNamespaces());
-               }
+                inclusiveNamespaces =
+                    InclusiveNamespaces.prefixStr2Set(in.getInclusiveNamespaces());
             }
-         }
 
-         return nodes.getHTMLRepresentation(inclusiveNamespaces);
-      } catch (TransformationException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (InvalidTransformException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (XMLSecurityException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+            return nodes.getHTMLRepresentation(inclusiveNamespaces);
+        } catch (TransformationException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (InvalidTransformException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (XMLSecurityException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /**
-    * This method only works works after a call to verify.
-    * @return the transformed output(i.e. what is going to be digested).
-    */
-   public XMLSignatureInput getTransformsOutput() {
-      return this._transformsOutput;
-   }
+    /**
+     * This method only works works after a call to verify.
+     * @return the transformed output(i.e. what is going to be digested).
+     */
+    public XMLSignatureInput getTransformsOutput() {
+        return this.transformsOutput;
+    }
 
-   /**
-    * This method returns the {@link XMLSignatureInput} which is referenced by the
-    * URI Attribute.
-    * @param os where to write the transformation can be null.
-    * @return the element to digest
-    *
-    * @throws XMLSignatureException
-    * @see Manifest#verifyReferences()
-    */
-   protected XMLSignatureInput dereferenceURIandPerformTransforms(OutputStream os)
-           throws XMLSignatureException {
+    /**
+     * Get the ReferenceData that corresponds to the cached representation of the dereferenced
+     * object before transformation.
+     */
+    public ReferenceData getReferenceData() {
+        return referenceData;
+    }
 
-      try {
-         XMLSignatureInput input = this.getContentsBeforeTransformation();
-         XMLSignatureInput output = this.getContentsAfterTransformation(input, os);
+    /**
+     * This method returns the {@link XMLSignatureInput} which is referenced by the
+     * URI Attribute.
+     * @param os where to write the transformation can be null.
+     * @return the element to digest
+     *
+     * @throws XMLSignatureException
+     * @see Manifest#verifyReferences()
+     */
+    protected XMLSignatureInput dereferenceURIandPerformTransforms(OutputStream os)
+        throws XMLSignatureException {
+        try {
+            XMLSignatureInput input = this.getContentsBeforeTransformation();
+            cacheDereferencedElement(input);
 
-         /* at this stage, this._transformsInput and this._transformsOutput
-          * contain a huge amount of nodes. When we do not cache these nodes
-          * but only preserve the octets, the memory footprint is dramatically
-          * reduced.
-          */
-         if (!Reference.CacheSignedNodes) {
+            XMLSignatureInput output = this.getContentsAfterTransformation(input, os);
+            this.transformsOutput = output;
+            return output;
+        } catch (XMLSecurityException ex) {
+            throw new ReferenceNotInitializedException("empty", ex);
+        }
+    }
 
-            this._transformsOutput = output;//new XMLSignatureInput(output.getBytes());
+    /**
+     * Store the dereferenced Element(s) so that it/they can be retrieved later.
+     */
+    private void cacheDereferencedElement(XMLSignatureInput input) {
+        if (input.isNodeSet()) {
+            try {
+                final Set s = input.getNodeSet();
+                referenceData = new ReferenceNodeSetData() {
+                    public Iterator iterator() {
+                        return new Iterator() {
 
-            //this._transformsOutput.setSourceURI(output.getSourceURI());
-         }
-         return output;
-      } catch (XMLSecurityException ex) {
-         throw new ReferenceNotInitializedException("empty", ex);
-      }
-   }
+                            Iterator sIterator = s.iterator();
 
-   /**
-    * Method getTransforms
-    *
-    * @return The transforms that applied this reference.
-    * @throws InvalidTransformException
-    * @throws TransformationException
-    * @throws XMLSecurityException
-    * @throws XMLSignatureException
-    */
-   public Transforms getTransforms()
-           throws XMLSignatureException, InvalidTransformException,
-                  TransformationException, XMLSecurityException {
+                            public boolean hasNext() {
+                                return sIterator.hasNext();
+                            }
 
-      return transforms;
-   }
+                            public Node next() {
+                                return sIterator.next();
+                            }
 
-   /**
-    * Method getReferencedBytes
-    *
-    * @return the bytes that will be used to generated digest.
-    * @throws ReferenceNotInitializedException
-    * @throws XMLSignatureException
-    */
-   public byte[] getReferencedBytes()
-           throws ReferenceNotInitializedException, XMLSignatureException {
-    try {
-        XMLSignatureInput output=this.dereferenceURIandPerformTransforms(null);
+                            public void remove() {
+                                throw new UnsupportedOperationException();
+                            }
+                        };
+                    }
+                };
+            } catch (Exception e) {
+                // log a warning
+                log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + e);
+            }
+        } else if (input.isElement()) {
+            referenceData = new ReferenceSubTreeData
+                (input.getSubNode(), input.isExcludeComments());
+        } else if (input.isOctetStream() || input.isByteArray()) {
+            try {
+                referenceData = new ReferenceOctetStreamData
+                    (input.getOctetStream(), input.getSourceURI(),
+                        input.getMIMEType());
+            } catch (IOException ioe) {
+                // log a warning
+                log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + ioe);
+            }
+        }
+    }
 
-        byte[] signedBytes = output.getBytes();
+    /**
+     * Method getTransforms
+     *
+     * @return The transforms that applied this reference.
+     * @throws InvalidTransformException
+     * @throws TransformationException
+     * @throws XMLSecurityException
+     * @throws XMLSignatureException
+     */
+    public Transforms getTransforms()
+        throws XMLSignatureException, InvalidTransformException,
+        TransformationException, XMLSecurityException {
+        return transforms;
+    }
 
-        return signedBytes;
-     } catch (IOException ex) {
-        throw new ReferenceNotInitializedException("empty", ex);
-     } catch (CanonicalizationException ex) {
-        throw new ReferenceNotInitializedException("empty", ex);
-     }
-
-   }
+    /**
+     * Method getReferencedBytes
+     *
+     * @return the bytes that will be used to generated digest.
+     * @throws ReferenceNotInitializedException
+     * @throws XMLSignatureException
+     */
+    public byte[] getReferencedBytes()
+        throws ReferenceNotInitializedException, XMLSignatureException {
+        try {
+            XMLSignatureInput output = this.dereferenceURIandPerformTransforms(null);
+            return output.getBytes();
+        } catch (IOException ex) {
+            throw new ReferenceNotInitializedException("empty", ex);
+        } catch (CanonicalizationException ex) {
+            throw new ReferenceNotInitializedException("empty", ex);
+        }
+    }
 
 
-   /**
-    * Method calculateDigest
-    *
-    * @param validating true if validating the reference
-    * @return reference Calculate the digest of this reference.
-    * @throws ReferenceNotInitializedException
-    * @throws XMLSignatureException
-    */
-   private byte[] calculateDigest(boolean validating)
-           throws ReferenceNotInitializedException, XMLSignatureException {
+    /**
+     * Method calculateDigest
+     *
+     * @param validating true if validating the reference
+     * @return reference Calculate the digest of this reference.
+     * @throws ReferenceNotInitializedException
+     * @throws XMLSignatureException
+     */
+    private byte[] calculateDigest(boolean validating)
+        throws ReferenceNotInitializedException, XMLSignatureException {
+        OutputStream os = null;
+        try {
+            MessageDigestAlgorithm mda = this.getMessageDigestAlgorithm();
 
-      try {
+            mda.reset();
+            DigesterOutputStream diOs = new DigesterOutputStream(mda);
+            os = new UnsyncBufferedOutputStream(diOs);
+            XMLSignatureInput output = this.dereferenceURIandPerformTransforms(os);
+            // if signing and c14n11 property == true explicitly add
+            // C14N11 transform if needed
+            if (Reference.useC14N11 && !validating && !output.isOutputStreamSet()
+                && !output.isOctetStream()) {
+                if (transforms == null) {
+                    transforms = new Transforms(this.doc);
+                    transforms.setSecureValidation(secureValidation);
+                    this.constructionElement.insertBefore(transforms.getElement(), digestMethodElem);
+                }
+                transforms.addTransform(Transforms.TRANSFORM_C14N11_OMIT_COMMENTS);
+                output.updateOutputStream(os, true);
+            } else {
+                output.updateOutputStream(os);
+            }
+            os.flush();
 
-         MessageDigestAlgorithm mda = this.getMessageDigestAlgorithm();
+            if (output.getOctetStreamReal() != null) {
+                output.getOctetStreamReal().close();
+            }
 
-         mda.reset();
-         DigesterOutputStream diOs=new DigesterOutputStream(mda);
-         OutputStream os=new UnsyncBufferedOutputStream(diOs);
-         XMLSignatureInput output=this.dereferenceURIandPerformTransforms(os);
-         // if signing and c14n11 property == true explicitly add
-         // C14N11 transform if needed
-         if (Reference.useC14N11 && !validating &&
-             !output.isOutputStreamSet() && !output.isOctetStream()) {
-             if (transforms == null) {
-                 transforms = new Transforms(this._doc);
-                 this._constructionElement.insertBefore
-                     (transforms.getElement(), digestMethodElem);
-             }
-             transforms.addTransform(Transforms.TRANSFORM_C14N11_OMIT_COMMENTS);
-             output.updateOutputStream(os, true);
-         } else {
-             output.updateOutputStream(os);
-         }
-         os.flush();
-         //this.getReferencedBytes(diOs);
-         //mda.update(data);
+            //this.getReferencedBytes(diOs);
+            //mda.update(data);
 
-         return diOs.getDigestValue();
-      } catch (XMLSecurityException ex) {
-         throw new ReferenceNotInitializedException("empty", ex);
-      } catch (IOException ex) {
-         throw new ReferenceNotInitializedException("empty", ex);
-      }
-   }
+            return diOs.getDigestValue();
+        } catch (XMLSecurityException ex) {
+            throw new ReferenceNotInitializedException("empty", ex);
+        } catch (IOException ex) {
+            throw new ReferenceNotInitializedException("empty", ex);
+        } finally {
+            if (os != null) {
+                try {
+                    os.close();
+                } catch (IOException ex) {
+                    throw new ReferenceNotInitializedException("empty", ex);
+                }
+            }
+        }
+    }
 
-   /**
-    * Returns the digest value.
-    *
-    * @return the digest value.
-    * @throws Base64DecodingException if Reference contains no proper base64 encoded data.
-    * @throws XMLSecurityException if the Reference does not contain a DigestValue element
-    */
-   public byte[] getDigestValue() throws Base64DecodingException, XMLSecurityException {
-      if (digestValueElement == null) {
-                  // The required element is not in the XML!
-                  Object[] exArgs ={ Constants._TAG_DIGESTVALUE,
-                                                         Constants.SignatureSpecNS };
-                  throw new XMLSecurityException(
-                                        "signature.Verification.NoSignatureElement",
-                                        exArgs);
-          }
-      byte[] elemDig = Base64.decode(digestValueElement);
-      return elemDig;
-   }
+    /**
+     * Returns the digest value.
+     *
+     * @return the digest value.
+     * @throws Base64DecodingException if Reference contains no proper base64 encoded data.
+     * @throws XMLSecurityException if the Reference does not contain a DigestValue element
+     */
+    public byte[] getDigestValue() throws Base64DecodingException, XMLSecurityException {
+        if (digestValueElement == null) {
+            // The required element is not in the XML!
+            Object[] exArgs ={ Constants._TAG_DIGESTVALUE, Constants.SignatureSpecNS };
+            throw new XMLSecurityException(
+                "signature.Verification.NoSignatureElement", exArgs
+            );
+        }
+        return Base64.decode(digestValueElement);
+    }
 
 
-   /**
-    * Tests reference valdiation is success or false
-    *
-    * @return true if reference valdiation is success, otherwise false
-    * @throws ReferenceNotInitializedException
-    * @throws XMLSecurityException
-    */
-   public boolean verify()
-           throws ReferenceNotInitializedException, XMLSecurityException {
+    /**
+     * Tests reference validation is success or false
+     *
+     * @return true if reference validation is success, otherwise false
+     * @throws ReferenceNotInitializedException
+     * @throws XMLSecurityException
+     */
+    public boolean verify()
+        throws ReferenceNotInitializedException, XMLSecurityException {
+        byte[] elemDig = this.getDigestValue();
+        byte[] calcDig = this.calculateDigest(true);
+        boolean equal = MessageDigestAlgorithm.isEqual(elemDig, calcDig);
 
-      byte[] elemDig = this.getDigestValue();
-      byte[] calcDig = this.calculateDigest(true);
-      boolean equal = MessageDigestAlgorithm.isEqual(elemDig, calcDig);
+        if (!equal) {
+            log.log(java.util.logging.Level.WARNING, "Verification failed for URI \"" + this.getURI() + "\"");
+            log.log(java.util.logging.Level.WARNING, "Expected Digest: " + Base64.encode(elemDig));
+            log.log(java.util.logging.Level.WARNING, "Actual Digest: " + Base64.encode(calcDig));
+        } else {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "Verification successful for URI \"" + this.getURI() + "\"");
+            }
+        }
 
-      if (!equal) {
-         log.log(java.util.logging.Level.WARNING, "Verification failed for URI \"" + this.getURI() + "\"");
-         log.log(java.util.logging.Level.WARNING, "Expected Digest: " + Base64.encode(elemDig));
-         log.log(java.util.logging.Level.WARNING, "Actual Digest: " + Base64.encode(calcDig));
-      } else {
-         log.log(java.util.logging.Level.INFO, "Verification successful for URI \"" + this.getURI() + "\"");
-      }
+        return equal;
+    }
 
-      return equal;
-   }
-
-   /**
-    * Method getBaseLocalName
-    * @inheritDoc
-    *
-    */
-   public String getBaseLocalName() {
-      return Constants._TAG_REFERENCE;
-   }
+    /**
+     * Method getBaseLocalName
+     * @inheritDoc
+     */
+    public String getBaseLocalName() {
+        return Constants._TAG_REFERENCE;
+    }
 }
diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java
index 98dd0a2ee52..95da73e68b8 100644
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java
@@ -2,28 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
  *
- *  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.
+ * 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 com.sun.org.apache.xml.internal.security.signature;
 
-
-
-
-
 /**
  * Raised if verifying a {@link com.sun.org.apache.xml.internal.security.signature.Reference} fails
  * because of an uninitialized {@link com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput}
@@ -32,58 +30,56 @@ package com.sun.org.apache.xml.internal.security.signature;
  */
 public class ReferenceNotInitializedException extends XMLSignatureException {
 
-   /**
-         *
-         */
-        private static final long serialVersionUID = 1L;
+    /**
+     *
+     */
+    private static final long serialVersionUID = 1L;
 
-   /**
-    * Constructor ReferenceNotInitializedException
-    *
-    */
-   public ReferenceNotInitializedException() {
-      super();
-   }
+    /**
+     * Constructor ReferenceNotInitializedException
+     *
+     */
+    public ReferenceNotInitializedException() {
+        super();
+    }
 
-   /**
-    * Constructor ReferenceNotInitializedException
-    *
-    * @param _msgID
-    */
-   public ReferenceNotInitializedException(String _msgID) {
-      super(_msgID);
-   }
+    /**
+     * Constructor ReferenceNotInitializedException
+     *
+     * @param msgID
+     */
+    public ReferenceNotInitializedException(String msgID) {
+        super(msgID);
+    }
 
-   /**
-    * Constructor ReferenceNotInitializedException
-    *
-    * @param _msgID
-    * @param exArgs
-    */
-   public ReferenceNotInitializedException(String _msgID, Object exArgs[]) {
-      super(_msgID, exArgs);
-   }
+    /**
+     * Constructor ReferenceNotInitializedException
+     *
+     * @param msgID
+     * @param exArgs
+     */
+    public ReferenceNotInitializedException(String msgID, Object exArgs[]) {
+        super(msgID, exArgs);
+    }
 
-   /**
-    * Constructor ReferenceNotInitializedException
-    *
-    * @param _msgID
-    * @param _originalException
-    */
-   public ReferenceNotInitializedException(String _msgID,
-                                           Exception _originalException) {
-      super(_msgID, _originalException);
-   }
+    /**
+     * Constructor ReferenceNotInitializedException
+     *
+     * @param msgID
+     * @param originalException
+     */
+    public ReferenceNotInitializedException(String msgID, Exception originalException) {
+        super(msgID, originalException);
+    }
 
-   /**
-    * Constructor ReferenceNotInitializedException
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param _originalException
-    */
-   public ReferenceNotInitializedException(String _msgID, Object exArgs[],
-                                           Exception _originalException) {
-      super(_msgID, exArgs, _originalException);
-   }
+    /**
+     * Constructor ReferenceNotInitializedException
+     *
+     * @param msgID
+     * @param exArgs
+     * @param originalException
+     */
+    public ReferenceNotInitializedException(String msgID, Object exArgs[], Exception originalException) {
+        super(msgID, exArgs, originalException);
+    }
 }
diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java
index e81875aa0ce..2dcbb3c28d0 100644
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java
@@ -2,34 +2,34 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
  *
- *  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.
+ * 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 com.sun.org.apache.xml.internal.security.signature;
 
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-
 /**
  * Handles <ds:SignatureProperties> elements
  * This Element holds {@link SignatureProperty} that contian additional information items
@@ -37,120 +37,112 @@ import org.w3c.dom.Element;
  * for example, data-time stamp, serial number of cryptographic hardware.
  *
  * @author Christian Geuer-Pollmann
- *
  */
 public class SignatureProperties extends SignatureElementProxy {
 
-   /**
-    * Constructor SignatureProperties
-    *
-    * @param doc
-    */
-   public SignatureProperties(Document doc) {
+    /**
+     * Constructor SignatureProperties
+     *
+     * @param doc
+     */
+    public SignatureProperties(Document doc) {
+        super(doc);
 
-      super(doc);
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
-      XMLUtils.addReturnToElement(this._constructionElement);
-   }
+    /**
+     * Constructs {@link SignatureProperties} from {@link Element}
+     * @param element SignatureProperties element
+     * @param BaseURI the URI of the resource where the XML instance was stored
+     * @throws XMLSecurityException
+     */
+    public SignatureProperties(Element element, String BaseURI) throws XMLSecurityException {
+        super(element, BaseURI);
 
-   /**
-    * Constructs {@link SignatureProperties} from {@link Element}
-    * @param element SignatureProperties elementt
-    * @param BaseURI the URI of the resource where the XML instance was stored
-    * @throws XMLSecurityException
-    */
-   public SignatureProperties(Element element, String BaseURI)
-           throws XMLSecurityException {
-      super(element, BaseURI);
+        Attr attr = element.getAttributeNodeNS(null, "Id");
+        if (attr != null) {
+            element.setIdAttributeNode(attr, true);
+        }
 
-      Attr attr = element.getAttributeNodeNS(null, "Id");
-      if (attr != null) {
-          element.setIdAttributeNode(attr, true);
-      }
+        int length = getLength();
+        for (int i = 0; i < length; i++) {
+            Element propertyElem =
+                XMLUtils.selectDsNode(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY, i);
+            Attr propertyAttr = propertyElem.getAttributeNodeNS(null, "Id");
+            if (propertyAttr != null) {
+                propertyElem.setIdAttributeNode(propertyAttr, true);
+            }
+        }
+    }
 
-      int length = getLength();
-      for (int i = 0; i < length; i++) {
-          Element propertyElem =
-              XMLUtils.selectDsNode(getElement(), Constants._TAG_SIGNATUREPROPERTY, i);
-          Attr propertyAttr = propertyElem.getAttributeNodeNS(null, "Id");
-          if (propertyAttr != null) {
-              propertyElem.setIdAttributeNode(propertyAttr, true);
-          }
-      }
-   }
+    /**
+     * Return the nonnegative number of added SignatureProperty elements.
+     *
+     * @return the number of SignatureProperty elements
+     */
+    public int getLength() {
+        Element[] propertyElems =
+            XMLUtils.selectDsNodes(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY);
 
-   /**
-    * Return the nonnegative number of added SignatureProperty elements.
-    *
-    * @return the number of SignatureProperty elements
-    */
-   public int getLength() {
+        return propertyElems.length;
+    }
 
-         Element[] propertyElems =
-            XMLUtils.selectDsNodes(this._constructionElement,
-                                     Constants._TAG_SIGNATUREPROPERTY
-                                    );
+    /**
+     * Return the ith SignatureProperty. Valid i
+     * values are 0 to {link@ getSize}-1.
+     *
+     * @param i Index of the requested {@link SignatureProperty}
+     * @return the ith SignatureProperty
+     * @throws XMLSignatureException
+     */
+    public SignatureProperty item(int i) throws XMLSignatureException {
+        try {
+            Element propertyElem =
+                XMLUtils.selectDsNode(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY, i);
 
-         return propertyElems.length;
-   }
+            if (propertyElem == null) {
+                return null;
+            }
+            return new SignatureProperty(propertyElem, this.baseURI);
+        } catch (XMLSecurityException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /**
-    * Return the ith SignatureProperty.  Valid i
-    * values are 0 to {link@ getSize}-1.
-    *
-    * @param i Index of the requested {@link SignatureProperty}
-    * @return the ith SignatureProperty
-    * @throws XMLSignatureException
-    */
-   public SignatureProperty item(int i) throws XMLSignatureException {
-          try {
-         Element propertyElem =
-            XMLUtils.selectDsNode(this._constructionElement,
-                                 Constants._TAG_SIGNATUREPROPERTY,
-                                 i );
+    /**
+     * Sets the Id attribute
+     *
+     * @param Id the Id attribute
+     */
+    public void setId(String Id) {
+        if (Id != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
+            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+        }
+    }
 
-         if (propertyElem == null) {
-            return null;
-         }
-         return new SignatureProperty(propertyElem, this._baseURI);
-      } catch (XMLSecurityException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+    /**
+     * Returns the Id attribute
+     *
+     * @return the Id attribute
+     */
+    public String getId() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+    }
 
-   /**
-    * Sets the Id attribute
-    *
-    * @param Id the Id attribute
-    */
-   public void setId(String Id) {
+    /**
+     * Method addSignatureProperty
+     *
+     * @param sp
+     */
+    public void addSignatureProperty(SignatureProperty sp) {
+        this.constructionElement.appendChild(sp.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
-      if (Id != null) {
-          setLocalIdAttribute(Constants._ATT_ID, Id);
-      }
-   }
-
-   /**
-    * Returns the Id attribute
-    *
-    * @return the Id attribute
-    */
-   public String getId() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
-   }
-
-   /**
-    * Method addSignatureProperty
-    *
-    * @param sp
-    */
-   public void addSignatureProperty(SignatureProperty sp) {
-      this._constructionElement.appendChild(sp.getElement());
-      XMLUtils.addReturnToElement(this._constructionElement);
-   }
-
-   /** @inheritDoc */
-   public String getBaseLocalName() {
-      return Constants._TAG_SIGNATUREPROPERTIES;
-   }
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_SIGNATUREPROPERTIES;
+    }
 }
diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java
index 969ee922e1b..3229a0487cc 100644
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java
@@ -2,27 +2,28 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
  *
- *  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.
+ * 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 com.sun.org.apache.xml.internal.security.signature;
 
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -37,96 +38,96 @@ import org.w3c.dom.Node;
  */
 public class SignatureProperty extends SignatureElementProxy {
 
-   /**
-    * Constructs{@link SignatureProperty} using specified Target attribute
-    *
-    * @param doc the {@link Document} in which XMLsignature is placed
-    * @param Target the Target attribute references the Signature element to which the property applies SignatureProperty
-    */
-   public SignatureProperty(Document doc, String Target) {
-      this(doc, Target, null);
-   }
+    /**
+     * Constructs{@link SignatureProperty} using specified target attribute
+     *
+     * @param doc the {@link Document} in which XMLsignature is placed
+     * @param target the target attribute references the Signature
+     * element to which the property applies SignatureProperty
+     */
+    public SignatureProperty(Document doc, String target) {
+        this(doc, target, null);
+    }
 
-   /**
-    * Constructs {@link SignatureProperty} using sepcified Target attribute and Id attribute
-    *
-    * @param doc the {@link Document} in which XMLsignature is placed
-    * @param Target the Target attribute references the Signature element to which the property applies
-    * @param Id the Id will be specified by {@link Reference#getURI} in validation
-    */
-   public SignatureProperty(Document doc, String Target, String Id) {
+    /**
+     * Constructs {@link SignatureProperty} using sepcified target attribute and
+     * id attribute
+     *
+     * @param doc the {@link Document} in which XMLsignature is placed
+     * @param target the target attribute references the Signature
+     *  element to which the property applies
+     * @param id the id will be specified by {@link Reference#getURI} in validation
+     */
+    public SignatureProperty(Document doc, String target, String id) {
+        super(doc);
 
-      super(doc);
+        this.setTarget(target);
+        this.setId(id);
+    }
 
-      this.setTarget(Target);
-      this.setId(Id);
-   }
+    /**
+     * Constructs a {@link SignatureProperty} from an {@link Element}
+     * @param element SignatureProperty element
+     * @param BaseURI the URI of the resource where the XML instance was stored
+     * @throws XMLSecurityException
+     */
+    public SignatureProperty(Element element, String BaseURI) throws XMLSecurityException {
+        super(element, BaseURI);
+    }
 
-   /**
-    * Constructs a {@link SignatureProperty} from an {@link Element}
-    * @param element SignatureProperty element
-    * @param BaseURI the URI of the resource where the XML instance was stored
-    * @throws XMLSecurityException
-    */
-   public SignatureProperty(Element element, String BaseURI)
-           throws XMLSecurityException {
-      super(element, BaseURI);
-   }
+    /**
+     *   Sets the id attribute
+     *
+     *   @param id the id attribute
+     */
+    public void setId(String id) {
+        if (id != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
+            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+        }
+    }
 
-   /**
-    *   Sets the Id attribute
-    *
-    *   @param Id the Id attribute
-    */
-   public void setId(String Id) {
+    /**
+     * Returns the id attribute
+     *
+     * @return the id attribute
+     */
+    public String getId() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+    }
 
-      if (Id != null) {
-          setLocalIdAttribute(Constants._ATT_ID, Id);
-      }
-   }
+    /**
+     * Sets the target attribute
+     *
+     * @param target the target attribute
+     */
+    public void setTarget(String target) {
+        if (target != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_TARGET, target);
+        }
+    }
 
-   /**
-    * Returns the Id attribute
-    *
-    * @return the Id attribute
-    */
-   public String getId() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
-   }
+    /**
+     * Returns the target attribute
+     *
+     * @return the target attribute
+     */
+    public String getTarget() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_TARGET);
+    }
 
-   /**
-    * Sets the Target attribute
-    *
-    * @param Target the Target attribute
-    */
-   public void setTarget(String Target) {
+    /**
+     * Method appendChild
+     *
+     * @param node
+     * @return the node in this element.
+     */
+    public Node appendChild(Node node) {
+        return this.constructionElement.appendChild(node);
+    }
 
-      if ((Target != null)) {
-         this._constructionElement.setAttributeNS(null, Constants._ATT_TARGET, Target);
-      }
-   }
-
-   /**
-    * Returns the Target attribute
-    *
-    * @return the Target attribute
-    */
-   public String getTarget() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_TARGET);
-   }
-
-   /**
-    * Method appendChild
-    *
-    * @param node
-    * @return the node in this element.
-    */
-   public Node appendChild(Node node) {
-      return this._constructionElement.appendChild(node);
-   }
-
-   /** @inheritDoc */
-   public String getBaseLocalName() {
-      return Constants._TAG_SIGNATUREPROPERTY;
-   }
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_SIGNATUREPROPERTY;
+    }
 }
diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java
index f2e04602984..98bfca4a9b2 100644
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
  *
- *  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.
+ * 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 com.sun.org.apache.xml.internal.security.signature;
 
@@ -50,11 +52,11 @@ import org.xml.sax.SAXException;
  */
 public class SignedInfo extends Manifest {
 
-    /** Field _signatureAlgorithm */
-    private SignatureAlgorithm _signatureAlgorithm = null;
+    /** Field signatureAlgorithm */
+    private SignatureAlgorithm signatureAlgorithm = null;
 
-    /** Field _c14nizedBytes           */
-    private byte[] _c14nizedBytes = null;
+    /** Field c14nizedBytes           */
+    private byte[] c14nizedBytes = null;
 
     private Element c14nMethod;
     private Element signatureMethod;
@@ -83,9 +85,9 @@ public class SignedInfo extends Manifest {
      *    Canonicalization method
      * @throws XMLSecurityException
      */
-    public SignedInfo(Document doc, String signatureMethodURI,
-        String canonicalizationMethodURI)
-              throws XMLSecurityException {
+    public SignedInfo(
+        Document doc, String signatureMethodURI, String canonicalizationMethodURI
+    ) throws XMLSecurityException {
         this(doc, signatureMethodURI, 0, canonicalizationMethodURI);
     }
 
@@ -100,31 +102,29 @@ public class SignedInfo extends Manifest {
      *    Canonicalization method
      * @throws XMLSecurityException
      */
-    public SignedInfo(Document doc, String signatureMethodURI,
-        int hMACOutputLength, String canonicalizationMethodURI)
-              throws XMLSecurityException {
-
+    public SignedInfo(
+        Document doc, String signatureMethodURI,
+        int hMACOutputLength, String canonicalizationMethodURI
+    ) throws XMLSecurityException {
         super(doc);
 
-        c14nMethod = XMLUtils.createElementInSignatureSpace(this._doc,
-                                Constants._TAG_CANONICALIZATIONMETHOD);
+        c14nMethod =
+            XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_CANONICALIZATIONMETHOD);
 
-        c14nMethod.setAttributeNS(null, Constants._ATT_ALGORITHM,
-                                  canonicalizationMethodURI);
-        this._constructionElement.appendChild(c14nMethod);
-        XMLUtils.addReturnToElement(this._constructionElement);
+        c14nMethod.setAttributeNS(null, Constants._ATT_ALGORITHM, canonicalizationMethodURI);
+        this.constructionElement.appendChild(c14nMethod);
+        XMLUtils.addReturnToElement(this.constructionElement);
 
         if (hMACOutputLength > 0) {
-            this._signatureAlgorithm = new SignatureAlgorithm(this._doc,
-                    signatureMethodURI, hMACOutputLength);
+            this.signatureAlgorithm =
+                new SignatureAlgorithm(this.doc, signatureMethodURI, hMACOutputLength);
         } else {
-            this._signatureAlgorithm = new SignatureAlgorithm(this._doc,
-                    signatureMethodURI);
+            this.signatureAlgorithm = new SignatureAlgorithm(this.doc, signatureMethodURI);
         }
 
-        signatureMethod = this._signatureAlgorithm.getElement();
-        this._constructionElement.appendChild(signatureMethod);
-        XMLUtils.addReturnToElement(this._constructionElement);
+        signatureMethod = this.signatureAlgorithm.getElement();
+        this.constructionElement.appendChild(signatureMethod);
+        XMLUtils.addReturnToElement(this.constructionElement);
     }
 
     /**
@@ -133,22 +133,22 @@ public class SignedInfo extends Manifest {
      * @param canonicalizationMethodElem
      * @throws XMLSecurityException
      */
-    public SignedInfo(Document doc, Element signatureMethodElem,
-        Element canonicalizationMethodElem) throws XMLSecurityException {
-
+    public SignedInfo(
+        Document doc, Element signatureMethodElem, Element canonicalizationMethodElem
+    ) throws XMLSecurityException {
         super(doc);
         // Check this?
         this.c14nMethod = canonicalizationMethodElem;
-        this._constructionElement.appendChild(c14nMethod);
-        XMLUtils.addReturnToElement(this._constructionElement);
+        this.constructionElement.appendChild(c14nMethod);
+        XMLUtils.addReturnToElement(this.constructionElement);
 
-        this._signatureAlgorithm =
+        this.signatureAlgorithm =
             new SignatureAlgorithm(signatureMethodElem, null);
 
-        signatureMethod = this._signatureAlgorithm.getElement();
-        this._constructionElement.appendChild(signatureMethod);
+        signatureMethod = this.signatureAlgorithm.getElement();
+        this.constructionElement.appendChild(signatureMethod);
 
-        XMLUtils.addReturnToElement(this._constructionElement);
+        XMLUtils.addReturnToElement(this.constructionElement);
     }
 
     /**
@@ -157,48 +157,76 @@ public class SignedInfo extends Manifest {
      * @param element SignedInfo
      * @param baseURI the URI of the resource where the XML instance was stored
      * @throws XMLSecurityException
-     * @see Question
-     * @see Answer
+     * @see 
+     * Question
+     * @see 
+     * Answer
      */
-    public SignedInfo(Element element, String baseURI)
-           throws XMLSecurityException {
+    public SignedInfo(Element element, String baseURI) throws XMLSecurityException {
+        this(element, baseURI, false);
+    }
 
+    /**
+     * Build a {@link SignedInfo} from an {@link Element}
+     *
+     * @param element SignedInfo
+     * @param baseURI the URI of the resource where the XML instance was stored
+     * @param secureValidation whether secure validation is enabled or not
+     * @throws XMLSecurityException
+     * @see 
+     * Question
+     * @see 
+     * Answer
+     */
+    public SignedInfo(
+        Element element, String baseURI, boolean secureValidation
+    ) throws XMLSecurityException {
         // Parse the Reference children and Id attribute in the Manifest
-        super(element, baseURI);
+        super(reparseSignedInfoElem(element), baseURI, secureValidation);
 
-        /* canonicalize ds:SignedInfo, reparse it into a new document
+        c14nMethod = XMLUtils.getNextElement(element.getFirstChild());
+        signatureMethod = XMLUtils.getNextElement(c14nMethod.getNextSibling());
+        this.signatureAlgorithm =
+            new SignatureAlgorithm(signatureMethod, this.getBaseURI(), secureValidation);
+    }
+
+    private static Element reparseSignedInfoElem(Element element)
+        throws XMLSecurityException {
+        /*
+         * If a custom canonicalizationMethod is used, canonicalize
+         * ds:SignedInfo, reparse it into a new document
          * and replace the original not-canonicalized ds:SignedInfo by
          * the re-parsed canonicalized one.
          */
-        c14nMethod = XMLUtils.getNextElement(element.getFirstChild());
-        String c14nMethodURI = this.getCanonicalizationMethodURI();
+        Element c14nMethod = XMLUtils.getNextElement(element.getFirstChild());
+        String c14nMethodURI =
+            c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
         if (!(c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS) ||
-              c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS) ||
-              c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS) ||
-              c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS))) {
+            c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS) ||
+            c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS) ||
+            c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS) ||
+            c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS) ||
+            c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS))) {
             // the c14n is not a secure one and can rewrite the URIs or like
-            // that reparse the SignedInfo to be sure
+            // so reparse the SignedInfo to be sure
             try {
                 Canonicalizer c14nizer =
-                Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
+                    Canonicalizer.getInstance(c14nMethodURI);
 
-                this._c14nizedBytes =
-                    c14nizer.canonicalizeSubtree(this._constructionElement);
+                byte[] c14nizedBytes = c14nizer.canonicalizeSubtree(element);
                 javax.xml.parsers.DocumentBuilderFactory dbf =
                     javax.xml.parsers.DocumentBuilderFactory.newInstance();
                 dbf.setNamespaceAware(true);
-                dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
-                               Boolean.TRUE);
+                dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
                 javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
                 Document newdoc =
-                    db.parse(new ByteArrayInputStream(this._c14nizedBytes));
+                    db.parse(new ByteArrayInputStream(c14nizedBytes));
                 Node imported =
-                    this._doc.importNode(newdoc.getDocumentElement(), true);
+                    element.getOwnerDocument().importNode(newdoc.getDocumentElement(), true);
 
-                this._constructionElement.getParentNode().replaceChild(imported,
-                    this._constructionElement);
+                element.getParentNode().replaceChild(imported, element);
 
-                this._constructionElement = (Element) imported;
+                return (Element) imported;
             } catch (ParserConfigurationException ex) {
                 throw new XMLSecurityException("empty", ex);
             } catch (IOException ex) {
@@ -207,184 +235,163 @@ public class SignedInfo extends Manifest {
                 throw new XMLSecurityException("empty", ex);
             }
         }
-        signatureMethod = XMLUtils.getNextElement(c14nMethod.getNextSibling());
-        this._signatureAlgorithm =
-            new SignatureAlgorithm(signatureMethod, this.getBaseURI());
+        return element;
     }
 
-   /**
-    * Tests core validation process
-    *
-    * @return true if verification was successful
-    * @throws MissingResourceFailureException
-    * @throws XMLSecurityException
-    */
-   public boolean verify()
-           throws MissingResourceFailureException, XMLSecurityException {
-      return super.verifyReferences(false);
-   }
-
-   /**
-    * Tests core validation process
-    *
-    * @param followManifests defines whether the verification process has to verify referenced ds:Manifests, too
-    * @return true if verification was successful
-    * @throws MissingResourceFailureException
-    * @throws XMLSecurityException
-    */
-   public boolean verify(boolean followManifests)
-           throws MissingResourceFailureException, XMLSecurityException {
-      return super.verifyReferences(followManifests);
-   }
-
-   /**
-    * Returns getCanonicalizedOctetStream
-    *
-    * @return the canonicalization result octedt stream of SignedInfo element
-    * @throws CanonicalizationException
-    * @throws InvalidCanonicalizerException
-    * @throws XMLSecurityException
-    */
-   public byte[] getCanonicalizedOctetStream()
-           throws CanonicalizationException, InvalidCanonicalizerException,
-                 XMLSecurityException {
-
-      if ((this._c14nizedBytes == null)
-              /*&& (this._state == ElementProxy.MODE_SIGN)*/) {
-         Canonicalizer c14nizer =
-            Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
-
-         this._c14nizedBytes =
-            c14nizer.canonicalizeSubtree(this._constructionElement);
-      }
-
-      // make defensive copy
-      byte[] output = new byte[this._c14nizedBytes.length];
-
-      System.arraycopy(this._c14nizedBytes, 0, output, 0, output.length);
-
-      return output;
-   }
-
-   /**
-    *  Output the C14n stream to the give outputstream.
-    * @param os
-    * @throws CanonicalizationException
-    * @throws InvalidCanonicalizerException
-    * @throws XMLSecurityException
-    */
-   public void signInOctectStream(OutputStream os)
-       throws CanonicalizationException, InvalidCanonicalizerException,
-           XMLSecurityException {
-
-        if ((this._c14nizedBytes == null)) {
-       Canonicalizer c14nizer =
-          Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
-       c14nizer.setWriter(os);
-       String inclusiveNamespaces = this.getInclusiveNamespaces();
-
-       if(inclusiveNamespaces == null)
-        c14nizer.canonicalizeSubtree(this._constructionElement);
-       else
-        c14nizer.canonicalizeSubtree(this._constructionElement, inclusiveNamespaces);
-    } else {
-        try {
-                        os.write(this._c14nizedBytes);
-                } catch (IOException e) {
-                        throw new RuntimeException(""+e);
-                }
+    /**
+     * Tests core validation process
+     *
+     * @return true if verification was successful
+     * @throws MissingResourceFailureException
+     * @throws XMLSecurityException
+     */
+    public boolean verify()
+        throws MissingResourceFailureException, XMLSecurityException {
+        return super.verifyReferences(false);
     }
-   }
 
-   /**
-    * Returns the Canonicalization method URI
-    *
-    * @return the Canonicalization method URI
-    */
-   public String getCanonicalizationMethodURI() {
+    /**
+     * Tests core validation process
+     *
+     * @param followManifests defines whether the verification process has to verify referenced ds:Manifests, too
+     * @return true if verification was successful
+     * @throws MissingResourceFailureException
+     * @throws XMLSecurityException
+     */
+    public boolean verify(boolean followManifests)
+        throws MissingResourceFailureException, XMLSecurityException {
+        return super.verifyReferences(followManifests);
+    }
 
+    /**
+     * Returns getCanonicalizedOctetStream
+     *
+     * @return the canonicalization result octet stream of SignedInfo element
+     * @throws CanonicalizationException
+     * @throws InvalidCanonicalizerException
+     * @throws XMLSecurityException
+     */
+    public byte[] getCanonicalizedOctetStream()
+        throws CanonicalizationException, InvalidCanonicalizerException, XMLSecurityException {
+        if (this.c14nizedBytes == null) {
+            Canonicalizer c14nizer =
+                Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
 
-     return c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
-   }
+            this.c14nizedBytes =
+                c14nizer.canonicalizeSubtree(this.constructionElement);
+        }
 
-   /**
-    * Returns the Signature method URI
-    *
-    * @return the Signature method URI
-    */
-   public String getSignatureMethodURI() {
+        // make defensive copy
+        return this.c14nizedBytes.clone();
+    }
 
-      Element signatureElement = this.getSignatureMethodElement();
+    /**
+     * Output the C14n stream to the given OutputStream.
+     * @param os
+     * @throws CanonicalizationException
+     * @throws InvalidCanonicalizerException
+     * @throws XMLSecurityException
+     */
+    public void signInOctetStream(OutputStream os)
+        throws CanonicalizationException, InvalidCanonicalizerException, XMLSecurityException {
+        if (this.c14nizedBytes == null) {
+            Canonicalizer c14nizer =
+                Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
+            c14nizer.setWriter(os);
+            String inclusiveNamespaces = this.getInclusiveNamespaces();
 
-      if (signatureElement != null) {
-         return signatureElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
-      }
+            if (inclusiveNamespaces == null) {
+                c14nizer.canonicalizeSubtree(this.constructionElement);
+            } else {
+                c14nizer.canonicalizeSubtree(this.constructionElement, inclusiveNamespaces);
+            }
+        } else {
+            try {
+                os.write(this.c14nizedBytes);
+            } catch (IOException e) {
+                throw new RuntimeException(e);
+            }
+        }
+    }
 
-      return null;
-   }
+    /**
+     * Returns the Canonicalization method URI
+     *
+     * @return the Canonicalization method URI
+     */
+    public String getCanonicalizationMethodURI() {
+        return c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
+    }
 
-   /**
-    * Method getSignatureMethodElement
-    * @return gets The SignatureMethod Node.
-    *
-    */
-   public Element getSignatureMethodElement() {
-           return signatureMethod;
-   }
+    /**
+     * Returns the Signature method URI
+     *
+     * @return the Signature method URI
+     */
+    public String getSignatureMethodURI() {
+        Element signatureElement = this.getSignatureMethodElement();
 
-   /**
-    * Creates a SecretKey for the appropriate Mac algorithm based on a
-    * byte[] array password.
-    *
-    * @param secretKeyBytes
-    * @return the secret key for the SignedInfo element.
-    */
-   public SecretKey createSecretKey(byte[] secretKeyBytes)
-   {
+        if (signatureElement != null) {
+            return signatureElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
+        }
 
-      return new SecretKeySpec(secretKeyBytes,
-                               this._signatureAlgorithm
-                                  .getJCEAlgorithmString());
-   }
+        return null;
+    }
 
-   protected SignatureAlgorithm getSignatureAlgorithm() {
-           return _signatureAlgorithm;
-   }
-   /**
-    * Method getBaseLocalName
-    * @inheritDoc
-    *
-    */
-   public String getBaseLocalName() {
-      return Constants._TAG_SIGNEDINFO;
-   }
+    /**
+     * Method getSignatureMethodElement
+     * @return returns the SignatureMethod Element
+     *
+     */
+    public Element getSignatureMethodElement() {
+        return signatureMethod;
+    }
 
-   public String getInclusiveNamespaces() {
+    /**
+     * Creates a SecretKey for the appropriate Mac algorithm based on a
+     * byte[] array password.
+     *
+     * @param secretKeyBytes
+     * @return the secret key for the SignedInfo element.
+     */
+    public SecretKey createSecretKey(byte[] secretKeyBytes) {
+        return new SecretKeySpec(secretKeyBytes, this.signatureAlgorithm.getJCEAlgorithmString());
+    }
 
+    protected SignatureAlgorithm getSignatureAlgorithm() {
+        return signatureAlgorithm;
+    }
 
+    /**
+     * Method getBaseLocalName
+     * @inheritDoc
+     *
+     */
+    public String getBaseLocalName() {
+        return Constants._TAG_SIGNEDINFO;
+    }
 
-     String c14nMethodURI = c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
-     if(!(c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#") ||
-                        c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#WithComments"))) {
+    public String getInclusiveNamespaces() {
+        String c14nMethodURI = c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
+        if (!(c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#") ||
+            c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#WithComments"))) {
+            return null;
+        }
+
+        Element inclusiveElement = XMLUtils.getNextElement(c14nMethod.getFirstChild());
+
+        if (inclusiveElement != null) {
+            try {
+                String inclusiveNamespaces =
+                    new InclusiveNamespaces(
+                        inclusiveElement,
+                        InclusiveNamespaces.ExclusiveCanonicalizationNamespace
+                    ).getInclusiveNamespaces();
+                return inclusiveNamespaces;
+            } catch (XMLSecurityException e) {
                 return null;
             }
-
-     Element inclusiveElement = XMLUtils.getNextElement(
-                 c14nMethod.getFirstChild());
-
-     if(inclusiveElement != null)
-     {
-         try
-         {
-             String inclusiveNamespaces = new InclusiveNamespaces(inclusiveElement,
-                         InclusiveNamespaces.ExclusiveCanonicalizationNamespace).getInclusiveNamespaces();
-             return inclusiveNamespaces;
-         }
-         catch (XMLSecurityException e)
-         {
-             return null;
-         }
-     }
-     return null;
+        }
+        return null;
     }
 }
diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java
index a1a69ddb1d4..490f184c57f 100644
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java
@@ -2,26 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
  *
- *  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.
+ * 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 com.sun.org.apache.xml.internal.security.signature;
 
-
-
 import java.io.IOException;
 import java.io.OutputStream;
 import java.security.Key;
@@ -42,7 +42,6 @@ import com.sun.org.apache.xml.internal.security.transforms.Transforms;
 import com.sun.org.apache.xml.internal.security.utils.Base64;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.I18n;
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
 import com.sun.org.apache.xml.internal.security.utils.SignerOutputStream;
 import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream;
@@ -56,7 +55,6 @@ import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 import org.w3c.dom.Text;
 
-
 /**
  * Handles <ds:Signature> elements.
  * This is the main class that deals with creating and verifying signatures.
@@ -64,7 +62,7 @@ import org.w3c.dom.Text;
  * 

There are 2 types of constructors for this class. The ones that take a * document, baseURI and 1 or more Java Objects. This is mostly used for * signing purposes. - * The other constructor is the one that takes a DOM Element and a BaseURI. + * The other constructor is the one that takes a DOM Element and a baseURI. * This is used mostly with for verifying, when you have a SignatureElement. * * There are a few different types of methods: @@ -76,329 +74,391 @@ import org.w3c.dom.Text; * ObjectContainer during signing. *

  • sign and checkSignatureValue methods are used to sign and validate the * signature.
  • - * - * @author $Author: mullan $ */ public final class XMLSignature extends SignatureElementProxy { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** MAC - Required HMAC-SHA1 */ + public static final String ALGO_ID_MAC_HMAC_SHA1 = + Constants.SignatureSpecNS + "hmac-sha1"; + + /** Signature - Required DSAwithSHA1 (DSS) */ + public static final String ALGO_ID_SIGNATURE_DSA = + Constants.SignatureSpecNS + "dsa-sha1"; + + /** Signature - Recommended RSAwithSHA1 */ + public static final String ALGO_ID_SIGNATURE_RSA = + Constants.SignatureSpecNS + "rsa-sha1"; + + /** Signature - Recommended RSAwithSHA1 */ + public static final String ALGO_ID_SIGNATURE_RSA_SHA1 = + Constants.SignatureSpecNS + "rsa-sha1"; + + /** Signature - NOT Recommended RSAwithMD5 */ + public static final String ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5 = + Constants.MoreAlgorithmsSpecNS + "rsa-md5"; + + /** Signature - Optional RSAwithRIPEMD160 */ + public static final String ALGO_ID_SIGNATURE_RSA_RIPEMD160 = + Constants.MoreAlgorithmsSpecNS + "rsa-ripemd160"; + + /** Signature - Optional RSAwithSHA256 */ + public static final String ALGO_ID_SIGNATURE_RSA_SHA256 = + Constants.MoreAlgorithmsSpecNS + "rsa-sha256"; + + /** Signature - Optional RSAwithSHA384 */ + public static final String ALGO_ID_SIGNATURE_RSA_SHA384 = + Constants.MoreAlgorithmsSpecNS + "rsa-sha384"; + + /** Signature - Optional RSAwithSHA512 */ + public static final String ALGO_ID_SIGNATURE_RSA_SHA512 = + Constants.MoreAlgorithmsSpecNS + "rsa-sha512"; + + /** HMAC - NOT Recommended HMAC-MD5 */ + public static final String ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5 = + Constants.MoreAlgorithmsSpecNS + "hmac-md5"; + + /** HMAC - Optional HMAC-RIPEMD160 */ + public static final String ALGO_ID_MAC_HMAC_RIPEMD160 = + Constants.MoreAlgorithmsSpecNS + "hmac-ripemd160"; + + /** HMAC - Optional HMAC-SHA256 */ + public static final String ALGO_ID_MAC_HMAC_SHA256 = + Constants.MoreAlgorithmsSpecNS + "hmac-sha256"; + + /** HMAC - Optional HMAC-SHA284 */ + public static final String ALGO_ID_MAC_HMAC_SHA384 = + Constants.MoreAlgorithmsSpecNS + "hmac-sha384"; + + /** HMAC - Optional HMAC-SHA512 */ + public static final String ALGO_ID_MAC_HMAC_SHA512 = + Constants.MoreAlgorithmsSpecNS + "hmac-sha512"; + + /**Signature - Optional ECDSAwithSHA1 */ + public static final String ALGO_ID_SIGNATURE_ECDSA_SHA1 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"; + + /**Signature - Optional ECDSAwithSHA256 */ + public static final String ALGO_ID_SIGNATURE_ECDSA_SHA256 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"; + + /**Signature - Optional ECDSAwithSHA384 */ + public static final String ALGO_ID_SIGNATURE_ECDSA_SHA384 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384"; + + /**Signature - Optional ECDSAwithSHA512 */ + public static final String ALGO_ID_SIGNATURE_ECDSA_SHA512 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"; + + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(XMLSignature.class.getName()); - //J- - /** MAC - Required HMAC-SHA1 */ - public static final String ALGO_ID_MAC_HMAC_SHA1 = Constants.SignatureSpecNS + "hmac-sha1"; + /** ds:Signature.ds:SignedInfo element */ + private SignedInfo signedInfo; - /** Signature - Required DSAwithSHA1 (DSS) */ - public static final String ALGO_ID_SIGNATURE_DSA = Constants.SignatureSpecNS + "dsa-sha1"; + /** ds:Signature.ds:KeyInfo */ + private KeyInfo keyInfo; - /** Signature - Recommended RSAwithSHA1 */ - public static final String ALGO_ID_SIGNATURE_RSA = Constants.SignatureSpecNS + "rsa-sha1"; - /** Signature - Recommended RSAwithSHA1 */ - public static final String ALGO_ID_SIGNATURE_RSA_SHA1 = Constants.SignatureSpecNS + "rsa-sha1"; - /** Signature - NOT Recommended RSAwithMD5 */ - public static final String ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5 = Constants.MoreAlgorithmsSpecNS + "rsa-md5"; - /** Signature - Optional RSAwithRIPEMD160 */ - public static final String ALGO_ID_SIGNATURE_RSA_RIPEMD160 = Constants.MoreAlgorithmsSpecNS + "rsa-ripemd160"; - /** Signature - Optional RSAwithSHA256 */ - public static final String ALGO_ID_SIGNATURE_RSA_SHA256 = Constants.MoreAlgorithmsSpecNS + "rsa-sha256"; - /** Signature - Optional RSAwithSHA384 */ - public static final String ALGO_ID_SIGNATURE_RSA_SHA384 = Constants.MoreAlgorithmsSpecNS + "rsa-sha384"; - /** Signature - Optional RSAwithSHA512 */ - public static final String ALGO_ID_SIGNATURE_RSA_SHA512 = Constants.MoreAlgorithmsSpecNS + "rsa-sha512"; + /** + * Checking the digests in References in a Signature are mandatory, but for + * References inside a Manifest it is application specific. This boolean is + * to indicate that the References inside Manifests should be validated. + */ + private boolean followManifestsDuringValidation = false; - /** HMAC - NOT Recommended HMAC-MD5 */ - public static final String ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5 = Constants.MoreAlgorithmsSpecNS + "hmac-md5"; - /** HMAC - Optional HMAC-RIPEMD160 */ - public static final String ALGO_ID_MAC_HMAC_RIPEMD160 = Constants.MoreAlgorithmsSpecNS + "hmac-ripemd160"; - /** HMAC - Optional HMAC-SHA256 */ - public static final String ALGO_ID_MAC_HMAC_SHA256 = Constants.MoreAlgorithmsSpecNS + "hmac-sha256"; - /** HMAC - Optional HMAC-SHA284 */ - public static final String ALGO_ID_MAC_HMAC_SHA384 = Constants.MoreAlgorithmsSpecNS + "hmac-sha384"; - /** HMAC - Optional HMAC-SHA512 */ - public static final String ALGO_ID_MAC_HMAC_SHA512 = Constants.MoreAlgorithmsSpecNS + "hmac-sha512"; - /**Signature - Optional ECDSAwithSHA1 */ - public static final String ALGO_ID_SIGNATURE_ECDSA_SHA1 = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"; + private Element signatureValueElement; + private static final int MODE_SIGN = 0; + private static final int MODE_VERIFY = 1; + private int state = MODE_SIGN; - //J+ + /** + * This creates a new ds:Signature Element and adds an empty + * ds:SignedInfo. + * The ds:SignedInfo is initialized with the specified Signature + * algorithm and Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS which is REQUIRED + * by the spec. This method's main use is for creating a new signature. + * + * @param doc Document in which the signature will be appended after creation. + * @param baseURI URI to be used as context for all relative URIs. + * @param signatureMethodURI signature algorithm to use. + * @throws XMLSecurityException + */ + public XMLSignature(Document doc, String baseURI, String signatureMethodURI) + throws XMLSecurityException { + this(doc, baseURI, signatureMethodURI, 0, Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS); + } - /** ds:Signature.ds:SignedInfo element */ - private SignedInfo _signedInfo = null; + /** + * Constructor XMLSignature + * + * @param doc + * @param baseURI + * @param signatureMethodURI the Signature method to be used. + * @param hmacOutputLength + * @throws XMLSecurityException + */ + public XMLSignature(Document doc, String baseURI, String signatureMethodURI, + int hmacOutputLength) throws XMLSecurityException { + this( + doc, baseURI, signatureMethodURI, hmacOutputLength, + Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS + ); + } - /** ds:Signature.ds:KeyInfo */ - private KeyInfo _keyInfo = null; + /** + * Constructor XMLSignature + * + * @param doc + * @param baseURI + * @param signatureMethodURI the Signature method to be used. + * @param canonicalizationMethodURI the canonicalization algorithm to be + * used to c14nize the SignedInfo element. + * @throws XMLSecurityException + */ + public XMLSignature( + Document doc, + String baseURI, + String signatureMethodURI, + String canonicalizationMethodURI + ) throws XMLSecurityException { + this(doc, baseURI, signatureMethodURI, 0, canonicalizationMethodURI); + } - /** - * Checking the digests in References in a Signature are mandatory, but for - * References inside a Manifest it is application specific. This boolean is - * to indicate that the References inside Manifests should be validated. - */ - private boolean _followManifestsDuringValidation = false; + /** + * Constructor XMLSignature + * + * @param doc + * @param baseURI + * @param signatureMethodURI + * @param hmacOutputLength + * @param canonicalizationMethodURI + * @throws XMLSecurityException + */ + public XMLSignature( + Document doc, + String baseURI, + String signatureMethodURI, + int hmacOutputLength, + String canonicalizationMethodURI + ) throws XMLSecurityException { + super(doc); -private Element signatureValueElement; + String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS); + if (xmlnsDsPrefix == null || xmlnsDsPrefix.length() == 0) { + this.constructionElement.setAttributeNS( + Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS + ); + } else { + this.constructionElement.setAttributeNS( + Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS + ); + } + XMLUtils.addReturnToElement(this.constructionElement); - /** - * This creates a new ds:Signature Element and adds an empty - * ds:SignedInfo. - * The ds:SignedInfo is initialized with the specified Signature - * algorithm and Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS which is REQUIRED - * by the spec. This method's main use is for creating a new signature. - * - * @param doc Document in which the signature will be appended after creation. - * @param BaseURI URI to be used as context for all relative URIs. - * @param SignatureMethodURI signature algorithm to use. - * @throws XMLSecurityException - */ - public XMLSignature(Document doc, String BaseURI, String SignatureMethodURI) - throws XMLSecurityException { - this(doc, BaseURI, SignatureMethodURI, 0, - Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS); - } + this.baseURI = baseURI; + this.signedInfo = + new SignedInfo( + this.doc, signatureMethodURI, hmacOutputLength, canonicalizationMethodURI + ); - /** - * Constructor XMLSignature - * - * @param doc - * @param BaseURI - * @param SignatureMethodURI the Signature method to be used. - * @param HMACOutputLength - * @throws XMLSecurityException - */ - public XMLSignature( - Document doc, String BaseURI, String SignatureMethodURI, int HMACOutputLength) - throws XMLSecurityException { - this(doc, BaseURI, SignatureMethodURI, HMACOutputLength, - Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS); - } + this.constructionElement.appendChild(this.signedInfo.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); - /** - * Constructor XMLSignature - * - * @param doc - * @param BaseURI - * @param SignatureMethodURI the Signature method to be used. - * @param CanonicalizationMethodURI the canonicalization algorithm to be used to c14nize the SignedInfo element. - * @throws XMLSecurityException - */ - public XMLSignature( - Document doc, String BaseURI, String SignatureMethodURI, String CanonicalizationMethodURI) - throws XMLSecurityException { - this(doc, BaseURI, SignatureMethodURI, 0, CanonicalizationMethodURI); - } + // create an empty SignatureValue; this is filled by setSignatureValueElement + signatureValueElement = + XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_SIGNATUREVALUE); - /** - * Constructor XMLSignature - * - * @param doc - * @param BaseURI - * @param SignatureMethodURI - * @param HMACOutputLength - * @param CanonicalizationMethodURI - * @throws XMLSecurityException - */ - public XMLSignature( - Document doc, String BaseURI, String SignatureMethodURI, int HMACOutputLength, String CanonicalizationMethodURI) - throws XMLSecurityException { + this.constructionElement.appendChild(signatureValueElement); + XMLUtils.addReturnToElement(this.constructionElement); + } - super(doc); + /** + * Creates a XMLSignature in a Document + * @param doc + * @param baseURI + * @param SignatureMethodElem + * @param CanonicalizationMethodElem + * @throws XMLSecurityException + */ + public XMLSignature( + Document doc, + String baseURI, + Element SignatureMethodElem, + Element CanonicalizationMethodElem + ) throws XMLSecurityException { + super(doc); - String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS); - if (xmlnsDsPrefix == null) { - this._constructionElement.setAttributeNS - (Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS); - } else { - this._constructionElement.setAttributeNS - (Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS); - } - XMLUtils.addReturnToElement(this._constructionElement); + String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS); + if (xmlnsDsPrefix == null || xmlnsDsPrefix.length() == 0) { + this.constructionElement.setAttributeNS( + Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS + ); + } else { + this.constructionElement.setAttributeNS( + Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS + ); + } + XMLUtils.addReturnToElement(this.constructionElement); - this._baseURI = BaseURI; - this._signedInfo = new SignedInfo(this._doc, SignatureMethodURI, - HMACOutputLength, - CanonicalizationMethodURI); + this.baseURI = baseURI; + this.signedInfo = + new SignedInfo(this.doc, SignatureMethodElem, CanonicalizationMethodElem); - this._constructionElement.appendChild(this._signedInfo.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); + this.constructionElement.appendChild(this.signedInfo.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); - // create an empty SignatureValue; this is filled by setSignatureValueElement - signatureValueElement = - XMLUtils.createElementInSignatureSpace(this._doc, - Constants._TAG_SIGNATUREVALUE); + // create an empty SignatureValue; this is filled by setSignatureValueElement + signatureValueElement = + XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_SIGNATUREVALUE); - this._constructionElement.appendChild(signatureValueElement); - XMLUtils.addReturnToElement(this._constructionElement); - } - /** - * Creates a XMLSignature in a Document - * @param doc - * @param BaseURI - * @param SignatureMethodElem - * @param CanonicalizationMethodElem - * @throws XMLSecurityException - */ - public XMLSignature( - Document doc, String BaseURI, Element SignatureMethodElem, Element CanonicalizationMethodElem) - throws XMLSecurityException { + this.constructionElement.appendChild(signatureValueElement); + XMLUtils.addReturnToElement(this.constructionElement); + } - super(doc); + /** + * This will parse the element and construct the Java Objects. + * That will allow a user to validate the signature. + * + * @param element ds:Signature element that contains the whole signature + * @param baseURI URI to be prepended to all relative URIs + * @throws XMLSecurityException + * @throws XMLSignatureException if the signature is badly formatted + */ + public XMLSignature(Element element, String baseURI) + throws XMLSignatureException, XMLSecurityException { + this(element, baseURI, false); + } - String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS); - if (xmlnsDsPrefix == null) { - this._constructionElement.setAttributeNS - (Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS); - } else { - this._constructionElement.setAttributeNS - (Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS); - } - XMLUtils.addReturnToElement(this._constructionElement); + /** + * This will parse the element and construct the Java Objects. + * That will allow a user to validate the signature. + * + * @param element ds:Signature element that contains the whole signature + * @param baseURI URI to be prepended to all relative URIs + * @param secureValidation whether secure secureValidation is enabled or not + * @throws XMLSecurityException + * @throws XMLSignatureException if the signature is badly formatted + */ + public XMLSignature(Element element, String baseURI, boolean secureValidation) + throws XMLSignatureException, XMLSecurityException { + super(element, baseURI); - this._baseURI = BaseURI; - this._signedInfo = new SignedInfo(this._doc, SignatureMethodElem, CanonicalizationMethodElem); + // check out SignedInfo child + Element signedInfoElem = XMLUtils.getNextElement(element.getFirstChild()); - this._constructionElement.appendChild(this._signedInfo.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); + // check to see if it is there + if (signedInfoElem == null) { + Object exArgs[] = { Constants._TAG_SIGNEDINFO, Constants._TAG_SIGNATURE }; + throw new XMLSignatureException("xml.WrongContent", exArgs); + } - // create an empty SignatureValue; this is filled by setSignatureValueElement - signatureValueElement = - XMLUtils.createElementInSignatureSpace(this._doc, - Constants._TAG_SIGNATUREVALUE); + // create a SignedInfo object from that element + this.signedInfo = new SignedInfo(signedInfoElem, baseURI, secureValidation); + // get signedInfoElem again in case it has changed + signedInfoElem = XMLUtils.getNextElement(element.getFirstChild()); - this._constructionElement.appendChild(signatureValueElement); - XMLUtils.addReturnToElement(this._constructionElement); - } + // check out SignatureValue child + this.signatureValueElement = + XMLUtils.getNextElement(signedInfoElem.getNextSibling()); - /** - * This will parse the element and construct the Java Objects. - * That will allow a user to validate the signature. - * - * @param element ds:Signature element that contains the whole signature - * @param BaseURI URI to be prepended to all relative URIs - * @throws XMLSecurityException - * @throws XMLSignatureException if the signature is badly formatted - */ - public XMLSignature(Element element, String BaseURI) - throws XMLSignatureException, XMLSecurityException { + // check to see if it exists + if (signatureValueElement == null) { + Object exArgs[] = { Constants._TAG_SIGNATUREVALUE, Constants._TAG_SIGNATURE }; + throw new XMLSignatureException("xml.WrongContent", exArgs); + } + Attr signatureValueAttr = signatureValueElement.getAttributeNodeNS(null, "Id"); + if (signatureValueAttr != null) { + signatureValueElement.setIdAttributeNode(signatureValueAttr, true); + } - super(element, BaseURI); + // + Element keyInfoElem = + XMLUtils.getNextElement(signatureValueElement.getNextSibling()); - // check out SignedInfo child - Element signedInfoElem = XMLUtils.getNextElement(element.getFirstChild());// XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - //Constants._TAG_SIGNEDINFO,0); + // If it exists use it, but it's not mandatory + if (keyInfoElem != null + && keyInfoElem.getNamespaceURI().equals(Constants.SignatureSpecNS) + && keyInfoElem.getLocalName().equals(Constants._TAG_KEYINFO)) { + this.keyInfo = new KeyInfo(keyInfoElem, baseURI); + this.keyInfo.setSecureValidation(secureValidation); + } - // check to see if it is there - if (signedInfoElem == null) { - Object exArgs[] = { Constants._TAG_SIGNEDINFO, - Constants._TAG_SIGNATURE }; + // + Element objectElem = + XMLUtils.getNextElement(signatureValueElement.getNextSibling()); + while (objectElem != null) { + Attr objectAttr = objectElem.getAttributeNodeNS(null, "Id"); + if (objectAttr != null) { + objectElem.setIdAttributeNode(objectAttr, true); + } - throw new XMLSignatureException("xml.WrongContent", exArgs); - } + NodeList nodes = objectElem.getChildNodes(); + int length = nodes.getLength(); + // Register Ids of the Object child elements + for (int i = 0; i < length; i++) { + Node child = nodes.item(i); + if (child.getNodeType() == Node.ELEMENT_NODE) { + Element childElem = (Element)child; + String tag = childElem.getLocalName(); + if (tag.equals("Manifest")) { + new Manifest(childElem, baseURI); + } else if (tag.equals("SignatureProperties")) { + new SignatureProperties(childElem, baseURI); + } + } + } - // create a SignedInfo object from that element - this._signedInfo = new SignedInfo(signedInfoElem, BaseURI); + objectElem = XMLUtils.getNextElement(objectElem.getNextSibling()); + } - // check out SignatureValue child - this.signatureValueElement =XMLUtils.getNextElement(signedInfoElem.getNextSibling()); //XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - // Constants._TAG_SIGNATUREVALUE,0); + this.state = MODE_VERIFY; + } - // check to see if it exists - if (signatureValueElement == null) { - Object exArgs[] = { Constants._TAG_SIGNATUREVALUE, - Constants._TAG_SIGNATURE }; + /** + * Sets the Id attribute + * + * @param id Id value for the id attribute on the Signature Element + */ + public void setId(String id) { + if (id != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id); + this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true); + } + } - throw new XMLSignatureException("xml.WrongContent", exArgs); - } - Attr signatureValueAttr = signatureValueElement.getAttributeNodeNS(null, "Id"); - if (signatureValueAttr != null) { - signatureValueElement.setIdAttributeNode(signatureValueAttr, true); - } + /** + * Returns the Id attribute + * + * @return the Id attribute + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } - // - Element keyInfoElem = XMLUtils.getNextElement(signatureValueElement.getNextSibling());//XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - // Constants._TAG_KEYINFO,0); + /** + * Returns the completely parsed SignedInfo object. + * + * @return the completely parsed SignedInfo object. + */ + public SignedInfo getSignedInfo() { + return this.signedInfo; + } - // If it exists use it, but it's not mandatory - if ((keyInfoElem != null) && (keyInfoElem.getNamespaceURI().equals(Constants.SignatureSpecNS) && - keyInfoElem.getLocalName().equals(Constants._TAG_KEYINFO)) ) { - this._keyInfo = new KeyInfo(keyInfoElem, BaseURI); - } - - // - Element objectElem = - XMLUtils.getNextElement(signatureValueElement.getNextSibling()); - while (objectElem != null) { - Attr objectAttr = objectElem.getAttributeNodeNS(null, "Id"); - if (objectAttr != null) { - objectElem.setIdAttributeNode(objectAttr, true); - } - - NodeList nodes = objectElem.getChildNodes(); - int length = nodes.getLength(); - // Register Ids of the Object child elements - for (int i = 0; i < length; i++) { - Node child = nodes.item(i); - if (child.getNodeType() == Node.ELEMENT_NODE) { - Element childElem = (Element)child; - String tag = childElem.getLocalName(); - if (tag.equals("Manifest")) { - new Manifest(childElem, BaseURI); - } else if (tag.equals("SignatureProperties")) { - new SignatureProperties(childElem, BaseURI); - } - } - } - - objectElem = XMLUtils.getNextElement(objectElem.getNextSibling()); - } - } - - /** - * Sets the Id attribute - * - * @param Id Id value to be used by the id attribute on the Signature Element - */ - public void setId(String Id) { - - if (Id != null) { - setLocalIdAttribute(Constants._ATT_ID, Id); - } - } - - /** - * Returns the Id attribute - * - * @return the Id attribute - */ - public String getId() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ID); - } - - /** - * Returns the completely parsed SignedInfo object. - * - * @return the completely parsed SignedInfo object. - */ - public SignedInfo getSignedInfo() { - return this._signedInfo; - } - - /** - * Returns the octet value of the SignatureValue element. - * Throws an XMLSignatureException if it has no or wrong content. - * - * @return the value of the SignatureValue element. - * @throws XMLSignatureException If there is no content - */ - public byte[] getSignatureValue() throws XMLSignatureException { - - try { - byte[] signatureValue = Base64.decode(signatureValueElement); - - return signatureValue; - } catch (Base64DecodingException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * Returns the octet value of the SignatureValue element. + * Throws an XMLSignatureException if it has no or wrong content. + * + * @return the value of the SignatureValue element. + * @throws XMLSignatureException If there is no content + */ + public byte[] getSignatureValue() throws XMLSignatureException { + try { + return Base64.decode(signatureValueElement); + } catch (Base64DecodingException ex) { + throw new XMLSignatureException("empty", ex); + } + } /** * Base64 encodes and sets the bytes as the content of the SignatureValue @@ -409,8 +469,7 @@ private Element signatureValueElement; private void setSignatureValueElement(byte[] bytes) { while (signatureValueElement.hasChildNodes()) { - signatureValueElement.removeChild - (signatureValueElement.getFirstChild()); + signatureValueElement.removeChild(signatureValueElement.getFirstChild()); } String base64codedValue = Base64.encode(bytes); @@ -419,373 +478,393 @@ private Element signatureValueElement; base64codedValue = "\n" + base64codedValue + "\n"; } - Text t = this._doc.createTextNode(base64codedValue); + Text t = this.doc.createTextNode(base64codedValue); signatureValueElement.appendChild(t); } - /** - * Returns the KeyInfo child. If we are in signing mode and the KeyInfo - * does not exist yet, it is created on demand and added to the Signature. - *
    - * This allows to add arbitrary content to the KeyInfo during signing. - * - * @return the KeyInfo object - */ - public KeyInfo getKeyInfo() { + /** + * Returns the KeyInfo child. If we are in signing mode and the KeyInfo + * does not exist yet, it is created on demand and added to the Signature. + *
    + * This allows to add arbitrary content to the KeyInfo during signing. + * + * @return the KeyInfo object + */ + public KeyInfo getKeyInfo() { + // check to see if we are signing and if we have to create a keyinfo + if (this.state == MODE_SIGN && this.keyInfo == null) { - // check to see if we are signing and if we have to create a keyinfo - if ( (this._keyInfo == null)) { + // create the KeyInfo + this.keyInfo = new KeyInfo(this.doc); - // create the KeyInfo - this._keyInfo = new KeyInfo(this._doc); - - // get the Element from KeyInfo - Element keyInfoElement = this._keyInfo.getElement(); - Element firstObject=null; - Node sibling= this._constructionElement.getFirstChild(); - firstObject = XMLUtils.selectDsNode(sibling,Constants._TAG_OBJECT,0); + // get the Element from KeyInfo + Element keyInfoElement = this.keyInfo.getElement(); + Element firstObject = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_OBJECT, 0 + ); if (firstObject != null) { - - // add it before the object - this._constructionElement.insertBefore(keyInfoElement, - firstObject); - XMLUtils.addReturnBeforeChild(this._constructionElement, firstObject); + // add it before the object + this.constructionElement.insertBefore(keyInfoElement, firstObject); + XMLUtils.addReturnBeforeChild(this.constructionElement, firstObject); } else { - - // add it as the last element to the signature - this._constructionElement.appendChild(keyInfoElement); - XMLUtils.addReturnToElement(this._constructionElement); + // add it as the last element to the signature + this.constructionElement.appendChild(keyInfoElement); + XMLUtils.addReturnToElement(this.constructionElement); } - } + } - return this._keyInfo; - } + return this.keyInfo; + } - /** - * Appends an Object (not a java.lang.Object but an Object - * element) to the Signature. Please note that this is only possible - * when signing. - * - * @param object ds:Object to be appended. - * @throws XMLSignatureException When this object is used to verify. - */ - public void appendObject(ObjectContainer object) - throws XMLSignatureException { + /** + * Appends an Object (not a java.lang.Object but an Object + * element) to the Signature. Please note that this is only possible + * when signing. + * + * @param object ds:Object to be appended. + * @throws XMLSignatureException When this object is used to verify. + */ + public void appendObject(ObjectContainer object) throws XMLSignatureException { + //try { + //if (this.state != MODE_SIGN) { + // throw new XMLSignatureException( + // "signature.operationOnlyBeforeSign"); + //} - //try { - //if (this._state != MODE_SIGN) { - // throw new XMLSignatureException( - // "signature.operationOnlyBeforeSign"); - //} - - this._constructionElement.appendChild(object.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - //} catch (XMLSecurityException ex) { + this.constructionElement.appendChild(object.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + //} catch (XMLSecurityException ex) { // throw new XMLSignatureException("empty", ex); - //} - } + //} + } - /** - * Returns the ith ds:Object child of the signature - * or null if no such ds:Object element exists. - * - * @param i - * @return the ith ds:Object child of the signature or null if no such ds:Object element exists. - */ - public ObjectContainer getObjectItem(int i) { + /** + * Returns the ith ds:Object child of the signature + * or null if no such ds:Object element exists. + * + * @param i + * @return the ith ds:Object child of the signature + * or null if no such ds:Object element exists. + */ + public ObjectContainer getObjectItem(int i) { + Element objElem = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_OBJECT, i + ); - Element objElem = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_OBJECT,i); + try { + return new ObjectContainer(objElem, this.baseURI); + } catch (XMLSecurityException ex) { + return null; + } + } - try { - return new ObjectContainer(objElem, this._baseURI); - } catch (XMLSecurityException ex) { - return null; - } - } + /** + * Returns the number of all ds:Object elements. + * + * @return the number of all ds:Object elements. + */ + public int getObjectLength() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_OBJECT); + } - /** - * Returns the number of all ds:Object elements. - * - * @return the number of all ds:Object elements. - */ - public int getObjectLength() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_OBJECT); - } + /** + * Digests all References in the SignedInfo, calculates the signature value + * and sets it in the SignatureValue Element. + * + * @param signingKey the {@link java.security.PrivateKey} or + * {@link javax.crypto.SecretKey} that is used to sign. + * @throws XMLSignatureException + */ + public void sign(Key signingKey) throws XMLSignatureException { - /** - * Digests all References in the SignedInfo, calculates the signature value and - * sets it in the SignatureValue Element. - * - * @param signingKey the {@link java.security.PrivateKey} or {@link javax.crypto.SecretKey} that is used to sign. - * @throws XMLSignatureException - */ - public void sign(Key signingKey) throws XMLSignatureException { + if (signingKey instanceof PublicKey) { + throw new IllegalArgumentException( + I18n.translate("algorithms.operationOnlyVerification") + ); + } - if (signingKey instanceof PublicKey) { - throw new IllegalArgumentException(I18n - .translate("algorithms.operationOnlyVerification")); - } - - try { - // if (this._state == MODE_SIGN) { + try { //Create a SignatureAlgorithm object - SignedInfo si = this.getSignedInfo(); + SignedInfo si = this.getSignedInfo(); SignatureAlgorithm sa = si.getSignatureAlgorithm(); - // initialize SignatureAlgorithm for signing - sa.initSign(signingKey); - - // generate digest values for all References in this SignedInfo - si.generateDigestValues(); - OutputStream so=new UnsyncBufferedOutputStream(new SignerOutputStream(sa)); + OutputStream so = null; try { - so.close(); - } catch (IOException e) { - //Imposible + // initialize SignatureAlgorithm for signing + sa.initSign(signingKey); + + // generate digest values for all References in this SignedInfo + si.generateDigestValues(); + so = new UnsyncBufferedOutputStream(new SignerOutputStream(sa)); + // get the canonicalized bytes from SignedInfo + si.signInOctetStream(so); + } catch (XMLSecurityException ex) { + throw ex; + } finally { + if (so != null) { + try { + so.close(); + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + } + } } - // get the canonicalized bytes from SignedInfo - si.signInOctectStream(so); - byte jcebytes[] = sa.sign(); + // set them on the SignatureValue element + this.setSignatureValueElement(sa.sign()); + } catch (XMLSignatureException ex) { + throw ex; + } catch (CanonicalizationException ex) { + throw new XMLSignatureException("empty", ex); + } catch (InvalidCanonicalizerException ex) { + throw new XMLSignatureException("empty", ex); + } catch (XMLSecurityException ex) { + throw new XMLSignatureException("empty", ex); + } + } - // set them on the SignateValue element - this.setSignatureValueElement(jcebytes); - //} - } catch (CanonicalizationException ex) { - throw new XMLSignatureException("empty", ex); - } catch (InvalidCanonicalizerException ex) { - throw new XMLSignatureException("empty", ex); - } catch (XMLSecurityException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * Adds a {@link ResourceResolver} to enable the retrieval of resources. + * + * @param resolver + */ + public void addResourceResolver(ResourceResolver resolver) { + this.getSignedInfo().addResourceResolver(resolver); + } - /** - * Adds a {@link ResourceResolver} to enable the retrieval of resources. - * - * @param resolver - */ - public void addResourceResolver(ResourceResolver resolver) { - this.getSignedInfo().addResourceResolver(resolver); - } + /** + * Adds a {@link ResourceResolverSpi} to enable the retrieval of resources. + * + * @param resolver + */ + public void addResourceResolver(ResourceResolverSpi resolver) { + this.getSignedInfo().addResourceResolver(resolver); + } - /** - * Adds a {@link ResourceResolverSpi} to enable the retrieval of resources. - * - * @param resolver - */ - public void addResourceResolver(ResourceResolverSpi resolver) { - this.getSignedInfo().addResourceResolver(resolver); - } + /** + * Extracts the public key from the certificate and verifies if the signature + * is valid by re-digesting all References, comparing those against the + * stored DigestValues and then checking to see if the Signatures match on + * the SignedInfo. + * + * @param cert Certificate that contains the public key part of the keypair + * that was used to sign. + * @return true if the signature is valid, false otherwise + * @throws XMLSignatureException + */ + public boolean checkSignatureValue(X509Certificate cert) + throws XMLSignatureException { + // see if cert is null + if (cert != null) { + // check the values with the public key from the cert + return this.checkSignatureValue(cert.getPublicKey()); + } - /** - * Extracts the public key from the certificate and verifies if the signature - * is valid by re-digesting all References, comparing those against the - * stored DigestValues and then checking to see if the Signatures match on - * the SignedInfo. - * - * @param cert Certificate that contains the public key part of the keypair that was used to sign. - * @return true if the signature is valid, false otherwise - * @throws XMLSignatureException - */ - public boolean checkSignatureValue(X509Certificate cert) - throws XMLSignatureException { + Object exArgs[] = { "Didn't get a certificate" }; + throw new XMLSignatureException("empty", exArgs); + } - // see if cert is null - if (cert != null) { - - //check the values with the public key from the cert - return this.checkSignatureValue(cert.getPublicKey()); - } - - Object exArgs[] = { "Didn't get a certificate" }; - throw new XMLSignatureException("empty", exArgs); - - } - - /** - * Verifies if the signature is valid by redigesting all References, - * comparing those against the stored DigestValues and then checking to see - * if the Signatures match on the SignedInfo. - * - * @param pk {@link java.security.PublicKey} part of the keypair or {@link javax.crypto.SecretKey} that was used to sign - * @return true if the signature is valid, false otherwise - * @throws XMLSignatureException - */ - public boolean checkSignatureValue(Key pk) throws XMLSignatureException { - - //COMMENT: pk suggests it can only be a public key? - //check to see if the key is not null - if (pk == null) { - Object exArgs[] = { "Didn't get a key" }; - - throw new XMLSignatureException("empty", exArgs); - } - // all references inside the signedinfo need to be dereferenced and - // digested again to see if the outcome matches the stored value in the - // SignedInfo. - // If _followManifestsDuringValidation is true it will do the same for - // References inside a Manifest. - try { - SignedInfo si=this.getSignedInfo(); - //create a SignatureAlgorithms from the SignatureMethod inside - //SignedInfo. This is used to validate the signature. - SignatureAlgorithm sa =si.getSignatureAlgorithm(); - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "SignatureMethodURI = " + sa.getAlgorithmURI()); + /** + * Verifies if the signature is valid by redigesting all References, + * comparing those against the stored DigestValues and then checking to see + * if the Signatures match on the SignedInfo. + * + * @param pk {@link java.security.PublicKey} part of the keypair or + * {@link javax.crypto.SecretKey} that was used to sign + * @return true if the signature is valid, false otherwise + * @throws XMLSignatureException + */ + public boolean checkSignatureValue(Key pk) throws XMLSignatureException { + //COMMENT: pk suggests it can only be a public key? + //check to see if the key is not null + if (pk == null) { + Object exArgs[] = { "Didn't get a key" }; + throw new XMLSignatureException("empty", exArgs); + } + // all references inside the signedinfo need to be dereferenced and + // digested again to see if the outcome matches the stored value in the + // SignedInfo. + // If followManifestsDuringValidation is true it will do the same for + // References inside a Manifest. + try { + SignedInfo si = this.getSignedInfo(); + //create a SignatureAlgorithms from the SignatureMethod inside + //SignedInfo. This is used to validate the signature. + SignatureAlgorithm sa = si.getSignatureAlgorithm(); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "signatureMethodURI = " + sa.getAlgorithmURI()); log.log(java.util.logging.Level.FINE, "jceSigAlgorithm = " + sa.getJCEAlgorithmString()); log.log(java.util.logging.Level.FINE, "jceSigProvider = " + sa.getJCEProviderName()); log.log(java.util.logging.Level.FINE, "PublicKey = " + pk); - } - sa.initVerify(pk); + } + byte sigBytes[] = null; + try { + sa.initVerify(pk); - // Get the canonicalized (normalized) SignedInfo - SignerOutputStream so=new SignerOutputStream(sa); - OutputStream bos=new UnsyncBufferedOutputStream(so); - si.signInOctectStream(bos); - try { + // Get the canonicalized (normalized) SignedInfo + SignerOutputStream so = new SignerOutputStream(sa); + OutputStream bos = new UnsyncBufferedOutputStream(so); + + si.signInOctetStream(bos); bos.close(); - } catch (IOException e) { - //Imposible - } + // retrieve the byte[] from the stored signature + sigBytes = this.getSignatureValue(); + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + // Impossible... + } catch (XMLSecurityException ex) { + throw ex; + } - //retrieve the byte[] from the stored signature - byte sigBytes[] = this.getSignatureValue(); + // have SignatureAlgorithm sign the input bytes and compare them to + // the bytes that were stored in the signature. + if (!sa.verify(sigBytes)) { + log.log(java.util.logging.Level.WARNING, "Signature verification failed."); + return false; + } - //Have SignatureAlgorithm sign the input bytes and compare them to the - //bytes that were stored in the signature. - if (!sa.verify(sigBytes)) { - log.log(java.util.logging.Level.WARNING, "Signature verification failed."); - return false; - } + return si.verify(this.followManifestsDuringValidation); + } catch (XMLSignatureException ex) { + throw ex; + } catch (XMLSecurityException ex) { + throw new XMLSignatureException("empty", ex); + } + } - return si.verify(this._followManifestsDuringValidation); - } catch (XMLSecurityException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * Add a Reference with full parameters to this Signature + * + * @param referenceURI URI of the resource to be signed. Can be null in + * which case the dereferencing is application specific. Can be "" in which + * it's the parent node (or parent document?). There can only be one "" in + * each signature. + * @param trans Optional list of transformations to be done before digesting + * @param digestURI Mandatory URI of the digesting algorithm to use. + * @param referenceId Optional id attribute for this Reference + * @param referenceType Optional mimetype for the URI + * @throws XMLSignatureException + */ + public void addDocument( + String referenceURI, + Transforms trans, + String digestURI, + String referenceId, + String referenceType + ) throws XMLSignatureException { + this.signedInfo.addDocument( + this.baseURI, referenceURI, trans, digestURI, referenceId, referenceType + ); + } - /** - * Add a Reference with full parameters to this Signature - * - * @param referenceURI URI of the resource to be signed. Can be null in which - * case the dereferencing is application specific. Can be "" in which it's - * the parent node (or parent document?). There can only be one "" in each - * signature. - * @param trans Optional list of transformations to be done before digesting - * @param digestURI Mandatory URI of the digesting algorithm to use. - * @param ReferenceId Optional id attribute for this Reference - * @param ReferenceType Optional mimetype for the URI - * @throws XMLSignatureException - */ - public void addDocument( - String referenceURI, Transforms trans, String digestURI, String ReferenceId, String ReferenceType) - throws XMLSignatureException { - this._signedInfo.addDocument(this._baseURI, referenceURI, trans, - digestURI, ReferenceId, ReferenceType); - } + /** + * This method is a proxy method for the {@link Manifest#addDocument} method. + * + * @param referenceURI URI according to the XML Signature specification. + * @param trans List of transformations to be applied. + * @param digestURI URI of the digest algorithm to be used. + * @see Manifest#addDocument + * @throws XMLSignatureException + */ + public void addDocument( + String referenceURI, + Transforms trans, + String digestURI + ) throws XMLSignatureException { + this.signedInfo.addDocument(this.baseURI, referenceURI, trans, digestURI, null, null); + } - /** - * This method is a proxy method for the {@link Manifest#addDocument} method. - * - * @param referenceURI URI according to the XML Signature specification. - * @param trans List of transformations to be applied. - * @param digestURI URI of the digest algorithm to be used. - * @see Manifest#addDocument - * @throws XMLSignatureException - */ - public void addDocument( - String referenceURI, Transforms trans, String digestURI) - throws XMLSignatureException { - this._signedInfo.addDocument(this._baseURI, referenceURI, trans, - digestURI, null, null); - } + /** + * Adds a Reference with just the URI and the transforms. This used the + * SHA1 algorithm as a default digest algorithm. + * + * @param referenceURI URI according to the XML Signature specification. + * @param trans List of transformations to be applied. + * @throws XMLSignatureException + */ + public void addDocument(String referenceURI, Transforms trans) + throws XMLSignatureException { + this.signedInfo.addDocument( + this.baseURI, referenceURI, trans, Constants.ALGO_ID_DIGEST_SHA1, null, null + ); + } - /** - * Adds a Reference with just the URI and the transforms. This used the - * SHA1 algorithm as a default digest algorithm. - * - * @param referenceURI URI according to the XML Signature specification. - * @param trans List of transformations to be applied. - * @throws XMLSignatureException - */ - public void addDocument(String referenceURI, Transforms trans) - throws XMLSignatureException { - this._signedInfo.addDocument(this._baseURI, referenceURI, trans, - Constants.ALGO_ID_DIGEST_SHA1, null, null); - } + /** + * Add a Reference with just this URI. It uses SHA1 by default as the digest + * algorithm + * + * @param referenceURI URI according to the XML Signature specification. + * @throws XMLSignatureException + */ + public void addDocument(String referenceURI) throws XMLSignatureException { + this.signedInfo.addDocument( + this.baseURI, referenceURI, null, Constants.ALGO_ID_DIGEST_SHA1, null, null + ); + } - /** - * Add a Reference with just this URI. It uses SHA1 by default as the digest - * algorithm - * - * @param referenceURI URI according to the XML Signature specification. - * @throws XMLSignatureException - */ - public void addDocument(String referenceURI) throws XMLSignatureException { - this._signedInfo.addDocument(this._baseURI, referenceURI, null, - Constants.ALGO_ID_DIGEST_SHA1, null, null); - } + /** + * Add an X509 Certificate to the KeyInfo. This will include the whole cert + * inside X509Data/X509Certificate tags. + * + * @param cert Certificate to be included. This should be the certificate of + * the key that was used to sign. + * @throws XMLSecurityException + */ + public void addKeyInfo(X509Certificate cert) throws XMLSecurityException { + X509Data x509data = new X509Data(this.doc); - /** - * Add an X509 Certificate to the KeyInfo. This will include the whole cert - * inside X509Data/X509Certificate tags. - * - * @param cert Certificate to be included. This should be the certificate of the key that was used to sign. - * @throws XMLSecurityException - */ - public void addKeyInfo(X509Certificate cert) throws XMLSecurityException { + x509data.addCertificate(cert); + this.getKeyInfo().add(x509data); + } - X509Data x509data = new X509Data(this._doc); + /** + * Add this public key to the KeyInfo. This will include the complete key in + * the KeyInfo structure. + * + * @param pk + */ + public void addKeyInfo(PublicKey pk) { + this.getKeyInfo().add(pk); + } - x509data.addCertificate(cert); - this.getKeyInfo().add(x509data); - } + /** + * Proxy method for {@link SignedInfo#createSecretKey(byte[])}. If you want + * to create a MAC, this method helps you to obtain the + * {@link javax.crypto.SecretKey} from octets. + * + * @param secretKeyBytes + * @return the secret key created. + * @see SignedInfo#createSecretKey(byte[]) + */ + public SecretKey createSecretKey(byte[] secretKeyBytes) { + return this.getSignedInfo().createSecretKey(secretKeyBytes); + } - /** - * Add this public key to the KeyInfo. This will include the complete key in - * the KeyInfo structure. - * - * @param pk - */ - public void addKeyInfo(PublicKey pk) { - this.getKeyInfo().add(pk); - } + /** + * Signal wether Manifest should be automatically validated. + * Checking the digests in References in a Signature are mandatory, but for + * References inside a Manifest it is application specific. This boolean is + * to indicate that the References inside Manifests should be validated. + * + * @param followManifests + * @see + * Core validation section in the XML Signature Rec. + */ + public void setFollowNestedManifests(boolean followManifests) { + this.followManifestsDuringValidation = followManifests; + } - /** - * Proxy method for {@link SignedInfo#createSecretKey(byte[])}. If you want to - * create a MAC, this method helps you to obtain the {@link javax.crypto.SecretKey} - * from octets. - * - * @param secretKeyBytes - * @return the secret key created. - * @see SignedInfo#createSecretKey(byte[]) - */ - public SecretKey createSecretKey(byte[] secretKeyBytes) - { - return this.getSignedInfo().createSecretKey(secretKeyBytes); - } - - /** - * Signal wether Manifest should be automatically validated. - * Checking the digests in References in a Signature are mandatory, but for - * References inside a Manifest it is application specific. This boolean is - * to indicate that the References inside Manifests should be validated. - * - * @param followManifests - * @see Core validation section in the XML Signature Rec. - */ - public void setFollowNestedManifests(boolean followManifests) { - this._followManifestsDuringValidation = followManifests; - } - - /** - * Get the local name of this element - * - * @return Constant._TAG_SIGNATURE - */ - public String getBaseLocalName() { - return Constants._TAG_SIGNATURE; - } + /** + * Get the local name of this element + * + * @return Constants._TAG_SIGNATURE + */ + public String getBaseLocalName() { + return Constants._TAG_SIGNATURE; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java index 744f62dc461..863ddbbedca 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java @@ -2,29 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.signature; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - /** * All XML Signature related exceptions inherit herefrom. * @@ -33,57 +32,56 @@ import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; */ public class XMLSignatureException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor XMLSignatureException - * - */ - public XMLSignatureException() { - super(); - } + /** + * Constructor XMLSignatureException + * + */ + public XMLSignatureException() { + super(); + } - /** - * Constructor XMLSignatureException - * - * @param _msgID - */ - public XMLSignatureException(String _msgID) { - super(_msgID); - } + /** + * Constructor XMLSignatureException + * + * @param msgID + */ + public XMLSignatureException(String msgID) { + super(msgID); + } - /** - * Constructor XMLSignatureException - * - * @param _msgID - * @param exArgs - */ - public XMLSignatureException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor XMLSignatureException + * + * @param msgID + * @param exArgs + */ + public XMLSignatureException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor XMLSignatureException - * - * @param _msgID - * @param _originalException - */ - public XMLSignatureException(String _msgID, Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor XMLSignatureException + * + * @param msgID + * @param originalException + */ + public XMLSignatureException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor XMLSignatureException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public XMLSignatureException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * Constructor XMLSignatureException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public XMLSignatureException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java index 89990a10ac4..6451642cb70 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.signature; @@ -25,7 +27,6 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; @@ -53,17 +54,13 @@ import org.xml.sax.SAXException; * @author Christian Geuer-Pollmann * $todo$ check whether an XMLSignatureInput can be _both_, octet stream _and_ node set? */ -public class XMLSignatureInput implements Cloneable { - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger - (XMLSignatureInput.class.getName()); - +public class XMLSignatureInput { /* * The XMLSignature Input can be either: * A byteArray like with/or without InputStream. * Or a nodeSet like defined either: * * as a collection of nodes - * * or as subnode excluding or not commets and excluding or + * * or as subnode excluding or not comments and excluding or * not other nodes. */ @@ -71,63 +68,55 @@ public class XMLSignatureInput implements Cloneable { * Some InputStreams do not support the {@link java.io.InputStream#reset} * method, so we read it in completely and work on our Proxy. */ - InputStream _inputOctetStreamProxy = null; + private InputStream inputOctetStreamProxy = null; /** * The original NodeSet for this XMLSignatureInput */ - Set _inputNodeSet = null; + private Set inputNodeSet = null; /** * The original Element */ - Node _subNode=null; + private Node subNode = null; /** * Exclude Node *for enveloped transformations* */ - Node excludeNode=null; + private Node excludeNode = null; /** * */ - boolean excludeComments=false; + private boolean excludeComments = false; - boolean isNodeSet=false; + private boolean isNodeSet = false; /** * A cached bytes */ - byte []bytes=null; + private byte[] bytes = null; /** - * Some Transforms may require explicit MIME type, charset (IANA registered "character set"), or other such information concerning the data they are receiving from an earlier Transform or the source data, although no Transform algorithm specified in this document needs such explicit information. Such data characteristics are provided as parameters to the Transform algorithm and should be described in the specification for the algorithm. + * Some Transforms may require explicit MIME type, charset (IANA registered + * "character set"), or other such information concerning the data they are + * receiving from an earlier Transform or the source data, although no + * Transform algorithm specified in this document needs such explicit + * information. Such data characteristics are provided as parameters to the + * Transform algorithm and should be described in the specification for the + * algorithm. */ - private String _MIMEType = null; + private String mimeType = null; /** - * Field _SourceURI + * Field sourceURI */ - private String _SourceURI = null; + private String sourceURI = null; /** * Node Filter list. */ - List nodeFilters=new ArrayList(); + private List nodeFilters = new ArrayList(); - boolean needsToBeExpanded=false; - OutputStream outputStream=null; + private boolean needsToBeExpanded = false; + private OutputStream outputStream = null; - /** - * Check if the structured is needed to be circumbented. - * @return true if so. - */ - public boolean isNeedsToBeExpanded() { - return needsToBeExpanded; - } - - /** - * Set if the structured is needed to be circumbented. - * @param needsToBeExpanded true if so. - */ - public void setNeedsToBeExpanded(boolean needsToBeExpanded) { - this.needsToBeExpanded = needsToBeExpanded; - } + private DocumentBuilderFactory dfactory; /** * Construct a XMLSignatureInput from an octet array. @@ -138,11 +127,8 @@ public class XMLSignatureInput implements Cloneable { * @param inputOctets an octet array which including XML document or node */ public XMLSignatureInput(byte[] inputOctets) { - - // NO defensive copy - - //this._inputOctetStreamProxy = new ByteArrayInputStream(inputOctets); - this.bytes=inputOctets; + // NO defensive copy + this.bytes = inputOctets; } /** @@ -152,39 +138,7 @@ public class XMLSignatureInput implements Cloneable { * @param inputOctetStream */ public XMLSignatureInput(InputStream inputOctetStream) { - this._inputOctetStreamProxy=inputOctetStream; - - //this(JavaUtils.getBytesFromStream(inputOctetStream)); - } - - /** - * Construct a XMLSignatureInput from a String. - *

    - * This is a comfort method, which internally converts the String into a byte - * [] array using the {@link java.lang.String#getBytes()} method. - * @deprecated - * @param inputStr the input String which including XML document or node - */ - @Deprecated - public XMLSignatureInput(String inputStr) { - this(inputStr.getBytes()); - } - - /** - * Construct a XMLSignatureInput from a String with a given encoding. - *

    - * This is a comfort method, which internally converts the String into a byte - * [] array using the {@link java.lang.String#getBytes()} method. - * - * @deprecated - * @param inputStr the input String with encoding encoding - * @param encoding the encoding of inputStr - * @throws UnsupportedEncodingException - */ - @Deprecated - public XMLSignatureInput(String inputStr, String encoding) - throws UnsupportedEncodingException { - this(inputStr.getBytes(encoding)); + this.inputOctetStreamProxy = inputOctetStream; } /** @@ -193,19 +147,33 @@ public class XMLSignatureInput implements Cloneable { * * @param rootNode */ - public XMLSignatureInput(Node rootNode) - { - this._subNode = rootNode; + public XMLSignatureInput(Node rootNode) { + this.subNode = rootNode; } /** * Constructor XMLSignatureInput * * @param inputNodeSet - * @param usedXPathAPI */ public XMLSignatureInput(Set inputNodeSet) { - this._inputNodeSet = inputNodeSet; + this.inputNodeSet = inputNodeSet; + } + + /** + * Check if the structure needs to be expanded. + * @return true if so. + */ + public boolean isNeedsToBeExpanded() { + return needsToBeExpanded; + } + + /** + * Set if the structure needs to be expanded. + * @param needsToBeExpanded true if so. + */ + public void setNeedsToBeExpanded(boolean needsToBeExpanded) { + this.needsToBeExpanded = needsToBeExpanded; } /** @@ -218,11 +186,19 @@ public class XMLSignatureInput implements Cloneable { * @throws ParserConfigurationException * @throws CanonicalizationException */ - public Set getNodeSet() throws CanonicalizationException, - ParserConfigurationException, IOException, SAXException { + public Set getNodeSet() throws CanonicalizationException, ParserConfigurationException, + IOException, SAXException { return getNodeSet(false); } + /** + * Get the Input NodeSet. + * @return the Input NodeSet. + */ + public Set getInputNodeSet() { + return inputNodeSet; + } + /** * Returns the node set from input which was specified as the parameter of * {@link XMLSignatureInput} constructor @@ -234,51 +210,54 @@ public class XMLSignatureInput implements Cloneable { * @throws ParserConfigurationException * @throws CanonicalizationException */ - public Set getNodeSet(boolean circumvent) - throws ParserConfigurationException, IOException, SAXException, - CanonicalizationException { - if (this._inputNodeSet!=null) { - return this._inputNodeSet; + public Set getNodeSet(boolean circumvent) throws ParserConfigurationException, + IOException, SAXException, CanonicalizationException { + if (inputNodeSet != null) { + return inputNodeSet; } - if ((this._inputOctetStreamProxy==null)&& (this._subNode!=null) ) { - + if (inputOctetStreamProxy == null && subNode != null) { if (circumvent) { - XMLUtils.circumventBug2650(XMLUtils.getOwnerDocument(_subNode)); + XMLUtils.circumventBug2650(XMLUtils.getOwnerDocument(subNode)); } - this._inputNodeSet = new LinkedHashSet(); - XMLUtils.getSet(_subNode,this._inputNodeSet, excludeNode, this.excludeComments); - - return this._inputNodeSet; - } else if (this.isOctetStream()) { + inputNodeSet = new LinkedHashSet(); + XMLUtils.getSet(subNode, inputNodeSet, excludeNode, excludeComments); + return inputNodeSet; + } else if (isOctetStream()) { convertToNodes(); - LinkedHashSet result = new LinkedHashSet(); - XMLUtils.getSet(_subNode, result,null,false); - //this._inputNodeSet=result; + Set result = new LinkedHashSet(); + XMLUtils.getSet(subNode, result, null, false); return result; } - throw new RuntimeException( - "getNodeSet() called but no input data present"); + throw new RuntimeException("getNodeSet() called but no input data present"); } /** - * Returns the Octect stream(byte Stream) from input which was specified as + * Returns the Octet stream(byte Stream) from input which was specified as * the parameter of {@link XMLSignatureInput} constructor * - * @return the Octect stream(byte Stream) from input which was specified as + * @return the Octet stream(byte Stream) from input which was specified as * the parameter of {@link XMLSignatureInput} constructor * @throws IOException */ public InputStream getOctetStream() throws IOException { + if (inputOctetStreamProxy != null) { + return inputOctetStreamProxy; + } - return getResetableInputStream(); + if (bytes != null) { + inputOctetStreamProxy = new ByteArrayInputStream(bytes); + return inputOctetStreamProxy; + } + + return null; } /** - * @return real octect stream + * @return real octet stream */ - public InputStream getOctetStreamReal () { - return this._inputOctetStreamProxy; + public InputStream getOctetStreamReal() { + return inputOctetStreamProxy; } /** @@ -292,21 +271,12 @@ public class XMLSignatureInput implements Cloneable { * @throws IOException */ public byte[] getBytes() throws IOException, CanonicalizationException { - if (bytes!=null) { - return bytes; + byte[] inputBytes = getBytesFromInputStream(); + if (inputBytes != null) { + return inputBytes; } - InputStream is = getResetableInputStream(); - if (is!=null) { - //resetable can read again bytes. - if (bytes==null) { - is.reset(); - bytes=JavaUtils.getBytesFromStream(is); - } - return bytes; - } - Canonicalizer20010315OmitComments c14nizer = - new Canonicalizer20010315OmitComments(); - bytes=c14nizer.engineCanonicalize(this); + Canonicalizer20010315OmitComments c14nizer = new Canonicalizer20010315OmitComments(); + bytes = c14nizer.engineCanonicalize(this); return bytes; } @@ -316,18 +286,18 @@ public class XMLSignatureInput implements Cloneable { * @return true if the object has been set up with a Node set */ public boolean isNodeSet() { - return (( (this._inputOctetStreamProxy == null) - && (this._inputNodeSet != null) ) || isNodeSet); + return ((inputOctetStreamProxy == null + && inputNodeSet != null) || isNodeSet); } /** * Determines if the object has been set up with an Element * - * @return true if the object has been set up with a Node set + * @return true if the object has been set up with an Element */ public boolean isElement() { - return ((this._inputOctetStreamProxy==null)&& (this._subNode!=null) - && (this._inputNodeSet==null) && !isNodeSet); + return (inputOctetStreamProxy == null && subNode != null + && inputNodeSet == null && !isNodeSet); } /** @@ -336,8 +306,8 @@ public class XMLSignatureInput implements Cloneable { * @return true if the object has been set up with an octet stream */ public boolean isOctetStream() { - return ( ((this._inputOctetStreamProxy != null) || bytes!=null) - && ((this._inputNodeSet == null) && _subNode ==null)); + return ((inputOctetStreamProxy != null || bytes != null) + && (inputNodeSet == null && subNode == null)); } /** @@ -357,8 +327,7 @@ public class XMLSignatureInput implements Cloneable { * @return true is the object has been set up with an octet stream */ public boolean isByteArray() { - return ( (bytes!=null) - && ((this._inputNodeSet == null) && _subNode ==null)); + return (bytes != null && (this.inputNodeSet == null && subNode == null)); } /** @@ -367,25 +336,25 @@ public class XMLSignatureInput implements Cloneable { * @return true if the object has been set up correctly */ public boolean isInitialized() { - return (this.isOctetStream() || this.isNodeSet()); + return isOctetStream() || isNodeSet(); } /** - * Returns MIMEType + * Returns mimeType * - * @return MIMEType + * @return mimeType */ public String getMIMEType() { - return this._MIMEType; + return mimeType; } /** - * Sets MIMEType + * Sets mimeType * - * @param MIMEType + * @param mimeType */ - public void setMIMEType(String MIMEType) { - this._MIMEType = MIMEType; + public void setMIMEType(String mimeType) { + this.mimeType = mimeType; } /** @@ -394,16 +363,16 @@ public class XMLSignatureInput implements Cloneable { * @return SourceURI */ public String getSourceURI() { - return this._SourceURI; + return sourceURI; } /** * Sets SourceURI * - * @param SourceURI + * @param sourceURI */ - public void setSourceURI(String SourceURI) { - this._SourceURI = SourceURI; + public void setSourceURI(String sourceURI) { + this.sourceURI = sourceURI; } /** @@ -411,22 +380,22 @@ public class XMLSignatureInput implements Cloneable { * @inheritDoc */ public String toString() { - if (this.isNodeSet()) { - return "XMLSignatureInput/NodeSet/" + this._inputNodeSet.size() - + " nodes/" + this.getSourceURI(); + if (isNodeSet()) { + return "XMLSignatureInput/NodeSet/" + inputNodeSet.size() + + " nodes/" + getSourceURI(); } - if (this.isElement()) { - return "XMLSignatureInput/Element/" + this._subNode - + " exclude "+ this.excludeNode + " comments:" + - this.excludeComments +"/" + this.getSourceURI(); + if (isElement()) { + return "XMLSignatureInput/Element/" + subNode + + " exclude "+ excludeNode + " comments:" + + excludeComments +"/" + getSourceURI(); } try { - return "XMLSignatureInput/OctetStream/" + this.getBytes().length - + " octets/" + this.getSourceURI(); + return "XMLSignatureInput/OctetStream/" + getBytes().length + + " octets/" + getSourceURI(); } catch (IOException iex) { - return "XMLSignatureInput/OctetStream//" + this.getSourceURI(); + return "XMLSignatureInput/OctetStream//" + getSourceURI(); } catch (CanonicalizationException cex) { - return "XMLSignatureInput/OctetStream//" + this.getSourceURI(); + return "XMLSignatureInput/OctetStream//" + getSourceURI(); } } @@ -437,9 +406,7 @@ public class XMLSignatureInput implements Cloneable { * @return The HTML representation for this XMLSignature */ public String getHTMLRepresentation() throws XMLSignatureException { - XMLSignatureInputDebugger db = new XMLSignatureInputDebugger(this); - return db.getHTMLRepresentation(); } @@ -451,11 +418,9 @@ public class XMLSignatureInput implements Cloneable { * @return The HTML representation for this XMLSignature */ public String getHTMLRepresentation(Set inclusiveNamespaces) - throws XMLSignatureException { - - XMLSignatureInputDebugger db = new XMLSignatureInputDebugger( this, - inclusiveNamespaces); - + throws XMLSignatureException { + XMLSignatureInputDebugger db = + new XMLSignatureInputDebugger(this, inclusiveNamespaces); return db.getHTMLRepresentation(); } @@ -480,7 +445,7 @@ public class XMLSignatureInput implements Cloneable { * @return The excludeNode set. */ public Node getSubNode() { - return _subNode; + return subNode; } /** @@ -503,19 +468,18 @@ public class XMLSignatureInput implements Cloneable { * @throws CanonicalizationException */ public void updateOutputStream(OutputStream diOs) - throws CanonicalizationException, IOException { + throws CanonicalizationException, IOException { updateOutputStream(diOs, false); } public void updateOutputStream(OutputStream diOs, boolean c14n11) - throws CanonicalizationException, IOException { - if (diOs==outputStream) { + throws CanonicalizationException, IOException { + if (diOs == outputStream) { return; } - if (bytes!=null) { + if (bytes != null) { diOs.write(bytes); - return; - } else if (_inputOctetStreamProxy==null) { + } else if (inputOctetStreamProxy == null) { CanonicalizerBase c14nizer = null; if (c14n11) { c14nizer = new Canonicalizer11_OmitComments(); @@ -524,19 +488,16 @@ public class XMLSignatureInput implements Cloneable { } c14nizer.setWriter(diOs); c14nizer.engineCanonicalize(this); - return; } else { - InputStream is = getResetableInputStream(); - if (bytes!=null) { - //already read write it, can be rea. - diOs.write(bytes,0,bytes.length); - return; - } - is.reset(); - int num; - byte[] bytesT = new byte[1024]; - while ((num=is.read(bytesT))>0) { - diOs.write(bytesT,0,num); + byte[] buffer = new byte[4 * 1024]; + int bytesread = 0; + try { + while ((bytesread = inputOctetStreamProxy.read(buffer)) != -1) { + diOs.write(buffer, 0, bytesread); + } + } catch (IOException ex) { + inputOctetStreamProxy.close(); + throw ex; } } } @@ -545,29 +506,22 @@ public class XMLSignatureInput implements Cloneable { * @param os */ public void setOutputStream(OutputStream os) { - outputStream=os; + outputStream = os; } - protected InputStream getResetableInputStream() throws IOException{ - if ((_inputOctetStreamProxy instanceof ByteArrayInputStream) ) { - if (!_inputOctetStreamProxy.markSupported()) { - throw new RuntimeException("Accepted as Markable but not truly been"+_inputOctetStreamProxy); - } - return _inputOctetStreamProxy; + private byte[] getBytesFromInputStream() throws IOException { + if (bytes != null) { + return bytes; } - if (bytes!=null) { - _inputOctetStreamProxy=new ByteArrayInputStream(bytes); - return _inputOctetStreamProxy; - } - if (_inputOctetStreamProxy ==null) + if (inputOctetStreamProxy == null) { return null; - if (_inputOctetStreamProxy.markSupported()) { - log.log(java.util.logging.Level.INFO, "Mark Suported but not used as reset"); } - bytes=JavaUtils.getBytesFromStream(_inputOctetStreamProxy); - _inputOctetStreamProxy.close(); - _inputOctetStreamProxy=new ByteArrayInputStream(bytes); - return _inputOctetStreamProxy; + try { + bytes = JavaUtils.getBytesFromStream(inputOctetStreamProxy); + } finally { + inputOctetStreamProxy.close(); + } + return bytes; } /** @@ -578,7 +532,9 @@ public class XMLSignatureInput implements Cloneable { try { convertToNodes(); } catch (Exception e) { - throw new XMLSecurityRuntimeException("signature.XMLSignatureInput.nodesetReference",e); + throw new XMLSecurityRuntimeException( + "signature.XMLSignatureInput.nodesetReference", e + ); } } nodeFilters.add(filter); @@ -588,7 +544,6 @@ public class XMLSignatureInput implements Cloneable { * @return the node filters */ public List getNodeFilters() { - // TODO Auto-generated method stub return nodeFilters; } @@ -596,39 +551,42 @@ public class XMLSignatureInput implements Cloneable { * @param b */ public void setNodeSet(boolean b) { - isNodeSet=b; + isNodeSet = b; } void convertToNodes() throws CanonicalizationException, ParserConfigurationException, IOException, SAXException { - DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); - dfactory.setValidating(false); - dfactory.setNamespaceAware(true); - dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, - Boolean.TRUE); + if (dfactory == null) { + dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + dfactory.setValidating(false); + dfactory.setNamespaceAware(true); + } DocumentBuilder db = dfactory.newDocumentBuilder(); // select all nodes, also the comments. try { - db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils - .IgnoreAllErrorHandler()); + db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler()); Document doc = db.parse(this.getOctetStream()); - - this._subNode=doc.getDocumentElement(); + this.subNode = doc; } catch (SAXException ex) { - // if a not-wellformed nodeset exists, put a container around it... ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write("".getBytes()); + baos.write("".getBytes("UTF-8")); baos.write(this.getBytes()); - baos.write("".getBytes()); + baos.write("".getBytes("UTF-8")); byte result[] = baos.toByteArray(); Document document = db.parse(new ByteArrayInputStream(result)); - this._subNode=document.getDocumentElement().getFirstChild().getFirstChild(); + this.subNode = document.getDocumentElement().getFirstChild().getFirstChild(); + } finally { + if (this.inputOctetStreamProxy != null) { + this.inputOctetStreamProxy.close(); + } + this.inputOctetStreamProxy = null; + this.bytes = null; } - this._inputOctetStreamProxy=null; - this.bytes=null; } + } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java index 3186ef4d6a8..e565b22aeee 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.signature; @@ -38,681 +40,591 @@ import org.w3c.dom.ProcessingInstruction; /** * Class XMLSignatureInputDebugger - * - * @author $Author: mullan $ - * @version $Revision: 1.3 $ */ public class XMLSignatureInputDebugger { + /** Field _xmlSignatureInput */ + private Set xpathNodeSet; + private Set inclusiveNamespaces; - /** Field _xmlSignatureInput */ - private Set _xpathNodeSet; + /** Field doc */ + private Document doc = null; - private Set _inclusiveNamespaces; + /** Field writer */ + private Writer writer = null; - /** Field _doc */ - private Document _doc = null; + /** The HTML Prefix* */ + static final String HTMLPrefix = + "\n" + + "\n" + + "\n" + + "Caninical XML node set\n" + + " \n" + + "\n" + + "\n" + + "

    Explanation of the output

    \n" + + "

    The following text contains the nodeset of the given Reference before it is canonicalized. There exist four different styles to indicate how a given node is treated.

    \n" + + "
      \n" + + "
    • A node which is in the node set is labeled using the INCLUDED style.
    • \n" + + "
    • A node which is NOT in the node set is labeled EXCLUDED style.
    • \n" + + "
    • A namespace which is in the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.
    • \n" + + "
    • A namespace which is in NOT the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.
    • \n" + + "
    \n" + "

    Output

    \n" + "
    \n";
     
    -        /** Field _writer */
    -        private Writer _writer = null;
    +    /** HTML Suffix * */
    +    static final String HTMLSuffix = "
    "; - // J- - // public static final String HTMLPrefix = "
    ";
    -        /** The HTML Prefix* */
    -        static final String HTMLPrefix = "\n"
    -                        + "\n"
    -                        + "\n"
    -                        + "Caninical XML node set\n"
    -                        + " \n"
    -                        + "\n"
    -                        + "\n"
    -                        + "

    Explanation of the output

    \n" - + "

    The following text contains the nodeset of the given Reference before it is canonicalized. There exist four different styles to indicate how a given node is treated.

    \n" - + "
      \n" - + "
    • A node which is in the node set is labeled using the INCLUDED style.
    • \n" - + "
    • A node which is NOT in the node set is labeled EXCLUDED style.
    • \n" - + "
    • A namespace which is in the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.
    • \n" - + "
    • A namespace which is in NOT the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.
    • \n" - + "
    \n" + "

    Output

    \n" + "
    \n";
    +    static final String HTMLExcludePrefix = "";
     
    -        /** HTML Suffix * */
    -        static final String HTMLSuffix = "
    "; + static final String HTMLIncludePrefix = ""; - static final String HTMLExcludePrefix = ""; + static final String HTMLIncludeOrExcludeSuffix = ""; - static final String HTMLExcludeSuffix = ""; + static final String HTMLIncludedInclusiveNamespacePrefix = ""; - static final String HTMLIncludePrefix = ""; + static final String HTMLExcludedInclusiveNamespacePrefix = ""; - static final String HTMLIncludeSuffix = ""; + private static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1; - static final String HTMLIncludedInclusiveNamespacePrefix = ""; + private static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0; - static final String HTMLIncludedInclusiveNamespaceSuffix = ""; + private static final int NODE_AFTER_DOCUMENT_ELEMENT = 1; - static final String HTMLExcludedInclusiveNamespacePrefix = ""; + static final AttrCompare ATTR_COMPARE = new AttrCompare(); - static final String HTMLExcludedInclusiveNamespaceSuffix = ""; + /** + * Constructor XMLSignatureInputDebugger + * + * @param xmlSignatureInput the signature to pretty print + */ + public XMLSignatureInputDebugger(XMLSignatureInput xmlSignatureInput) { + if (!xmlSignatureInput.isNodeSet()) { + this.xpathNodeSet = null; + } else { + this.xpathNodeSet = xmlSignatureInput.getInputNodeSet(); + } + } - private static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1; + /** + * Constructor XMLSignatureInputDebugger + * + * @param xmlSignatureInput the signatur to pretty print + * @param inclusiveNamespace + */ + public XMLSignatureInputDebugger( + XMLSignatureInput xmlSignatureInput, + Set inclusiveNamespace + ) { + this(xmlSignatureInput); + this.inclusiveNamespaces = inclusiveNamespace; + } - private static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0; - - private static final int NODE_AFTER_DOCUMENT_ELEMENT = 1; - - static final AttrCompare ATTR_COMPARE = new AttrCompare(); - - // J+ - private XMLSignatureInputDebugger() { - // do nothing + /** + * Method getHTMLRepresentation + * + * @return The HTML Representation. + * @throws XMLSignatureException + */ + public String getHTMLRepresentation() throws XMLSignatureException { + if ((this.xpathNodeSet == null) || (this.xpathNodeSet.size() == 0)) { + return HTMLPrefix + "no node set, sorry" + HTMLSuffix; } - /** - * Constructor XMLSignatureInputDebugger - * - * @param xmlSignatureInput the signatur to pretty print - */ - public XMLSignatureInputDebugger( - XMLSignatureInput xmlSignatureInput) { + // get only a single node as anchor to fetch the owner document + Node n = this.xpathNodeSet.iterator().next(); - if (!xmlSignatureInput.isNodeSet()) { - this._xpathNodeSet = null; + this.doc = XMLUtils.getOwnerDocument(n); + + try { + this.writer = new StringWriter(); + + this.canonicalizeXPathNodeSet(this.doc); + this.writer.close(); + + return this.writer.toString(); + } catch (IOException ex) { + throw new XMLSignatureException("empty", ex); + } finally { + this.xpathNodeSet = null; + this.doc = null; + this.writer = null; + } + } + + /** + * Method canonicalizeXPathNodeSet + * + * @param currentNode + * @throws XMLSignatureException + * @throws IOException + */ + private void canonicalizeXPathNodeSet(Node currentNode) + throws XMLSignatureException, IOException { + + int currentNodeType = currentNode.getNodeType(); + switch (currentNodeType) { + + + case Node.ENTITY_NODE: + case Node.NOTATION_NODE: + case Node.DOCUMENT_FRAGMENT_NODE: + case Node.ATTRIBUTE_NODE: + throw new XMLSignatureException("empty"); + case Node.DOCUMENT_NODE: + this.writer.write(HTMLPrefix); + + for (Node currentChild = currentNode.getFirstChild(); + currentChild != null; currentChild = currentChild.getNextSibling()) { + this.canonicalizeXPathNodeSet(currentChild); + } + + this.writer.write(HTMLSuffix); + break; + + case Node.COMMENT_NODE: + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + int position = getPositionRelativeToDocumentElement(currentNode); + + if (position == NODE_AFTER_DOCUMENT_ELEMENT) { + this.writer.write("\n"); + } + + this.outputCommentToWriter((Comment) currentNode); + + if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { + this.writer.write("\n"); + } + + this.writer.write(HTMLIncludeOrExcludeSuffix); + break; + + case Node.PROCESSING_INSTRUCTION_NODE: + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + position = getPositionRelativeToDocumentElement(currentNode); + + if (position == NODE_AFTER_DOCUMENT_ELEMENT) { + this.writer.write("\n"); + } + + this.outputPItoWriter((ProcessingInstruction) currentNode); + + if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { + this.writer.write("\n"); + } + + this.writer.write(HTMLIncludeOrExcludeSuffix); + break; + + case Node.TEXT_NODE: + case Node.CDATA_SECTION_NODE: + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + outputTextToWriter(currentNode.getNodeValue()); + + for (Node nextSibling = currentNode.getNextSibling(); + (nextSibling != null) + && ((nextSibling.getNodeType() == Node.TEXT_NODE) + || (nextSibling.getNodeType() == Node.CDATA_SECTION_NODE)); + nextSibling = nextSibling.getNextSibling()) { + /* + * The XPath data model allows to select only the first of a + * sequence of mixed text and CDATA nodes. But we must output + * them all, so we must search: + * + * @see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=6329 + */ + this.outputTextToWriter(nextSibling.getNodeValue()); + } + + this.writer.write(HTMLIncludeOrExcludeSuffix); + break; + + case Node.ELEMENT_NODE: + Element currentElement = (Element) currentNode; + + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + this.writer.write("<"); + this.writer.write(currentElement.getTagName()); + + this.writer.write(HTMLIncludeOrExcludeSuffix); + + // we output all Attrs which are available + NamedNodeMap attrs = currentElement.getAttributes(); + int attrsLength = attrs.getLength(); + Attr attrs2[] = new Attr[attrsLength]; + + for (int i = 0; i < attrsLength; i++) { + attrs2[i] = (Attr)attrs.item(i); + } + + Arrays.sort(attrs2, ATTR_COMPARE); + Object attrs3[] = attrs2; + + for (int i = 0; i < attrsLength; i++) { + Attr a = (Attr) attrs3[i]; + boolean included = this.xpathNodeSet.contains(a); + boolean inclusive = this.inclusiveNamespaces.contains(a.getName()); + + if (included) { + if (inclusive) { + // included and inclusive + this.writer.write(HTMLIncludedInclusiveNamespacePrefix); + } else { + // included and not inclusive + this.writer.write(HTMLIncludePrefix); + } } else { - this._xpathNodeSet = xmlSignatureInput._inputNodeSet; - } - } - - /** - * Constructor XMLSignatureInputDebugger - * - * @param xmlSignatureInput the signatur to pretty print - * @param inclusiveNamespace - */ - public XMLSignatureInputDebugger( - XMLSignatureInput xmlSignatureInput, Set inclusiveNamespace) { - - this(xmlSignatureInput); - - this._inclusiveNamespaces = inclusiveNamespace; - } - - /** - * Method getHTMLRepresentation - * - * @return The HTML Representation. - * @throws XMLSignatureException - */ - public String getHTMLRepresentation() throws XMLSignatureException { - - if ((this._xpathNodeSet == null) || (this._xpathNodeSet.size() == 0)) { - return HTMLPrefix + "no node set, sorry" - + HTMLSuffix; - } - - { - - // get only a single node as anchor to fetch the owner document - Node n = this._xpathNodeSet.iterator().next(); - - this._doc = XMLUtils.getOwnerDocument(n); - } - - try { - this._writer = new StringWriter(); - - this.canonicalizeXPathNodeSet(this._doc); - this._writer.close(); - - return this._writer.toString(); - } catch (IOException ex) { - throw new XMLSignatureException("empty", ex); - } finally { - this._xpathNodeSet = null; - this._doc = null; - this._writer = null; - } - } - - /** - * Method canonicalizeXPathNodeSet - * - * @param currentNode - * @throws XMLSignatureException - * @throws IOException - */ - private void canonicalizeXPathNodeSet(Node currentNode) - throws XMLSignatureException, IOException { - - int currentNodeType = currentNode.getNodeType(); - switch (currentNodeType) { - - case Node.DOCUMENT_TYPE_NODE: - default: - break; - - case Node.ENTITY_NODE: - case Node.NOTATION_NODE: - case Node.DOCUMENT_FRAGMENT_NODE: - case Node.ATTRIBUTE_NODE: - throw new XMLSignatureException("empty"); - case Node.DOCUMENT_NODE: - this._writer.write(HTMLPrefix); - - for (Node currentChild = currentNode.getFirstChild(); currentChild != null; currentChild = currentChild - .getNextSibling()) { - this.canonicalizeXPathNodeSet(currentChild); - } - - this._writer.write(HTMLSuffix); - break; - - case Node.COMMENT_NODE: - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - int position = getPositionRelativeToDocumentElement(currentNode); - - if (position == NODE_AFTER_DOCUMENT_ELEMENT) { - this._writer.write("\n"); - } - - this.outputCommentToWriter((Comment) currentNode); - - if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { - this._writer.write("\n"); - } - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - break; - - case Node.PROCESSING_INSTRUCTION_NODE: - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - position = getPositionRelativeToDocumentElement(currentNode); - - if (position == NODE_AFTER_DOCUMENT_ELEMENT) { - this._writer.write("\n"); - } - - this.outputPItoWriter((ProcessingInstruction) currentNode); - - if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { - this._writer.write("\n"); - } - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - break; - - case Node.TEXT_NODE: - case Node.CDATA_SECTION_NODE: - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - outputTextToWriter(currentNode.getNodeValue()); - - for (Node nextSibling = currentNode.getNextSibling(); (nextSibling != null) - && ((nextSibling.getNodeType() == Node.TEXT_NODE) || (nextSibling - .getNodeType() == Node.CDATA_SECTION_NODE)); nextSibling = nextSibling - .getNextSibling()) { - - /* - * The XPath data model allows to select only the first of a - * sequence of mixed text and CDATA nodes. But we must output - * them all, so we must search: - * - * @see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=6329 - */ - this.outputTextToWriter(nextSibling.getNodeValue()); - } - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - break; - - case Node.ELEMENT_NODE: - Element currentElement = (Element) currentNode; - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - this._writer.write("<"); - this._writer.write(currentElement.getTagName()); - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - - // we output all Attrs which are available - NamedNodeMap attrs = currentElement.getAttributes(); - int attrsLength = attrs.getLength(); - Attr attrs2[] = new Attr[attrsLength]; - - for (int i = 0; i < attrsLength; i++) { - attrs2[i] = (Attr)attrs.item(i); - } - - Arrays.sort(attrs2, ATTR_COMPARE); - Object attrs3[] = attrs2; - - for (int i = 0; i < attrsLength; i++) { - Attr a = (Attr) attrs3[i]; - boolean included = this._xpathNodeSet.contains(a); - boolean inclusive = this._inclusiveNamespaces.contains(a - .getName()); - - if (included) { - if (inclusive) { - - // included and inclusive - this._writer - .write(HTMLIncludedInclusiveNamespacePrefix); - } else { - - // included and not inclusive - this._writer.write(HTMLIncludePrefix); - } - } else { - if (inclusive) { - - // excluded and inclusive - this._writer - .write(HTMLExcludedInclusiveNamespacePrefix); - } else { - - // excluded and not inclusive - this._writer.write(HTMLExcludePrefix); - } - } - - this.outputAttrToWriter(a.getNodeName(), a.getNodeValue()); - - if (included) { - if (inclusive) { - - // included and inclusive - this._writer - .write(HTMLIncludedInclusiveNamespaceSuffix); - } else { - - // included and not inclusive - this._writer.write(HTMLIncludeSuffix); - } - } else { - if (inclusive) { - - // excluded and inclusive - this._writer - .write(HTMLExcludedInclusiveNamespaceSuffix); - } else { - - // excluded and not inclusive - this._writer.write(HTMLExcludeSuffix); - } - } - } - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - this._writer.write(">"); - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - - // traversal - for (Node currentChild = currentNode.getFirstChild(); currentChild != null; currentChild = currentChild - .getNextSibling()) { - this.canonicalizeXPathNodeSet(currentChild); - } - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - this._writer.write("</"); - this._writer.write(currentElement.getTagName()); - this._writer.write(">"); - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - break; - } - } - - /** - * Checks whether a Comment or ProcessingInstruction is before or after the - * document element. This is needed for prepending or appending "\n"s. - * - * @param currentNode - * comment or pi to check - * @return NODE_BEFORE_DOCUMENT_ELEMENT, - * NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT or - * NODE_AFTER_DOCUMENT_ELEMENT - * @see #NODE_BEFORE_DOCUMENT_ELEMENT - * @see #NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT - * @see #NODE_AFTER_DOCUMENT_ELEMENT - */ - private int getPositionRelativeToDocumentElement(Node currentNode) { - - if (currentNode == null) { - return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - } - - Document doc = currentNode.getOwnerDocument(); - - if (currentNode.getParentNode() != doc) { - return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - } - - Element documentElement = doc.getDocumentElement(); - - if (documentElement == null) { - return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - } - - if (documentElement == currentNode) { - return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - } - - for (Node x = currentNode; x != null; x = x.getNextSibling()) { - if (x == documentElement) { - return NODE_BEFORE_DOCUMENT_ELEMENT; - } - } - - return NODE_AFTER_DOCUMENT_ELEMENT; - } - - /** - * Normalizes an {@link Attr}ibute value - * - * The string value of the node is modified by replacing - *
      - *
    • all ampersands (&) with &amp;
    • - *
    • all open angle brackets (<) with &lt;
    • - *
    • all quotation mark characters with &quot;
    • - *
    • and the whitespace characters #x9, #xA, and #xD, - * with character references. The character references are written in - * uppercase hexadecimal with no leading zeroes (for example, #xD - * is represented by the character reference &#xD;)
    • - *
    - * - * @param name - * @param value - * @throws IOException - */ - private void outputAttrToWriter(String name, String value) - throws IOException { - - this._writer.write(" "); - this._writer.write(name); - this._writer.write("=\""); - - int length = value.length(); - - for (int i = 0; i < length; i++) { - char c = value.charAt(i); - - switch (c) { - - case '&': - this._writer.write("&amp;"); - break; - - case '<': - this._writer.write("&lt;"); - break; - - case '"': - this._writer.write("&quot;"); - break; - - case 0x09: // '\t' - this._writer.write("&#x9;"); - break; - - case 0x0A: // '\n' - this._writer.write("&#xA;"); - break; - - case 0x0D: // '\r' - this._writer.write("&#xD;"); - break; - - default: - this._writer.write(c); - break; - } - } - - this._writer.write("\""); - } - - /** - * Normalizes a {@link org.w3c.dom.Comment} value - * - * @param currentPI - * @throws IOException - */ - private void outputPItoWriter(ProcessingInstruction currentPI) - throws IOException { - - if (currentPI == null) { - return; - } - - this._writer.write("<?"); - - String target = currentPI.getTarget(); - int length = target.length(); - - for (int i = 0; i < length; i++) { - char c = target.charAt(i); - - switch (c) { - - case 0x0D: - this._writer.write("&#xD;"); - break; - - case ' ': - this._writer.write("·"); - break; - - case '\n': - this._writer.write("¶\n"); - break; - - default: - this._writer.write(c); - break; - } - } - - String data = currentPI.getData(); - - length = data.length(); - - if (length > 0) { - this._writer.write(" "); - - for (int i = 0; i < length; i++) { - char c = data.charAt(i); - - switch (c) { - - case 0x0D: - this._writer.write("&#xD;"); - break; - - default: - this._writer.write(c); - break; - } + if (inclusive) { + // excluded and inclusive + this.writer.write(HTMLExcludedInclusiveNamespacePrefix); + } else { + // excluded and not inclusive + this.writer.write(HTMLExcludePrefix); } } - this._writer.write("?>"); + this.outputAttrToWriter(a.getNodeName(), a.getNodeValue()); + this.writer.write(HTMLIncludeOrExcludeSuffix); + } + + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + this.writer.write(">"); + + this.writer.write(HTMLIncludeOrExcludeSuffix); + + // traversal + for (Node currentChild = currentNode.getFirstChild(); + currentChild != null; + currentChild = currentChild.getNextSibling()) { + this.canonicalizeXPathNodeSet(currentChild); + } + + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + this.writer.write("</"); + this.writer.write(currentElement.getTagName()); + this.writer.write(">"); + + this.writer.write(HTMLIncludeOrExcludeSuffix); + break; + + case Node.DOCUMENT_TYPE_NODE: + default: + break; + } + } + + /** + * Checks whether a Comment or ProcessingInstruction is before or after the + * document element. This is needed for prepending or appending "\n"s. + * + * @param currentNode + * comment or pi to check + * @return NODE_BEFORE_DOCUMENT_ELEMENT, + * NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT or + * NODE_AFTER_DOCUMENT_ELEMENT + * @see #NODE_BEFORE_DOCUMENT_ELEMENT + * @see #NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT + * @see #NODE_AFTER_DOCUMENT_ELEMENT + */ + private int getPositionRelativeToDocumentElement(Node currentNode) { + if (currentNode == null) { + return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; } - /** - * Method outputCommentToWriter - * - * @param currentComment - * @throws IOException - */ - private void outputCommentToWriter(Comment currentComment) - throws IOException { + Document doc = currentNode.getOwnerDocument(); - if (currentComment == null) { - return; - } - - this._writer.write("<!--"); - - String data = currentComment.getData(); - int length = data.length(); - - for (int i = 0; i < length; i++) { - char c = data.charAt(i); - - switch (c) { - - case 0x0D: - this._writer.write("&#xD;"); - break; - - case ' ': - this._writer.write("·"); - break; - - case '\n': - this._writer.write("¶\n"); - break; - - default: - this._writer.write(c); - break; - } - } - - this._writer.write("-->"); + if (currentNode.getParentNode() != doc) { + return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; } - /** - * Method outputTextToWriter - * - * @param text - * @throws IOException - */ - private void outputTextToWriter(String text) throws IOException { + Element documentElement = doc.getDocumentElement(); - if (text == null) { - return; - } - - int length = text.length(); - - for (int i = 0; i < length; i++) { - char c = text.charAt(i); - - switch (c) { - - case '&': - this._writer.write("&amp;"); - break; - - case '<': - this._writer.write("&lt;"); - break; - - case '>': - this._writer.write("&gt;"); - break; - - case 0xD: - this._writer.write("&#xD;"); - break; - - case ' ': - this._writer.write("·"); - break; - - case '\n': - this._writer.write("¶\n"); - break; - - default: - this._writer.write(c); - break; - } - } + if (documentElement == null) { + return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; } + + if (documentElement == currentNode) { + return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; + } + + for (Node x = currentNode; x != null; x = x.getNextSibling()) { + if (x == documentElement) { + return NODE_BEFORE_DOCUMENT_ELEMENT; + } + } + + return NODE_AFTER_DOCUMENT_ELEMENT; + } + + /** + * Normalizes an {@link Attr}ibute value + * + * The string value of the node is modified by replacing + *
      + *
    • all ampersands (&) with &amp;
    • + *
    • all open angle brackets (<) with &lt;
    • + *
    • all quotation mark characters with &quot;
    • + *
    • and the whitespace characters #x9, #xA, and #xD, + * with character references. The character references are written in + * uppercase hexadecimal with no leading zeroes (for example, #xD + * is represented by the character reference &#xD;)
    • + *
    + * + * @param name + * @param value + * @throws IOException + */ + private void outputAttrToWriter(String name, String value) throws IOException { + this.writer.write(" "); + this.writer.write(name); + this.writer.write("=\""); + + int length = value.length(); + + for (int i = 0; i < length; i++) { + char c = value.charAt(i); + + switch (c) { + + case '&': + this.writer.write("&amp;"); + break; + + case '<': + this.writer.write("&lt;"); + break; + + case '"': + this.writer.write("&quot;"); + break; + + case 0x09: // '\t' + this.writer.write("&#x9;"); + break; + + case 0x0A: // '\n' + this.writer.write("&#xA;"); + break; + + case 0x0D: // '\r' + this.writer.write("&#xD;"); + break; + + default: + this.writer.write(c); + break; + } + } + + this.writer.write("\""); + } + + /** + * Normalizes a {@link org.w3c.dom.Comment} value + * + * @param currentPI + * @throws IOException + */ + private void outputPItoWriter(ProcessingInstruction currentPI) throws IOException { + + if (currentPI == null) { + return; + } + + this.writer.write("<?"); + + String target = currentPI.getTarget(); + int length = target.length(); + + for (int i = 0; i < length; i++) { + char c = target.charAt(i); + + switch (c) { + + case 0x0D: + this.writer.write("&#xD;"); + break; + + case ' ': + this.writer.write("·"); + break; + + case '\n': + this.writer.write("¶\n"); + break; + + default: + this.writer.write(c); + break; + } + } + + String data = currentPI.getData(); + + length = data.length(); + + if (length > 0) { + this.writer.write(" "); + + for (int i = 0; i < length; i++) { + char c = data.charAt(i); + + switch (c) { + + case 0x0D: + this.writer.write("&#xD;"); + break; + + default: + this.writer.write(c); + break; + } + } + } + + this.writer.write("?>"); + } + + /** + * Method outputCommentToWriter + * + * @param currentComment + * @throws IOException + */ + private void outputCommentToWriter(Comment currentComment) throws IOException { + + if (currentComment == null) { + return; + } + + this.writer.write("<!--"); + + String data = currentComment.getData(); + int length = data.length(); + + for (int i = 0; i < length; i++) { + char c = data.charAt(i); + + switch (c) { + + case 0x0D: + this.writer.write("&#xD;"); + break; + + case ' ': + this.writer.write("·"); + break; + + case '\n': + this.writer.write("¶\n"); + break; + + default: + this.writer.write(c); + break; + } + } + + this.writer.write("-->"); + } + + /** + * Method outputTextToWriter + * + * @param text + * @throws IOException + */ + private void outputTextToWriter(String text) throws IOException { + if (text == null) { + return; + } + + int length = text.length(); + + for (int i = 0; i < length; i++) { + char c = text.charAt(i); + + switch (c) { + + case '&': + this.writer.write("&amp;"); + break; + + case '<': + this.writer.write("&lt;"); + break; + + case '>': + this.writer.write("&gt;"); + break; + + case 0xD: + this.writer.write("&#xD;"); + break; + + case ' ': + this.writer.write("·"); + break; + + case '\n': + this.writer.write("¶\n"); + break; + + default: + this.writer.write(c); + break; + } + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceData.java new file mode 100644 index 00000000000..81de122aead --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceData.java @@ -0,0 +1,34 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ +/* + * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + */ +/* + * $Id$ + */ +package com.sun.org.apache.xml.internal.security.signature.reference; + +/** + * An abstract representation of the result of dereferencing a ds:Reference URI. + */ +public interface ReferenceData { } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceNodeSetData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceNodeSetData.java new file mode 100644 index 00000000000..dc18c427eb7 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceNodeSetData.java @@ -0,0 +1,53 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ +/* + * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + */ +/* + * $Id$ + */ +package com.sun.org.apache.xml.internal.security.signature.reference; + +import java.util.Iterator; + +import org.w3c.dom.Node; + +/** + * An abstract representation of a ReferenceData type containing a node-set. + */ +public interface ReferenceNodeSetData extends ReferenceData { + + /** + * Returns a read-only iterator over the nodes contained in this + * NodeSetData in + * + * document order. Attempts to modify the returned iterator + * via the remove method throw + * UnsupportedOperationException. + * + * @return an Iterator over the nodes in this + * NodeSetData in document order + */ + Iterator iterator(); + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceOctetStreamData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceOctetStreamData.java new file mode 100644 index 00000000000..0f59fb95bcf --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceOctetStreamData.java @@ -0,0 +1,105 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ +/* + * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + */ +/* + * $Id$ + */ +package com.sun.org.apache.xml.internal.security.signature.reference; + +import java.io.InputStream; + +/** + * A representation of a ReferenceData type containing an OctetStream. + */ +public class ReferenceOctetStreamData implements ReferenceData { + private InputStream octetStream; + private String uri; + private String mimeType; + + /** + * Creates a new ReferenceOctetStreamData. + * + * @param octetStream the input stream containing the octets + * @throws NullPointerException if octetStream is + * null + */ + public ReferenceOctetStreamData(InputStream octetStream) { + if (octetStream == null) { + throw new NullPointerException("octetStream is null"); + } + this.octetStream = octetStream; + } + + /** + * Creates a new ReferenceOctetStreamData. + * + * @param octetStream the input stream containing the octets + * @param uri the URI String identifying the data object (may be + * null) + * @param mimeType the MIME type associated with the data object (may be + * null) + * @throws NullPointerException if octetStream is + * null + */ + public ReferenceOctetStreamData(InputStream octetStream, String uri, + String mimeType) { + if (octetStream == null) { + throw new NullPointerException("octetStream is null"); + } + this.octetStream = octetStream; + this.uri = uri; + this.mimeType = mimeType; + } + + /** + * Returns the input stream of this ReferenceOctetStreamData. + * + * @return the input stream of this ReferenceOctetStreamData. + */ + public InputStream getOctetStream() { + return octetStream; + } + + /** + * Returns the URI String identifying the data object represented by this + * ReferenceOctetStreamData. + * + * @return the URI String or null if not applicable + */ + public String getURI() { + return uri; + } + + /** + * Returns the MIME type associated with the data object represented by this + * ReferenceOctetStreamData. + * + * @return the MIME type or null if not applicable + */ + public String getMimeType() { + return mimeType; + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java new file mode 100644 index 00000000000..cfa45e0435a --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java @@ -0,0 +1,181 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ +/* + * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + */ +/* + * $Id$ + */ +package com.sun.org.apache.xml.internal.security.signature.reference; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.NoSuchElementException; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; + +/** + * A representation of a ReferenceNodeSetData type containing a node-set. + * This is a subtype of NodeSetData that represents a dereferenced + * same-document URI as the root of a subdocument. The main reason is + * for efficiency and performance, as some transforms can operate + * directly on the subdocument and there is no need to convert it + * first to an XPath node-set. + */ +public class ReferenceSubTreeData implements ReferenceNodeSetData { + + private boolean excludeComments; + private Node root; + + public ReferenceSubTreeData(Node root, boolean excludeComments) { + this.root = root; + this.excludeComments = excludeComments; + } + + public Iterator iterator() { + return new DelayedNodeIterator(root, excludeComments); + } + + public Node getRoot() { + return root; + } + + public boolean excludeComments() { + return excludeComments; + } + + /** + * This is an Iterator that contains a backing node-set that is + * not populated until the caller first attempts to advance the iterator. + */ + static class DelayedNodeIterator implements Iterator { + private Node root; + private List nodeSet; + private ListIterator li; + private boolean withComments; + + DelayedNodeIterator(Node root, boolean excludeComments) { + this.root = root; + this.withComments = !excludeComments; + } + + public boolean hasNext() { + if (nodeSet == null) { + nodeSet = dereferenceSameDocumentURI(root); + li = nodeSet.listIterator(); + } + return li.hasNext(); + } + + public Node next() { + if (nodeSet == null) { + nodeSet = dereferenceSameDocumentURI(root); + li = nodeSet.listIterator(); + } + if (li.hasNext()) { + return li.next(); + } else { + throw new NoSuchElementException(); + } + } + + public void remove() { + throw new UnsupportedOperationException(); + } + + /** + * Dereferences a same-document URI fragment. + * + * @param node the node (document or element) referenced by the + * URI fragment. If null, returns an empty set. + * @return a set of nodes (minus any comment nodes) + */ + private List dereferenceSameDocumentURI(Node node) { + List nodeSet = new ArrayList(); + if (node != null) { + nodeSetMinusCommentNodes(node, nodeSet, null); + } + return nodeSet; + } + + /** + * Recursively traverses the subtree, and returns an XPath-equivalent + * node-set of all nodes traversed, excluding any comment nodes, + * if specified. + * + * @param node the node to traverse + * @param nodeSet the set of nodes traversed so far + * @param the previous sibling node + */ + @SuppressWarnings("fallthrough") + private void nodeSetMinusCommentNodes(Node node, List nodeSet, + Node prevSibling) + { + switch (node.getNodeType()) { + case Node.ELEMENT_NODE : + nodeSet.add(node); + NamedNodeMap attrs = node.getAttributes(); + if (attrs != null) { + for (int i = 0, len = attrs.getLength(); i < len; i++) { + nodeSet.add(attrs.item(i)); + } + } + Node pSibling = null; + for (Node child = node.getFirstChild(); child != null; + child = child.getNextSibling()) { + nodeSetMinusCommentNodes(child, nodeSet, pSibling); + pSibling = child; + } + break; + case Node.DOCUMENT_NODE : + pSibling = null; + for (Node child = node.getFirstChild(); child != null; + child = child.getNextSibling()) { + nodeSetMinusCommentNodes(child, nodeSet, pSibling); + pSibling = child; + } + break; + case Node.TEXT_NODE : + case Node.CDATA_SECTION_NODE: + // emulate XPath which only returns the first node in + // contiguous text/cdata nodes + if (prevSibling != null && + (prevSibling.getNodeType() == Node.TEXT_NODE || + prevSibling.getNodeType() == Node.CDATA_SECTION_NODE)) { + return; + } + nodeSet.add(node); + break; + case Node.PROCESSING_INSTRUCTION_NODE : + nodeSet.add(node); + break; + case Node.COMMENT_NODE: + if (withComments) { + nodeSet.add(node); + } + } + } + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java index 2236e950853..68ceb3bf243 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java @@ -2,86 +2,84 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - /** * * @author Christian Geuer-Pollmann */ public class InvalidTransformException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor InvalidTransformException - * - */ - public InvalidTransformException() { - super(); - } + /** + * Constructor InvalidTransformException + * + */ + public InvalidTransformException() { + super(); + } - /** - * Constructor InvalidTransformException - * - * @param _msgId - */ - public InvalidTransformException(String _msgId) { - super(_msgId); - } + /** + * Constructor InvalidTransformException + * + * @param msgId + */ + public InvalidTransformException(String msgId) { + super(msgId); + } - /** - * Constructor InvalidTransformException - * - * @param _msgId - * @param exArgs - */ - public InvalidTransformException(String _msgId, Object exArgs[]) { - super(_msgId, exArgs); - } + /** + * Constructor InvalidTransformException + * + * @param msgId + * @param exArgs + */ + public InvalidTransformException(String msgId, Object exArgs[]) { + super(msgId, exArgs); + } - /** - * Constructor InvalidTransformException - * - * @param _msgId - * @param _originalException - */ - public InvalidTransformException(String _msgId, Exception _originalException) { - super(_msgId, _originalException); - } + /** + * Constructor InvalidTransformException + * + * @param msgId + * @param originalException + */ + public InvalidTransformException(String msgId, Exception originalException) { + super(msgId, originalException); + } - /** - * Constructor InvalidTransformException - * - * @param _msgId - * @param exArgs - * @param _originalException - */ - public InvalidTransformException(String _msgId, Object exArgs[], - Exception _originalException) { - super(_msgId, exArgs, _originalException); - } + /** + * Constructor InvalidTransformException + * + * @param msgId + * @param exArgs + * @param originalException + */ + public InvalidTransformException(String msgId, Object exArgs[], Exception originalException) { + super(msgId, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java index 3c910219bfd..37d67ba9f24 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java @@ -263,7 +263,7 @@ public final class Transform extends SignatureElementProxy { * @return the URI representation of Transformation algorithm */ public String getURI() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM); + return this.constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM); } /** @@ -329,7 +329,7 @@ public final class Transform extends SignatureElementProxy { private TransformSpi initializeTransform(String algorithmURI, NodeList contextNodes) throws InvalidTransformException { - this._constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI); + this.constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI); Class transformSpiClass = transformSpiHash.get(algorithmURI); if (transformSpiClass == null) { @@ -360,7 +360,7 @@ public final class Transform extends SignatureElementProxy { // give it to the current document if (contextNodes != null) { for (int i = 0; i < contextNodes.getLength(); i++) { - this._constructionElement.appendChild(contextNodes.item(i).cloneNode(true)); + this.constructionElement.appendChild(contextNodes.item(i).cloneNode(true)); } } return newTransformSpi; diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java index d6c16fa771e..0624c8c7759 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java @@ -2,29 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms; -/** - * - * @author $Author: mullan $ - */ - public interface TransformParam { -} +} \ No newline at end of file diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java index 35aa9ff0f6e..7607d188be5 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms; @@ -37,28 +39,13 @@ import org.xml.sax.SAXException; * @author Christian Geuer-Pollmann */ public abstract class TransformSpi { - /** - * For API compatibility not thread safe. - * @deprecated - */ - @Deprecated - protected Transform _transformObject = null; - /** - * Set the transform object. - * Depeprecated For API compatibility. - * @param transform the Transform - * @deprecated - */ - @Deprecated - protected void setTransform(Transform transform) { - this._transformObject = transform; - } + /** * The mega method which MUST be implemented by the Transformation Algorithm. * * @param input {@link XMLSignatureInput} as the input of transformation * @param os where to output this transformation. - * @param _transformObject the Transform + * @param transformObject the Transform object * @return {@link XMLSignatureInput} as the result of transformation * @throws CanonicalizationException * @throws IOException @@ -68,13 +55,12 @@ public abstract class TransformSpi { * @throws TransformationException */ protected XMLSignatureInput enginePerformTransform( - XMLSignatureInput input, OutputStream os, Transform _transformObject) - throws IOException, - CanonicalizationException, InvalidCanonicalizerException, - TransformationException, ParserConfigurationException, - SAXException { - return enginePerformTransform(input, _transformObject); + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws IOException, CanonicalizationException, InvalidCanonicalizerException, + TransformationException, ParserConfigurationException, SAXException { + throw new UnsupportedOperationException(); } + /** * The mega method which MUST be implemented by the Transformation Algorithm. * In order to be compatible with preexisting Transform implementations, @@ -83,7 +69,7 @@ public abstract class TransformSpi { * implementation. * * @param input {@link XMLSignatureInput} as the input of transformation - * @param _transformObject the Transform + * @param transformObject the Transform object * @return {@link XMLSignatureInput} as the result of transformation * @throws CanonicalizationException * @throws IOException @@ -93,26 +79,14 @@ public abstract class TransformSpi { * @throws TransformationException */ protected XMLSignatureInput enginePerformTransform( - XMLSignatureInput input, Transform _transformObject) - throws IOException, - CanonicalizationException, InvalidCanonicalizerException, - TransformationException, ParserConfigurationException, - SAXException { - //Default implementation overide with a much better - try { - TransformSpi tmp = (TransformSpi) getClass().newInstance(); - tmp.setTransform(_transformObject); - return tmp.enginePerformTransform(input); - } catch (InstantiationException e) { - throw new TransformationException("",e); - } catch (IllegalAccessException e) { - throw new TransformationException("",e); - } + XMLSignatureInput input, Transform transformObject + ) throws IOException, CanonicalizationException, InvalidCanonicalizerException, + TransformationException, ParserConfigurationException, SAXException { + return enginePerformTransform(input, null, transformObject); } /** * The mega method which MUST be implemented by the Transformation Algorithm. - * @deprecated * @param input {@link XMLSignatureInput} as the input of transformation * @return {@link XMLSignatureInput} as the result of transformation * @throws CanonicalizationException @@ -122,15 +96,13 @@ public abstract class TransformSpi { * @throws SAXException * @throws TransformationException */ - @Deprecated protected XMLSignatureInput enginePerformTransform( - XMLSignatureInput input) - throws IOException, - CanonicalizationException, InvalidCanonicalizerException, - TransformationException, ParserConfigurationException, - SAXException { - throw new UnsupportedOperationException(); + XMLSignatureInput input + ) throws IOException, CanonicalizationException, InvalidCanonicalizerException, + TransformationException, ParserConfigurationException, SAXException { + return enginePerformTransform(input, null); } + /** * Returns the URI representation of Transformation algorithm * diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java index 10e8723e238..1296475f6b1 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java @@ -2,86 +2,83 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - /** * * @author Christian Geuer-Pollmann */ public class TransformationException extends XMLSecurityException { + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * Constructor TransformationException + * + */ + public TransformationException() { + super(); + } - /** - * Constructor TransformationException - * - */ - public TransformationException() { - super(); - } + /** + * Constructor TransformationException + * + * @param msgID + */ + public TransformationException(String msgID) { + super(msgID); + } - /** - * Constructor TransformationException - * - * @param _msgID - */ - public TransformationException(String _msgID) { - super(_msgID); - } + /** + * Constructor TransformationException + * + * @param msgID + * @param exArgs + */ + public TransformationException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor TransformationException - * - * @param _msgID - * @param exArgs - */ - public TransformationException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor TransformationException + * + * @param msgID + * @param originalException + */ + public TransformationException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor TransformationException - * - * @param _msgID - * @param _originalException - */ - public TransformationException(String _msgID, Exception _originalException) { - super(_msgID, _originalException); - } - - /** - * Constructor TransformationException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public TransformationException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * Constructor TransformationException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public TransformationException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java index ce44e1713e4..7f29fd6a9f9 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms; @@ -51,56 +53,64 @@ import org.w3c.dom.NodeList; */ public class Transforms extends SignatureElementProxy { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(Transforms.class.getName()); /** Canonicalization - Required Canonical XML (omits comments) */ public static final String TRANSFORM_C14N_OMIT_COMMENTS = Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS; + /** Canonicalization - Recommended Canonical XML with Comments */ public static final String TRANSFORM_C14N_WITH_COMMENTS = Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS; + /** Canonicalization - Required Canonical XML 1.1 (omits comments) */ public static final String TRANSFORM_C14N11_OMIT_COMMENTS = Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS; + /** Canonicalization - Recommended Canonical XML 1.1 with Comments */ public static final String TRANSFORM_C14N11_WITH_COMMENTS = Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS; + /** Canonicalization - Required Exclusive Canonicalization (omits comments) */ public static final String TRANSFORM_C14N_EXCL_OMIT_COMMENTS = Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; + /** Canonicalization - Recommended Exclusive Canonicalization with Comments */ public static final String TRANSFORM_C14N_EXCL_WITH_COMMENTS = Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS; + /** Transform - Optional XSLT */ public static final String TRANSFORM_XSLT = "http://www.w3.org/TR/1999/REC-xslt-19991116"; + /** Transform - Required base64 decoding */ public static final String TRANSFORM_BASE64_DECODE = Constants.SignatureSpecNS + "base64"; + /** Transform - Recommended XPath */ public static final String TRANSFORM_XPATH = "http://www.w3.org/TR/1999/REC-xpath-19991116"; + /** Transform - Required Enveloped Signature */ public static final String TRANSFORM_ENVELOPED_SIGNATURE = Constants.SignatureSpecNS + "enveloped-signature"; + /** Transform - XPointer */ public static final String TRANSFORM_XPOINTER = "http://www.w3.org/TR/2001/WD-xptr-20010108"; - /** Transform - XPath Filter v2.0 */ - public static final String TRANSFORM_XPATH2FILTER04 - = "http://www.w3.org/2002/04/xmldsig-filter2"; + /** Transform - XPath Filter */ public static final String TRANSFORM_XPATH2FILTER = "http://www.w3.org/2002/06/xmldsig-filter2"; - /** Transform - XPath Filter CHGP private */ - public static final String TRANSFORM_XPATHFILTERCHGP - = "http://www.nue.et-inf.uni-siegen.de/~geuer-pollmann/#xpathFilter"; - Element []transforms; + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(Transforms.class.getName()); + + private Element[] transforms; protected Transforms() { }; + private boolean secureValidation; + /** * Constructs {@link Transforms}. * @@ -109,7 +119,7 @@ public class Transforms extends SignatureElementProxy { */ public Transforms(Document doc) { super(doc); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); } /** @@ -125,24 +135,27 @@ public class Transforms extends SignatureElementProxy { * @throws XMLSignatureException */ public Transforms(Element element, String BaseURI) - throws DOMException, XMLSignatureException, - InvalidTransformException, TransformationException, - XMLSecurityException { - + throws DOMException, XMLSignatureException, InvalidTransformException, + TransformationException, XMLSecurityException { super(element, BaseURI); int numberOfTransformElems = this.getLength(); if (numberOfTransformElems == 0) { - // At least one Transform element must be present. Bad. - Object exArgs[] = { Constants._TAG_TRANSFORM, - Constants._TAG_TRANSFORMS }; + Object exArgs[] = { Constants._TAG_TRANSFORM, Constants._TAG_TRANSFORMS }; throw new TransformationException("xml.WrongContent", exArgs); } } + /** + * Set whether secure validation is enabled or not. The default is false. + */ + public void setSecureValidation(boolean secureValidation) { + this.secureValidation = secureValidation; + } + /** * Adds the Transform with the specified Transform * algorithm URI @@ -151,14 +164,13 @@ public class Transforms extends SignatureElementProxy { * transformation is applied to data * @throws TransformationException */ - public void addTransform(String transformURI) - throws TransformationException { - + public void addTransform(String transformURI) throws TransformationException { try { - if (log.isLoggable(java.util.logging.Level.FINE)) + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transformURI + ")"); + } - Transform transform = new Transform(this._doc, transformURI); + Transform transform = new Transform(this.doc, transformURI); this.addTransform(transform); } catch (InvalidTransformException ex) { @@ -174,16 +186,15 @@ public class Transforms extends SignatureElementProxy { * transformation is applied to data * @param contextElement * @throws TransformationException - * @see Transform#getInstance(Document doc, String algorithmURI, Element childElement) */ public void addTransform(String transformURI, Element contextElement) - throws TransformationException { - + throws TransformationException { try { - if (log.isLoggable(java.util.logging.Level.FINE)) + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transformURI + ")"); + } - Transform transform = new Transform(this._doc, transformURI, contextElement); + Transform transform = new Transform(this.doc, transformURI, contextElement); this.addTransform(transform); } catch (InvalidTransformException ex) { @@ -199,13 +210,12 @@ public class Transforms extends SignatureElementProxy { * transformation is applied to data * @param contextNodes * @throws TransformationException - * @see Transform#getInstance(Document doc, String algorithmURI, NodeList contextNodes) */ public void addTransform(String transformURI, NodeList contextNodes) - throws TransformationException { + throws TransformationException { try { - Transform transform = new Transform(this._doc, transformURI, contextNodes); + Transform transform = new Transform(this.doc, transformURI, contextNodes); this.addTransform(transform); } catch (InvalidTransformException ex) { throw new TransformationException("empty", ex); @@ -218,13 +228,14 @@ public class Transforms extends SignatureElementProxy { * @param transform {@link Transform} object */ private void addTransform(Transform transform) { - if (log.isLoggable(java.util.logging.Level.FINE)) + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transform.getURI() + ")"); + } Element transformElement = transform.getElement(); - this._constructionElement.appendChild(transformElement); - XMLUtils.addReturnToElement(this._constructionElement); + this.constructionElement.appendChild(transformElement); + XMLUtils.addReturnToElement(this.constructionElement); } /** @@ -236,7 +247,8 @@ public class Transforms extends SignatureElementProxy { * @throws TransformationException */ public XMLSignatureInput performTransforms( - XMLSignatureInput xmlSignatureInput) throws TransformationException { + XMLSignatureInput xmlSignatureInput + ) throws TransformationException { return performTransforms(xmlSignatureInput, null); } @@ -250,21 +262,22 @@ public class Transforms extends SignatureElementProxy { * @throws TransformationException */ public XMLSignatureInput performTransforms( - XMLSignatureInput xmlSignatureInput, OutputStream os) - throws TransformationException { - + XMLSignatureInput xmlSignatureInput, OutputStream os + ) throws TransformationException { try { - int last=this.getLength()-1; + int last = this.getLength() - 1; for (int i = 0; i < last; i++) { Transform t = this.item(i); + String uri = t.getURI(); if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Perform the (" + i + ")th " + t.getURI() - + " transform"); + log.log(java.util.logging.Level.FINE, "Perform the (" + i + ")th " + uri + " transform"); } + checkSecureValidation(t); xmlSignatureInput = t.performTransform(xmlSignatureInput); } - if (last>=0) { + if (last >= 0) { Transform t = this.item(last); + checkSecureValidation(t); xmlSignatureInput = t.performTransform(xmlSignatureInput, os); } @@ -278,16 +291,26 @@ public class Transforms extends SignatureElementProxy { } } + private void checkSecureValidation(Transform transform) throws TransformationException { + String uri = transform.getURI(); + if (secureValidation && Transforms.TRANSFORM_XSLT.equals(uri)) { + Object exArgs[] = { uri }; + + throw new TransformationException( + "signature.Transform.ForbiddenTransform", exArgs + ); + } + } + /** * Return the nonnegative number of transformations. * * @return the number of transformations */ - public int getLength() - { + public int getLength() { if (transforms == null) { - transforms = XMLUtils.selectDsNodes - (this._constructionElement.getFirstChild(), "Transform"); + transforms = + XMLUtils.selectDsNodes(this.constructionElement.getFirstChild(), "Transform"); } return transforms.length; } @@ -301,13 +324,12 @@ public class Transforms extends SignatureElementProxy { * @throws TransformationException */ public Transform item(int i) throws TransformationException { - try { if (transforms == null) { - transforms = XMLUtils.selectDsNodes - (this._constructionElement.getFirstChild(), "Transform"); + transforms = + XMLUtils.selectDsNodes(this.constructionElement.getFirstChild(), "Transform"); } - return new Transform(transforms[i], this._baseURI); + return new Transform(transforms[i], this.baseURI); } catch (XMLSecurityException ex) { throw new TransformationException("empty", ex); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java index 15c1b576df5..7d8cc74e1ef 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms.implementations; - - import javax.xml.transform.TransformerException; import com.sun.org.apache.xml.internal.dtm.DTM; @@ -36,7 +36,6 @@ import com.sun.org.apache.xpath.internal.res.XPATHErrorResources; import org.w3c.dom.Document; import org.w3c.dom.Node; - /** * The 'here()' function returns a node-set containing the attribute or * processing instruction node or the parent element of the text node @@ -56,107 +55,98 @@ import org.w3c.dom.Node; */ public class FuncHere extends Function { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * The here function returns a node-set containing the attribute or - * processing instruction node or the parent element of the text node - * that directly bears the XPath expression. This expression results - * in an error if the containing XPath expression does not appear in the - * same XML document against which the XPath expression is being evaluated. - * - * @param xctxt - * @return the xobject - * @throws javax.xml.transform.TransformerException - */ - public XObject execute(XPathContext xctxt) - throws javax.xml.transform.TransformerException { + /** + * The here function returns a node-set containing the attribute or + * processing instruction node or the parent element of the text node + * that directly bears the XPath expression. This expression results + * in an error if the containing XPath expression does not appear in the + * same XML document against which the XPath expression is being evaluated. + * + * @param xctxt + * @return the xobject + * @throws javax.xml.transform.TransformerException + */ + @Override + public XObject execute(XPathContext xctxt) + throws javax.xml.transform.TransformerException { - Node xpathOwnerNode = (Node) xctxt.getOwnerObject(); + Node xpathOwnerNode = (Node) xctxt.getOwnerObject(); - if (xpathOwnerNode == null) { - return null; - } + if (xpathOwnerNode == null) { + return null; + } - int xpathOwnerNodeDTM = xctxt.getDTMHandleFromNode(xpathOwnerNode); + int xpathOwnerNodeDTM = xctxt.getDTMHandleFromNode(xpathOwnerNode); - int currentNode = xctxt.getCurrentNode(); - DTM dtm = xctxt.getDTM(currentNode); - int docContext = dtm.getDocument(); + int currentNode = xctxt.getCurrentNode(); + DTM dtm = xctxt.getDTM(currentNode); + int docContext = dtm.getDocument(); - if (DTM.NULL == docContext) { - error(xctxt, XPATHErrorResources.ER_CONTEXT_HAS_NO_OWNERDOC, null); - } + if (DTM.NULL == docContext) { + error(xctxt, XPATHErrorResources.ER_CONTEXT_HAS_NO_OWNERDOC, null); + } - { + { + // check whether currentNode and the node containing the XPath expression + // are in the same document + Document currentDoc = + XMLUtils.getOwnerDocument(dtm.getNode(currentNode)); + Document xpathOwnerDoc = XMLUtils.getOwnerDocument(xpathOwnerNode); - // check whether currentNode and the node containing the XPath expression - // are in the same document - Document currentDoc = - XMLUtils.getOwnerDocument(dtm.getNode(currentNode)); - Document xpathOwnerDoc = XMLUtils.getOwnerDocument(xpathOwnerNode); + if (currentDoc != xpathOwnerDoc) { + throw new TransformerException(I18n.translate("xpath.funcHere.documentsDiffer")); + } + } - if (currentDoc != xpathOwnerDoc) { - throw new TransformerException(I18n - .translate("xpath.funcHere.documentsDiffer")); - } - } + XNodeSet nodes = new XNodeSet(xctxt.getDTMManager()); + NodeSetDTM nodeSet = nodes.mutableNodeset(); - XNodeSet nodes = new XNodeSet(xctxt.getDTMManager()); - NodeSetDTM nodeSet = nodes.mutableNodeset(); + { + int hereNode = DTM.NULL; - { - int hereNode = DTM.NULL; + switch (dtm.getNodeType(xpathOwnerNodeDTM)) { - switch (dtm.getNodeType(xpathOwnerNodeDTM)) { + case Node.ATTRIBUTE_NODE : + case Node.PROCESSING_INSTRUCTION_NODE : { + // returns a node-set containing the attribute / processing instruction node + hereNode = xpathOwnerNodeDTM; - case Node.ATTRIBUTE_NODE : { - // returns a node-set containing the attribute - hereNode = xpathOwnerNodeDTM; + nodeSet.addNode(hereNode); - nodeSet.addNode(hereNode); + break; + } + case Node.TEXT_NODE : { + // returns a node-set containing the parent element of the + // text node that directly bears the XPath expression + hereNode = dtm.getParent(xpathOwnerNodeDTM); - break; - } - case Node.PROCESSING_INSTRUCTION_NODE : { - // returns a node-set containing the processing instruction node - hereNode = xpathOwnerNodeDTM; + nodeSet.addNode(hereNode); - nodeSet.addNode(hereNode); + break; + } + default : + break; + } + } - break; - } - case Node.TEXT_NODE : { - // returns a node-set containing the parent element of the - // text node that directly bears the XPath expression - hereNode = dtm.getParent(xpathOwnerNodeDTM); + /** $todo$ Do I have to do this detach() call? */ + nodeSet.detach(); - nodeSet.addNode(hereNode); + return nodes; + } - break; - } - default : - break; - } - } - - /** $todo$ Do I have to do this detach() call? */ - nodeSet.detach(); - - return nodes; - } - - /** - * No arguments to process, so this does nothing. - * @param vars - * @param globalsSize - */ - @SuppressWarnings("rawtypes") - public void fixupVariables(java.util.Vector vars, int globalsSize) { - - // do nothing - } + /** + * No arguments to process, so this does nothing. + * @param vars + * @param globalsSize + */ + @SuppressWarnings("rawtypes") + public void fixupVariables(java.util.Vector vars, int globalsSize) { + // do nothing + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHereContext.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHereContext.java deleted file mode 100644 index 6cc15ae3898..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHereContext.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * 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 com.sun.org.apache.xml.internal.security.transforms.implementations; - - - -import com.sun.org.apache.xml.internal.dtm.DTMManager; -import com.sun.org.apache.xml.internal.security.utils.I18n; -import com.sun.org.apache.xpath.internal.CachedXPathAPI; -import com.sun.org.apache.xpath.internal.XPathContext; -import org.w3c.dom.Node; - - -/** - * {@link FuncHereContext} extends {@link XPathContext} for supplying context - * for the here() function. The here() function needs to know - * where in an XML instance the XPath text string appeared. This can be - * in {@link org.w3c.dom.Text}, {@link org.w3c.dom.Attr}ibutes and {@ProcessingInstrinction} nodes. The - * correct node must be supplied to the constructor of {@link FuncHereContext}. - * The supplied Node MUST contain the XPath which is to be executed. - * - *
    - * From: Scott_Boag\@lotus.com
    - * To: Christian Geuer-Pollmann 
    - * CC: xalan-dev@xml.apache.org
    - * Subject: Re: Cleanup of XPathContext & definition of XSLTContext
    - * Date: Tue, 21 Aug 2001 18:36:24 -0400
    - *
    - * > My point is to say to get this baby to run, the XPath must have a
    - * > possibility to retrieve the information where itself occured in a
    - * > document.
    - *
    - * It sounds to me like you have to derive an XMLSigContext from the
    - * XPathContext?
    - *
    - * > and supplied the Node which contains the xpath string as "owner". Question:
    - * > Is this the correct use of the owner object? It works, but I don't know
    - * > whether this is correct from the xalan-philosophy...
    - *
    - * Philosophically it's fine.  The owner is the TransformerImpl if XPath is
    - * running under XSLT.  If it is not running under XSLT, it can be whatever
    - * you want.
    - *
    - * -scott
    - * 
    - * - * @author $Author: mullan $ - * @see com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHere - * @see com.sun.org.apache.xml.internal.security.utils.XPathFuncHereAPI - * @see XML Signature - The here() function - */ -public class FuncHereContext extends XPathContext { - - /** - * This constuctor is disabled because if we use the here() function we - * always need to know in which node the XPath occured. - */ - private FuncHereContext() {} - - /** - * Constructor FuncHereContext - * - * @param owner - */ - public FuncHereContext(Node owner) { - super(owner); - } - - /** - * Constructor FuncHereContext - * - * @param owner - * @param xpathContext - */ - public FuncHereContext(Node owner, XPathContext xpathContext) { - - super(owner); - - try { - super.m_dtmManager = xpathContext.getDTMManager(); - } catch (IllegalAccessError iae) { - throw new IllegalAccessError(I18n.translate("endorsed.jdk1.4.0") - + " Original message was \"" - + iae.getMessage() + "\""); - } - } - - /** - * Constructor FuncHereContext - * - * @param owner - * @param previouslyUsed - */ - public FuncHereContext(Node owner, CachedXPathAPI previouslyUsed) { - - super(owner); - - try { - super.m_dtmManager = previouslyUsed.getXPathContext().getDTMManager(); - } catch (IllegalAccessError iae) { - throw new IllegalAccessError(I18n.translate("endorsed.jdk1.4.0") - + " Original message was \"" - + iae.getMessage() + "\""); - } - } - - /** - * Constructor FuncHereContext - * - * @param owner - * @param dtmManager - */ - public FuncHereContext(Node owner, DTMManager dtmManager) { - - super(owner); - - try { - super.m_dtmManager = dtmManager; - } catch (IllegalAccessError iae) { - throw new IllegalAccessError(I18n.translate("endorsed.jdk1.4.0") - + " Original message was \"" - + iae.getMessage() + "\""); - } - } -} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java index b1d3de8bce7..206d31016cd 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms.implementations; - - import java.io.BufferedInputStream; import java.io.IOException; import java.io.OutputStream; @@ -72,115 +72,106 @@ import org.xml.sax.SAXException; */ public class TransformBase64Decode extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_BASE64_DECODE; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_BASE64_DECODE; - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return TransformBase64Decode.implementedTransformURI; - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return TransformBase64Decode.implementedTransformURI; + } - /** - * Method enginePerformTransform - * - * @param input - * @return {@link XMLSignatureInput} as the result of transformation - * @inheritDoc - * @throws CanonicalizationException - * @throws IOException - * @throws TransformationException - */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws IOException, CanonicalizationException, - TransformationException { - return enginePerformTransform(input, null, _transformObject); - } + /** + * Method enginePerformTransform + * + * @param input + * @return {@link XMLSignatureInput} as the result of transformation + * @inheritDoc + * @throws CanonicalizationException + * @throws IOException + * @throws TransformationException + */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, Transform transformObject + ) throws IOException, CanonicalizationException, TransformationException { + return enginePerformTransform(input, null, transformObject); + } - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, - OutputStream os, Transform _transformObject) - throws IOException, CanonicalizationException, - TransformationException { - try { - if (input.isElement()) { - Node el=input.getSubNode(); - if (input.getSubNode().getNodeType()==Node.TEXT_NODE) { - el=el.getParentNode(); - } - StringBuffer sb=new StringBuffer(); - traverseElement((Element)el,sb); - if (os==null) { + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws IOException, CanonicalizationException, TransformationException { + try { + if (input.isElement()) { + Node el = input.getSubNode(); + if (input.getSubNode().getNodeType() == Node.TEXT_NODE) { + el = el.getParentNode(); + } + StringBuilder sb = new StringBuilder(); + traverseElement((Element)el, sb); + if (os == null) { + byte[] decodedBytes = Base64.decode(sb.toString()); + return new XMLSignatureInput(decodedBytes); + } + Base64.decode(sb.toString(), os); + XMLSignatureInput output = new XMLSignatureInput((byte[])null); + output.setOutputStream(os); + return output; + } + + if (input.isOctetStream() || input.isNodeSet()) { + if (os == null) { + byte[] base64Bytes = input.getBytes(); + byte[] decodedBytes = Base64.decode(base64Bytes); + return new XMLSignatureInput(decodedBytes); + } + if (input.isByteArray() || input.isNodeSet()) { + Base64.decode(input.getBytes(), os); + } else { + Base64.decode(new BufferedInputStream(input.getOctetStreamReal()), os); + } + XMLSignatureInput output = new XMLSignatureInput((byte[])null); + output.setOutputStream(os); + return output; + } + + try { + //Exceptional case there is current not text case testing this(Before it was a + //a common case). + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + Document doc = + dbf.newDocumentBuilder().parse(input.getOctetStream()); + + Element rootNode = doc.getDocumentElement(); + StringBuilder sb = new StringBuilder(); + traverseElement(rootNode, sb); byte[] decodedBytes = Base64.decode(sb.toString()); return new XMLSignatureInput(decodedBytes); - } - Base64.decode(sb.toString(),os); - XMLSignatureInput output=new XMLSignatureInput((byte[])null); - output.setOutputStream(os); - return output; - - } - if (input.isOctetStream() || input.isNodeSet()) { - - - if (os==null) { - byte[] base64Bytes = input.getBytes(); - byte[] decodedBytes = Base64.decode(base64Bytes); - return new XMLSignatureInput(decodedBytes); - } - if (input.isByteArray() || input.isNodeSet()) { - Base64.decode(input.getBytes(),os); - } else { - Base64.decode(new BufferedInputStream(input.getOctetStreamReal()) - ,os); - } - XMLSignatureInput output=new XMLSignatureInput((byte[])null); - output.setOutputStream(os); - return output; - - - } - - try { - // Exceptional case there is current not text case testing this - // (before it was a a common case). - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, - Boolean.TRUE); - Document doc = - dbf.newDocumentBuilder().parse(input.getOctetStream()); - - Element rootNode = doc.getDocumentElement(); - StringBuffer sb = new StringBuffer(); - traverseElement(rootNode,sb); - byte[] decodedBytes = Base64.decode(sb.toString()); - - return new XMLSignatureInput(decodedBytes); - } catch (ParserConfigurationException e) { - throw new TransformationException("c14n.Canonicalizer.Exception",e); - } catch (SAXException e) { - throw new TransformationException("SAX exception", e); - } + } catch (ParserConfigurationException e) { + throw new TransformationException("c14n.Canonicalizer.Exception",e); + } catch (SAXException e) { + throw new TransformationException("SAX exception", e); + } } catch (Base64DecodingException e) { throw new TransformationException("Base64Decoding", e); } - } + } - void traverseElement(org.w3c.dom.Element node,StringBuffer sb) { - Node sibling=node.getFirstChild(); - while (sibling!=null) { - switch (sibling.getNodeType()) { - case Node.ELEMENT_NODE: - traverseElement((Element)sibling,sb); - break; - case Node.TEXT_NODE: - sb.append(((Text)sibling).getData()); + void traverseElement(org.w3c.dom.Element node, StringBuilder sb) { + Node sibling = node.getFirstChild(); + while (sibling != null) { + switch (sibling.getNodeType()) { + case Node.ELEMENT_NODE: + traverseElement((Element)sibling, sb); + break; + case Node.TEXT_NODE: + sb.append(((Text)sibling).getData()); } - sibling=sibling.getNextSibling(); + sibling = sibling.getNextSibling(); } - } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java index 1b0c7fb6448..9c94199be05 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms.implementations; @@ -37,39 +39,30 @@ import com.sun.org.apache.xml.internal.security.transforms.Transforms; */ public class TransformC14N extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_C14N_OMIT_COMMENTS; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_C14N_OMIT_COMMENTS; + /** + * @inheritDoc + */ + protected String engineGetURI() { + return TransformC14N.implementedTransformURI; + } - /** - * @inheritDoc - */ - protected String engineGetURI() { - return TransformC14N.implementedTransformURI; - } - - /** - * @inheritDoc - */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws CanonicalizationException { - return enginePerformTransform(input, null, _transformObject); - } - - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream os, Transform _transformObject) - throws CanonicalizationException { - Canonicalizer20010315OmitComments c14n = new Canonicalizer20010315OmitComments(); - if (os!=null) { - c14n.setWriter(os); - } - byte[] result = null; - result=c14n.engineCanonicalize(input); - XMLSignatureInput output=new XMLSignatureInput(result); - if (os!=null) { + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws CanonicalizationException { + Canonicalizer20010315OmitComments c14n = new Canonicalizer20010315OmitComments(); + if (os != null) { + c14n.setWriter(os); + } + byte[] result = null; + result = c14n.engineCanonicalize(input); + XMLSignatureInput output = new XMLSignatureInput(result); + if (os != null) { output.setOutputStream(os); - } - return output; - } + } + return output; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java index a4f6e34025f..b3510fc06b5 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms.implementations; @@ -41,15 +43,9 @@ public class TransformC14N11 extends TransformSpi { return Transforms.TRANSFORM_C14N11_OMIT_COMMENTS; } - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform transform) - throws CanonicalizationException { - return enginePerformTransform(input, null, transform); - } - - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, OutputStream os, Transform transform) - throws CanonicalizationException { + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transform + ) throws CanonicalizationException { Canonicalizer11_OmitComments c14n = new Canonicalizer11_OmitComments(); if (os != null) { c14n.setWriter(os); diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java index 1a7a213e718..e01f17312c7 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms.implementations; @@ -41,15 +43,9 @@ public class TransformC14N11_WithComments extends TransformSpi { return Transforms.TRANSFORM_C14N11_WITH_COMMENTS; } - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform transform) - throws CanonicalizationException { - return enginePerformTransform(input, null, transform); - } - - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, OutputStream os, Transform transform) - throws CanonicalizationException { + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transform + ) throws CanonicalizationException { Canonicalizer11_WithComments c14n = new Canonicalizer11_WithComments(); if (os != null) { diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java index f4b2407055b..3b7bdd13691 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms.implementations; @@ -36,71 +38,59 @@ import org.w3c.dom.Element; /** * Class TransformC14NExclusive * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public class TransformC14NExclusive extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS; - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; + } - /** - * Method enginePerformTransform - * - * @param input - * @return the transformed of the input - * @throws CanonicalizationException - */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws CanonicalizationException { - return enginePerformTransform(input, null, _transformObject); - } + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws CanonicalizationException { + try { + String inclusiveNamespaces = null; - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream os, Transform _transformObject) - throws CanonicalizationException { - try { - String inclusiveNamespaces = null; + if (transformObject.length( + InclusiveNamespaces.ExclusiveCanonicalizationNamespace, + InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES) == 1 + ) { + Element inclusiveElement = + XMLUtils.selectNode( + transformObject.getElement().getFirstChild(), + InclusiveNamespaces.ExclusiveCanonicalizationNamespace, + InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES, + 0 + ); - if (_transformObject - .length(InclusiveNamespaces - .ExclusiveCanonicalizationNamespace, InclusiveNamespaces - ._TAG_EC_INCLUSIVENAMESPACES) == 1) { - Element inclusiveElement = - XMLUtils.selectNode( - _transformObject.getElement().getFirstChild(), - InclusiveNamespaces.ExclusiveCanonicalizationNamespace, - InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,0); + inclusiveNamespaces = + new InclusiveNamespaces( + inclusiveElement, transformObject.getBaseURI()).getInclusiveNamespaces(); + } - inclusiveNamespaces = new InclusiveNamespaces(inclusiveElement, - _transformObject.getBaseURI()).getInclusiveNamespaces(); - } + Canonicalizer20010315ExclOmitComments c14n = + new Canonicalizer20010315ExclOmitComments(); + if (os != null) { + c14n.setWriter(os); + } + byte[] result = c14n.engineCanonicalize(input, inclusiveNamespaces); - Canonicalizer20010315ExclOmitComments c14n = - new Canonicalizer20010315ExclOmitComments(); - if (os!=null) { - c14n.setWriter(os); - } - byte []result; - result =c14n.engineCanonicalize(input, inclusiveNamespaces); - - XMLSignatureInput output=new XMLSignatureInput(result); - if (os!=null) { - output.setOutputStream(os); - } - return output; - } catch (XMLSecurityException ex) { - throw new CanonicalizationException("empty", ex); - } - } + XMLSignatureInput output = new XMLSignatureInput(result); + if (os != null) { + output.setOutputStream(os); + } + return output; + } catch (XMLSecurityException ex) { + throw new CanonicalizationException("empty", ex); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java index 2380750d052..d1456b30e00 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms.implementations; @@ -41,59 +43,54 @@ import org.w3c.dom.Element; */ public class TransformC14NExclusiveWithComments extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS; - /** - * Method engineGetURI - *@inheritDoc - * - */ - protected String engineGetURI() { - return implementedTransformURI; - } + /** + * Method engineGetURI + *@inheritDoc + * + */ + protected String engineGetURI() { + return implementedTransformURI; + } - /** - * @inheritDoc - */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws CanonicalizationException { - return enginePerformTransform(input, null, _transformObject); - } + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws CanonicalizationException { + try { + String inclusiveNamespaces = null; - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream os, Transform _transformObject) - throws CanonicalizationException { - try { - String inclusiveNamespaces = null; + if (transformObject.length( + InclusiveNamespaces.ExclusiveCanonicalizationNamespace, + InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES) == 1 + ) { + Element inclusiveElement = + XMLUtils.selectNode( + transformObject.getElement().getFirstChild(), + InclusiveNamespaces.ExclusiveCanonicalizationNamespace, + InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES, + 0 + ); - if (_transformObject - .length(InclusiveNamespaces - .ExclusiveCanonicalizationNamespace, InclusiveNamespaces - ._TAG_EC_INCLUSIVENAMESPACES) == 1) { - Element inclusiveElement = - XMLUtils.selectNode( - _transformObject.getElement().getFirstChild(), - InclusiveNamespaces.ExclusiveCanonicalizationNamespace, - InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,0); + inclusiveNamespaces = + new InclusiveNamespaces( + inclusiveElement, transformObject.getBaseURI() + ).getInclusiveNamespaces(); + } - inclusiveNamespaces = new InclusiveNamespaces(inclusiveElement, - _transformObject.getBaseURI()).getInclusiveNamespaces(); + Canonicalizer20010315ExclWithComments c14n = + new Canonicalizer20010315ExclWithComments(); + if (os != null) { + c14n.setWriter(os); + } + byte[] result = c14n.engineCanonicalize(input, inclusiveNamespaces); + XMLSignatureInput output = new XMLSignatureInput(result); + + return output; + } catch (XMLSecurityException ex) { + throw new CanonicalizationException("empty", ex); } - - Canonicalizer20010315ExclWithComments c14n = - new Canonicalizer20010315ExclWithComments(); - if (os!=null) { - c14n.setWriter( os); - } - byte []result; - result =c14n.engineCanonicalize(input, inclusiveNamespaces); - XMLSignatureInput output=new XMLSignatureInput(result); - - return output; - } catch (XMLSecurityException ex) { - throw new CanonicalizationException("empty", ex); - } - } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java index b1087076d27..33aee9cd753 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms.implementations; @@ -37,37 +39,31 @@ import com.sun.org.apache.xml.internal.security.transforms.Transforms; */ public class TransformC14NWithComments extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_C14N_WITH_COMMENTS; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_C14N_WITH_COMMENTS; - /** @inheritDoc */ - protected String engineGetURI() { - return implementedTransformURI; - } + /** @inheritDoc */ + protected String engineGetURI() { + return implementedTransformURI; + } - /** @inheritDoc */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws CanonicalizationException { - return enginePerformTransform(input, null, _transformObject); - } - - /** @inheritDoc */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream os, Transform _transformObject) - throws CanonicalizationException { + /** @inheritDoc */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws CanonicalizationException { Canonicalizer20010315WithComments c14n = new Canonicalizer20010315WithComments(); - if (os!=null) { - c14n.setWriter( os); + if (os != null) { + c14n.setWriter(os); } - byte[] result = null; - result=c14n.engineCanonicalize(input); - XMLSignatureInput output=new XMLSignatureInput(result); - if (os!=null) { - output.setOutputStream(os); - } - return output; - } + byte[] result = null; + result = c14n.engineCanonicalize(input); + XMLSignatureInput output = new XMLSignatureInput(result); + if (os != null) { + output.setOutputStream(os); + } + return output; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java index c447468bd63..9f108c1bb10 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java @@ -2,24 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms.implementations; +import java.io.OutputStream; + import com.sun.org.apache.xml.internal.security.signature.NodeFilter; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.transforms.Transform; @@ -39,99 +43,99 @@ import org.w3c.dom.Node; */ public class TransformEnvelopedSignature extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_ENVELOPED_SIGNATURE; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_ENVELOPED_SIGNATURE; - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } - - /** - * @inheritDoc - */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject) - throws TransformationException { - - - - /** - * If the actual input is an octet stream, then the application MUST - * convert the octet stream to an XPath node-set suitable for use by - * Canonical XML with Comments. (A subsequent application of the - * REQUIRED Canonical XML algorithm would strip away these comments.) - * - * ... - * - * The evaluation of this expression includes all of the document's nodes - * (including comments) in the node-set representing the octet stream. - */ - - Node signatureElement = _transformObject.getElement(); - - - signatureElement = searchSignatureElement(signatureElement); - input.setExcludeNode(signatureElement); - input.addNodeFilter(new EnvelopedNodeFilter(signatureElement)); - return input; - - // - - - } - - /** - * @param signatureElement - * @return the node that is the signature - * @throws TransformationException - */ - private static Node searchSignatureElement(Node signatureElement) throws TransformationException { - boolean found=false; - - while (true) { - if ((signatureElement == null) - || (signatureElement.getNodeType() == Node.DOCUMENT_NODE)) { - break; - } - Element el=(Element)signatureElement; - if (el.getNamespaceURI().equals(Constants.SignatureSpecNS) - && - el.getLocalName().equals(Constants._TAG_SIGNATURE)) { - found = true; - break; - } - - signatureElement = signatureElement.getParentNode(); - } - - if (!found) { - throw new TransformationException( - "envelopedSignatureTransformNotInSignatureElement"); - } - return signatureElement; + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; } - static class EnvelopedNodeFilter implements NodeFilter { - Node exclude; - EnvelopedNodeFilter(Node n) { - exclude=n; + + /** + * @inheritDoc + */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws TransformationException { + /** + * If the actual input is an octet stream, then the application MUST + * convert the octet stream to an XPath node-set suitable for use by + * Canonical XML with Comments. (A subsequent application of the + * REQUIRED Canonical XML algorithm would strip away these comments.) + * + * ... + * + * The evaluation of this expression includes all of the document's nodes + * (including comments) in the node-set representing the octet stream. + */ + + Node signatureElement = transformObject.getElement(); + + signatureElement = searchSignatureElement(signatureElement); + input.setExcludeNode(signatureElement); + input.addNodeFilter(new EnvelopedNodeFilter(signatureElement)); + return input; + } + + /** + * @param signatureElement + * @return the node that is the signature + * @throws TransformationException + */ + private static Node searchSignatureElement(Node signatureElement) + throws TransformationException { + boolean found = false; + + while (true) { + if (signatureElement == null + || signatureElement.getNodeType() == Node.DOCUMENT_NODE) { + break; + } + Element el = (Element) signatureElement; + if (el.getNamespaceURI().equals(Constants.SignatureSpecNS) + && el.getLocalName().equals(Constants._TAG_SIGNATURE)) { + found = true; + break; + } + + signatureElement = signatureElement.getParentNode(); } - public int isNodeIncludeDO(Node n, int level) { - if ((n==exclude)) - return -1; - return 1; + + if (!found) { + throw new TransformationException( + "transform.envelopedSignatureTransformNotInSignatureElement"); + } + return signatureElement; } + + static class EnvelopedNodeFilter implements NodeFilter { + + Node exclude; + + EnvelopedNodeFilter(Node n) { + exclude = n; + } + + public int isNodeIncludeDO(Node n, int level) { + if (n == exclude) { + return -1; + } + return 1; + } + /** * @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node) */ public int isNodeInclude(Node n) { - if ((n==exclude) || XMLUtils.isDescendantOrSelf(exclude,n)) - return -1; - return 1; + if (n == exclude || XMLUtils.isDescendantOrSelf(exclude, n)) { + return -1; + } + return 1; //return !XMLUtils.isDescendantOrSelf(exclude,n); } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java index f7411344f42..db958096963 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java @@ -2,24 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms.implementations; +import java.io.OutputStream; + import javax.xml.transform.TransformerException; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityRuntimeException; @@ -29,12 +33,10 @@ import com.sun.org.apache.xml.internal.security.transforms.Transform; import com.sun.org.apache.xml.internal.security.transforms.TransformSpi; import com.sun.org.apache.xml.internal.security.transforms.TransformationException; import com.sun.org.apache.xml.internal.security.transforms.Transforms; -import com.sun.org.apache.xml.internal.security.utils.CachedXPathAPIHolder; -import com.sun.org.apache.xml.internal.security.utils.CachedXPathFuncHereAPI; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; -import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault; -import com.sun.org.apache.xpath.internal.objects.XObject; +import com.sun.org.apache.xml.internal.security.utils.XPathAPI; +import com.sun.org.apache.xml.internal.security.utils.XPathFactory; import org.w3c.dom.DOMException; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -51,118 +53,112 @@ import org.w3c.dom.Node; */ public class TransformXPath extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_XPATH; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = Transforms.TRANSFORM_XPATH; - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; + } - /** - * Method enginePerformTransform - * @inheritDoc - * @param input - * - * @throws TransformationException - */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject) - throws TransformationException { + /** + * Method enginePerformTransform + * @inheritDoc + * @param input + * + * @throws TransformationException + */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws TransformationException { + try { + /** + * If the actual input is an octet stream, then the application MUST + * convert the octet stream to an XPath node-set suitable for use by + * Canonical XML with Comments. (A subsequent application of the + * REQUIRED Canonical XML algorithm would strip away these comments.) + * + * ... + * + * The evaluation of this expression includes all of the document's nodes + * (including comments) in the node-set representing the octet stream. + */ + Element xpathElement = + XMLUtils.selectDsNode( + transformObject.getElement().getFirstChild(), Constants._TAG_XPATH, 0); - try { + if (xpathElement == null) { + Object exArgs[] = { "ds:XPath", "Transform" }; - /** - * If the actual input is an octet stream, then the application MUST - * convert the octet stream to an XPath node-set suitable for use by - * Canonical XML with Comments. (A subsequent application of the - * REQUIRED Canonical XML algorithm would strip away these comments.) - * - * ... - * - * The evaluation of this expression includes all of the document's nodes - * (including comments) in the node-set representing the octet stream. - */ - CachedXPathAPIHolder.setDoc(_transformObject.getElement().getOwnerDocument()); + throw new TransformationException("xml.WrongContent", exArgs); + } + Node xpathnode = xpathElement.getChildNodes().item(0); + String str = XMLUtils.getStrFromNode(xpathnode); + input.setNeedsToBeExpanded(needsCircumvent(str)); + if (xpathnode == null) { + throw new DOMException( + DOMException.HIERARCHY_REQUEST_ERR, "Text must be in ds:Xpath" + ); + } + XPathFactory xpathFactory = XPathFactory.newInstance(); + XPathAPI xpathAPIInstance = xpathFactory.newXPathAPI(); + input.addNodeFilter(new XPathNodeFilter(xpathElement, xpathnode, str, xpathAPIInstance)); + input.setNodeSet(true); + return input; + } catch (DOMException ex) { + throw new TransformationException("empty", ex); + } + } - - Element xpathElement =XMLUtils.selectDsNode( - _transformObject.getElement().getFirstChild(), - Constants._TAG_XPATH,0); - - if (xpathElement == null) { - Object exArgs[] = { "ds:XPath", "Transform" }; - - throw new TransformationException("xml.WrongContent", exArgs); - } - Node xpathnode = xpathElement.getChildNodes().item(0); - String str=CachedXPathFuncHereAPI.getStrFromNode(xpathnode); - input.setNeedsToBeExpanded(needsCircunvent(str)); - if (xpathnode == null) { - throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, - "Text must be in ds:Xpath"); - } - - - input.addNodeFilter(new XPathNodeFilter( xpathElement, xpathnode, str)); - input.setNodeSet(true); - return input; - } catch (DOMException ex) { - throw new TransformationException("empty", ex); - } - } - - /** - * @param str - * @return true if needs to be circunvent for bug. - */ - private boolean needsCircunvent(String str) { - //return true; - //return false; + /** + * @param str + * @return true if needs to be circumvent for bug. + */ + private boolean needsCircumvent(String str) { return (str.indexOf("namespace") != -1) || (str.indexOf("name()") != -1); } static class XPathNodeFilter implements NodeFilter { - PrefixResolverDefault prefixResolver; - CachedXPathFuncHereAPI xPathFuncHereAPI = - new CachedXPathFuncHereAPI(CachedXPathAPIHolder.getCachedXPathAPI()); + + XPathAPI xPathAPI; Node xpathnode; + Element xpathElement; String str; - XPathNodeFilter(Element xpathElement, - Node xpathnode, String str) { - this.xpathnode=xpathnode; - this.str=str; - prefixResolver =new PrefixResolverDefault(xpathElement); + + XPathNodeFilter(Element xpathElement, Node xpathnode, String str, XPathAPI xPathAPI) { + this.xpathnode = xpathnode; + this.str = str; + this.xpathElement = xpathElement; + this.xPathAPI = xPathAPI; } /** * @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node) */ public int isNodeInclude(Node currentNode) { - XObject includeInResult; try { - includeInResult = xPathFuncHereAPI.eval(currentNode, - xpathnode, str,prefixResolver); - if (includeInResult.bool()) - return 1; + boolean include = xPathAPI.evaluate(currentNode, xpathnode, str, xpathElement); + if (include) { + return 1; + } return 0; } catch (TransformerException e) { Object[] eArgs = {currentNode}; - throw new XMLSecurityRuntimeException - ("signature.Transform.node", eArgs, e); + throw new XMLSecurityRuntimeException("signature.Transform.node", eArgs, e); } catch (Exception e) { - Object[] eArgs = {currentNode, new Short(currentNode.getNodeType())}; - throw new XMLSecurityRuntimeException - ("signature.Transform.nodeAndType",eArgs, e); + Object[] eArgs = {currentNode, Short.valueOf(currentNode.getNodeType())}; + throw new XMLSecurityRuntimeException("signature.Transform.nodeAndType",eArgs, e); } } + public int isNodeIncludeDO(Node n, int level) { - return isNodeInclude(n); + return isNodeInclude(n); } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java index 2d805d13dd2..d35142222ae 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java @@ -2,30 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms.implementations; - - import java.io.IOException; +import java.io.OutputStream; import java.util.ArrayList; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Set; @@ -42,9 +42,9 @@ import com.sun.org.apache.xml.internal.security.transforms.TransformSpi; import com.sun.org.apache.xml.internal.security.transforms.TransformationException; import com.sun.org.apache.xml.internal.security.transforms.Transforms; import com.sun.org.apache.xml.internal.security.transforms.params.XPath2FilterContainer; -import com.sun.org.apache.xml.internal.security.utils.CachedXPathAPIHolder; -import com.sun.org.apache.xml.internal.security.utils.CachedXPathFuncHereAPI; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import com.sun.org.apache.xml.internal.security.utils.XPathAPI; +import com.sun.org.apache.xml.internal.security.utils.XPathFactory; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -55,254 +55,241 @@ import org.xml.sax.SAXException; /** * Implements the XML Signature XPath Filter v2.0 * - * @author $Author: mullan $ * @see XPath Filter v2.0 (TR) - * @see XPath Filter v2.0 (editors copy) */ public class TransformXPath2Filter extends TransformSpi { - /** {@link java.util.logging} logging facility */ -// static java.util.logging.Logger log = -// java.util.logging.Logger.getLogger( -// TransformXPath2Filter.class.getName()); + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_XPATH2FILTER; - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_XPATH2FILTER; - //J- - // contains the type of the filter + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; + } - // contains the node set + /** + * Method enginePerformTransform + * @inheritDoc + * @param input + * + * @throws TransformationException + */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws TransformationException { + try { + List unionNodes = new ArrayList(); + List subtractNodes = new ArrayList(); + List intersectNodes = new ArrayList(); - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } + Element[] xpathElements = + XMLUtils.selectNodes( + transformObject.getElement().getFirstChild(), + XPath2FilterContainer.XPathFilter2NS, + XPath2FilterContainer._TAG_XPATH2 + ); + if (xpathElements.length == 0) { + Object exArgs[] = { Transforms.TRANSFORM_XPATH2FILTER, "XPath" }; + throw new TransformationException("xml.WrongContent", exArgs); + } + Document inputDoc = null; + if (input.getSubNode() != null) { + inputDoc = XMLUtils.getOwnerDocument(input.getSubNode()); + } else { + inputDoc = XMLUtils.getOwnerDocument(input.getNodeSet()); + } - /** - * Method enginePerformTransform - * @inheritDoc - * @param input - * - * @throws TransformationException - */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject) - throws TransformationException { - CachedXPathAPIHolder.setDoc(_transformObject.getElement().getOwnerDocument()); - try { - List unionNodes=new ArrayList(); - List substractNodes=new ArrayList(); - List intersectNodes=new ArrayList(); + for (int i = 0; i < xpathElements.length; i++) { + Element xpathElement = xpathElements[i]; - CachedXPathFuncHereAPI xPathFuncHereAPI = - new CachedXPathFuncHereAPI(CachedXPathAPIHolder.getCachedXPathAPI()); + XPath2FilterContainer xpathContainer = + XPath2FilterContainer.newInstance(xpathElement, input.getSourceURI()); + String str = + XMLUtils.getStrFromNode(xpathContainer.getXPathFilterTextNode()); - Element []xpathElements =XMLUtils.selectNodes( - _transformObject.getElement().getFirstChild(), - XPath2FilterContainer.XPathFilter2NS, - XPath2FilterContainer._TAG_XPATH2); - int noOfSteps = xpathElements.length; + XPathFactory xpathFactory = XPathFactory.newInstance(); + XPathAPI xpathAPIInstance = xpathFactory.newXPathAPI(); + NodeList subtreeRoots = + xpathAPIInstance.selectNodeList( + inputDoc, + xpathContainer.getXPathFilterTextNode(), + str, + xpathContainer.getElement()); + if (xpathContainer.isIntersect()) { + intersectNodes.add(subtreeRoots); + } else if (xpathContainer.isSubtract()) { + subtractNodes.add(subtreeRoots); + } else if (xpathContainer.isUnion()) { + unionNodes.add(subtreeRoots); + } + } - if (noOfSteps == 0) { - Object exArgs[] = { Transforms.TRANSFORM_XPATH2FILTER, "XPath" }; - - throw new TransformationException("xml.WrongContent", exArgs); - } - - Document inputDoc = null; - if (input.getSubNode() != null) { - inputDoc = XMLUtils.getOwnerDocument(input.getSubNode()); - } else { - inputDoc = XMLUtils.getOwnerDocument(input.getNodeSet()); - } - - for (int i = 0; i < noOfSteps; i++) { - Element xpathElement =XMLUtils.selectNode( - _transformObject.getElement().getFirstChild(), - XPath2FilterContainer.XPathFilter2NS, - XPath2FilterContainer._TAG_XPATH2,i); - XPath2FilterContainer xpathContainer = - XPath2FilterContainer.newInstance(xpathElement, - input.getSourceURI()); - - - NodeList subtreeRoots = xPathFuncHereAPI.selectNodeList(inputDoc, - xpathContainer.getXPathFilterTextNode(), - CachedXPathFuncHereAPI.getStrFromNode(xpathContainer.getXPathFilterTextNode()), - xpathContainer.getElement()); - if (xpathContainer.isIntersect()) { - intersectNodes.add(subtreeRoots); - } else if (xpathContainer.isSubtract()) { - substractNodes.add(subtreeRoots); - } else if (xpathContainer.isUnion()) { - unionNodes.add(subtreeRoots); - } - } - - - input.addNodeFilter(new XPath2NodeFilter(unionNodes, substractNodes, - intersectNodes)); - input.setNodeSet(true); - return input; - } catch (TransformerException ex) { - throw new TransformationException("empty", ex); - } catch (DOMException ex) { - throw new TransformationException("empty", ex); - } catch (CanonicalizationException ex) { - throw new TransformationException("empty", ex); - } catch (InvalidCanonicalizerException ex) { - throw new TransformationException("empty", ex); - } catch (XMLSecurityException ex) { - throw new TransformationException("empty", ex); - } catch (SAXException ex) { - throw new TransformationException("empty", ex); - } catch (IOException ex) { - throw new TransformationException("empty", ex); - } catch (ParserConfigurationException ex) { - throw new TransformationException("empty", ex); - } - } + input.addNodeFilter( + new XPath2NodeFilter(unionNodes, subtractNodes, intersectNodes) + ); + input.setNodeSet(true); + return input; + } catch (TransformerException ex) { + throw new TransformationException("empty", ex); + } catch (DOMException ex) { + throw new TransformationException("empty", ex); + } catch (CanonicalizationException ex) { + throw new TransformationException("empty", ex); + } catch (InvalidCanonicalizerException ex) { + throw new TransformationException("empty", ex); + } catch (XMLSecurityException ex) { + throw new TransformationException("empty", ex); + } catch (SAXException ex) { + throw new TransformationException("empty", ex); + } catch (IOException ex) { + throw new TransformationException("empty", ex); + } catch (ParserConfigurationException ex) { + throw new TransformationException("empty", ex); + } + } } class XPath2NodeFilter implements NodeFilter { - boolean hasUnionFilter; - boolean hasSubstractFilter; - boolean hasIntersectFilter; - XPath2NodeFilter(List unionNodes, List substractNodes, - List intersectNodes) { - hasUnionFilter=!unionNodes.isEmpty(); - this.unionNodes=convertNodeListToSet(unionNodes); - hasSubstractFilter=!substractNodes.isEmpty(); - this.substractNodes=convertNodeListToSet(substractNodes); - hasIntersectFilter=!intersectNodes.isEmpty(); - this.intersectNodes=convertNodeListToSet(intersectNodes); + + boolean hasUnionFilter; + boolean hasSubtractFilter; + boolean hasIntersectFilter; + Set unionNodes; + Set subtractNodes; + Set intersectNodes; + int inSubtract = -1; + int inIntersect = -1; + int inUnion = -1; + + XPath2NodeFilter(List unionNodes, List subtractNodes, + List intersectNodes) { + hasUnionFilter = !unionNodes.isEmpty(); + this.unionNodes = convertNodeListToSet(unionNodes); + hasSubtractFilter = !subtractNodes.isEmpty(); + this.subtractNodes = convertNodeListToSet(subtractNodes); + hasIntersectFilter = !intersectNodes.isEmpty(); + this.intersectNodes = convertNodeListToSet(intersectNodes); + } + + /** + * @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node) + */ + public int isNodeInclude(Node currentNode) { + int result = 1; + + if (hasSubtractFilter && rooted(currentNode, subtractNodes)) { + result = -1; + } else if (hasIntersectFilter && !rooted(currentNode, intersectNodes)) { + result = 0; } - Set unionNodes; - Set substractNodes; - Set intersectNodes; + //TODO OPTIMIZE + if (result == 1) { + return 1; + } + if (hasUnionFilter) { + if (rooted(currentNode, unionNodes)) { + return 1; + } + result = 0; + } + return result; + } - /** - * @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node) - */ - public int isNodeInclude(Node currentNode) { - int result=1; + public int isNodeIncludeDO(Node n, int level) { + int result = 1; + if (hasSubtractFilter) { + if ((inSubtract == -1) || (level <= inSubtract)) { + if (inList(n, subtractNodes)) { + inSubtract = level; + } else { + inSubtract = -1; + } + } + if (inSubtract != -1){ + result = -1; + } + } + if (result != -1 && hasIntersectFilter + && ((inIntersect == -1) || (level <= inIntersect))) { + if (!inList(n, intersectNodes)) { + inIntersect = -1; + result = 0; + } else { + inIntersect = level; + } + } - if (hasSubstractFilter && rooted(currentNode, substractNodes)) { - result = -1; - } else if (hasIntersectFilter && !rooted(currentNode, intersectNodes)) { - result = 0; - } + if (level <= inUnion) { + inUnion = -1; + } + if (result == 1) { + return 1; + } + if (hasUnionFilter) { + if ((inUnion == -1) && inList(n, unionNodes)) { + inUnion = level; + } + if (inUnion != -1) { + return 1; + } + result=0; + } - //TODO OPTIMIZE - if (result==1) - return 1; - if (hasUnionFilter) { - if (rooted(currentNode, unionNodes)) { - return 1; - } - result=0; - } - return result; + return result; + } - } - int inSubstract=-1; - int inIntersect=-1; - int inUnion=-1; - public int isNodeIncludeDO(Node n, int level) { - int result=1; - if (hasSubstractFilter) { - if ((inSubstract==-1) || (level<=inSubstract)) { - if (inList(n, substractNodes)) { - inSubstract=level; - } else { - inSubstract=-1; - } - } - if (inSubstract!=-1){ - result=-1; - } - } - if (result!=-1){ - if (hasIntersectFilter) { - if ((inIntersect==-1) || (level<=inIntersect)) { - if (!inList(n, intersectNodes)) { - inIntersect=-1; - result=0; - } else { - inIntersect=level; - } - } - } - } + /** + * Method rooted + * @param currentNode + * @param nodeList + * + * @return if rooted bye the rootnodes + */ + static boolean rooted(Node currentNode, Set nodeList) { + if (nodeList.isEmpty()) { + return false; + } + if (nodeList.contains(currentNode)) { + return true; + } + for (Node rootNode : nodeList) { + if (XMLUtils.isDescendantOrSelf(rootNode, currentNode)) { + return true; + } + } + return false; + } - if (level<=inUnion) - inUnion=-1; - if (result==1) - return 1; - if (hasUnionFilter) { - if ((inUnion==-1) && inList(n, unionNodes)) { - inUnion=level; - } - if (inUnion!=-1) - return 1; - result=0; - } - - return result; - } - - /** - * Method rooted - * @param currentNode - * @param nodeList - * - * @return if rooted bye the rootnodes - */ - static boolean rooted(Node currentNode, Set nodeList ) { - if (nodeList.isEmpty()) { - return false; - } - if (nodeList.contains(currentNode)) { - return true; - } - - for(Node rootNode : nodeList) { - if (XMLUtils.isDescendantOrSelf(rootNode,currentNode)) { - return true; - } - } - return false; - } - - /** - * Method rooted - * @param currentNode - * @param nodeList - * - * @return if rooted bye the rootnodes - */ - static boolean inList(Node currentNode, Set nodeList ) { - return nodeList.contains(currentNode); - } - - private static Set convertNodeListToSet(List l){ - Set result=new HashSet(); + /** + * Method rooted + * @param currentNode + * @param nodeList + * + * @return if rooted bye the rootnodes + */ + static boolean inList(Node currentNode, Set nodeList) { + return nodeList.contains(currentNode); + } + private static Set convertNodeListToSet(List l) { + Set result = new HashSet(); for (NodeList rootNodes : l) { - int length = rootNodes.getLength(); - for (int i = 0; i < length; i++) { - Node rootNode = rootNodes.item(i); - result.add(rootNode); - } + int length = rootNodes.getLength(); + + for (int i = 0; i < length; i++) { + Node rootNode = rootNodes.item(i); + result.add(rootNode); + } } return result; } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java index 71ba9604d1c..e2cae9b0237 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java @@ -2,26 +2,27 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms.implementations; - - +import java.io.OutputStream; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.transforms.Transform; @@ -29,8 +30,6 @@ import com.sun.org.apache.xml.internal.security.transforms.TransformSpi; import com.sun.org.apache.xml.internal.security.transforms.TransformationException; import com.sun.org.apache.xml.internal.security.transforms.Transforms; - - /** * Class TransformXPointer * @@ -38,30 +37,29 @@ import com.sun.org.apache.xml.internal.security.transforms.Transforms; */ public class TransformXPointer extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_XPOINTER; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_XPOINTER; - /** @inheritDoc */ - protected String engineGetURI() { - return implementedTransformURI; - } + /** @inheritDoc */ + protected String engineGetURI() { + return implementedTransformURI; + } - /** - * Method enginePerformTransform - * - * @param input - * @return {@link XMLSignatureInput} as the result of transformation - * @throws TransformationException - * - */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject) - throws TransformationException { + /** + * Method enginePerformTransform + * + * @param input + * @return {@link XMLSignatureInput} as the result of transformation + * @throws TransformationException + */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws TransformationException { - Object exArgs[] = { implementedTransformURI }; + Object exArgs[] = { implementedTransformURI }; - throw new TransformationException( - "signature.Transform.NotYetImplemented", exArgs); - } + throw new TransformationException("signature.Transform.NotYetImplemented", exArgs); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java index 12c8f636ca4..bf9adf5096e 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2007 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms.implementations; @@ -24,7 +26,6 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; -import java.lang.reflect.Method; import javax.xml.XMLConstants; import javax.xml.transform.Source; @@ -55,132 +56,112 @@ import org.w3c.dom.Element; */ public class TransformXSLT extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_XSLT; - //J- - static final String XSLTSpecNS = "http://www.w3.org/1999/XSL/Transform"; - static final String defaultXSLTSpecNSprefix = "xslt"; - static final String XSLTSTYLESHEET = "stylesheet"; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_XSLT; - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - TransformXSLT.class.getName()); + static final String XSLTSpecNS = "http://www.w3.org/1999/XSL/Transform"; + static final String defaultXSLTSpecNSprefix = "xslt"; + static final String XSLTSTYLESHEET = "stylesheet"; - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(TransformXSLT.class.getName()); - /** - * Method enginePerformTransform - * - * @param input the input for this transform - * @return the result of this Transform - * @throws IOException - * @throws TransformationException - */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws IOException, - TransformationException { - return enginePerformTransform(input, null, _transformObject); - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; + } - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream baos, Transform _transformObject) - throws IOException, - TransformationException { - try { - Element transformElement = _transformObject.getElement(); + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream baos, Transform transformObject + ) throws IOException, TransformationException { + try { + Element transformElement = transformObject.getElement(); - Element _xsltElement = - XMLUtils.selectNode(transformElement.getFirstChild(), - XSLTSpecNS,"stylesheet", 0); + Element xsltElement = + XMLUtils.selectNode(transformElement.getFirstChild(), XSLTSpecNS, "stylesheet", 0); - if (_xsltElement == null) { - Object exArgs[] = { "xslt:stylesheet", "Transform" }; + if (xsltElement == null) { + Object exArgs[] = { "xslt:stylesheet", "Transform" }; - throw new TransformationException("xml.WrongContent", exArgs); - } + throw new TransformationException("xml.WrongContent", exArgs); + } - TransformerFactory tFactory = TransformerFactory.newInstance(); + TransformerFactory tFactory = TransformerFactory.newInstance(); + // Process XSLT stylesheets in a secure manner + tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); - // Process XSLT stylesheets in a secure manner - tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, - Boolean.TRUE); - /* - * This transform requires an octet stream as input. If the actual - * input is an XPath node-set, then the signature application should - * attempt to convert it to octets (apply Canonical XML]) as described - * in the Reference Processing Model (section 4.3.3.2). - */ - Source xmlSource = - new StreamSource(new ByteArrayInputStream(input.getBytes())); - Source stylesheet; + /* + * This transform requires an octet stream as input. If the actual + * input is an XPath node-set, then the signature application should + * attempt to convert it to octets (apply Canonical XML]) as described + * in the Reference Processing Model (section 4.3.3.2). + */ + Source xmlSource = + new StreamSource(new ByteArrayInputStream(input.getBytes())); + Source stylesheet; - /* - * This complicated transformation of the stylesheet itself is necessary - * because of the need to get the pure style sheet. If we simply say - * Source stylesheet = new DOMSource(this._xsltElement); - * whereby this._xsltElement is not the rootElement of the Document, - * this causes problems; - * so we convert the stylesheet to byte[] and use this as input stream - */ - { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - Transformer transformer = tFactory.newTransformer(); - DOMSource source = new DOMSource(_xsltElement); - StreamResult result = new StreamResult(os); + /* + * This complicated transformation of the stylesheet itself is necessary + * because of the need to get the pure style sheet. If we simply say + * Source stylesheet = new DOMSource(this.xsltElement); + * whereby this.xsltElement is not the rootElement of the Document, + * this causes problems; + * so we convert the stylesheet to byte[] and use this as input stream + */ + { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + Transformer transformer = tFactory.newTransformer(); + DOMSource source = new DOMSource(xsltElement); + StreamResult result = new StreamResult(os); - transformer.transform(source, result); + transformer.transform(source, result); - stylesheet = - new StreamSource(new ByteArrayInputStream(os.toByteArray())); - } + stylesheet = + new StreamSource(new ByteArrayInputStream(os.toByteArray())); + } - Transformer transformer = tFactory.newTransformer(stylesheet); + Transformer transformer = tFactory.newTransformer(stylesheet); - // Force Xalan to use \n as line separator on all OSes. This - // avoids OS specific signature validation failures due to line - // separator differences in the transformed output. Unfortunately, - // this is not a standard JAXP property so will not work with non-Xalan - // implementations. - try { - transformer.setOutputProperty - ("{http://xml.apache.org/xalan}line-separator", "\n"); - } catch (Exception e) { - log.log(java.util.logging.Level.WARNING, "Unable to set Xalan line-separator property: " - + e.getMessage()); - } + // Force Xalan to use \n as line separator on all OSes. This + // avoids OS specific signature validation failures due to line + // separator differences in the transformed output. Unfortunately, + // this is not a standard JAXP property so will not work with non-Xalan + // implementations. + try { + transformer.setOutputProperty("{http://xml.apache.org/xalan}line-separator", "\n"); + } catch (Exception e) { + log.log(java.util.logging.Level.WARNING, "Unable to set Xalan line-separator property: " + e.getMessage()); + } + + if (baos == null) { + ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); + StreamResult outputTarget = new StreamResult(baos1); + transformer.transform(xmlSource, outputTarget); + return new XMLSignatureInput(baos1.toByteArray()); + } + StreamResult outputTarget = new StreamResult(baos); - if (baos==null) { - ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); - StreamResult outputTarget = new StreamResult(baos1); transformer.transform(xmlSource, outputTarget); - return new XMLSignatureInput(baos1.toByteArray()); - } - StreamResult outputTarget = new StreamResult(baos); + XMLSignatureInput output = new XMLSignatureInput((byte[])null); + output.setOutputStream(baos); + return output; + } catch (XMLSecurityException ex) { + Object exArgs[] = { ex.getMessage() }; - transformer.transform(xmlSource, outputTarget); - XMLSignatureInput output=new XMLSignatureInput((byte[])null); - output.setOutputStream(baos); - return output; - } catch (XMLSecurityException ex) { - Object exArgs[] = { ex.getMessage() }; + throw new TransformationException("generic.EmptyMessage", exArgs, ex); + } catch (TransformerConfigurationException ex) { + Object exArgs[] = { ex.getMessage() }; - throw new TransformationException("generic.EmptyMessage", exArgs, ex); - } catch (TransformerConfigurationException ex) { - Object exArgs[] = { ex.getMessage() }; + throw new TransformationException("generic.EmptyMessage", exArgs, ex); + } catch (TransformerException ex) { + Object exArgs[] = { ex.getMessage() }; - throw new TransformationException("generic.EmptyMessage", exArgs, ex); - } catch (TransformerException ex) { - Object exArgs[] = { ex.getMessage() }; - - throw new TransformationException("generic.EmptyMessage", exArgs, ex); - } - } + throw new TransformationException("generic.EmptyMessage", exArgs, ex); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java index f615881bade..2b6f5da2f16 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java @@ -2,30 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms.params; - - -import java.util.Iterator; import java.util.Set; import java.util.SortedSet; -import java.util.StringTokenizer; import java.util.TreeSet; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; @@ -34,7 +32,6 @@ import com.sun.org.apache.xml.internal.security.utils.ElementProxy; import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * This Object serves as Content for the ds:Transforms for exclusive * Canonicalization. @@ -44,136 +41,130 @@ import org.w3c.dom.Element; * * @author Christian Geuer-Pollmann */ -public class InclusiveNamespaces extends ElementProxy - implements TransformParam { +public class InclusiveNamespaces extends ElementProxy implements TransformParam { - /** Field _TAG_EC_INCLUSIVENAMESPACES */ - public static final String _TAG_EC_INCLUSIVENAMESPACES = - "InclusiveNamespaces"; + /** Field _TAG_EC_INCLUSIVENAMESPACES */ + public static final String _TAG_EC_INCLUSIVENAMESPACES = + "InclusiveNamespaces"; - /** Field _ATT_EC_PREFIXLIST */ - public static final String _ATT_EC_PREFIXLIST = "PrefixList"; + /** Field _ATT_EC_PREFIXLIST */ + public static final String _ATT_EC_PREFIXLIST = "PrefixList"; - /** Field ExclusiveCanonicalizationNamespace */ - public static final String ExclusiveCanonicalizationNamespace = - "http://www.w3.org/2001/10/xml-exc-c14n#"; + /** Field ExclusiveCanonicalizationNamespace */ + public static final String ExclusiveCanonicalizationNamespace = + "http://www.w3.org/2001/10/xml-exc-c14n#"; - /** - * Constructor XPathContainer - * - * @param doc - * @param prefixList - */ - public InclusiveNamespaces(Document doc, String prefixList) { - this(doc, InclusiveNamespaces.prefixStr2Set(prefixList)); - } + /** + * Constructor XPathContainer + * + * @param doc + * @param prefixList + */ + public InclusiveNamespaces(Document doc, String prefixList) { + this(doc, InclusiveNamespaces.prefixStr2Set(prefixList)); + } - /** - * Constructor InclusiveNamespaces - * - * @param doc - * @param prefixes - */ - public InclusiveNamespaces(Document doc, Set prefixes) { + /** + * Constructor InclusiveNamespaces + * + * @param doc + * @param prefixes + */ + public InclusiveNamespaces(Document doc, Set prefixes) { + super(doc); - super(doc); + SortedSet prefixList = null; + if (prefixes instanceof SortedSet) { + prefixList = (SortedSet)prefixes; + } else { + prefixList = new TreeSet(prefixes); + } - StringBuffer sb = new StringBuffer(); - SortedSet prefixList = new TreeSet(prefixes); + StringBuilder sb = new StringBuilder(); + for (String prefix : prefixList) { + if (prefix.equals("xmlns")) { + sb.append("#default "); + } else { + sb.append(prefix + " "); + } + } + this.constructionElement.setAttributeNS( + null, InclusiveNamespaces._ATT_EC_PREFIXLIST, sb.toString().trim()); + } + /** + * Constructor InclusiveNamespaces + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public InclusiveNamespaces(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } - for (String prefix : prefixList) { - if (prefix.equals("xmlns")) { - sb.append("#default "); - } else { - sb.append(prefix + " "); - } - } + /** + * Method getInclusiveNamespaces + * + * @return The Inclusive Namespace string + */ + public String getInclusiveNamespaces() { + return this.constructionElement.getAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST); + } - this._constructionElement - .setAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST, - sb.toString().trim()); - } + /** + * Decodes the inclusiveNamespaces String and returns all + * selected namespace prefixes as a Set. The #default + * namespace token is represented as an empty namespace prefix + * ("xmlns"). + *
    + * The String inclusiveNamespaces=" xenc ds #default" + * is returned as a Set containing the following Strings: + *
      + *
    • xmlns
    • + *
    • xenc
    • + *
    • ds
    • + *
    + * + * @param inclusiveNamespaces + * @return A set to string + */ + public static SortedSet prefixStr2Set(String inclusiveNamespaces) { + SortedSet prefixes = new TreeSet(); - /** - * Method getInclusiveNamespaces - * - * @return The Inclusive Namespace string - */ - public String getInclusiveNamespaces() { - return this._constructionElement - .getAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST); - } + if ((inclusiveNamespaces == null) || (inclusiveNamespaces.length() == 0)) { + return prefixes; + } - /** - * Constructor InclusiveNamespaces - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public InclusiveNamespaces(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + String[] tokens = inclusiveNamespaces.split("\\s"); + for (String prefix : tokens) { + if (prefix.equals("#default")) { + prefixes.add("xmlns"); + } else { + prefixes.add(prefix); + } + } - /** - * Decodes the inclusiveNamespaces String and returns all - * selected namespace prefixes as a Set. The #default - * namespace token is represented as an empty namespace prefix - * ("xmlns"). - *
    - * The String inclusiveNamespaces=" xenc ds #default" - * is returned as a Set containing the following Strings: - *
      - *
    • xmlns
    • - *
    • xenc
    • - *
    • ds
    • - *
    - * - * @param inclusiveNamespaces - * @return A set to string - */ - public static SortedSet prefixStr2Set(String inclusiveNamespaces) { + return prefixes; + } - SortedSet prefixes = new TreeSet(); + /** + * Method getBaseNamespace + * + * @inheritDoc + */ + public String getBaseNamespace() { + return InclusiveNamespaces.ExclusiveCanonicalizationNamespace; + } - if ((inclusiveNamespaces == null) - || (inclusiveNamespaces.length() == 0)) { - return prefixes; - } - - StringTokenizer st = new StringTokenizer(inclusiveNamespaces, " \t\r\n"); - - while (st.hasMoreTokens()) { - String prefix = st.nextToken(); - - if (prefix.equals("#default")) { - prefixes.add("xmlns" ); - } else { - prefixes.add( prefix); - } - } - - return prefixes; - } - - /** - * Method getBaseNamespace - * - * @inheritDoc - */ - public String getBaseNamespace() { - return InclusiveNamespaces.ExclusiveCanonicalizationNamespace; - } - - /** - * Method getBaseLocalName - * - * @inheritDoc - */ - public String getBaseLocalName() { - return InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES; - } + /** + * Method getBaseLocalName + * + * @inheritDoc + */ + public String getBaseLocalName() { + return InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java index 366f31acf80..19de51976cf 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms.params; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.transforms.TransformParam; import com.sun.org.apache.xml.internal.security.utils.ElementProxy; @@ -32,284 +32,261 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; - /** * Implements the parameters for the XPath Filter v2.0. * - * @author $Author: mullan $ + * @author $Author: coheigea $ * @see XPath Filter v2.0 (TR) - * @see XPath Filter v2.0 (editors copy) */ -public class XPath2FilterContainer extends ElementProxy - implements TransformParam { +public class XPath2FilterContainer extends ElementProxy implements TransformParam { - /** Field _ATT_FILTER */ - private static final String _ATT_FILTER = "Filter"; + /** Field _ATT_FILTER */ + private static final String _ATT_FILTER = "Filter"; - /** Field _ATT_FILTER_VALUE_INTERSECT */ - private static final String _ATT_FILTER_VALUE_INTERSECT = "intersect"; + /** Field _ATT_FILTER_VALUE_INTERSECT */ + private static final String _ATT_FILTER_VALUE_INTERSECT = "intersect"; - /** Field _ATT_FILTER_VALUE_SUBTRACT */ - private static final String _ATT_FILTER_VALUE_SUBTRACT = "subtract"; + /** Field _ATT_FILTER_VALUE_SUBTRACT */ + private static final String _ATT_FILTER_VALUE_SUBTRACT = "subtract"; - /** Field _ATT_FILTER_VALUE_UNION */ - private static final String _ATT_FILTER_VALUE_UNION = "union"; + /** Field _ATT_FILTER_VALUE_UNION */ + private static final String _ATT_FILTER_VALUE_UNION = "union"; - /** Field INTERSECT */ - public static final String INTERSECT = - XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT; + /** Field INTERSECT */ + public static final String INTERSECT = + XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT; - /** Field SUBTRACT */ - public static final String SUBTRACT = - XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT; + /** Field SUBTRACT */ + public static final String SUBTRACT = + XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT; - /** Field UNION */ - public static final String UNION = - XPath2FilterContainer._ATT_FILTER_VALUE_UNION; + /** Field UNION */ + public static final String UNION = + XPath2FilterContainer._ATT_FILTER_VALUE_UNION; - /** Field _TAG_XPATH2 */ - public static final String _TAG_XPATH2 = "XPath"; + /** Field _TAG_XPATH2 */ + public static final String _TAG_XPATH2 = "XPath"; - /** Field XPathFiler2NS */ - public static final String XPathFilter2NS = - "http://www.w3.org/2002/06/xmldsig-filter2"; + /** Field XPathFiler2NS */ + public static final String XPathFilter2NS = + "http://www.w3.org/2002/06/xmldsig-filter2"; - /** - * Constructor XPath2FilterContainer - * - */ - private XPath2FilterContainer() { + /** + * Constructor XPath2FilterContainer + * + */ + private XPath2FilterContainer() { + // no instantiation + } - // no instantiation - } + /** + * Constructor XPath2FilterContainer + * + * @param doc + * @param xpath2filter + * @param filterType + */ + private XPath2FilterContainer(Document doc, String xpath2filter, String filterType) { + super(doc); - /** - * Constructor XPath2FilterContainer - * - * @param doc - * @param xpath2filter - * @param filterType - */ - private XPath2FilterContainer(Document doc, String xpath2filter, - String filterType) { + this.constructionElement.setAttributeNS( + null, XPath2FilterContainer._ATT_FILTER, filterType); + this.constructionElement.appendChild(doc.createTextNode(xpath2filter)); + } - super(doc); + /** + * Constructor XPath2FilterContainer + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + private XPath2FilterContainer(Element element, String BaseURI) throws XMLSecurityException { - this._constructionElement - .setAttributeNS(null, XPath2FilterContainer._ATT_FILTER, filterType); - this._constructionElement.appendChild(doc.createTextNode(xpath2filter)); - } + super(element, BaseURI); - /** - * Constructor XPath2FilterContainer - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - private XPath2FilterContainer(Element element, String BaseURI) - throws XMLSecurityException { + String filterStr = + this.constructionElement.getAttributeNS(null, XPath2FilterContainer._ATT_FILTER); - super(element, BaseURI); + if (!filterStr.equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT) + && !filterStr.equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT) + && !filterStr.equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION)) { + Object exArgs[] = { XPath2FilterContainer._ATT_FILTER, filterStr, + XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT + + ", " + + XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT + + " or " + + XPath2FilterContainer._ATT_FILTER_VALUE_UNION }; - String filterStr = this._constructionElement.getAttributeNS(null, - XPath2FilterContainer._ATT_FILTER); + throw new XMLSecurityException("attributeValueIllegal", exArgs); + } + } - if (!filterStr - .equals(XPath2FilterContainer - ._ATT_FILTER_VALUE_INTERSECT) &&!filterStr - .equals(XPath2FilterContainer - ._ATT_FILTER_VALUE_SUBTRACT) &&!filterStr - .equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION)) { - Object exArgs[] = { XPath2FilterContainer._ATT_FILTER, filterStr, - XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT - + ", " - + XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT - + " or " - + XPath2FilterContainer._ATT_FILTER_VALUE_UNION }; + /** + * Creates a new XPath2FilterContainer with the filter type "intersect". + * + * @param doc + * @param xpath2filter + * @return the filter. + */ + public static XPath2FilterContainer newInstanceIntersect( + Document doc, String xpath2filter + ) { + return new XPath2FilterContainer( + doc, xpath2filter, XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT); + } - throw new XMLSecurityException("attributeValueIllegal", exArgs); - } - } + /** + * Creates a new XPath2FilterContainer with the filter type "subtract". + * + * @param doc + * @param xpath2filter + * @return the filter. + */ + public static XPath2FilterContainer newInstanceSubtract(Document doc, String xpath2filter) { + return new XPath2FilterContainer( + doc, xpath2filter, XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT); + } - /** - * Creates a new XPath2FilterContainer with the filter type "intersect". - * - * @param doc - * @param xpath2filter - * @return the filter. - */ - public static XPath2FilterContainer newInstanceIntersect(Document doc, - String xpath2filter) { + /** + * Creates a new XPath2FilterContainer with the filter type "union". + * + * @param doc + * @param xpath2filter + * @return the filter + */ + public static XPath2FilterContainer newInstanceUnion(Document doc, String xpath2filter) { + return new XPath2FilterContainer( + doc, xpath2filter, XPath2FilterContainer._ATT_FILTER_VALUE_UNION); + } - return new XPath2FilterContainer(doc, xpath2filter, - XPath2FilterContainer - ._ATT_FILTER_VALUE_INTERSECT); - } + /** + * Method newInstances + * + * @param doc + * @param params + * @return the nodelist with the data + */ + public static NodeList newInstances(Document doc, String[][] params) { + HelperNodeList nl = new HelperNodeList(); - /** - * Creates a new XPath2FilterContainer with the filter type "subtract". - * - * @param doc - * @param xpath2filter - * @return the filter. - */ - public static XPath2FilterContainer newInstanceSubtract(Document doc, - String xpath2filter) { + XMLUtils.addReturnToElement(doc, nl); - return new XPath2FilterContainer(doc, xpath2filter, - XPath2FilterContainer - ._ATT_FILTER_VALUE_SUBTRACT); - } + for (int i = 0; i < params.length; i++) { + String type = params[i][0]; + String xpath = params[i][1]; - /** - * Creates a new XPath2FilterContainer with the filter type "union". - * - * @param doc - * @param xpath2filter - * @return the filter - */ - public static XPath2FilterContainer newInstanceUnion(Document doc, - String xpath2filter) { + if (!(type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT) + || type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT) + || type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION))){ + throw new IllegalArgumentException("The type(" + i + ")=\"" + type + + "\" is illegal"); + } - return new XPath2FilterContainer(doc, xpath2filter, - XPath2FilterContainer - ._ATT_FILTER_VALUE_UNION); - } + XPath2FilterContainer c = new XPath2FilterContainer(doc, xpath, type); - /** - * Method newInstances - * - * @param doc - * @param params - * @return the nodelist with the data - */ - public static NodeList newInstances(Document doc, String[][] params) { + nl.appendChild(c.getElement()); + XMLUtils.addReturnToElement(doc, nl); + } - HelperNodeList nl = new HelperNodeList(); + return nl; + } - XMLUtils.addReturnToElement(doc, nl); + /** + * Creates a XPath2FilterContainer from an existing Element; needed for verification. + * + * @param element + * @param BaseURI + * @return the filter + * + * @throws XMLSecurityException + */ + public static XPath2FilterContainer newInstance( + Element element, String BaseURI + ) throws XMLSecurityException { + return new XPath2FilterContainer(element, BaseURI); + } - for (int i = 0; i < params.length; i++) { - String type = params[i][0]; - String xpath = params[i][1]; + /** + * Returns true if the Filter attribute has value "intersect". + * + * @return true if the Filter attribute has value "intersect". + */ + public boolean isIntersect() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer._ATT_FILTER + ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT); + } - if (!(type.equals(XPath2FilterContainer - ._ATT_FILTER_VALUE_INTERSECT) || type - .equals(XPath2FilterContainer - ._ATT_FILTER_VALUE_SUBTRACT) || type - .equals(XPath2FilterContainer - ._ATT_FILTER_VALUE_UNION))) { - throw new IllegalArgumentException("The type(" + i + ")=\"" + type - + "\" is illegal"); - } + /** + * Returns true if the Filter attribute has value "subtract". + * + * @return true if the Filter attribute has value "subtract". + */ + public boolean isSubtract() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer._ATT_FILTER + ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT); + } - XPath2FilterContainer c = new XPath2FilterContainer(doc, xpath, type); + /** + * Returns true if the Filter attribute has value "union". + * + * @return true if the Filter attribute has value "union". + */ + public boolean isUnion() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer._ATT_FILTER + ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION); + } - nl.appendChild(c.getElement()); - XMLUtils.addReturnToElement(doc, nl); - } + /** + * Returns the XPath 2 Filter String + * + * @return the XPath 2 Filter String + */ + public String getXPathFilterStr() { + return this.getTextFromTextChild(); + } - return nl; - } + /** + * Returns the first Text node which contains information from the XPath 2 + * Filter String. We must use this stupid hook to enable the here() function + * to work. + * + * $todo$ I dunno whether this crashes: here()/ds:Signature[1] + * @return the first Text node which contains information from the XPath 2 Filter String + */ + public Node getXPathFilterTextNode() { - /** - * Creates a XPath2FilterContainer from an existing Element; needed for verification. - * - * @param element - * @param BaseURI - * @return the filter - * - * @throws XMLSecurityException - */ - public static XPath2FilterContainer newInstance( - Element element, String BaseURI) throws XMLSecurityException { - return new XPath2FilterContainer(element, BaseURI); - } + NodeList children = this.constructionElement.getChildNodes(); + int length = children.getLength(); - /** - * Returns true if the Filter attribute has value "intersect". - * - * @return true if the Filter attribute has value "intersect". - */ - public boolean isIntersect() { + for (int i = 0; i < length; i++) { + if (children.item(i).getNodeType() == Node.TEXT_NODE) { + return children.item(i); + } + } - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer._ATT_FILTER) - .equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT); - } + return null; + } - /** - * Returns true if the Filter attribute has value "subtract". - * - * @return true if the Filter attribute has value "subtract". - */ - public boolean isSubtract() { + /** + * Method getBaseLocalName + * + * @return the XPATH2 tag + */ + public final String getBaseLocalName() { + return XPath2FilterContainer._TAG_XPATH2; + } - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer._ATT_FILTER) - .equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT); - } - - /** - * Returns true if the Filter attribute has value "union". - * - * @return true if the Filter attribute has value "union". - */ - public boolean isUnion() { - - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer._ATT_FILTER) - .equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION); - } - - /** - * Returns the XPath 2 Filter String - * - * @return the XPath 2 Filter String - */ - public String getXPathFilterStr() { - return this.getTextFromTextChild(); - } - - /** - * Returns the first Text node which contains information from the XPath 2 - * Filter String. We must use this stupid hook to enable the here() function - * to work. - * - * $todo$ I dunno whether this crashes: here()/ds:Signature[1] - * @return the first Text node which contains information from the XPath 2 Filter String - */ - public Node getXPathFilterTextNode() { - - NodeList children = this._constructionElement.getChildNodes(); - int length = children.getLength(); - - for (int i = 0; i < length; i++) { - if (children.item(i).getNodeType() == Node.TEXT_NODE) { - return children.item(i); - } - } - - return null; - } - - /** - * Method getBaseLocalName - * - * @return the XPATH2 tag - */ - public final String getBaseLocalName() { - return XPath2FilterContainer._TAG_XPATH2; - } - - /** - * Method getBaseNamespace - * - * @return XPATH2 tag namespace - */ - public final String getBaseNamespace() { - return XPath2FilterContainer.XPathFilter2NS; - } + /** + * Method getBaseNamespace + * + * @return XPATH2 tag namespace + */ + public final String getBaseNamespace() { + return XPath2FilterContainer.XPathFilter2NS; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java index 25008eed743..2eed2cb1fdf 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms.params; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.transforms.TransformParam; import com.sun.org.apache.xml.internal.security.utils.ElementProxy; @@ -31,237 +31,222 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; - /** * Implements the parameters for the XPath Filter v2.0. * - * @author $Author: mullan $ + * @author $Author: coheigea $ * @see XPath Filter v2.0 (TR) - * @see XPath Filter v2.0 (editors copy) */ -public class XPath2FilterContainer04 extends ElementProxy - implements TransformParam { +public class XPath2FilterContainer04 extends ElementProxy implements TransformParam { - /** Field _ATT_FILTER */ - private static final String _ATT_FILTER = "Filter"; + /** Field _ATT_FILTER */ + private static final String _ATT_FILTER = "Filter"; - /** Field _ATT_FILTER_VALUE_INTERSECT */ - private static final String _ATT_FILTER_VALUE_INTERSECT = "intersect"; + /** Field _ATT_FILTER_VALUE_INTERSECT */ + private static final String _ATT_FILTER_VALUE_INTERSECT = "intersect"; - /** Field _ATT_FILTER_VALUE_SUBTRACT */ - private static final String _ATT_FILTER_VALUE_SUBTRACT = "subtract"; + /** Field _ATT_FILTER_VALUE_SUBTRACT */ + private static final String _ATT_FILTER_VALUE_SUBTRACT = "subtract"; - /** Field _ATT_FILTER_VALUE_UNION */ - private static final String _ATT_FILTER_VALUE_UNION = "union"; + /** Field _ATT_FILTER_VALUE_UNION */ + private static final String _ATT_FILTER_VALUE_UNION = "union"; - /** Field _TAG_XPATH2 */ - public static final String _TAG_XPATH2 = "XPath"; + /** Field _TAG_XPATH2 */ + public static final String _TAG_XPATH2 = "XPath"; - /** Field XPathFiler2NS */ - public static final String XPathFilter2NS = - "http://www.w3.org/2002/04/xmldsig-filter2"; + /** Field XPathFiler2NS */ + public static final String XPathFilter2NS = + "http://www.w3.org/2002/04/xmldsig-filter2"; - /** - * Constructor XPath2FilterContainer04 - * - */ - private XPath2FilterContainer04() { + /** + * Constructor XPath2FilterContainer04 + * + */ + private XPath2FilterContainer04() { - // no instantiation - } + // no instantiation + } - /** - * Constructor XPath2FilterContainer04 - * - * @param doc - * @param xpath2filter - * @param filterType - */ - private XPath2FilterContainer04(Document doc, String xpath2filter, - String filterType) { + /** + * Constructor XPath2FilterContainer04 + * + * @param doc + * @param xpath2filter + * @param filterType + */ + private XPath2FilterContainer04(Document doc, String xpath2filter, String filterType) { + super(doc); - super(doc); + this.constructionElement.setAttributeNS( + null, XPath2FilterContainer04._ATT_FILTER, filterType); - this._constructionElement.setAttributeNS(null, XPath2FilterContainer04._ATT_FILTER, - filterType); + if ((xpath2filter.length() > 2) + && (!Character.isWhitespace(xpath2filter.charAt(0)))) { + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(doc.createTextNode(xpath2filter)); + XMLUtils.addReturnToElement(this.constructionElement); + } else { + this.constructionElement.appendChild(doc.createTextNode(xpath2filter)); + } + } - if ((xpath2filter.length() > 2) - && (!Character.isWhitespace(xpath2filter.charAt(0)))) { - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(doc.createTextNode(xpath2filter)); - XMLUtils.addReturnToElement(this._constructionElement); - } else { - this._constructionElement - .appendChild(doc.createTextNode(xpath2filter)); - } - } + /** + * Constructor XPath2FilterContainer04 + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + private XPath2FilterContainer04(Element element, String BaseURI) + throws XMLSecurityException { - /** - * Constructor XPath2FilterContainer04 - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - private XPath2FilterContainer04(Element element, String BaseURI) - throws XMLSecurityException { + super(element, BaseURI); - super(element, BaseURI); + String filterStr = + this.constructionElement.getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER); - String filterStr = - this._constructionElement - .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER); + if (!filterStr.equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT) + && !filterStr.equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT) + && !filterStr.equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION)) { + Object exArgs[] = { XPath2FilterContainer04._ATT_FILTER, filterStr, + XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT + + ", " + + XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT + + " or " + + XPath2FilterContainer04._ATT_FILTER_VALUE_UNION }; - if (!filterStr - .equals(XPath2FilterContainer04 - ._ATT_FILTER_VALUE_INTERSECT) &&!filterStr - .equals(XPath2FilterContainer04 - ._ATT_FILTER_VALUE_SUBTRACT) &&!filterStr - .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION)) { - Object exArgs[] = { XPath2FilterContainer04._ATT_FILTER, filterStr, - XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT - + ", " - + XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT - + " or " - + XPath2FilterContainer04._ATT_FILTER_VALUE_UNION }; + throw new XMLSecurityException("attributeValueIllegal", exArgs); + } + } - throw new XMLSecurityException("attributeValueIllegal", exArgs); - } - } + /** + * Creates a new XPath2FilterContainer04 with the filter type "intersect". + * + * @param doc + * @param xpath2filter + * @return the instance + */ + public static XPath2FilterContainer04 newInstanceIntersect( + Document doc, String xpath2filter + ) { + return new XPath2FilterContainer04( + doc, xpath2filter, XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT); + } - /** - * Creates a new XPath2FilterContainer04 with the filter type "intersect". - * - * @param doc - * @param xpath2filter - * @return the instance - */ - public static XPath2FilterContainer04 newInstanceIntersect(Document doc, - String xpath2filter) { + /** + * Creates a new XPath2FilterContainer04 with the filter type "subtract". + * + * @param doc + * @param xpath2filter + * @return the instance + */ + public static XPath2FilterContainer04 newInstanceSubtract( + Document doc, String xpath2filter + ) { + return new XPath2FilterContainer04( + doc, xpath2filter, XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT); + } - return new XPath2FilterContainer04(doc, xpath2filter, - XPath2FilterContainer04 - ._ATT_FILTER_VALUE_INTERSECT); - } + /** + * Creates a new XPath2FilterContainer04 with the filter type "union". + * + * @param doc + * @param xpath2filter + * @return the instance + */ + public static XPath2FilterContainer04 newInstanceUnion( + Document doc, String xpath2filter + ) { + return new XPath2FilterContainer04( + doc, xpath2filter, XPath2FilterContainer04._ATT_FILTER_VALUE_UNION); + } - /** - * Creates a new XPath2FilterContainer04 with the filter type "subtract". - * - * @param doc - * @param xpath2filter - * @return the instance - */ - public static XPath2FilterContainer04 newInstanceSubtract(Document doc, - String xpath2filter) { + /** + * Creates a XPath2FilterContainer04 from an existing Element; needed for verification. + * + * @param element + * @param BaseURI + * @return the instance + * + * @throws XMLSecurityException + */ + public static XPath2FilterContainer04 newInstance( + Element element, String BaseURI + ) throws XMLSecurityException { + return new XPath2FilterContainer04(element, BaseURI); + } - return new XPath2FilterContainer04(doc, xpath2filter, - XPath2FilterContainer04 - ._ATT_FILTER_VALUE_SUBTRACT); - } + /** + * Returns true if the Filter attribute has value "intersect". + * + * @return true if the Filter attribute has value "intersect". + */ + public boolean isIntersect() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer04._ATT_FILTER + ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT); + } - /** - * Creates a new XPath2FilterContainer04 with the filter type "union". - * - * @param doc - * @param xpath2filter - * @return the instance - */ - public static XPath2FilterContainer04 newInstanceUnion(Document doc, - String xpath2filter) { + /** + * Returns true if the Filter attribute has value "subtract". + * + * @return true if the Filter attribute has value "subtract". + */ + public boolean isSubtract() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer04._ATT_FILTER + ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT); + } - return new XPath2FilterContainer04(doc, xpath2filter, - XPath2FilterContainer04 - ._ATT_FILTER_VALUE_UNION); - } + /** + * Returns true if the Filter attribute has value "union". + * + * @return true if the Filter attribute has value "union". + */ + public boolean isUnion() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer04._ATT_FILTER + ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION); + } - /** - * Creates a XPath2FilterContainer04 from an existing Element; needed for verification. - * - * @param element - * @param BaseURI - * @return the instance - * - * @throws XMLSecurityException - */ - public static XPath2FilterContainer04 newInstance( - Element element, String BaseURI) throws XMLSecurityException { - return new XPath2FilterContainer04(element, BaseURI); - } + /** + * Returns the XPath 2 Filter String + * + * @return the XPath 2 Filter String + */ + public String getXPathFilterStr() { + return this.getTextFromTextChild(); + } - /** - * Returns true if the Filter attribute has value "intersect". - * - * @return true if the Filter attribute has value "intersect". - */ - public boolean isIntersect() { + /** + * Returns the first Text node which contains information from the XPath 2 + * Filter String. We must use this stupid hook to enable the here() function + * to work. + * + * $todo$ I dunno whether this crashes: here()/ds:Signature[1] + * @return the first Text node which contains information from the XPath 2 Filter String + */ + public Node getXPathFilterTextNode() { + NodeList children = this.constructionElement.getChildNodes(); + int length = children.getLength(); - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER) - .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT); - } + for (int i = 0; i < length; i++) { + if (children.item(i).getNodeType() == Node.TEXT_NODE) { + return children.item(i); + } + } - /** - * Returns true if the Filter attribute has value "subtract". - * - * @return true if the Filter attribute has value "subtract". - */ - public boolean isSubtract() { + return null; + } - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER) - .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT); - } + /** @inheritDoc */ + public final String getBaseLocalName() { + return XPath2FilterContainer04._TAG_XPATH2; + } - /** - * Returns true if the Filter attribute has value "union". - * - * @return true if the Filter attribute has value "union". - */ - public boolean isUnion() { - - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER) - .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION); - } - - /** - * Returns the XPath 2 Filter String - * - * @return the XPath 2 Filter String - */ - public String getXPathFilterStr() { - return this.getTextFromTextChild(); - } - - /** - * Returns the first Text node which contains information from the XPath 2 - * Filter String. We must use this stupid hook to enable the here() function - * to work. - * - * $todo$ I dunno whether this crashes: here()/ds:Signature[1] - * @return the first Text node which contains information from the XPath 2 Filter String - */ - public Node getXPathFilterTextNode() { - NodeList children = this._constructionElement.getChildNodes(); - int length = children.getLength(); - - for (int i = 0; i < length; i++) { - if (children.item(i).getNodeType() == Node.TEXT_NODE) { - return children.item(i); - } - } - - return null; - } - - /** @inheritDoc */ - public final String getBaseLocalName() { - return XPath2FilterContainer04._TAG_XPATH2; - } - - /** @inheritDoc */ - public final String getBaseNamespace() { - return XPath2FilterContainer04.XPathFilter2NS; - } + /** @inheritDoc */ + public final String getBaseNamespace() { + return XPath2FilterContainer04.XPathFilter2NS; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java index 717889d576f..74f2ff1f50d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java @@ -2,26 +2,27 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms.params; - import com.sun.org.apache.xml.internal.security.transforms.TransformParam; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; @@ -29,7 +30,6 @@ import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Text; - /** * This Object serves both as namespace prefix resolver and as container for * the ds:XPath Element. It implements the {@link org.w3c.dom.Element} interface @@ -39,45 +39,44 @@ import org.w3c.dom.Text; */ public class XPathContainer extends SignatureElementProxy implements TransformParam { - /** - * Constructor XPathContainer - * - * @param doc - */ - public XPathContainer(Document doc) { - super(doc); - } + /** + * Constructor XPathContainer + * + * @param doc + */ + public XPathContainer(Document doc) { + super(doc); + } - /** - * Sets the TEXT value of the ds:XPath Element. - * - * @param xpath - */ - public void setXPath(String xpath) { + /** + * Sets the TEXT value of the ds:XPath Element. + * + * @param xpath + */ + public void setXPath(String xpath) { + if (this.constructionElement.getChildNodes() != null) { + NodeList nl = this.constructionElement.getChildNodes(); - if (this._constructionElement.getChildNodes() != null) { - NodeList nl = this._constructionElement.getChildNodes(); + for (int i = 0; i < nl.getLength(); i++) { + this.constructionElement.removeChild(nl.item(i)); + } + } - for (int i = 0; i < nl.getLength(); i++) { - this._constructionElement.removeChild(nl.item(i)); - } - } + Text xpathText = this.doc.createTextNode(xpath); + this.constructionElement.appendChild(xpathText); + } - Text xpathText = this._doc.createTextNode(xpath); - this._constructionElement.appendChild(xpathText); - } + /** + * Returns the TEXT value of the ds:XPath Element. + * + * @return the TEXT value of the ds:XPath Element. + */ + public String getXPath() { + return this.getTextFromTextChild(); + } - /** - * Returns the TEXT value of the ds:XPath Element. - * - * @return the TEXT value of the ds:XPath Element. - */ - public String getXPath() { - return this.getTextFromTextChild(); - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_XPATH; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_XPATH; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java index 86199d7ab63..0bb4f7e5f09 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java @@ -2,320 +2,315 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.transforms.params; - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.transforms.TransformParam; -import com.sun.org.apache.xml.internal.security.transforms.Transforms; import com.sun.org.apache.xml.internal.security.utils.ElementProxy; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; - /** * Implements the parameters for a custom Transform which has a better performance - * thatn the xfilter2. + * than the xfilter2. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ -public class XPathFilterCHGPContainer extends ElementProxy - implements TransformParam { +public class XPathFilterCHGPContainer extends ElementProxy implements TransformParam { - /** Field _ATT_FILTER_VALUE_INTERSECT */ - private static final String _TAG_INCLUDE_BUT_SEARCH = "IncludeButSearch"; + public static final String TRANSFORM_XPATHFILTERCHGP = + "http://www.nue.et-inf.uni-siegen.de/~geuer-pollmann/#xpathFilter"; - /** Field _ATT_FILTER_VALUE_SUBTRACT */ - private static final String _TAG_EXCLUDE_BUT_SEARCH = "ExcludeButSearch"; + /** Field _ATT_FILTER_VALUE_INTERSECT */ + private static final String _TAG_INCLUDE_BUT_SEARCH = "IncludeButSearch"; - /** Field _ATT_FILTER_VALUE_UNION */ - private static final String _TAG_EXCLUDE = "Exclude"; + /** Field _ATT_FILTER_VALUE_SUBTRACT */ + private static final String _TAG_EXCLUDE_BUT_SEARCH = "ExcludeButSearch"; - /** Field _TAG_XPATHCHGP */ - public static final String _TAG_XPATHCHGP = "XPathAlternative"; + /** Field _ATT_FILTER_VALUE_UNION */ + private static final String _TAG_EXCLUDE = "Exclude"; - /** Field _ATT_INCLUDESLASH */ - public static final String _ATT_INCLUDESLASH = "IncludeSlashPolicy"; + /** Field _TAG_XPATHCHGP */ + public static final String _TAG_XPATHCHGP = "XPathAlternative"; - /** Field IncludeSlash */ - public static final boolean IncludeSlash = true; + /** Field _ATT_INCLUDESLASH */ + public static final String _ATT_INCLUDESLASH = "IncludeSlashPolicy"; - /** Field ExcludeSlash */ - public static final boolean ExcludeSlash = false; + /** Field IncludeSlash */ + public static final boolean IncludeSlash = true; - /** - * Constructor XPathFilterCHGPContainer - * - */ - private XPathFilterCHGPContainer() { + /** Field ExcludeSlash */ + public static final boolean ExcludeSlash = false; - // no instantiation - } + /** + * Constructor XPathFilterCHGPContainer + * + */ + private XPathFilterCHGPContainer() { + // no instantiation + } - /** - * Constructor XPathFilterCHGPContainer - * - * @param doc - * @param includeSlashPolicy - * @param includeButSearch - * @param excludeButSearch - * @param exclude - */ - private XPathFilterCHGPContainer(Document doc, boolean includeSlashPolicy, - String includeButSearch, - String excludeButSearch, String exclude) { + /** + * Constructor XPathFilterCHGPContainer + * + * @param doc + * @param includeSlashPolicy + * @param includeButSearch + * @param excludeButSearch + * @param exclude + */ + private XPathFilterCHGPContainer( + Document doc, boolean includeSlashPolicy, String includeButSearch, + String excludeButSearch, String exclude + ) { + super(doc); - super(doc); + if (includeSlashPolicy) { + this.constructionElement.setAttributeNS( + null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "true" + ); + } else { + this.constructionElement.setAttributeNS( + null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "false" + ); + } - if (includeSlashPolicy) { - this._constructionElement - .setAttributeNS(null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "true"); - } else { - this._constructionElement - .setAttributeNS(null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "false"); - } + if ((includeButSearch != null) && (includeButSearch.trim().length() > 0)) { + Element includeButSearchElem = + ElementProxy.createElementForFamily( + doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH + ); - if ((includeButSearch != null) - && (includeButSearch.trim().length() > 0)) { - Element includeButSearchElem = - ElementProxy.createElementForFamily(doc, this.getBaseNamespace(), - XPathFilterCHGPContainer - ._TAG_INCLUDE_BUT_SEARCH); + includeButSearchElem.appendChild( + this.doc.createTextNode(indentXPathText(includeButSearch)) + ); + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(includeButSearchElem); + } - includeButSearchElem - .appendChild(this._doc - .createTextNode(indentXPathText(includeButSearch))); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(includeButSearchElem); - } + if ((excludeButSearch != null) && (excludeButSearch.trim().length() > 0)) { + Element excludeButSearchElem = + ElementProxy.createElementForFamily( + doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH + ); - if ((excludeButSearch != null) - && (excludeButSearch.trim().length() > 0)) { - Element excludeButSearchElem = - ElementProxy.createElementForFamily(doc, this.getBaseNamespace(), - XPathFilterCHGPContainer - ._TAG_EXCLUDE_BUT_SEARCH); + excludeButSearchElem.appendChild( + this.doc.createTextNode(indentXPathText(excludeButSearch))); - excludeButSearchElem - .appendChild(this._doc - .createTextNode(indentXPathText(excludeButSearch))); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(excludeButSearchElem); - } + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(excludeButSearchElem); + } - if ((exclude != null) && (exclude.trim().length() > 0)) { - Element excludeElem = ElementProxy.createElementForFamily(doc, - this.getBaseNamespace(), - XPathFilterCHGPContainer._TAG_EXCLUDE); + if ((exclude != null) && (exclude.trim().length() > 0)) { + Element excludeElem = + ElementProxy.createElementForFamily( + doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_EXCLUDE); - excludeElem - .appendChild(this._doc.createTextNode(indentXPathText(exclude))); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(excludeElem); - } + excludeElem.appendChild(this.doc.createTextNode(indentXPathText(exclude))); + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(excludeElem); + } - XMLUtils.addReturnToElement(this._constructionElement); - } + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * Method indentXPathText - * - * @param xp - * @return the string with enters - */ - static String indentXPathText(String xp) { + /** + * Method indentXPathText + * + * @param xp + * @return the string with enters + */ + static String indentXPathText(String xp) { + if ((xp.length() > 2) && (!Character.isWhitespace(xp.charAt(0)))) { + return "\n" + xp + "\n"; + } + return xp; + } - if ((xp.length() > 2) && (!Character.isWhitespace(xp.charAt(0)))) { - return "\n" + xp + "\n"; - } - return xp; + /** + * Constructor XPathFilterCHGPContainer + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + private XPathFilterCHGPContainer(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } - } + /** + * Creates a new XPathFilterCHGPContainer; needed for generation. + * + * @param doc + * @param includeSlashPolicy + * @param includeButSearch + * @param excludeButSearch + * @param exclude + * @return the created object + */ + public static XPathFilterCHGPContainer getInstance( + Document doc, boolean includeSlashPolicy, String includeButSearch, + String excludeButSearch, String exclude + ) { + return new XPathFilterCHGPContainer( + doc, includeSlashPolicy, includeButSearch, excludeButSearch, exclude); + } - /** - * Constructor XPathFilterCHGPContainer - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - private XPathFilterCHGPContainer(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Creates a XPathFilterCHGPContainer from an existing Element; needed for verification. + * + * @param element + * @param BaseURI + * + * @throws XMLSecurityException + * @return the created object. + */ + public static XPathFilterCHGPContainer getInstance( + Element element, String BaseURI + ) throws XMLSecurityException { + return new XPathFilterCHGPContainer(element, BaseURI); + } - /** - * Creates a new XPathFilterCHGPContainer; needed for generation. - * - * @param doc - * @param includeSlashPolicy - * @param includeButSearch - * @param excludeButSearch - * @param exclude - * @return the created object - */ - public static XPathFilterCHGPContainer getInstance(Document doc, - boolean includeSlashPolicy, String includeButSearch, - String excludeButSearch, String exclude) { + /** + * Method getXStr + * + * @param type + * @return The Xstr + */ + private String getXStr(String type) { + if (this.length(this.getBaseNamespace(), type) != 1) { + return ""; + } - return new XPathFilterCHGPContainer(doc, includeSlashPolicy, - includeButSearch, excludeButSearch, - exclude); - } + Element xElem = + XMLUtils.selectNode( + this.constructionElement.getFirstChild(), this.getBaseNamespace(), type, 0 + ); - /** - * Creates a XPathFilterCHGPContainer from an existing Element; needed for verification. - * - * @param element - * @param BaseURI - * - * @throws XMLSecurityException - * @return the created object. - */ - public static XPathFilterCHGPContainer getInstance( - Element element, String BaseURI) throws XMLSecurityException { - return new XPathFilterCHGPContainer(element, BaseURI); - } + return XMLUtils.getFullTextChildrenFromElement(xElem); + } - /** - * Method getXStr - * - * @param type - * @return The Xstr - */ - private String getXStr(String type) { + /** + * Method getIncludeButSearch + * + * @return the string + */ + public String getIncludeButSearch() { + return this.getXStr(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH); + } - if (this.length(this.getBaseNamespace(), type) != 1) { - return ""; - } + /** + * Method getExcludeButSearch + * + * @return the string + */ + public String getExcludeButSearch() { + return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH); + } - Element xElem = XMLUtils.selectNode(this._constructionElement.getFirstChild(), this.getBaseNamespace(), - type,0); + /** + * Method getExclude + * + * @return the string + */ + public String getExclude() { + return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE); + } - return XMLUtils.getFullTextChildrenFromElement(xElem); - } + /** + * Method getIncludeSlashPolicy + * + * @return the string + */ + public boolean getIncludeSlashPolicy() { + return this.constructionElement.getAttributeNS( + null, XPathFilterCHGPContainer._ATT_INCLUDESLASH).equals("true"); + } - /** - * Method getIncludeButSearch - * - * @return the string - */ - public String getIncludeButSearch() { - return this.getXStr(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH); - } + /** + * Returns the first Text node which contains information from the XPath + * Filter String. We must use this stupid hook to enable the here() function + * to work. + * + * $todo$ I dunno whether this crashes: here()/ds:Signature[1] + * @param type + * @return the first Text node which contains information from the XPath 2 Filter String + */ + private Node getHereContextNode(String type) { - /** - * Method getExcludeButSearch - * - * @return the string - */ - public String getExcludeButSearch() { - return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH); - } + if (this.length(this.getBaseNamespace(), type) != 1) { + return null; + } - /** - * Method getExclude - * - * @return the string - */ - public String getExclude() { - return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE); - } + return XMLUtils.selectNodeText( + this.constructionElement.getFirstChild(), this.getBaseNamespace(), type, 0 + ); + } - /** - * Method getIncludeSlashPolicy - * - * @return the string - */ - public boolean getIncludeSlashPolicy() { + /** + * Method getHereContextNodeIncludeButSearch + * + * @return the string + */ + public Node getHereContextNodeIncludeButSearch() { + return this.getHereContextNode(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH); + } - return this._constructionElement - .getAttributeNS(null, XPathFilterCHGPContainer._ATT_INCLUDESLASH) - .equals("true"); - } + /** + * Method getHereContextNodeExcludeButSearch + * + * @return the string + */ + public Node getHereContextNodeExcludeButSearch() { + return this.getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH); + } - /** - * Returns the first Text node which contains information from the XPath - * Filter String. We must use this stupid hook to enable the here() function - * to work. - * - * $todo$ I dunno whether this crashes: here()/ds:Signature[1] - * @param type - * @return the first Text node which contains information from the XPath 2 Filter String - */ - private Node getHereContextNode(String type) { + /** + * Method getHereContextNodeExclude + * + * @return the string + */ + public Node getHereContextNodeExclude() { + return this.getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE); + } - if (this.length(this.getBaseNamespace(), type) != 1) { - return null; - } + /** + * Method getBaseLocalName + * + * @inheritDoc + */ + public final String getBaseLocalName() { + return XPathFilterCHGPContainer._TAG_XPATHCHGP; + } - return XMLUtils.selectNodeText(this._constructionElement.getFirstChild(), this.getBaseNamespace(), - type,0); - } - - /** - * Method getHereContextNodeIncludeButSearch - * - * @return the string - */ - public Node getHereContextNodeIncludeButSearch() { - return this - .getHereContextNode(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH); - } - - /** - * Method getHereContextNodeExcludeButSearch - * - * @return the string - */ - public Node getHereContextNodeExcludeButSearch() { - return this - .getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH); - } - - /** - * Method getHereContextNodeExclude - * - * @return the string - */ - public Node getHereContextNodeExclude() { - return this.getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE); - } - - /** - * Method getBaseLocalName - * - * @inheritDoc - */ - public final String getBaseLocalName() { - return XPathFilterCHGPContainer._TAG_XPATHCHGP; - } - - /** - * Method getBaseNamespace - * - * @inheritDoc - */ - public final String getBaseNamespace() { - return Transforms.TRANSFORM_XPATHFILTERCHGP; - } + /** + * Method getBaseNamespace + * + * @inheritDoc + */ + public final String getBaseNamespace() { + return TRANSFORM_XPATHFILTERCHGP; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java index 9e9c7de8b0f..db1f49eaee4 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils; @@ -32,762 +34,765 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; - /** * Implementation of MIME's Base64 encoding and decoding conversions. * Optimized code. (raw version taken from oreilly.jonathan.util, - * and currently com.sun.org.apache.xerces.internal.ds.util.Base64) + * and currently org.apache.xerces.ds.util.Base64) * * @author Raul Benito(Of the xerces copy, and little adaptations). * @author Anli Shundi * @author Christian Geuer-Pollmann - * @see RFC 2045 + * @see RFC 2045 * @see com.sun.org.apache.xml.internal.security.transforms.implementations.TransformBase64Decode */ public class Base64 { - - /** Field BASE64DEFAULTLENGTH */ - public static final int BASE64DEFAULTLENGTH = 76; - - private Base64() { - // we don't allow instantiation - } - - /** - * Returns a byte-array representation of a {@link BigInteger}. - * No sign-bit is outputed. - * - * N.B.: {@link BigInteger}'s toByteArray - * retunrs eventually longer arrays because of the leading sign-bit. - * - * @param big BigInteger to be converted - * @param bitlen int the desired length in bits of the representation - * @return a byte array with bitlen bits of big - */ - static final byte[] getBytes(BigInteger big, int bitlen) { - - //round bitlen - bitlen = ((bitlen + 7) >> 3) << 3; - - if (bitlen < big.bitLength()) { - throw new IllegalArgumentException(I18n - .translate("utils.Base64.IllegalBitlength")); - } - - byte[] bigBytes = big.toByteArray(); - - if (((big.bitLength() % 8) != 0) - && (((big.bitLength() / 8) + 1) == (bitlen / 8))) { - return bigBytes; - } - - // some copying needed - int startSrc = 0; // no need to skip anything - int bigLen = bigBytes.length; //valid length of the string - - if ((big.bitLength() % 8) == 0) { // correct values - startSrc = 1; // skip sign bit - - bigLen--; // valid length of the string - } - - int startDst = bitlen / 8 - bigLen; //pad with leading nulls - byte[] resizedBytes = new byte[bitlen / 8]; - - System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); - - return resizedBytes; - - } - - /** - * Encode in Base64 the given {@link BigInteger}. - * - * @param big - * @return String with Base64 encoding - */ - public static final String encode(BigInteger big) { - return encode(getBytes(big, big.bitLength())); - } - - /** - * Returns a byte-array representation of a {@link BigInteger}. - * No sign-bit is outputed. - * - * N.B.: {@link BigInteger}'s toByteArray - * retunrs eventually longer arrays because of the leading sign-bit. - * - * @param big BigInteger to be converted - * @param bitlen int the desired length in bits of the representation - * @return a byte array with bitlen bits of big - */ - public static final byte[] encode(BigInteger big, int bitlen) { - - //round bitlen - bitlen = ((bitlen + 7) >> 3) << 3; - - if (bitlen < big.bitLength()) { - throw new IllegalArgumentException(I18n - .translate("utils.Base64.IllegalBitlength")); - } - - byte[] bigBytes = big.toByteArray(); - - if (((big.bitLength() % 8) != 0) - && (((big.bitLength() / 8) + 1) == (bitlen / 8))) { - return bigBytes; - } - - // some copying needed - int startSrc = 0; // no need to skip anything - int bigLen = bigBytes.length; //valid length of the string - - if ((big.bitLength() % 8) == 0) { // correct values - startSrc = 1; // skip sign bit - - bigLen--; // valid length of the string - } - - int startDst = bitlen / 8 - bigLen; //pad with leading nulls - byte[] resizedBytes = new byte[bitlen / 8]; - - System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); - - return resizedBytes; - - } - - /** - * Method decodeBigIntegerFromElement - * - * @param element - * @return the biginter obtained from the node - * @throws Base64DecodingException - */ - public static final BigInteger decodeBigIntegerFromElement(Element element) throws Base64DecodingException - { - return new BigInteger(1, Base64.decode(element)); - } - - /** - * Method decodeBigIntegerFromText - * - * @param text - * @return the biginter obtained from the text node - * @throws Base64DecodingException - */ - public static final BigInteger decodeBigIntegerFromText(Text text) throws Base64DecodingException - { - return new BigInteger(1, Base64.decode(text.getData())); - } - - /** - * This method takes an (empty) Element and a BigInteger and adds the - * base64 encoded BigInteger to the Element. - * - * @param element - * @param biginteger - */ - public static final void fillElementWithBigInteger(Element element, - BigInteger biginteger) { - - String encodedInt = encode(biginteger); - - if (encodedInt.length() > 76) { - encodedInt = "\n" + encodedInt + "\n"; - } - - Document doc = element.getOwnerDocument(); - Text text = doc.createTextNode(encodedInt); - - element.appendChild(text); - } - - /** - * Method decode - * - * Takes the Text children of the Element and interprets - * them as input for the Base64.decode() function. - * - * @param element - * @return the byte obtained of the decoding the element - * $todo$ not tested yet - * @throws Base64DecodingException - */ - public static final byte[] decode(Element element) throws Base64DecodingException { - - Node sibling = element.getFirstChild(); - StringBuffer sb = new StringBuffer(); - - while (sibling!=null) { - if (sibling.getNodeType() == Node.TEXT_NODE) { - Text t = (Text) sibling; - - sb.append(t.getData()); - } - sibling=sibling.getNextSibling(); - } - - return decode(sb.toString()); - } - - /** - * Method encodeToElement - * - * @param doc - * @param localName - * @param bytes - * @return an Element with the base64 encoded in the text. - * - */ - public static final Element encodeToElement(Document doc, String localName, - byte[] bytes) { - - Element el = XMLUtils.createElementInSignatureSpace(doc, localName); - Text text = doc.createTextNode(encode(bytes)); - - el.appendChild(text); - - return el; - } - - /** - * Method decode - * - * - * @param base64 - * @return the UTF bytes of the base64 - * @throws Base64DecodingException - * - */ - public final static byte[] decode(byte[] base64) throws Base64DecodingException { - return decodeInternal(base64, -1); - } - - - - /** - * Encode a byte array and fold lines at the standard 76th character unless - * ignore line breaks property is set. - * - * @param binaryData byte[] to be base64 encoded - * @return the String with encoded data - */ - public static final String encode(byte[] binaryData) { - return XMLUtils.ignoreLineBreaks() - ? encode(binaryData, Integer.MAX_VALUE) - : encode(binaryData, BASE64DEFAULTLENGTH); - } - - /** - * Base64 decode the lines from the reader and return an InputStream - * with the bytes. - * - * - * @param reader - * @return InputStream with the decoded bytes - * @exception IOException passes what the reader throws - * @throws IOException - * @throws Base64DecodingException - */ - public final static byte[] decode(BufferedReader reader) - throws IOException, Base64DecodingException { - - UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream(); - String line; - - while (null != (line = reader.readLine())) { - byte[] bytes = decode(line); - - baos.write(bytes); - } - - return baos.toByteArray(); - } - - static private final int BASELENGTH = 255; - static private final int LOOKUPLENGTH = 64; - static private final int TWENTYFOURBITGROUP = 24; - static private final int EIGHTBIT = 8; - static private final int SIXTEENBIT = 16; - static private final int FOURBYTE = 4; - static private final int SIGN = -128; - static private final char PAD = '='; - static final private byte [] base64Alphabet = new byte[BASELENGTH]; - static final private char [] lookUpBase64Alphabet = new char[LOOKUPLENGTH]; - - static { - - for (int i = 0; i= 'A'; i--) { - base64Alphabet[i] = (byte) (i-'A'); - } - for (int i = 'z'; i>= 'a'; i--) { - base64Alphabet[i] = (byte) ( i-'a' + 26); - } - - for (int i = '9'; i >= '0'; i--) { - base64Alphabet[i] = (byte) (i-'0' + 52); - } - - base64Alphabet['+'] = 62; - base64Alphabet['/'] = 63; - - for (int i = 0; i<=25; i++) - lookUpBase64Alphabet[i] = (char)('A'+i); - - for (int i = 26, j = 0; i<=51; i++, j++) - lookUpBase64Alphabet[i] = (char)('a'+ j); - - for (int i = 52, j = 0; i<=61; i++, j++) - lookUpBase64Alphabet[i] = (char)('0' + j); - lookUpBase64Alphabet[62] = '+'; - lookUpBase64Alphabet[63] = '/'; - - } - - protected static final boolean isWhiteSpace(byte octect) { - return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9); - } - - protected static final boolean isPad(byte octect) { - return (octect == PAD); - } - - - /** - * Encodes hex octects into Base64 - * - * @param binaryData Array containing binaryData - * @return Encoded Base64 array - */ - /** - * Encode a byte array in Base64 format and return an optionally - * wrapped line. - * - * @param binaryData byte[] data to be encoded - * @param length int length of wrapped lines; No wrapping if less than 4. - * @return a String with encoded data - */ - public static final String encode(byte[] binaryData,int length) { - - if (length<4) { - length=Integer.MAX_VALUE; + /** Field BASE64DEFAULTLENGTH */ + public static final int BASE64DEFAULTLENGTH = 76; + + private static final int BASELENGTH = 255; + private static final int LOOKUPLENGTH = 64; + private static final int TWENTYFOURBITGROUP = 24; + private static final int EIGHTBIT = 8; + private static final int SIXTEENBIT = 16; + private static final int FOURBYTE = 4; + private static final int SIGN = -128; + private static final char PAD = '='; + private static final byte [] base64Alphabet = new byte[BASELENGTH]; + private static final char [] lookUpBase64Alphabet = new char[LOOKUPLENGTH]; + + static { + for (int i = 0; i < BASELENGTH; i++) { + base64Alphabet[i] = -1; + } + for (int i = 'Z'; i >= 'A'; i--) { + base64Alphabet[i] = (byte) (i - 'A'); + } + for (int i = 'z'; i>= 'a'; i--) { + base64Alphabet[i] = (byte) (i - 'a' + 26); } - if (binaryData == null) - return null; + for (int i = '9'; i >= '0'; i--) { + base64Alphabet[i] = (byte) (i - '0' + 52); + } - int lengthDataBits = binaryData.length*EIGHTBIT; - if (lengthDataBits == 0) { - return ""; - } + base64Alphabet['+'] = 62; + base64Alphabet['/'] = 63; - int fewerThan24bits = lengthDataBits%TWENTYFOURBITGROUP; - int numberTriplets = lengthDataBits/TWENTYFOURBITGROUP; - int numberQuartet = fewerThan24bits != 0 ? numberTriplets+1 : numberTriplets; - int quartesPerLine = length/4; - int numberLines = (numberQuartet-1)/quartesPerLine; - char encodedData[] = null; + for (int i = 0; i <= 25; i++) { + lookUpBase64Alphabet[i] = (char)('A' + i); + } - encodedData = new char[numberQuartet*4+numberLines]; + for (int i = 26, j = 0; i <= 51; i++, j++) { + lookUpBase64Alphabet[i] = (char)('a' + j); + } - byte k=0, l=0, b1=0,b2=0,b3=0; + for (int i = 52, j = 0; i <= 61; i++, j++) { + lookUpBase64Alphabet[i] = (char)('0' + j); + } + lookUpBase64Alphabet[62] = '+'; + lookUpBase64Alphabet[63] = '/'; + } - int encodedIndex = 0; - int dataIndex = 0; - int i = 0; - - - for (int line = 0; line < numberLines; line++) { - for (int quartet = 0; quartet < 19; quartet++) { - b1 = binaryData[dataIndex++]; - b2 = binaryData[dataIndex++]; - b3 = binaryData[dataIndex++]; - - - l = (byte)(b2 & 0x0f); - k = (byte)(b1 & 0x03); - - byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); - - byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0); - byte val3 = ((b3 & SIGN)==0)?(byte)(b3>>6):(byte)((b3)>>6^0xfc); - - - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ (l <<2 ) | val3 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ b3 & 0x3f ]; - - i++; - } - encodedData[encodedIndex++] = 0xa; - } - - for (; i>2):(byte)((b1)>>2^0xc0); - - byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0); - byte val3 = ((b3 & SIGN)==0)?(byte)(b3>>6):(byte)((b3)>>6^0xfc); - - - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ (l <<2 ) | val3 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ b3 & 0x3f ]; - } - - // form integral number of 6-bit groups - if (fewerThan24bits == EIGHTBIT) { - b1 = binaryData[dataIndex]; - k = (byte) ( b1 &0x03 ); - byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ k<<4 ]; - encodedData[encodedIndex++] = PAD; - encodedData[encodedIndex++] = PAD; - } else if (fewerThan24bits == SIXTEENBIT) { - b1 = binaryData[dataIndex]; - b2 = binaryData[dataIndex +1 ]; - l = ( byte ) ( b2 &0x0f ); - k = ( byte ) ( b1 &0x03 ); - - byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); - byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0); - - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ l<<2 ]; - encodedData[encodedIndex++] = PAD; - } - - //encodedData[encodedIndex] = 0xa; - - return new String(encodedData); - } + private Base64() { + // we don't allow instantiation + } /** - * Decodes Base64 data into octects + * Returns a byte-array representation of a {@link BigInteger}. + * No sign-bit is output. + * + * N.B.: {@link BigInteger}'s toByteArray + * returns eventually longer arrays because of the leading sign-bit. + * + * @param big BigInteger to be converted + * @param bitlen int the desired length in bits of the representation + * @return a byte array with bitlen bits of big + */ + static final byte[] getBytes(BigInteger big, int bitlen) { + + //round bitlen + bitlen = ((bitlen + 7) >> 3) << 3; + + if (bitlen < big.bitLength()) { + throw new IllegalArgumentException(I18n.translate("utils.Base64.IllegalBitlength")); + } + + byte[] bigBytes = big.toByteArray(); + + if (((big.bitLength() % 8) != 0) + && (((big.bitLength() / 8) + 1) == (bitlen / 8))) { + return bigBytes; + } + + // some copying needed + int startSrc = 0; // no need to skip anything + int bigLen = bigBytes.length; //valid length of the string + + if ((big.bitLength() % 8) == 0) { // correct values + startSrc = 1; // skip sign bit + + bigLen--; // valid length of the string + } + + int startDst = bitlen / 8 - bigLen; //pad with leading nulls + byte[] resizedBytes = new byte[bitlen / 8]; + + System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); + + return resizedBytes; + } + + /** + * Encode in Base64 the given {@link BigInteger}. + * + * @param big + * @return String with Base64 encoding + */ + public static final String encode(BigInteger big) { + return encode(getBytes(big, big.bitLength())); + } + + /** + * Returns a byte-array representation of a {@link BigInteger}. + * No sign-bit is output. + * + * N.B.: {@link BigInteger}'s toByteArray + * returns eventually longer arrays because of the leading sign-bit. + * + * @param big BigInteger to be converted + * @param bitlen int the desired length in bits of the representation + * @return a byte array with bitlen bits of big + */ + public static final byte[] encode(BigInteger big, int bitlen) { + + //round bitlen + bitlen = ((bitlen + 7) >> 3) << 3; + + if (bitlen < big.bitLength()) { + throw new IllegalArgumentException(I18n.translate("utils.Base64.IllegalBitlength")); + } + + byte[] bigBytes = big.toByteArray(); + + if (((big.bitLength() % 8) != 0) + && (((big.bitLength() / 8) + 1) == (bitlen / 8))) { + return bigBytes; + } + + // some copying needed + int startSrc = 0; // no need to skip anything + int bigLen = bigBytes.length; //valid length of the string + + if ((big.bitLength() % 8) == 0) { // correct values + startSrc = 1; // skip sign bit + + bigLen--; // valid length of the string + } + + int startDst = bitlen / 8 - bigLen; //pad with leading nulls + byte[] resizedBytes = new byte[bitlen / 8]; + + System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); + + return resizedBytes; + } + + /** + * Method decodeBigIntegerFromElement + * + * @param element + * @return the biginteger obtained from the node + * @throws Base64DecodingException + */ + public static final BigInteger decodeBigIntegerFromElement(Element element) + throws Base64DecodingException { + return new BigInteger(1, Base64.decode(element)); + } + + /** + * Method decodeBigIntegerFromText + * + * @param text + * @return the biginter obtained from the text node + * @throws Base64DecodingException + */ + public static final BigInteger decodeBigIntegerFromText(Text text) + throws Base64DecodingException { + return new BigInteger(1, Base64.decode(text.getData())); + } + + /** + * This method takes an (empty) Element and a BigInteger and adds the + * base64 encoded BigInteger to the Element. + * + * @param element + * @param biginteger + */ + public static final void fillElementWithBigInteger(Element element, BigInteger biginteger) { + + String encodedInt = encode(biginteger); + + if (!XMLUtils.ignoreLineBreaks() && encodedInt.length() > BASE64DEFAULTLENGTH) { + encodedInt = "\n" + encodedInt + "\n"; + } + + Document doc = element.getOwnerDocument(); + Text text = doc.createTextNode(encodedInt); + + element.appendChild(text); + } + + /** + * Method decode + * + * Takes the Text children of the Element and interprets + * them as input for the Base64.decode() function. + * + * @param element + * @return the byte obtained of the decoding the element + * $todo$ not tested yet + * @throws Base64DecodingException + */ + public static final byte[] decode(Element element) throws Base64DecodingException { + + Node sibling = element.getFirstChild(); + StringBuffer sb = new StringBuffer(); + + while (sibling != null) { + if (sibling.getNodeType() == Node.TEXT_NODE) { + Text t = (Text) sibling; + + sb.append(t.getData()); + } + sibling = sibling.getNextSibling(); + } + + return decode(sb.toString()); + } + + /** + * Method encodeToElement + * + * @param doc + * @param localName + * @param bytes + * @return an Element with the base64 encoded in the text. + * + */ + public static final Element encodeToElement(Document doc, String localName, byte[] bytes) { + Element el = XMLUtils.createElementInSignatureSpace(doc, localName); + Text text = doc.createTextNode(encode(bytes)); + + el.appendChild(text); + + return el; + } + + /** + * Method decode + * + * @param base64 + * @return the UTF bytes of the base64 + * @throws Base64DecodingException + * + */ + public static final byte[] decode(byte[] base64) throws Base64DecodingException { + return decodeInternal(base64, -1); + } + + /** + * Encode a byte array and fold lines at the standard 76th character unless + * ignore line breaks property is set. + * + * @param binaryData byte[] to be base64 encoded + * @return the String with encoded data + */ + public static final String encode(byte[] binaryData) { + return XMLUtils.ignoreLineBreaks() + ? encode(binaryData, Integer.MAX_VALUE) + : encode(binaryData, BASE64DEFAULTLENGTH); + } + + /** + * Base64 decode the lines from the reader and return an InputStream + * with the bytes. + * + * @param reader + * @return InputStream with the decoded bytes + * @exception IOException passes what the reader throws + * @throws IOException + * @throws Base64DecodingException + */ + public static final byte[] decode(BufferedReader reader) + throws IOException, Base64DecodingException { + + byte[] retBytes = null; + UnsyncByteArrayOutputStream baos = null; + try { + baos = new UnsyncByteArrayOutputStream(); + String line; + + while (null != (line = reader.readLine())) { + byte[] bytes = decode(line); + baos.write(bytes); + } + retBytes = baos.toByteArray(); + } finally { + baos.close(); + } + + return retBytes; + } + + protected static final boolean isWhiteSpace(byte octect) { + return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9); + } + + protected static final boolean isPad(byte octect) { + return (octect == PAD); + } + + /** + * Encodes hex octets into Base64 + * + * @param binaryData Array containing binaryData + * @return Encoded Base64 array + */ + /** + * Encode a byte array in Base64 format and return an optionally + * wrapped line. + * + * @param binaryData byte[] data to be encoded + * @param length int length of wrapped lines; No wrapping if less than 4. + * @return a String with encoded data + */ + public static final String encode(byte[] binaryData,int length) { + if (length < 4) { + length = Integer.MAX_VALUE; + } + + if (binaryData == null) { + return null; + } + + int lengthDataBits = binaryData.length * EIGHTBIT; + if (lengthDataBits == 0) { + return ""; + } + + int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; + int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; + int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets; + int quartesPerLine = length / 4; + int numberLines = (numberQuartet - 1) / quartesPerLine; + char encodedData[] = null; + + encodedData = new char[numberQuartet * 4 + numberLines]; + + byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; + int encodedIndex = 0; + int dataIndex = 0; + int i = 0; + + for (int line = 0; line < numberLines; line++) { + for (int quartet = 0; quartet < 19; quartet++) { + b1 = binaryData[dataIndex++]; + b2 = binaryData[dataIndex++]; + b3 = binaryData[dataIndex++]; + + l = (byte)(b2 & 0x0f); + k = (byte)(b1 & 0x03); + + byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2): (byte)((b1) >> 2 ^ 0xc0); + + byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); + byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); + + + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f]; + + i++; + } + encodedData[encodedIndex++] = 0xa; + } + + for (; i < numberTriplets; i++) { + b1 = binaryData[dataIndex++]; + b2 = binaryData[dataIndex++]; + b3 = binaryData[dataIndex++]; + + l = (byte)(b2 & 0x0f); + k = (byte)(b1 & 0x03); + + byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); + + byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); + byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); + + + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f]; + } + + // form integral number of 6-bit groups + if (fewerThan24bits == EIGHTBIT) { + b1 = binaryData[dataIndex]; + k = (byte) (b1 &0x03); + byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2):(byte)((b1) >> 2 ^ 0xc0); + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4]; + encodedData[encodedIndex++] = PAD; + encodedData[encodedIndex++] = PAD; + } else if (fewerThan24bits == SIXTEENBIT) { + b1 = binaryData[dataIndex]; + b2 = binaryData[dataIndex +1 ]; + l = ( byte ) (b2 & 0x0f); + k = ( byte ) (b1 & 0x03); + + byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); + byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); + + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2]; + encodedData[encodedIndex++] = PAD; + } + + //encodedData[encodedIndex] = 0xa; + + return new String(encodedData); + } + + /** + * Decodes Base64 data into octets * * @param encoded String containing base64 encoded data * @return byte array containing the decoded data * @throws Base64DecodingException if there is a problem decoding the data */ - public final static byte[] decode(String encoded) throws Base64DecodingException { - - if (encoded == null) - return null; - byte []bytes=new byte[encoded.length()]; - int len=getBytesInternal(encoded, bytes); - return decodeInternal(bytes, len); + public static final byte[] decode(String encoded) throws Base64DecodingException { + if (encoded == null) { + return null; } + byte[] bytes = new byte[encoded.length()]; + int len = getBytesInternal(encoded, bytes); + return decodeInternal(bytes, len); + } - protected static final int getBytesInternal(String s,byte[] result) { - int length=s.length(); + protected static final int getBytesInternal(String s, byte[] result) { + int length = s.length(); - int newSize=0; + int newSize = 0; for (int i = 0; i < length; i++) { - byte dataS=(byte)s.charAt(i); - if (!isWhiteSpace(dataS)) + byte dataS = (byte)s.charAt(i); + if (!isWhiteSpace(dataS)) { result[newSize++] = dataS; + } } return newSize; - } - protected final static byte[] decodeInternal(byte[] base64Data, int len) throws Base64DecodingException { - // remove white spaces - if (len==-1) - len = removeWhiteSpace(base64Data); - if (len%FOURBYTE != 0) { - throw new Base64DecodingException("decoding.divisible.four"); - //should be divisible by four - } + protected static final byte[] decodeInternal(byte[] base64Data, int len) + throws Base64DecodingException { + // remove white spaces + if (len == -1) { + len = removeWhiteSpace(base64Data); + } - int numberQuadruple = (len/FOURBYTE ); + if (len % FOURBYTE != 0) { + throw new Base64DecodingException("decoding.divisible.four"); + //should be divisible by four + } - if (numberQuadruple == 0) - return new byte[0]; + int numberQuadruple = (len / FOURBYTE); - byte decodedData[] = null; - byte b1=0,b2=0,b3=0, b4=0; + if (numberQuadruple == 0) { + return new byte[0]; + } + byte decodedData[] = null; + byte b1 = 0, b2 = 0, b3 = 0, b4 = 0; - int i = 0; - int encodedIndex = 0; - int dataIndex = 0; + int i = 0; + int encodedIndex = 0; + int dataIndex = 0; - //decodedData = new byte[ (numberQuadruple)*3]; - dataIndex=(numberQuadruple-1)*4; - encodedIndex=(numberQuadruple-1)*3; - //first last bits. - b1 = base64Alphabet[base64Data[dataIndex++]]; - b2 = base64Alphabet[base64Data[dataIndex++]]; - if ((b1==-1) || (b2==-1)) { - throw new Base64DecodingException("decoding.general");//if found "no data" just return null + //decodedData = new byte[ (numberQuadruple)*3]; + dataIndex = (numberQuadruple - 1) * 4; + encodedIndex = (numberQuadruple - 1) * 3; + //first last bits. + b1 = base64Alphabet[base64Data[dataIndex++]]; + b2 = base64Alphabet[base64Data[dataIndex++]]; + if ((b1==-1) || (b2==-1)) { + //if found "no data" just return null + throw new Base64DecodingException("decoding.general"); } - byte d3,d4; - b3 = base64Alphabet[d3=base64Data[dataIndex++]]; - b4 = base64Alphabet[d4=base64Data[dataIndex++]]; - if ((b3==-1 ) || (b4==-1) ) { - //Check if they are PAD characters - if (isPad( d3 ) && isPad( d4)) { //Two PAD e.g. 3c[Pad][Pad] - if ((b2 & 0xf) != 0)//last 4 bits should be zero - throw new Base64DecodingException("decoding.general"); - decodedData = new byte[ encodedIndex + 1 ]; - decodedData[encodedIndex] = (byte)( b1 <<2 | b2>>4 ) ; - } else if (!isPad( d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] - if ((b3 & 0x3 ) != 0)//last 2 bits should be zero - throw new Base64DecodingException("decoding.general"); - decodedData = new byte[ encodedIndex + 2 ]; - decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ); - decodedData[encodedIndex] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); + byte d3, d4; + b3 = base64Alphabet[d3 = base64Data[dataIndex++]]; + b4 = base64Alphabet[d4 = base64Data[dataIndex++]]; + if ((b3 == -1) || (b4 == -1) ) { + //Check if they are PAD characters + if (isPad(d3) && isPad(d4)) { //Two PAD e.g. 3c[Pad][Pad] + if ((b2 & 0xf) != 0) { //last 4 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + decodedData = new byte[encodedIndex + 1]; + decodedData[encodedIndex] = (byte)(b1 << 2 | b2 >> 4) ; + } else if (!isPad(d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] + if ((b3 & 0x3) != 0) { //last 2 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + decodedData = new byte[encodedIndex + 2]; + decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4); + decodedData[encodedIndex] = (byte)(((b2 & 0xf) << 4) |((b3 >> 2) & 0xf)); } else { - throw new Base64DecodingException("decoding.general");//an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data + //an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data + throw new Base64DecodingException("decoding.general"); } } else { //No PAD e.g 3cQl decodedData = new byte[encodedIndex+3]; - decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ) ; - decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); - decodedData[encodedIndex++] = (byte)( b3<<6 | b4 ); + decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4) ; + decodedData[encodedIndex++] = (byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); + decodedData[encodedIndex++] = (byte)(b3 << 6 | b4); } - encodedIndex=0; - dataIndex=0; - //the begin - for (i=numberQuadruple-1; i>0; i--) { - b1 = base64Alphabet[base64Data[dataIndex++]]; - b2 = base64Alphabet[base64Data[dataIndex++]]; - b3 = base64Alphabet[base64Data[dataIndex++]]; - b4 = base64Alphabet[base64Data[dataIndex++]]; + encodedIndex = 0; + dataIndex = 0; + //the begin + for (i = numberQuadruple - 1; i > 0; i--) { + b1 = base64Alphabet[base64Data[dataIndex++]]; + b2 = base64Alphabet[base64Data[dataIndex++]]; + b3 = base64Alphabet[base64Data[dataIndex++]]; + b4 = base64Alphabet[base64Data[dataIndex++]]; - if ( (b1==-1) || - (b2==-1) || - (b3==-1) || - (b4==-1) ) { - throw new Base64DecodingException("decoding.general");//if found "no data" just return null - } + if ((b1 == -1) || + (b2 == -1) || + (b3 == -1) || + (b4 == -1)) { + //if found "no data" just return null + throw new Base64DecodingException("decoding.general"); + } - decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ) ; - decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); - decodedData[encodedIndex++] = (byte)( b3<<6 | b4 ); - } - return decodedData; - } - /** - * Decodes Base64 data into outputstream - * - * @param base64Data String containing Base64 data - * @param os the outputstream - * @throws IOException - * @throws Base64DecodingException - */ - public final static void decode(String base64Data, - OutputStream os) throws Base64DecodingException, IOException { - byte[] bytes=new byte[base64Data.length()]; - int len=getBytesInternal(base64Data, bytes); - decode(bytes,os,len); - } - /** - * Decodes Base64 data into outputstream - * - * @param base64Data Byte array containing Base64 data - * @param os the outputstream - * @throws IOException - * @throws Base64DecodingException - */ - public final static void decode(byte[] base64Data, - OutputStream os) throws Base64DecodingException, IOException { - decode(base64Data,os,-1); - } - protected final static void decode(byte[] base64Data, - OutputStream os,int len) throws Base64DecodingException, IOException { - - // remove white spaces - if (len==-1) - len = removeWhiteSpace(base64Data); - - if (len%FOURBYTE != 0) { - throw new Base64DecodingException("decoding.divisible.four"); - //should be divisible by four + decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4) ; + decodedData[encodedIndex++] = (byte)(((b2 & 0xf) << 4) |((b3 >> 2) & 0xf)); + decodedData[encodedIndex++] = (byte)(b3 << 6 | b4 ); + } + return decodedData; } - int numberQuadruple = (len/FOURBYTE ); + /** + * Decodes Base64 data into outputstream + * + * @param base64Data String containing Base64 data + * @param os the outputstream + * @throws IOException + * @throws Base64DecodingException + */ + public static final void decode(String base64Data, OutputStream os) + throws Base64DecodingException, IOException { + byte[] bytes = new byte[base64Data.length()]; + int len = getBytesInternal(base64Data, bytes); + decode(bytes,os,len); + } - if (numberQuadruple == 0) - return; + /** + * Decodes Base64 data into outputstream + * + * @param base64Data Byte array containing Base64 data + * @param os the outputstream + * @throws IOException + * @throws Base64DecodingException + */ + public static final void decode(byte[] base64Data, OutputStream os) + throws Base64DecodingException, IOException { + decode(base64Data,os,-1); + } - //byte decodedData[] = null; - byte b1=0,b2=0,b3=0, b4=0; + protected static final void decode(byte[] base64Data, OutputStream os, int len) + throws Base64DecodingException, IOException { + // remove white spaces + if (len == -1) { + len = removeWhiteSpace(base64Data); + } - int i = 0; + if (len % FOURBYTE != 0) { + throw new Base64DecodingException("decoding.divisible.four"); + //should be divisible by four + } - int dataIndex = 0; + int numberQuadruple = (len / FOURBYTE); - //the begin - for (i=numberQuadruple-1; i>0; i--) { + if (numberQuadruple == 0) { + return; + } + + //byte decodedData[] = null; + byte b1 = 0, b2 = 0, b3 = 0, b4 = 0; + + int i = 0; + int dataIndex = 0; + + //the begin + for (i=numberQuadruple - 1; i > 0; i--) { + b1 = base64Alphabet[base64Data[dataIndex++]]; + b2 = base64Alphabet[base64Data[dataIndex++]]; + b3 = base64Alphabet[base64Data[dataIndex++]]; + b4 = base64Alphabet[base64Data[dataIndex++]]; + if ((b1 == -1) || + (b2 == -1) || + (b3 == -1) || + (b4 == -1) ) { + //if found "no data" just return null + throw new Base64DecodingException("decoding.general"); + } + + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write((byte)(((b2 & 0xf) << 4 ) | ((b3 >> 2) & 0xf))); + os.write( (byte)(b3 << 6 | b4)); + } b1 = base64Alphabet[base64Data[dataIndex++]]; b2 = base64Alphabet[base64Data[dataIndex++]]; - b3 = base64Alphabet[base64Data[dataIndex++]]; - b4 = base64Alphabet[base64Data[dataIndex++]]; - if ( (b1==-1) || - (b2==-1) || - (b3==-1) || - (b4==-1) ) - throw new Base64DecodingException("decoding.general");//if found "no data" just return null - - - os.write((byte)( b1 <<2 | b2>>4 ) ); - os.write((byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - os.write( (byte)( b3<<6 | b4 )); - } - b1 = base64Alphabet[base64Data[dataIndex++]]; - b2 = base64Alphabet[base64Data[dataIndex++]]; - - // first last bits. - if ((b1==-1) || - (b2==-1) ){ - throw new Base64DecodingException("decoding.general");//if found "no data" just return null - } - - byte d3,d4; - b3= base64Alphabet[d3 = base64Data[dataIndex++]]; - b4= base64Alphabet[d4 = base64Data[dataIndex++]]; - if ((b3==-1 ) || - (b4==-1) ) {//Check if they are PAD characters - if (isPad( d3 ) && isPad( d4)) { //Two PAD e.g. 3c[Pad][Pad] - if ((b2 & 0xf) != 0)//last 4 bits should be zero - throw new Base64DecodingException("decoding.general"); - os.write( (byte)( b1 <<2 | b2>>4 ) ); - } else if (!isPad( d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] - if ((b3 & 0x3 ) != 0)//last 2 bits should be zero - throw new Base64DecodingException("decoding.general"); - os.write( (byte)( b1 <<2 | b2>>4 )); - os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - } else { - throw new Base64DecodingException("decoding.general");//an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data - } - } else { - //No PAD e.g 3cQl - os.write((byte)( b1 <<2 | b2>>4 ) ); - os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - os.write((byte)( b3<<6 | b4 )); - } - return ; - } - - /** - * Decodes Base64 data into outputstream - * - * @param is containing Base64 data - * @param os the outputstream - * @throws IOException - * @throws Base64DecodingException - */ - public final static void decode(InputStream is, - OutputStream os) throws Base64DecodingException, IOException { - //byte decodedData[] = null; - byte b1=0,b2=0,b3=0, b4=0; - - int index=0; - byte []data=new byte[4]; - int read; - //the begin - while ((read=is.read())>0) { - byte readed=(byte)read; - if (isWhiteSpace(readed)) { - continue; - } - if (isPad(readed)) { - data[index++]=readed; - if (index==3) - data[index++]=(byte)is.read(); - break; + // first last bits. + if ((b1 == -1) || (b2 == -1) ) { + //if found "no data" just return null + throw new Base64DecodingException("decoding.general"); } - - if ((data[index++]=readed)==-1) { - throw new Base64DecodingException("decoding.general");//if found "no data" just return null - } - - if (index!=4) { - continue; + byte d3, d4; + b3 = base64Alphabet[d3 = base64Data[dataIndex++]]; + b4 = base64Alphabet[d4 = base64Data[dataIndex++]]; + if ((b3 == -1 ) || (b4 == -1) ) { //Check if they are PAD characters + if (isPad(d3) && isPad(d4)) { //Two PAD e.g. 3c[Pad][Pad] + if ((b2 & 0xf) != 0) { //last 4 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + os.write((byte)(b1 << 2 | b2 >> 4)); + } else if (!isPad(d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] + if ((b3 & 0x3 ) != 0) { //last 2 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write((byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf))); + } else { + //an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data + throw new Base64DecodingException("decoding.general"); + } + } else { + //No PAD e.g 3cQl + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write( (byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf))); + os.write((byte)(b3 << 6 | b4)); } - index=0; - b1 = base64Alphabet[data[0]]; - b2 = base64Alphabet[data[1]]; - b3 = base64Alphabet[data[2]]; - b4 = base64Alphabet[data[3]]; - - os.write((byte)( b1 <<2 | b2>>4 ) ); - os.write((byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - os.write( (byte)( b3<<6 | b4 )); } + /** + * Decodes Base64 data into outputstream + * + * @param is containing Base64 data + * @param os the outputstream + * @throws IOException + * @throws Base64DecodingException + */ + public static final void decode(InputStream is, OutputStream os) + throws Base64DecodingException, IOException { + //byte decodedData[] = null; + byte b1 = 0, b2 = 0, b3 = 0, b4 = 0; - byte d1=data[0],d2=data[1],d3=data[2], d4=data[3]; - b1 = base64Alphabet[d1]; - b2 = base64Alphabet[d2]; - b3 = base64Alphabet[ d3 ]; - b4 = base64Alphabet[ d4 ]; - if ((b3==-1 ) || - (b4==-1) ) {//Check if they are PAD characters - if (isPad( d3 ) && isPad( d4)) { //Two PAD e.g. 3c[Pad][Pad] - if ((b2 & 0xf) != 0)//last 4 bits should be zero - throw new Base64DecodingException("decoding.general"); - os.write( (byte)( b1 <<2 | b2>>4 ) ); - } else if (!isPad( d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] - b3 = base64Alphabet[ d3 ]; - if ((b3 & 0x3 ) != 0)//last 2 bits should be zero - throw new Base64DecodingException("decoding.general"); - os.write( (byte)( b1 <<2 | b2>>4 )); - os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - } else { - throw new Base64DecodingException("decoding.general");//an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data - } - } else { - //No PAD e.g 3cQl + int index=0; + byte[] data = new byte[4]; + int read; + //the begin + while ((read = is.read()) > 0) { + byte readed = (byte)read; + if (isWhiteSpace(readed)) { + continue; + } + if (isPad(readed)) { + data[index++] = readed; + if (index == 3) { + data[index++] = (byte)is.read(); + } + break; + } - os.write((byte)( b1 <<2 | b2>>4 ) ); - os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - os.write((byte)( b3<<6 | b4 )); - } + if ((data[index++] = readed) == -1) { + //if found "no data" just return null + throw new Base64DecodingException("decoding.general"); + } - return ; - } - /** - * remove WhiteSpace from MIME containing encoded Base64 data. - * - * @param data the byte array of base64 data (with WS) - * @return the new length - */ - protected static final int removeWhiteSpace(byte[] data) { - if (data == null) - return 0; + if (index != 4) { + continue; + } + index = 0; + b1 = base64Alphabet[data[0]]; + b2 = base64Alphabet[data[1]]; + b3 = base64Alphabet[data[2]]; + b4 = base64Alphabet[data[3]]; - // count characters that's not whitespace - int newSize = 0; - int len = data.length; - for (int i = 0; i < len; i++) { - byte dataS=data[i]; - if (!isWhiteSpace(dataS)) - data[newSize++] = dataS; - } - return newSize; - } + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write((byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf))); + os.write((byte)(b3 << 6 | b4)); + } + + byte d1 = data[0], d2 = data[1], d3 = data[2], d4 = data[3]; + b1 = base64Alphabet[d1]; + b2 = base64Alphabet[d2]; + b3 = base64Alphabet[d3]; + b4 = base64Alphabet[d4]; + if ((b3 == -1) || (b4 == -1)) { //Check if they are PAD characters + if (isPad(d3) && isPad(d4)) { //Two PAD e.g. 3c[Pad][Pad] + if ((b2 & 0xf) != 0) { //last 4 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + os.write((byte)(b1 << 2 | b2 >> 4)); + } else if (!isPad(d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] + b3 = base64Alphabet[d3]; + if ((b3 & 0x3) != 0) { //last 2 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write((byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf))); + } else { + //an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data + throw new Base64DecodingException("decoding.general"); + } + } else { + //No PAD e.g 3cQl + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write((byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf))); + os.write((byte)(b3 << 6 | b4)); + } + } + + /** + * remove WhiteSpace from MIME containing encoded Base64 data. + * + * @param data the byte array of base64 data (with WS) + * @return the new length + */ + protected static final int removeWhiteSpace(byte[] data) { + if (data == null) { + return 0; + } + + // count characters that's not whitespace + int newSize = 0; + int len = data.length; + for (int i = 0; i < len; i++) { + byte dataS = data[i]; + if (!isWhiteSpace(dataS)) { + data[newSize++] = dataS; + } + } + return newSize; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder.java deleted file mode 100644 index 0a7503a9331..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * 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 com.sun.org.apache.xml.internal.security.utils; - -import com.sun.org.apache.xpath.internal.CachedXPathAPI; -import org.w3c.dom.Document; - -/** - * @author Raul Benito - */ -public class CachedXPathAPIHolder { - - static ThreadLocal local=new ThreadLocal(); - static ThreadLocal localDoc=new ThreadLocal(); - - /** - * Sets the doc for the xpath transformation. Resets the cache if needed - * @param doc - */ - public static void setDoc(Document doc) { - if (localDoc.get()!=doc) { - CachedXPathAPI cx=local.get(); - if (cx==null) { - cx=new CachedXPathAPI(); - local.set(cx); - localDoc.set(doc); - return; - } - //Different docs reset. - cx.getXPathContext().reset(); - localDoc.set(doc); - } - } - - /** - * @return the cachexpathapi for this thread - */ - public static CachedXPathAPI getCachedXPathAPI() { - CachedXPathAPI cx=local.get(); - if (cx==null) { - cx=new CachedXPathAPI(); - local.set(cx); - localDoc.set(null); - } - return cx; - } -} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathFuncHereAPI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathFuncHereAPI.java deleted file mode 100644 index fe1ae841755..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathFuncHereAPI.java +++ /dev/null @@ -1,466 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * 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 com.sun.org.apache.xml.internal.security.utils; - - - -import com.sun.org.apache.xml.internal.dtm.DTMManager; -import com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHere; -import com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHereContext; -import com.sun.org.apache.xml.internal.utils.PrefixResolver; -import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault; -import com.sun.org.apache.xpath.internal.CachedXPathAPI; -import com.sun.org.apache.xpath.internal.Expression; -import com.sun.org.apache.xpath.internal.XPath; -import com.sun.org.apache.xpath.internal.XPathContext; -import com.sun.org.apache.xpath.internal.compiler.FunctionTable; -import com.sun.org.apache.xpath.internal.objects.XObject; -import org.w3c.dom.*; -import org.w3c.dom.traversal.NodeIterator; - -import javax.xml.transform.ErrorListener; -import javax.xml.transform.SourceLocator; -import javax.xml.transform.TransformerException; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * - * @author $Author: mullan $ - */ -public class CachedXPathFuncHereAPI { - - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(CachedXPathFuncHereAPI.class.getName()); - /** - * XPathContext, and thus DTMManager and DTMs, persists through multiple - * calls to this object. - */ - FuncHereContext _funcHereContext = null; - - /** Field _dtmManager */ - DTMManager _dtmManager = null; - - XPathContext _context = null; - - String xpathStr=null; - - XPath xpath=null; - - static FunctionTable _funcTable = null; - - static { - fixupFunctionTable(); - } - - /** - * Method getFuncHereContext - * @return the context for this object - * - */ - public FuncHereContext getFuncHereContext() { - return this._funcHereContext; - } - - /** - * Constructor CachedXPathFuncHereAPI - * - */ - private CachedXPathFuncHereAPI() {} - - /** - * Constructor CachedXPathFuncHereAPI - * - * @param existingXPathContext - */ - public CachedXPathFuncHereAPI(XPathContext existingXPathContext) { - this._dtmManager = existingXPathContext.getDTMManager(); - this._context=existingXPathContext; - } - - /** - * Constructor CachedXPathFuncHereAPI - * - * @param previouslyUsed - */ - public CachedXPathFuncHereAPI(CachedXPathAPI previouslyUsed) { - this._dtmManager = previouslyUsed.getXPathContext().getDTMManager(); - this._context=previouslyUsed.getXPathContext(); - } - - /** - * Use an XPath string to select a single node. XPath namespace - * prefixes are resolved from the context node, which may not - * be what you want (see the next method). - * - * @param contextNode The node to start searching from. - * @param xpathnode A Node containing a valid XPath string. - * @return The first node found that matches the XPath, or null. - * - * @throws TransformerException - */ - public Node selectSingleNode(Node contextNode, Node xpathnode) - throws TransformerException { - return selectSingleNode(contextNode, xpathnode, contextNode); - } - - /** - * Use an XPath string to select a single node. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return The first node found that matches the XPath, or null. - * - * @throws TransformerException - */ - public Node selectSingleNode( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Have the XObject return its result as a NodeSetDTM. - NodeIterator nl = selectNodeIterator(contextNode, xpathnode, - namespaceNode); - - // Return the first node, or null - return nl.nextNode(); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the contextNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public NodeIterator selectNodeIterator(Node contextNode, Node xpathnode) - throws TransformerException { - return selectNodeIterator(contextNode, xpathnode, contextNode); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - * @deprecated - */ - @Deprecated - public NodeIterator selectNodeIterator( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Execute the XPath, and have it return the result - XObject list = eval(contextNode, xpathnode, getStrFromNode(xpathnode), namespaceNode); - - // Have the XObject return its result as a NodeSetDTM. - return list.nodeset(); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the contextNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - * @deprecated - */ - @Deprecated - public NodeList selectNodeList(Node contextNode, Node xpathnode) - throws TransformerException { - return selectNodeList(contextNode, xpathnode, getStrFromNode(xpathnode), contextNode); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param str - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public NodeList selectNodeList( - Node contextNode, Node xpathnode, String str, Node namespaceNode) - throws TransformerException { - - // Execute the XPath, and have it return the result - XObject list = eval(contextNode, xpathnode, str, namespaceNode); - - // Return a NodeList. - return list.nodelist(); - } - - /** - * Evaluate XPath string to an XObject. Using this method, - * XPath namespace prefixes will be resolved from the namespaceNode. - * @param contextNode The node to start searching from. - * @param xpathnode - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - * @deprecated - */ - @Deprecated - public XObject eval(Node contextNode, Node xpathnode) - throws TransformerException { - return eval(contextNode, xpathnode, getStrFromNode(xpathnode),contextNode); - } - - /** - * Evaluate XPath string to an XObject. - * XPath namespace prefixes are resolved from the namespaceNode. - * The implementation of this is a little slow, since it creates - * a number of objects each time it is called. This could be optimized - * to keep the same objects around, but then thread-safety issues would arise. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param str - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - */ - public XObject eval(Node contextNode, Node xpathnode, String str, Node namespaceNode) - throws TransformerException { - // Create the XPath object. - //String str = CachedXPathFuncHereAPI.getStrFromNode(xpathnode); - - // Since we don't have a XML Parser involved here, install some default support - // for things like namespaces, etc. - // (Changed from: XPathContext xpathSupport = new XPathContext(); - // because XPathContext is weak in a number of areas... perhaps - // XPathContext should be done away with.) - if (this._funcHereContext == null) { - this._funcHereContext = new FuncHereContext(xpathnode, - this._dtmManager); - } - - // Create an object to resolve namespace prefixes. - // XPath namespaces are resolved from the input context node's document element - // if it is a root node, or else the current context node (for lack of a better - // resolution space, given the simplicity of this sample code). - PrefixResolverDefault prefixResolver = - new PrefixResolverDefault((namespaceNode.getNodeType() - == Node.DOCUMENT_NODE) - ? ((Document) namespaceNode) - .getDocumentElement() - : namespaceNode); - - // only check if string points to different object (for performance) - if (str!=xpathStr) { - if (str.indexOf("here()")>0) { - _context.reset(); - _dtmManager=_context.getDTMManager(); - } - xpath = createXPath(str, prefixResolver); - xpathStr=str; - } - - // Execute the XPath, and have it return the result - // return xpath.execute(xpathSupport, contextNode, prefixResolver); - int ctxtNode = this._funcHereContext.getDTMHandleFromNode(contextNode); - - return xpath.execute(this._funcHereContext, ctxtNode, prefixResolver); - } - - /** - * Evaluate XPath string to an XObject. - * XPath namespace prefixes are resolved from the namespaceNode. - * The implementation of this is a little slow, since it creates - * a number of objects each time it is called. This could be optimized - * to keep the same objects around, but then thread-safety issues would arise. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param str - * @param prefixResolver Will be called if the parser encounters namespace - * prefixes, to resolve the prefixes to URLs. - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - */ - public XObject eval( - Node contextNode, Node xpathnode, String str, PrefixResolver prefixResolver) - throws TransformerException { - - // Since we don't have a XML Parser involved here, install some default support - // for things like namespaces, etc. - // (Changed from: XPathContext xpathSupport = new XPathContext(); - // because XPathContext is weak in a number of areas... perhaps - // XPathContext should be done away with.) - // Create the XPath object. - //String str = CachedXPathFuncHereAPI.getStrFromNode(xpathnode); - // only check if string points to different object (for performance) - if (str!=xpathStr) { - if (str.indexOf("here()")>0) { - _context.reset(); - _dtmManager=_context.getDTMManager(); - } - try { - xpath = createXPath(str, prefixResolver); - } catch (TransformerException ex) { - //Try to see if it is a problem with the classloader. - Throwable th= ex.getCause(); - if (th instanceof ClassNotFoundException) { - if (th.getMessage().indexOf("FuncHere")>0) { - throw new RuntimeException(I18n.translate("endorsed.jdk1.4.0")/*,*/+ex); - } - } - throw ex; - } - xpathStr=str; - } - - // Execute the XPath, and have it return the result - if (this._funcHereContext == null) { - this._funcHereContext = new FuncHereContext(xpathnode, - this._dtmManager); - } - - int ctxtNode = this._funcHereContext.getDTMHandleFromNode(contextNode); - - return xpath.execute(this._funcHereContext, ctxtNode, prefixResolver); - } - - private XPath createXPath(String str, PrefixResolver prefixResolver) throws TransformerException { - XPath xpath = null; - Class[] classes = new Class[]{String.class, SourceLocator.class, PrefixResolver.class, int.class, - ErrorListener.class, FunctionTable.class}; - Object[] objects = new Object[]{str, null, prefixResolver, new Integer(XPath.SELECT), null, _funcTable}; - try { - Constructor constructor = XPath.class.getConstructor(classes); - xpath = constructor.newInstance(objects); - } catch (Throwable t) { - } - if (xpath == null) { - xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null); - } - return xpath; - } - - /** - * Method getStrFromNode - * - * @param xpathnode - * @return the string for the node. - */ - public static String getStrFromNode(Node xpathnode) { - - if (xpathnode.getNodeType() == Node.TEXT_NODE) { - - // we iterate over all siblings of the context node because eventually, - // the text is "polluted" with pi's or comments - StringBuffer sb = new StringBuffer(); - - for (Node currentSibling = xpathnode.getParentNode().getFirstChild(); - currentSibling != null; - currentSibling = currentSibling.getNextSibling()) { - if (currentSibling.getNodeType() == Node.TEXT_NODE) { - sb.append(((Text) currentSibling).getData()); - } - } - - return sb.toString(); - } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) { - return ((Attr) xpathnode).getNodeValue(); - } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { - return ((ProcessingInstruction) xpathnode).getNodeValue(); - } - - return null; - } - - private static void fixupFunctionTable() { - boolean installed = false; - log.log(java.util.logging.Level.INFO, "Registering Here function"); - /** - * Try to register our here() implementation as internal function. - */ - try { - Class []args = {String.class, Expression.class}; - Method installFunction = FunctionTable.class.getMethod("installFunction", args); - if ((installFunction.getModifiers() & Modifier.STATIC) != 0) { - Object []params = {"here", new FuncHere()}; - installFunction.invoke(null, params); - installed = true; - } - } catch (Throwable t) { - log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", t); - } - if(!installed) { - try { - _funcTable = new FunctionTable(); - Class []args = {String.class, Class.class}; - Method installFunction = FunctionTable.class.getMethod("installFunction", args); - Object []params = {"here", FuncHere.class}; - installFunction.invoke(_funcTable, params); - installed = true; - } catch (Throwable t) { - log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", t); - } - } - if (log.isLoggable(java.util.logging.Level.FINE)) { - if (installed) { - log.log(java.util.logging.Level.FINE, "Registered class " + FuncHere.class.getName() - + " for XPath function 'here()' function in internal table"); - } else { - log.log(java.util.logging.Level.FINE, "Unable to register class " + FuncHere.class.getName() - + " for XPath function 'here()' function in internal table"); - } - } - } -} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java new file mode 100644 index 00000000000..c9b910a4611 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java @@ -0,0 +1,277 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 com.sun.org.apache.xml.internal.security.utils; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; + +/** + * This class is extremely useful for loading resources and classes in a fault + * tolerant manner that works across different applications servers. Do not + * touch this unless you're a grizzled classloading guru veteran who is going to + * verify any change on 6 different application servers. + */ +final class ClassLoaderUtils { + + /** {@link org.apache.commons.logging} logging facility */ + private static final java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ClassLoaderUtils.class.getName()); + + private ClassLoaderUtils() { + } + + /** + * Load a given resource.

    This method will try to load the resource + * using the following methods (in order): + *

      + *
    • From Thread.currentThread().getContextClassLoader() + *
    • From ClassLoaderUtil.class.getClassLoader() + *
    • callingClass.getClassLoader() + *
    + * + * @param resourceName The name of the resource to load + * @param callingClass The Class object of the calling object + */ + static URL getResource(String resourceName, Class callingClass) { + URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName); + if (url == null && resourceName.startsWith("/")) { + //certain classloaders need it without the leading / + url = + Thread.currentThread().getContextClassLoader().getResource( + resourceName.substring(1) + ); + } + + ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader(); + if (cluClassloader == null) { + cluClassloader = ClassLoader.getSystemClassLoader(); + } + if (url == null) { + url = cluClassloader.getResource(resourceName); + } + if (url == null && resourceName.startsWith("/")) { + //certain classloaders need it without the leading / + url = cluClassloader.getResource(resourceName.substring(1)); + } + + if (url == null) { + ClassLoader cl = callingClass.getClassLoader(); + + if (cl != null) { + url = cl.getResource(resourceName); + } + } + + if (url == null) { + url = callingClass.getResource(resourceName); + } + + if ((url == null) && (resourceName != null) && (resourceName.charAt(0) != '/')) { + return getResource('/' + resourceName, callingClass); + } + + return url; + } + + /** + * Load a given resources.

    This method will try to load the resources + * using the following methods (in order): + *

      + *
    • From Thread.currentThread().getContextClassLoader() + *
    • From ClassLoaderUtil.class.getClassLoader() + *
    • callingClass.getClassLoader() + *
    + * + * @param resourceName The name of the resource to load + * @param callingClass The Class object of the calling object + */ + static List getResources(String resourceName, Class callingClass) { + List ret = new ArrayList(); + Enumeration urls = new Enumeration() { + public boolean hasMoreElements() { + return false; + } + public URL nextElement() { + return null; + } + + }; + try { + urls = Thread.currentThread().getContextClassLoader().getResources(resourceName); + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + //ignore + } + if (!urls.hasMoreElements() && resourceName.startsWith("/")) { + //certain classloaders need it without the leading / + try { + urls = + Thread.currentThread().getContextClassLoader().getResources( + resourceName.substring(1) + ); + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + // ignore + } + } + + ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader(); + if (cluClassloader == null) { + cluClassloader = ClassLoader.getSystemClassLoader(); + } + if (!urls.hasMoreElements()) { + try { + urls = cluClassloader.getResources(resourceName); + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + // ignore + } + } + if (!urls.hasMoreElements() && resourceName.startsWith("/")) { + //certain classloaders need it without the leading / + try { + urls = cluClassloader.getResources(resourceName.substring(1)); + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + // ignore + } + } + + if (!urls.hasMoreElements()) { + ClassLoader cl = callingClass.getClassLoader(); + + if (cl != null) { + try { + urls = cl.getResources(resourceName); + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + // ignore + } + } + } + + if (!urls.hasMoreElements()) { + URL url = callingClass.getResource(resourceName); + if (url != null) { + ret.add(url); + } + } + while (urls.hasMoreElements()) { + ret.add(urls.nextElement()); + } + + + if (ret.isEmpty() && (resourceName != null) && (resourceName.charAt(0) != '/')) { + return getResources('/' + resourceName, callingClass); + } + return ret; + } + + + /** + * This is a convenience method to load a resource as a stream.

    The + * algorithm used to find the resource is given in getResource() + * + * @param resourceName The name of the resource to load + * @param callingClass The Class object of the calling object + */ + static InputStream getResourceAsStream(String resourceName, Class callingClass) { + URL url = getResource(resourceName, callingClass); + + try { + return (url != null) ? url.openStream() : null; + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + return null; + } + } + + /** + * Load a class with a given name.

    It will try to load the class in the + * following order: + *

      + *
    • From Thread.currentThread().getContextClassLoader() + *
    • Using the basic Class.forName() + *
    • From ClassLoaderUtil.class.getClassLoader() + *
    • From the callingClass.getClassLoader() + *
    + * + * @param className The name of the class to load + * @param callingClass The Class object of the calling object + * @throws ClassNotFoundException If the class cannot be found anywhere. + */ + static Class loadClass(String className, Class callingClass) + throws ClassNotFoundException { + try { + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + + if (cl != null) { + return cl.loadClass(className); + } + } catch (ClassNotFoundException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + //ignore + } + return loadClass2(className, callingClass); + } + + private static Class loadClass2(String className, Class callingClass) + throws ClassNotFoundException { + try { + return Class.forName(className); + } catch (ClassNotFoundException ex) { + try { + if (ClassLoaderUtils.class.getClassLoader() != null) { + return ClassLoaderUtils.class.getClassLoader().loadClass(className); + } + } catch (ClassNotFoundException exc) { + if (callingClass != null && callingClass.getClassLoader() != null) { + return callingClass.getClassLoader().loadClass(className); + } + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + throw ex; + } + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java index 39ec71d8794..78907b09595 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils; -import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - /** * Provides all constants and some translation functions for i18n. * @@ -29,202 +29,245 @@ import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; * XML * Signature specification. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class Constants { - /** Field configurationFile */ - public static final String configurationFile = "data/websig.conf"; + /** Field configurationFile */ + public static final String configurationFile = "data/websig.conf"; - /** Field configurationFileNew */ - public static final String configurationFileNew = ".xmlsecurityconfig"; + /** Field configurationFileNew */ + public static final String configurationFileNew = ".xmlsecurityconfig"; - /** Field exceptionMessagesResourceBundleDir */ - public static final String exceptionMessagesResourceBundleDir = - "com/sun/org/apache/xml/internal/security/resource"; + /** Field exceptionMessagesResourceBundleDir */ + public static final String exceptionMessagesResourceBundleDir = + "com/sun/org/apache/xml/internal/security/resource"; - /** Field exceptionMessagesResourceBundleBase is the location of the ResourceBundle */ - public static final String exceptionMessagesResourceBundleBase = - exceptionMessagesResourceBundleDir + "/" + "xmlsecurity"; - //J- - /** - * The URL of the XML Signature specification - */ - public static final String SIGNATURESPECIFICATION_URL = "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/"; + /** Field exceptionMessagesResourceBundleBase is the location of the ResourceBundle */ + public static final String exceptionMessagesResourceBundleBase = + exceptionMessagesResourceBundleDir + "/" + "xmlsecurity"; - /** - * The namespace of the XML Signature specification - */ - public static final String SignatureSpecNS = "http://www.w3.org/2000/09/xmldsig#"; - /** The URL for more algorithm **/ - public static final String MoreAlgorithmsSpecNS = "http://www.w3.org/2001/04/xmldsig-more#"; - /** The URI for XML spec*/ - public static final String XML_LANG_SPACE_SpecNS = "http://www.w3.org/XML/1998/namespace"; - /** The URI for XMLNS spec*/ - public static final String NamespaceSpecNS = "http://www.w3.org/2000/xmlns/"; + /** + * The URL of the + * XML Signature specification + */ + public static final String SIGNATURESPECIFICATION_URL = + "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/"; - /** Tag of Attr Algorithm**/ - public static final String _ATT_ALGORITHM = "Algorithm"; - /** Tag of Attr URI**/ - public static final String _ATT_URI = "URI"; - /** Tag of Attr Type**/ - public static final String _ATT_TYPE = "Type"; - /** Tag of Attr Id**/ - public static final String _ATT_ID = "Id"; - /** Tag of Attr MimeType**/ - public static final String _ATT_MIMETYPE = "MimeType"; - /** Tag of Attr Encoding**/ - public static final String _ATT_ENCODING = "Encoding"; - /** Tag of Attr Target**/ - public static final String _ATT_TARGET = "Target"; + /** + * The namespace of the + * XML Signature specification + */ + public static final String SignatureSpecNS = "http://www.w3.org/2000/09/xmldsig#"; - // KeyInfo (KeyName|KeyValue|RetrievalMethod|X509Data|PGPData|SPKIData|MgmtData) - // KeyValue (DSAKeyValue|RSAKeyValue) - // DSAKeyValue (P, Q, G, Y, J?, (Seed, PgenCounter)?) - // RSAKeyValue (Modulus, Exponent) - // RetrievalMethod (Transforms?) - // X509Data ((X509IssuerSerial | X509SKI | X509SubjectName | X509Certificate)+ | X509CRL) - // X509IssuerSerial (X509IssuerName, X509SerialNumber) - // PGPData ((PGPKeyID, PGPKeyPacket?) | (PGPKeyPacket)) - // SPKIData (SPKISexp) + /** + * The namespace of the + * XML Signature specification + */ + public static final String SignatureSpec11NS = "http://www.w3.org/2009/xmldsig11#"; - /** Tag of Element CanonicalizationMethod **/ - public static final String _TAG_CANONICALIZATIONMETHOD = "CanonicalizationMethod"; - /** Tag of Element DigestMethod **/ - public static final String _TAG_DIGESTMETHOD = "DigestMethod"; - /** Tag of Element DigestValue **/ - public static final String _TAG_DIGESTVALUE = "DigestValue"; - /** Tag of Element Manifest **/ - public static final String _TAG_MANIFEST = "Manifest"; - /** Tag of Element Methods **/ - public static final String _TAG_METHODS = "Methods"; - /** Tag of Element Object **/ - public static final String _TAG_OBJECT = "Object"; - /** Tag of Element Reference **/ - public static final String _TAG_REFERENCE = "Reference"; - /** Tag of Element Signature **/ - public static final String _TAG_SIGNATURE = "Signature"; - /** Tag of Element SignatureMethod **/ - public static final String _TAG_SIGNATUREMETHOD = "SignatureMethod"; - /** Tag of Element HMACOutputLength **/ - public static final String _TAG_HMACOUTPUTLENGTH = "HMACOutputLength"; - /** Tag of Element SignatureProperties **/ - public static final String _TAG_SIGNATUREPROPERTIES = "SignatureProperties"; - /** Tag of Element SignatureProperty **/ - public static final String _TAG_SIGNATUREPROPERTY = "SignatureProperty"; - /** Tag of Element SignatureValue **/ - public static final String _TAG_SIGNATUREVALUE = "SignatureValue"; - /** Tag of Element SignedInfo **/ - public static final String _TAG_SIGNEDINFO = "SignedInfo"; - /** Tag of Element Transform **/ - public static final String _TAG_TRANSFORM = "Transform"; - /** Tag of Element Transforms **/ - public static final String _TAG_TRANSFORMS = "Transforms"; - /** Tag of Element XPath **/ - public static final String _TAG_XPATH = "XPath"; - /** Tag of Element KeyInfo **/ - public static final String _TAG_KEYINFO = "KeyInfo"; - /** Tag of Element KeyName **/ - public static final String _TAG_KEYNAME = "KeyName"; - /** Tag of Element KeyValue **/ - public static final String _TAG_KEYVALUE = "KeyValue"; - /** Tag of Element RetrievalMethod **/ - public static final String _TAG_RETRIEVALMETHOD = "RetrievalMethod"; - /** Tag of Element X509Data **/ - public static final String _TAG_X509DATA = "X509Data"; - /** Tag of Element PGPData **/ - public static final String _TAG_PGPDATA = "PGPData"; - /** Tag of Element SPKIData **/ - public static final String _TAG_SPKIDATA = "SPKIData"; - /** Tag of Element MgmtData **/ - public static final String _TAG_MGMTDATA = "MgmtData"; - /** Tag of Element RSAKeyValue **/ - public static final String _TAG_RSAKEYVALUE = "RSAKeyValue"; - /** Tag of Element Exponent **/ - public static final String _TAG_EXPONENT = "Exponent"; - /** Tag of Element Modulus **/ - public static final String _TAG_MODULUS = "Modulus"; - /** Tag of Element DSAKeyValue **/ - public static final String _TAG_DSAKEYVALUE = "DSAKeyValue"; - /** Tag of Element P **/ - public static final String _TAG_P = "P"; - /** Tag of Element Q **/ - public static final String _TAG_Q = "Q"; - /** Tag of Element G **/ - public static final String _TAG_G = "G"; - /** Tag of Element Y **/ - public static final String _TAG_Y = "Y"; - /** Tag of Element J **/ - public static final String _TAG_J = "J"; - /** Tag of Element Seed **/ - public static final String _TAG_SEED = "Seed"; - /** Tag of Element PgenCounter **/ - public static final String _TAG_PGENCOUNTER = "PgenCounter"; - /** Tag of Element rawX509Certificate **/ - public static final String _TAG_RAWX509CERTIFICATE = "rawX509Certificate"; - /** Tag of Element X509IssuerSerial **/ - public static final String _TAG_X509ISSUERSERIAL = "X509IssuerSerial"; - /** Tag of Element X509SKI **/ - public static final String _TAG_X509SKI = "X509SKI"; - /** Tag of Element X509SubjectName **/ - public static final String _TAG_X509SUBJECTNAME = "X509SubjectName"; - /** Tag of Element X509Certificate **/ - public static final String _TAG_X509CERTIFICATE = "X509Certificate"; - /** Tag of Element X509CRL **/ - public static final String _TAG_X509CRL = "X509CRL"; - /** Tag of Element X509IssuerName **/ - public static final String _TAG_X509ISSUERNAME = "X509IssuerName"; - /** Tag of Element X509SerialNumber **/ - public static final String _TAG_X509SERIALNUMBER = "X509SerialNumber"; - /** Tag of Element PGPKeyID **/ - public static final String _TAG_PGPKEYID = "PGPKeyID"; - /** Tag of Element PGPKeyPacket **/ - public static final String _TAG_PGPKEYPACKET = "PGPKeyPacket"; - /** Tag of Element SPKISexp **/ - public static final String _TAG_SPKISEXP = "SPKISexp"; + /** The URL for more algorithms **/ + public static final String MoreAlgorithmsSpecNS = "http://www.w3.org/2001/04/xmldsig-more#"; - /** Digest - Required SHA1 */ - public static final String ALGO_ID_DIGEST_SHA1 = SignatureSpecNS + "sha1"; + /** The URI for XML spec*/ + public static final String XML_LANG_SPACE_SpecNS = "http://www.w3.org/XML/1998/namespace"; - /** - * @see - * draft-blake-wilson-xmldsig-ecdsa-02.txt - */ - public static final String ALGO_ID_SIGNATURE_ECDSA_CERTICOM = "http://www.certicom.com/2000/11/xmlecdsig#ecdsa-sha1"; - //J+ + /** The URI for XMLNS spec*/ + public static final String NamespaceSpecNS = "http://www.w3.org/2000/xmlns/"; - private Constants() { - // we don't allow instantiation - } + /** Tag of Attr Algorithm**/ + public static final String _ATT_ALGORITHM = "Algorithm"; - /** - * Sets the namespace prefix which will be used to identify elements in the - * XML Signature Namespace. - * - *
    -    * Constants.setSignatureSpecNSprefix("dsig");
    -    * 
    - * - * @param newPrefix is the new namespace prefix. - * @throws XMLSecurityException - * @see com.sun.org.apache.xml.internal.security.utils.Constants#getSignatureSpecNSprefix - * $todo$ Add consistency checking for valid prefix - */ - public static void setSignatureSpecNSprefix(String newPrefix) throws XMLSecurityException { - ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, newPrefix); - } + /** Tag of Attr URI**/ + public static final String _ATT_URI = "URI"; + + /** Tag of Attr Type**/ + public static final String _ATT_TYPE = "Type"; + + /** Tag of Attr Id**/ + public static final String _ATT_ID = "Id"; + + /** Tag of Attr MimeType**/ + public static final String _ATT_MIMETYPE = "MimeType"; + + /** Tag of Attr Encoding**/ + public static final String _ATT_ENCODING = "Encoding"; + + /** Tag of Attr Target**/ + public static final String _ATT_TARGET = "Target"; + + // KeyInfo (KeyName|KeyValue|RetrievalMethod|X509Data|PGPData|SPKIData|MgmtData) + // KeyValue (DSAKeyValue|RSAKeyValue) + // DSAKeyValue (P, Q, G, Y, J?, (Seed, PgenCounter)?) + // RSAKeyValue (Modulus, Exponent) + // RetrievalMethod (Transforms?) + // X509Data ((X509IssuerSerial | X509SKI | X509SubjectName | X509Certificate)+ | X509CRL) + // X509IssuerSerial (X509IssuerName, X509SerialNumber) + // PGPData ((PGPKeyID, PGPKeyPacket?) | (PGPKeyPacket)) + // SPKIData (SPKISexp) + + /** Tag of Element CanonicalizationMethod **/ + public static final String _TAG_CANONICALIZATIONMETHOD = "CanonicalizationMethod"; + + /** Tag of Element DigestMethod **/ + public static final String _TAG_DIGESTMETHOD = "DigestMethod"; + + /** Tag of Element DigestValue **/ + public static final String _TAG_DIGESTVALUE = "DigestValue"; + + /** Tag of Element Manifest **/ + public static final String _TAG_MANIFEST = "Manifest"; + + /** Tag of Element Methods **/ + public static final String _TAG_METHODS = "Methods"; + + /** Tag of Element Object **/ + public static final String _TAG_OBJECT = "Object"; + + /** Tag of Element Reference **/ + public static final String _TAG_REFERENCE = "Reference"; + + /** Tag of Element Signature **/ + public static final String _TAG_SIGNATURE = "Signature"; + + /** Tag of Element SignatureMethod **/ + public static final String _TAG_SIGNATUREMETHOD = "SignatureMethod"; + + /** Tag of Element HMACOutputLength **/ + public static final String _TAG_HMACOUTPUTLENGTH = "HMACOutputLength"; + + /** Tag of Element SignatureProperties **/ + public static final String _TAG_SIGNATUREPROPERTIES = "SignatureProperties"; + + /** Tag of Element SignatureProperty **/ + public static final String _TAG_SIGNATUREPROPERTY = "SignatureProperty"; + + /** Tag of Element SignatureValue **/ + public static final String _TAG_SIGNATUREVALUE = "SignatureValue"; + + /** Tag of Element SignedInfo **/ + public static final String _TAG_SIGNEDINFO = "SignedInfo"; + + /** Tag of Element Transform **/ + public static final String _TAG_TRANSFORM = "Transform"; + + /** Tag of Element Transforms **/ + public static final String _TAG_TRANSFORMS = "Transforms"; + + /** Tag of Element XPath **/ + public static final String _TAG_XPATH = "XPath"; + + /** Tag of Element KeyInfo **/ + public static final String _TAG_KEYINFO = "KeyInfo"; + + /** Tag of Element KeyName **/ + public static final String _TAG_KEYNAME = "KeyName"; + + /** Tag of Element KeyValue **/ + public static final String _TAG_KEYVALUE = "KeyValue"; + + /** Tag of Element RetrievalMethod **/ + public static final String _TAG_RETRIEVALMETHOD = "RetrievalMethod"; + + /** Tag of Element X509Data **/ + public static final String _TAG_X509DATA = "X509Data"; + + /** Tag of Element PGPData **/ + public static final String _TAG_PGPDATA = "PGPData"; + + /** Tag of Element SPKIData **/ + public static final String _TAG_SPKIDATA = "SPKIData"; + + /** Tag of Element MgmtData **/ + public static final String _TAG_MGMTDATA = "MgmtData"; + + /** Tag of Element RSAKeyValue **/ + public static final String _TAG_RSAKEYVALUE = "RSAKeyValue"; + + /** Tag of Element Exponent **/ + public static final String _TAG_EXPONENT = "Exponent"; + + /** Tag of Element Modulus **/ + public static final String _TAG_MODULUS = "Modulus"; + + /** Tag of Element DSAKeyValue **/ + public static final String _TAG_DSAKEYVALUE = "DSAKeyValue"; + + /** Tag of Element P **/ + public static final String _TAG_P = "P"; + + /** Tag of Element Q **/ + public static final String _TAG_Q = "Q"; + + /** Tag of Element G **/ + public static final String _TAG_G = "G"; + + /** Tag of Element Y **/ + public static final String _TAG_Y = "Y"; + + /** Tag of Element J **/ + public static final String _TAG_J = "J"; + + /** Tag of Element Seed **/ + public static final String _TAG_SEED = "Seed"; + + /** Tag of Element PgenCounter **/ + public static final String _TAG_PGENCOUNTER = "PgenCounter"; + + /** Tag of Element rawX509Certificate **/ + public static final String _TAG_RAWX509CERTIFICATE = "rawX509Certificate"; + + /** Tag of Element X509IssuerSerial **/ + public static final String _TAG_X509ISSUERSERIAL= "X509IssuerSerial"; + + /** Tag of Element X509SKI **/ + public static final String _TAG_X509SKI = "X509SKI"; + + /** Tag of Element X509SubjectName **/ + public static final String _TAG_X509SUBJECTNAME = "X509SubjectName"; + + /** Tag of Element X509Certificate **/ + public static final String _TAG_X509CERTIFICATE = "X509Certificate"; + + /** Tag of Element X509CRL **/ + public static final String _TAG_X509CRL = "X509CRL"; + + /** Tag of Element X509IssuerName **/ + public static final String _TAG_X509ISSUERNAME = "X509IssuerName"; + + /** Tag of Element X509SerialNumber **/ + public static final String _TAG_X509SERIALNUMBER = "X509SerialNumber"; + + /** Tag of Element PGPKeyID **/ + public static final String _TAG_PGPKEYID = "PGPKeyID"; + + /** Tag of Element PGPKeyPacket **/ + public static final String _TAG_PGPKEYPACKET = "PGPKeyPacket"; + + /** Tag of Element PGPKeyPacket **/ + public static final String _TAG_DERENCODEDKEYVALUE = "DEREncodedKeyValue"; + + /** Tag of Element PGPKeyPacket **/ + public static final String _TAG_KEYINFOREFERENCE = "KeyInfoReference"; + + /** Tag of Element PGPKeyPacket **/ + public static final String _TAG_X509DIGEST = "X509Digest"; + + /** Tag of Element SPKISexp **/ + public static final String _TAG_SPKISEXP = "SPKISexp"; + + /** Digest - Required SHA1 */ + public static final String ALGO_ID_DIGEST_SHA1 = SignatureSpecNS + "sha1"; + + /** + * @see + * draft-blake-wilson-xmldsig-ecdsa-02.txt + */ + public static final String ALGO_ID_SIGNATURE_ECDSA_CERTICOM = + "http://www.certicom.com/2000/11/xmlecdsig#ecdsa-sha1"; + + private Constants() { + // we don't allow instantiation + } - /** - * Returns the XML namespace prefix which is used for elements in the XML - * Signature namespace. - * - * It is defaulted to dsig, but can be changed using the - * {@link #setSignatureSpecNSprefix} function. - * - * @return the current used namespace prefix - * @see #setSignatureSpecNSprefix - */ - public static String getSignatureSpecNSprefix() { - return ElementProxy.getDefaultPrefix(Constants.SignatureSpecNS); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java new file mode 100644 index 00000000000..b4572b481ca --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java @@ -0,0 +1,79 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 com.sun.org.apache.xml.internal.security.utils; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import javax.xml.namespace.NamespaceContext; + +import org.w3c.dom.Attr; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; + +/** + */ +public class DOMNamespaceContext implements NamespaceContext { + + private Map namespaceMap = new HashMap(); + + public DOMNamespaceContext(Node contextNode) { + addNamespaces(contextNode); + } + + public String getNamespaceURI(String arg0) { + return namespaceMap.get(arg0); + } + + public String getPrefix(String arg0) { + for (String key : namespaceMap.keySet()) { + String value = namespaceMap.get(key); + if (value.equals(arg0)) { + return key; + } + } + return null; + } + + public Iterator getPrefixes(String arg0) { + return namespaceMap.keySet().iterator(); + } + + private void addNamespaces(Node element) { + if (element.getParentNode() != null) { + addNamespaces(element.getParentNode()); + } + if (element instanceof Element) { + Element el = (Element)element; + NamedNodeMap map = el.getAttributes(); + for (int x = 0; x < map.getLength(); x++) { + Attr attr = (Attr)map.item(x); + if ("xmlns".equals(attr.getPrefix())) { + namespaceMap.put(attr.getLocalName(), attr.getValue()); + } + } + } + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java index bdf560dc78e..bd06b7d7c27 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils; @@ -29,16 +31,16 @@ import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorith * */ public class DigesterOutputStream extends ByteArrayOutputStream { + private static final java.util.logging.Logger log = + java.util.logging.Logger.getLogger(DigesterOutputStream.class.getName()); + final MessageDigestAlgorithm mda; - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger - (DigesterOutputStream.class.getName()); /** * @param mda */ public DigesterOutputStream(MessageDigestAlgorithm mda) { - this.mda=mda; + this.mda = mda; } /** @inheritDoc */ @@ -55,9 +57,9 @@ public class DigesterOutputStream extends ByteArrayOutputStream { public void write(byte[] arg0, int arg1, int arg2) { if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Pre-digested input:"); - StringBuffer sb = new StringBuffer(arg2); - for (int i=arg1; i<(arg1+arg2); i++) { - sb.append((char) arg0[i]); + StringBuilder sb = new StringBuilder(arg2); + for (int i = arg1; i < (arg1 + arg2); i++) { + sb.append((char)arg0[i]); } log.log(java.util.logging.Level.FINE, sb.toString()); } @@ -68,6 +70,6 @@ public class DigesterOutputStream extends ByteArrayOutputStream { * @return the digest value */ public byte[] getDigestValue() { - return mda.digest(); + return mda.digest(); } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java index 9da45ce8cd1..618659c9f19 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java @@ -1,17 +1,41 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 com.sun.org.apache.xml.internal.security.utils; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import org.w3c.dom.Element; import org.w3c.dom.Node; +/**@deprecated*/ +@Deprecated public interface ElementChecker { - /** - * Check that the elemnt is the one expect - * - * @throws XMLSecurityException - */ - public void guaranteeThatElementInCorrectSpace(ElementProxy expected, Element actual) - throws XMLSecurityException; + /** + * Check that the element is the one expect + * + * @throws XMLSecurityException + */ + void guaranteeThatElementInCorrectSpace(ElementProxy expected, Element actual) + throws XMLSecurityException; - public boolean isNamespaceElement(Node el, String type, String ns); + boolean isNamespaceElement(Node el, String type, String ns); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java index 5a94927d1c6..d71fd100384 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java @@ -1,60 +1,90 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 com.sun.org.apache.xml.internal.security.utils; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import org.w3c.dom.Element; import org.w3c.dom.Node; +/**@deprecated*/ +@Deprecated public abstract class ElementCheckerImpl implements ElementChecker { - public boolean isNamespaceElement(Node el, String type, String ns) { - if ((el == null) || - ns!=el.getNamespaceURI() || !el.getLocalName().equals(type)){ - return false; - } - return true; - } - /** A checker for DOM that interns NS */ - public static class InternedNsChecker extends ElementCheckerImpl{ - public void guaranteeThatElementInCorrectSpace(ElementProxy expected, - Element actual) throws XMLSecurityException { - - String localnameSHOULDBE = expected.getBaseLocalName(); - String namespaceSHOULDBE = expected.getBaseNamespace(); - - String localnameIS = actual.getLocalName(); - String namespaceIS = actual.getNamespaceURI(); - if ((namespaceSHOULDBE!=namespaceIS) || - !localnameSHOULDBE.equals(localnameIS) ) { - Object exArgs[] = { namespaceIS +":"+ localnameIS, - namespaceSHOULDBE +":"+ localnameSHOULDBE}; - throw new XMLSecurityException("xml.WrongElement", exArgs); - } - } + public boolean isNamespaceElement(Node el, String type, String ns) { + if ((el == null) || + ns != el.getNamespaceURI() || !el.getLocalName().equals(type)){ + return false; } - /** A checker for DOM that interns NS */ - public static class FullChecker extends ElementCheckerImpl { - public void guaranteeThatElementInCorrectSpace(ElementProxy expected, - Element actual) throws XMLSecurityException { + return true; + } - String localnameSHOULDBE = expected.getBaseLocalName(); - String namespaceSHOULDBE = expected.getBaseNamespace(); + /** A checker for DOM that interns NS */ + public static class InternedNsChecker extends ElementCheckerImpl { + public void guaranteeThatElementInCorrectSpace( + ElementProxy expected, Element actual + ) throws XMLSecurityException { - String localnameIS = actual.getLocalName(); - String namespaceIS = actual.getNamespaceURI(); - if ((!namespaceSHOULDBE.equals(namespaceIS)) || - !localnameSHOULDBE.equals(localnameIS) ) { - Object exArgs[] = { namespaceIS +":"+ localnameIS, - namespaceSHOULDBE +":"+ localnameSHOULDBE}; - throw new XMLSecurityException("xml.WrongElement", exArgs); - } - } + String expectedLocalname = expected.getBaseLocalName(); + String expectedNamespace = expected.getBaseNamespace(); + + String localnameIS = actual.getLocalName(); + String namespaceIS = actual.getNamespaceURI(); + if ((expectedNamespace != namespaceIS) || + !expectedLocalname.equals(localnameIS)) { + Object exArgs[] = { namespaceIS + ":" + localnameIS, + expectedNamespace + ":" + expectedLocalname}; + throw new XMLSecurityException("xml.WrongElement", exArgs); + } } + } - /** An empty checker if schema checking is used */ - public static class EmptyChecker extends ElementCheckerImpl { - public void guaranteeThatElementInCorrectSpace(ElementProxy expected, - Element actual) throws XMLSecurityException { - } + /** A checker for DOM that interns NS */ + public static class FullChecker extends ElementCheckerImpl { + + public void guaranteeThatElementInCorrectSpace( + ElementProxy expected, Element actual + ) throws XMLSecurityException { + String expectedLocalname = expected.getBaseLocalName(); + String expectedNamespace = expected.getBaseNamespace(); + + String localnameIS = actual.getLocalName(); + String namespaceIS = actual.getNamespaceURI(); + if ((!expectedNamespace.equals(namespaceIS)) || + !expectedLocalname.equals(localnameIS) ) { + Object exArgs[] = { namespaceIS + ":" + localnameIS, + expectedNamespace + ":" + expectedLocalname}; + throw new XMLSecurityException("xml.WrongElement", exArgs); + } } + } + + /** An empty checker if schema checking is used */ + public static class EmptyChecker extends ElementCheckerImpl { + public void guaranteeThatElementInCorrectSpace( + ElementProxy expected, Element actual + ) throws XMLSecurityException { + // empty + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java index 2d2fdeb61bb..ac7a53eba4f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java @@ -45,13 +45,13 @@ public abstract class ElementProxy { java.util.logging.Logger.getLogger(ElementProxy.class.getName()); /** Field constructionElement */ - protected Element _constructionElement = null; + protected Element constructionElement = null; /** Field baseURI */ - protected String _baseURI = null; + protected String baseURI = null; /** Field doc */ - protected Document _doc = null; + protected Document doc = null; /** Field prefixMappings */ private static Map prefixMappings = new ConcurrentHashMap(); @@ -73,9 +73,9 @@ public abstract class ElementProxy { throw new RuntimeException("Document is null"); } - this._doc = doc; - this._constructionElement = - createElementForFamilyLocal(this._doc, this.getBaseNamespace(), this.getBaseLocalName()); + this.doc = doc; + this.constructionElement = + createElementForFamilyLocal(this.doc, this.getBaseNamespace(), this.getBaseLocalName()); } /** @@ -94,9 +94,9 @@ public abstract class ElementProxy { log.log(java.util.logging.Level.FINE, "setElement(\"" + element.getTagName() + "\", \"" + BaseURI + "\")"); } - this._doc = element.getOwnerDocument(); - this._constructionElement = element; - this._baseURI = BaseURI; + this.doc = element.getOwnerDocument(); + this.constructionElement = element; + this.baseURI = BaseURI; this.guaranteeThatElementInCorrectSpace(); } @@ -184,9 +184,9 @@ public abstract class ElementProxy { log.log(java.util.logging.Level.FINE, "setElement(" + element.getTagName() + ", \"" + BaseURI + "\""); } - this._doc = element.getOwnerDocument(); - this._constructionElement = element; - this._baseURI = BaseURI; + this.doc = element.getOwnerDocument(); + this.constructionElement = element; + this.baseURI = BaseURI; } @@ -196,7 +196,7 @@ public abstract class ElementProxy { * @return the Element which was constructed by the Object. */ public final Element getElement() { - return this._constructionElement; + return this.constructionElement; } /** @@ -208,9 +208,9 @@ public abstract class ElementProxy { HelperNodeList nl = new HelperNodeList(); - nl.appendChild(this._doc.createTextNode("\n")); + nl.appendChild(this.doc.createTextNode("\n")); nl.appendChild(this.getElement()); - nl.appendChild(this._doc.createTextNode("\n")); + nl.appendChild(this.doc.createTextNode("\n")); return nl; } @@ -221,7 +221,7 @@ public abstract class ElementProxy { * @return the Document where this element is contained. */ public Document getDocument() { - return this._doc; + return this.doc; } /** @@ -230,7 +230,7 @@ public abstract class ElementProxy { * @return the base uri of the namespace of this element */ public String getBaseURI() { - return this._baseURI; + return this.baseURI; } /** @@ -243,8 +243,8 @@ public abstract class ElementProxy { String expectedLocalName = this.getBaseLocalName(); String expectedNamespaceUri = this.getBaseNamespace(); - String actualLocalName = this._constructionElement.getLocalName(); - String actualNamespaceUri = this._constructionElement.getNamespaceURI(); + String actualLocalName = this.constructionElement.getLocalName(); + String actualNamespaceUri = this.constructionElement.getNamespaceURI(); if(!expectedNamespaceUri.equals(actualNamespaceUri) && !expectedLocalName.equals(actualLocalName)) { @@ -262,11 +262,11 @@ public abstract class ElementProxy { */ public void addBigIntegerElement(BigInteger bi, String localname) { if (bi != null) { - Element e = XMLUtils.createElementInSignatureSpace(this._doc, localname); + Element e = XMLUtils.createElementInSignatureSpace(this.doc, localname); Base64.fillElementWithBigInteger(e, bi); - this._constructionElement.appendChild(e); - XMLUtils.addReturnToElement(this._constructionElement); + this.constructionElement.appendChild(e); + XMLUtils.addReturnToElement(this.constructionElement); } } @@ -278,11 +278,11 @@ public abstract class ElementProxy { */ public void addBase64Element(byte[] bytes, String localname) { if (bytes != null) { - Element e = Base64.encodeToElement(this._doc, localname, bytes); + Element e = Base64.encodeToElement(this.doc, localname, bytes); - this._constructionElement.appendChild(e); + this.constructionElement.appendChild(e); if (!XMLUtils.ignoreLineBreaks()) { - this._constructionElement.appendChild(this._doc.createTextNode("\n")); + this.constructionElement.appendChild(this.doc.createTextNode("\n")); } } } @@ -294,12 +294,12 @@ public abstract class ElementProxy { * @param localname */ public void addTextElement(String text, String localname) { - Element e = XMLUtils.createElementInSignatureSpace(this._doc, localname); - Text t = this._doc.createTextNode(text); + Element e = XMLUtils.createElementInSignatureSpace(this.doc, localname); + Text t = this.doc.createTextNode(text); e.appendChild(t); - this._constructionElement.appendChild(e); - XMLUtils.addReturnToElement(this._constructionElement); + this.constructionElement.appendChild(e); + XMLUtils.addReturnToElement(this.constructionElement); } /** @@ -310,9 +310,9 @@ public abstract class ElementProxy { public void addBase64Text(byte[] bytes) { if (bytes != null) { Text t = XMLUtils.ignoreLineBreaks() - ? this._doc.createTextNode(Base64.encode(bytes)) - : this._doc.createTextNode("\n" + Base64.encode(bytes) + "\n"); - this._constructionElement.appendChild(t); + ? this.doc.createTextNode(Base64.encode(bytes)) + : this.doc.createTextNode("\n" + Base64.encode(bytes) + "\n"); + this.constructionElement.appendChild(t); } } @@ -323,9 +323,9 @@ public abstract class ElementProxy { */ public void addText(String text) { if (text != null) { - Text t = this._doc.createTextNode(text); + Text t = this.doc.createTextNode(text); - this._constructionElement.appendChild(t); + this.constructionElement.appendChild(t); } } @@ -342,7 +342,7 @@ public abstract class ElementProxy { ) throws Base64DecodingException { return Base64.decodeBigIntegerFromText( XMLUtils.selectNodeText( - this._constructionElement.getFirstChild(), namespace, localname, 0 + this.constructionElement.getFirstChild(), namespace, localname, 0 ) ); } @@ -360,7 +360,7 @@ public abstract class ElementProxy { throws XMLSecurityException { Element e = XMLUtils.selectNode( - this._constructionElement.getFirstChild(), namespace, localname, 0 + this.constructionElement.getFirstChild(), namespace, localname, 0 ); return Base64.decode(e); @@ -375,7 +375,7 @@ public abstract class ElementProxy { */ public String getTextFromChildElement(String localname, String namespace) { return XMLUtils.selectNode( - this._constructionElement.getFirstChild(), + this.constructionElement.getFirstChild(), namespace, localname, 0).getTextContent(); @@ -388,7 +388,7 @@ public abstract class ElementProxy { * @throws XMLSecurityException */ public byte[] getBytesFromTextChild() throws XMLSecurityException { - return Base64.decode(XMLUtils.getFullTextChildrenFromElement(this._constructionElement)); + return Base64.decode(XMLUtils.getFullTextChildrenFromElement(this.constructionElement)); } /** @@ -398,7 +398,7 @@ public abstract class ElementProxy { * element */ public String getTextFromTextChild() { - return XMLUtils.getFullTextChildrenFromElement(this._constructionElement); + return XMLUtils.getFullTextChildrenFromElement(this.constructionElement); } /** @@ -410,7 +410,7 @@ public abstract class ElementProxy { */ public int length(String namespace, String localname) { int number = 0; - Node sibling = this._constructionElement.getFirstChild(); + Node sibling = this.constructionElement.getFirstChild(); while (sibling != null) { if (localname.equals(sibling.getLocalName()) && namespace.equals(sibling.getNamespaceURI())) { @@ -448,18 +448,18 @@ public abstract class ElementProxy { ns = "xmlns:" + prefix; } - Attr a = this._constructionElement.getAttributeNodeNS(Constants.NamespaceSpecNS, ns); + Attr a = this.constructionElement.getAttributeNodeNS(Constants.NamespaceSpecNS, ns); if (a != null) { if (!a.getNodeValue().equals(uri)) { - Object exArgs[] = { ns, this._constructionElement.getAttributeNS(null, ns) }; + Object exArgs[] = { ns, this.constructionElement.getAttributeNS(null, ns) }; throw new XMLSecurityException("namespacePrefixAlreadyUsedByOtherURI", exArgs); } return; } - this._constructionElement.setAttributeNS(Constants.NamespaceSpecNS, ns, uri); + this.constructionElement.setAttributeNS(Constants.NamespaceSpecNS, ns, uri); } /** @@ -515,16 +515,4 @@ public abstract class ElementProxy { return prefixMappings.get(namespace); } - protected void setLocalIdAttribute(String attrName, String value) { - - if (value != null) { - Attr attr = getDocument().createAttributeNS(null, attrName); - attr.setValue(value); - getElement().setAttributeNodeNS(attr); - getElement().setIdAttributeNode(attr, true); - } - else { - getElement().removeAttributeNS(null, attrName); - } - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java index e250bff2a16..175911e169f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java @@ -2,179 +2,238 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils; - - -import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - - -/** - * - * @author $Author: mullan $ - */ public class EncryptionConstants { - //J- - // Attributes that exist in XML Signature in the same way + // Attributes that exist in XML Signature in the same way /** Tag of Attr Algorithm **/ - public static final String _ATT_ALGORITHM = Constants._ATT_ALGORITHM; - /** Tag of Attr Id**/ - public static final String _ATT_ID = Constants._ATT_ID; - /** Tag of Attr Target **/ - public static final String _ATT_TARGET = Constants._ATT_TARGET; - /** Tag of Attr Type **/ - public static final String _ATT_TYPE = Constants._ATT_TYPE; - /** Tag of Attr URI **/ - public static final String _ATT_URI = Constants._ATT_URI; + public static final String _ATT_ALGORITHM = Constants._ATT_ALGORITHM; - // Attributes new in XML Encryption - /** Tag of Attr encoding **/ - public static final String _ATT_ENCODING = "Encoding"; - /** Tag of Attr recipient **/ - public static final String _ATT_RECIPIENT = "Recipient"; - /** Tag of Attr mimetype **/ - public static final String _ATT_MIMETYPE = "MimeType"; + /** Tag of Attr Id**/ + public static final String _ATT_ID = Constants._ATT_ID; - /** Tag of Element CarriedKeyName **/ - public static final String _TAG_CARRIEDKEYNAME = "CarriedKeyName"; - /** Tag of Element CipherData **/ - public static final String _TAG_CIPHERDATA = "CipherData"; - /** Tag of Element CipherReference **/ - public static final String _TAG_CIPHERREFERENCE = "CipherReference"; - /** Tag of Element CipherValue **/ - public static final String _TAG_CIPHERVALUE = "CipherValue"; - /** Tag of Element DataReference **/ - public static final String _TAG_DATAREFERENCE = "DataReference"; - /** Tag of Element EncryptedData **/ - public static final String _TAG_ENCRYPTEDDATA = "EncryptedData"; - /** Tag of Element EncryptedKey **/ - public static final String _TAG_ENCRYPTEDKEY = "EncryptedKey"; - /** Tag of Element EncryptionMethod **/ - public static final String _TAG_ENCRYPTIONMETHOD = "EncryptionMethod"; - /** Tag of Element EncryptionProperties **/ - public static final String _TAG_ENCRYPTIONPROPERTIES = "EncryptionProperties"; - /** Tag of Element EncryptionProperty **/ - public static final String _TAG_ENCRYPTIONPROPERTY = "EncryptionProperty"; - /** Tag of Element KeyReference **/ - public static final String _TAG_KEYREFERENCE = "KeyReference"; - /** Tag of Element KeySize **/ - public static final String _TAG_KEYSIZE = "KeySize"; - /** Tag of Element OAEPparams **/ - public static final String _TAG_OAEPPARAMS = "OAEPparams"; - /** Tag of Element ReferenceList **/ - public static final String _TAG_REFERENCELIST = "ReferenceList"; - /** Tag of Element Transforms **/ - public static final String _TAG_TRANSFORMS = "Transforms"; - /** Tag of Element AgreementMethod **/ - public static final String _TAG_AGREEMENTMETHOD = "AgreementMethod"; - /** Tag of Element KA-Nonce **/ - public static final String _TAG_KA_NONCE = "KA-Nonce"; - /** Tag of Element OriginatorKeyInfo **/ - public static final String _TAG_ORIGINATORKEYINFO = "OriginatorKeyInfo"; - /** Tag of Element RecipientKeyInfo **/ - public static final String _TAG_RECIPIENTKEYINFO = "RecipientKeyInfo"; + /** Tag of Attr Target **/ + public static final String _ATT_TARGET = Constants._ATT_TARGET; - /** Field ENCRYPTIONSPECIFICATION_URL */ - public static final String ENCRYPTIONSPECIFICATION_URL = "http://www.w3.org/TR/2001/WD-xmlenc-core-20010626/"; + /** Tag of Attr Type **/ + public static final String _ATT_TYPE = Constants._ATT_TYPE; - /** The namespace of the XML Encryption Syntax and Processing */ - public static final String EncryptionSpecNS = "http://www.w3.org/2001/04/xmlenc#"; + /** Tag of Attr URI **/ + public static final String _ATT_URI = Constants._ATT_URI; - /** URI for content*/ - public static final String TYPE_CONTENT = EncryptionSpecNS + "Content"; - /** URI for element*/ - public static final String TYPE_ELEMENT = EncryptionSpecNS + "Element"; - /** URI for mediatype*/ - public static final String TYPE_MEDIATYPE = "http://www.isi.edu/in-notes/iana/assignments/media-types/"; // + "*/*"; + // Attributes new in XML Encryption + /** Tag of Attr encoding **/ + public static final String _ATT_ENCODING = "Encoding"; - /** Block Encryption - REQUIRED TRIPLEDES */ - public static final String ALGO_ID_BLOCKCIPHER_TRIPLEDES = EncryptionConstants.EncryptionSpecNS + "tripledes-cbc"; - /** Block Encryption - REQUIRED AES-128 */ - public static final String ALGO_ID_BLOCKCIPHER_AES128 = EncryptionConstants.EncryptionSpecNS + "aes128-cbc"; - /** Block Encryption - REQUIRED AES-256 */ - public static final String ALGO_ID_BLOCKCIPHER_AES256 = EncryptionConstants.EncryptionSpecNS + "aes256-cbc"; - /** Block Encryption - OPTIONAL AES-192 */ - public static final String ALGO_ID_BLOCKCIPHER_AES192 = EncryptionConstants.EncryptionSpecNS + "aes192-cbc"; + /** Tag of Attr recipient **/ + public static final String _ATT_RECIPIENT = "Recipient"; - /** Key Transport - REQUIRED RSA-v1.5*/ - public static final String ALGO_ID_KEYTRANSPORT_RSA15 = EncryptionConstants.EncryptionSpecNS + "rsa-1_5"; - /** Key Transport - REQUIRED RSA-OAEP */ - public static final String ALGO_ID_KEYTRANSPORT_RSAOAEP = EncryptionConstants.EncryptionSpecNS + "rsa-oaep-mgf1p"; + /** Tag of Attr mimetype **/ + public static final String _ATT_MIMETYPE = "MimeType"; - /** Key Agreement - OPTIONAL Diffie-Hellman */ - public static final String ALGO_ID_KEYAGREEMENT_DH = EncryptionConstants.EncryptionSpecNS + "dh"; + /** Tag of Element CarriedKeyName **/ + public static final String _TAG_CARRIEDKEYNAME = "CarriedKeyName"; - /** Symmetric Key Wrap - REQUIRED TRIPLEDES KeyWrap */ - public static final String ALGO_ID_KEYWRAP_TRIPLEDES = EncryptionConstants.EncryptionSpecNS + "kw-tripledes"; - /** Symmetric Key Wrap - REQUIRED AES-128 KeyWrap */ - public static final String ALGO_ID_KEYWRAP_AES128 = EncryptionConstants.EncryptionSpecNS + "kw-aes128"; - /** Symmetric Key Wrap - REQUIRED AES-256 KeyWrap */ - public static final String ALGO_ID_KEYWRAP_AES256 = EncryptionConstants.EncryptionSpecNS + "kw-aes256"; - /** Symmetric Key Wrap - OPTIONAL AES-192 KeyWrap */ - public static final String ALGO_ID_KEYWRAP_AES192 = EncryptionConstants.EncryptionSpecNS + "kw-aes192"; + /** Tag of Element CipherData **/ + public static final String _TAG_CIPHERDATA = "CipherData"; - /* - // Message Digest - REQUIRED SHA1 - public static final String ALGO_ID_DIGEST_SHA160 = Constants.ALGO_ID_DIGEST_SHA1; - // Message Digest - RECOMMENDED SHA256 - public static final String ALGO_ID_DIGEST_SHA256 = EncryptionConstants.EncryptionSpecNS + "sha256"; - // Message Digest - OPTIONAL SHA512 - public static final String ALGO_ID_DIGEST_SHA512 = EncryptionConstants.EncryptionSpecNS + "sha512"; - // Message Digest - OPTIONAL RIPEMD-160 - public static final String ALGO_ID_DIGEST_RIPEMD160 = EncryptionConstants.EncryptionSpecNS + "ripemd160"; - */ + /** Tag of Element CipherReference **/ + public static final String _TAG_CIPHERREFERENCE = "CipherReference"; - /** Message Authentication - RECOMMENDED XML Digital Signature */ - public static final String ALGO_ID_AUTHENTICATION_XMLSIGNATURE = "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/"; + /** Tag of Element CipherValue **/ + public static final String _TAG_CIPHERVALUE = "CipherValue"; - /** Canonicalization - OPTIONAL Canonical XML with Comments */ - public static final String ALGO_ID_C14N_WITHCOMMENTS = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; - /** Canonicalization - OPTIONAL Canonical XML (omits comments) */ - public static final String ALGO_ID_C14N_OMITCOMMENTS = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; + /** Tag of Element DataReference **/ + public static final String _TAG_DATAREFERENCE = "DataReference"; - /** Encoding - REQUIRED base64 */ - public static final String ALGO_ID_ENCODING_BASE64 = "http://www.w3.org/2000/09/xmldsig#base64"; - //J+ + /** Tag of Element EncryptedData **/ + public static final String _TAG_ENCRYPTEDDATA = "EncryptedData"; - private EncryptionConstants() { - // we don't allow instantiation - } + /** Tag of Element EncryptedKey **/ + public static final String _TAG_ENCRYPTEDKEY = "EncryptedKey"; - /** - * Method setEncryptionSpecNSprefix - * - * @param newPrefix - * @throws XMLSecurityException - */ - public static void setEncryptionSpecNSprefix(String newPrefix) - throws XMLSecurityException { - ElementProxy.setDefaultPrefix(EncryptionConstants.EncryptionSpecNS, - newPrefix); - } + /** Tag of Element EncryptionMethod **/ + public static final String _TAG_ENCRYPTIONMETHOD = "EncryptionMethod"; + + /** Tag of Element EncryptionProperties **/ + public static final String _TAG_ENCRYPTIONPROPERTIES = "EncryptionProperties"; + + /** Tag of Element EncryptionProperty **/ + public static final String _TAG_ENCRYPTIONPROPERTY = "EncryptionProperty"; + + /** Tag of Element KeyReference **/ + public static final String _TAG_KEYREFERENCE = "KeyReference"; + + /** Tag of Element KeySize **/ + public static final String _TAG_KEYSIZE = "KeySize"; + + /** Tag of Element OAEPparams **/ + public static final String _TAG_OAEPPARAMS = "OAEPparams"; + + /** Tag of Element MGF **/ + public static final String _TAG_MGF = "MGF"; + + /** Tag of Element ReferenceList **/ + public static final String _TAG_REFERENCELIST = "ReferenceList"; + + /** Tag of Element Transforms **/ + public static final String _TAG_TRANSFORMS = "Transforms"; + + /** Tag of Element AgreementMethod **/ + public static final String _TAG_AGREEMENTMETHOD = "AgreementMethod"; + + /** Tag of Element KA-Nonce **/ + public static final String _TAG_KA_NONCE = "KA-Nonce"; + + /** Tag of Element OriginatorKeyInfo **/ + public static final String _TAG_ORIGINATORKEYINFO = "OriginatorKeyInfo"; + + /** Tag of Element RecipientKeyInfo **/ + public static final String _TAG_RECIPIENTKEYINFO = "RecipientKeyInfo"; + + /** Field ENCRYPTIONSPECIFICATION_URL */ + public static final String ENCRYPTIONSPECIFICATION_URL = + "http://www.w3.org/TR/2001/WD-xmlenc-core-20010626/"; + + /** The namespace of the + * + * XML Encryption Syntax and Processing */ + public static final String EncryptionSpecNS = + "http://www.w3.org/2001/04/xmlenc#"; + + /** + * The namespace of the XML Encryption 1.1 specification + */ + public static final String EncryptionSpec11NS = + "http://www.w3.org/2009/xmlenc11#"; + + /** URI for content*/ + public static final String TYPE_CONTENT = EncryptionSpecNS + "Content"; + + /** URI for element*/ + public static final String TYPE_ELEMENT = EncryptionSpecNS + "Element"; + + /** URI for mediatype*/ + public static final String TYPE_MEDIATYPE = + "http://www.isi.edu/in-notes/iana/assignments/media-types/"; + + /** Block Encryption - REQUIRED TRIPLEDES */ + public static final String ALGO_ID_BLOCKCIPHER_TRIPLEDES = + EncryptionConstants.EncryptionSpecNS + "tripledes-cbc"; + + /** Block Encryption - REQUIRED AES-128 */ + public static final String ALGO_ID_BLOCKCIPHER_AES128 = + EncryptionConstants.EncryptionSpecNS + "aes128-cbc"; + + /** Block Encryption - REQUIRED AES-256 */ + public static final String ALGO_ID_BLOCKCIPHER_AES256 = + EncryptionConstants.EncryptionSpecNS + "aes256-cbc"; + + /** Block Encryption - OPTIONAL AES-192 */ + public static final String ALGO_ID_BLOCKCIPHER_AES192 = + EncryptionConstants.EncryptionSpecNS + "aes192-cbc"; + + /** Block Encryption - OPTIONAL AES-128-GCM */ + public static final String ALGO_ID_BLOCKCIPHER_AES128_GCM = + "http://www.w3.org/2009/xmlenc11#aes128-gcm"; + + /** Block Encryption - OPTIONAL AES-192-GCM */ + public static final String ALGO_ID_BLOCKCIPHER_AES192_GCM = + "http://www.w3.org/2009/xmlenc11#aes192-gcm"; + + /** Block Encryption - OPTIONAL AES-256-GCM */ + public static final String ALGO_ID_BLOCKCIPHER_AES256_GCM = + "http://www.w3.org/2009/xmlenc11#aes256-gcm"; + + /** Key Transport - REQUIRED RSA-v1.5*/ + public static final String ALGO_ID_KEYTRANSPORT_RSA15 = + EncryptionConstants.EncryptionSpecNS + "rsa-1_5"; + + /** Key Transport - REQUIRED RSA-OAEP */ + public static final String ALGO_ID_KEYTRANSPORT_RSAOAEP = + EncryptionConstants.EncryptionSpecNS + "rsa-oaep-mgf1p"; + + /** Key Transport - OPTIONAL RSA-OAEP_11 */ + public static final String ALGO_ID_KEYTRANSPORT_RSAOAEP_11 = + EncryptionConstants.EncryptionSpec11NS + "rsa-oaep"; + + /** Key Agreement - OPTIONAL Diffie-Hellman */ + public static final String ALGO_ID_KEYAGREEMENT_DH = + EncryptionConstants.EncryptionSpecNS + "dh"; + + /** Symmetric Key Wrap - REQUIRED TRIPLEDES KeyWrap */ + public static final String ALGO_ID_KEYWRAP_TRIPLEDES = + EncryptionConstants.EncryptionSpecNS + "kw-tripledes"; + + /** Symmetric Key Wrap - REQUIRED AES-128 KeyWrap */ + public static final String ALGO_ID_KEYWRAP_AES128 = + EncryptionConstants.EncryptionSpecNS + "kw-aes128"; + + /** Symmetric Key Wrap - REQUIRED AES-256 KeyWrap */ + public static final String ALGO_ID_KEYWRAP_AES256 = + EncryptionConstants.EncryptionSpecNS + "kw-aes256"; + + /** Symmetric Key Wrap - OPTIONAL AES-192 KeyWrap */ + public static final String ALGO_ID_KEYWRAP_AES192 = + EncryptionConstants.EncryptionSpecNS + "kw-aes192"; + + /** Message Authentication - RECOMMENDED XML Digital Signature */ + public static final String ALGO_ID_AUTHENTICATION_XMLSIGNATURE = + "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/"; + + /** Canonicalization - OPTIONAL Canonical XML with Comments */ + public static final String ALGO_ID_C14N_WITHCOMMENTS = + "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; + + /** Canonicalization - OPTIONAL Canonical XML (omits comments) */ + public static final String ALGO_ID_C14N_OMITCOMMENTS = + "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; + + /** Encoding - REQUIRED base64 */ + public static final String ALGO_ID_ENCODING_BASE64 = + "http://www.w3.org/2000/09/xmldsig#base64"; + + /** MGF1 with SHA-1 */ + public static final String MGF1_SHA1 = + EncryptionConstants.EncryptionSpec11NS + "mgf1sha1"; + + /** MGF1 with SHA-224 */ + public static final String MGF1_SHA224 = + EncryptionConstants.EncryptionSpec11NS + "mgf1sha224"; + + /** MGF1 with SHA-256 */ + public static final String MGF1_SHA256 = + EncryptionConstants.EncryptionSpec11NS + "mgf1sha256"; + + /** MGF1 with SHA-384 */ + public static final String MGF1_SHA384 = + EncryptionConstants.EncryptionSpec11NS + "mgf1sha384"; + + /** MGF1 with SHA-512 */ + public static final String MGF1_SHA512 = + EncryptionConstants.EncryptionSpec11NS + "mgf1sha512"; + + + private EncryptionConstants() { + // we don't allow instantiation + } - /** - * Method getEncryptionSpecNSprefix - * - * @return the prefix for this node. - */ - public static String getEncryptionSpecNSprefix() { - return ElementProxy - .getDefaultPrefix(EncryptionConstants.EncryptionSpecNS); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java index d6fd93d1aa7..53a5cc88c5e 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java @@ -2,62 +2,62 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils; - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * This is the base object for all objects which map directly to an Element from * the xenc spec. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public abstract class EncryptionElementProxy extends ElementProxy { - /** - * Constructor EncryptionElementProxy - * - * @param doc - */ - public EncryptionElementProxy(Document doc) { - super(doc); - } + /** + * Constructor EncryptionElementProxy + * + * @param doc + */ + public EncryptionElementProxy(Document doc) { + super(doc); + } - /** - * Constructor EncryptionElementProxy - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public EncryptionElementProxy(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor EncryptionElementProxy + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public EncryptionElementProxy(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } - /** @inheritDoc */ - public final String getBaseNamespace() { - return EncryptionConstants.EncryptionSpecNS; - } + /** @inheritDoc */ + public final String getBaseNamespace() { + return EncryptionConstants.EncryptionSpecNS; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java index cd40b79d47a..8ba53a6153c 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils; @@ -28,75 +30,69 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** - * * @author Christian Geuer-Pollmann - * */ public class HelperNodeList implements NodeList { - /** Field nodes */ - List nodes = new ArrayList(20); - boolean _allNodesMustHaveSameParent = false; + /** Field nodes */ + List nodes = new ArrayList(); + boolean allNodesMustHaveSameParent = false; - /** - * - */ - public HelperNodeList() { - this(false); - } + /** + * + */ + public HelperNodeList() { + this(false); + } - /** - * @param allNodesMustHaveSameParent - */ - public HelperNodeList(boolean allNodesMustHaveSameParent) { - this._allNodesMustHaveSameParent = allNodesMustHaveSameParent; - } + /** + * @param allNodesMustHaveSameParent + */ + public HelperNodeList(boolean allNodesMustHaveSameParent) { + this.allNodesMustHaveSameParent = allNodesMustHaveSameParent; + } - /** - * Method item - * - * @param index - * @return node with inde i - */ - public Node item(int index) { + /** + * Method item + * + * @param index + * @return node with index i + */ + public Node item(int index) { + return nodes.get(index); + } - // log.log(java.util.logging.Level.FINE, "item(" + index + ") of " + this.getLength() + " nodes"); + /** + * Method getLength + * + * @return length of the list + */ + public int getLength() { + return nodes.size(); + } - return nodes.get(index); - } - - /** - * Method getLength - * - * @return length of the list - */ - public int getLength() { - return nodes.size(); - } - - /** - * Method appendChild - * - * @param node - * @throws IllegalArgumentException - */ - public void appendChild(Node node) throws IllegalArgumentException { - if (this._allNodesMustHaveSameParent && this.getLength() > 0) { - if (this.item(0).getParentNode() != node.getParentNode()) { + /** + * Method appendChild + * + * @param node + * @throws IllegalArgumentException + */ + public void appendChild(Node node) throws IllegalArgumentException { + if (this.allNodesMustHaveSameParent && this.getLength() > 0 + && this.item(0).getParentNode() != node.getParentNode()) { throw new IllegalArgumentException("Nodes have not the same Parent"); - } - } - nodes.add(node); - } + } + nodes.add(node); + } - /** - * @return the document that contains this nodelist - */ - public Document getOwnerDocument() { - if (this.getLength() == 0) { - return null; - } - return XMLUtils.getOwnerDocument(this.item(0)); - } + /** + * @return the document that contains this nodelist + */ + public Document getOwnerDocument() { + if (this.getLength() == 0) { + return null; + } + return XMLUtils.getOwnerDocument(this.item(0)); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java index 4ee51ac92ab..ea9ec28d6e8 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java @@ -2,85 +2,42 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils; -import java.lang.ref.WeakReference; -import java.util.Arrays; -import java.util.WeakHashMap; -import java.util.Map; - import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; /** * Purpose of this class is to enable the XML Parser to keep track of ID * attributes. This is done by 'registering' attributes of type ID at the - * IdResolver. This is necessary if we create a document from scratch and we - * sign some resources with a URI using a fragent identifier... - *
    - * The problem is that if you do not validate a document, you cannot use the - * getElementByID functionality. So this modules uses some implicit - * knowledge on selected Schemas and DTDs to pick the right Element for a given - * ID: We know that all @Id attributes in an Element from the XML - * Signature namespace are of type ID. - * - * @author $Author: mullan $ - * @see "Identity Crisis" on xml.com + * IdResolver. + * @deprecated */ +@Deprecated public class IdResolver { - /** {@link java.util.logging} logging facility */ - private static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(IdResolver.class.getName()); - - private static Map>> docMap = - new WeakHashMap>>(); - - /** - * Constructor IdResolver - * - */ private IdResolver() { - // we don't allow instantiation - } - - /** - * Method registerElementById - * - * @param element the element to register - * @param idValue the value of the ID attribute - */ - public static void registerElementById(Element element, String idValue) { - Document doc = element.getOwnerDocument(); - Map> elementMap; - synchronized (docMap) { - elementMap = docMap.get(doc); - if (elementMap == null) { - elementMap = new WeakHashMap>(); - docMap.put(doc, elementMap); - } - } - elementMap.put(idValue, new WeakReference(element)); + // we don't allow instantiation } /** @@ -90,7 +47,7 @@ public class IdResolver { * @param id the ID attribute */ public static void registerElementById(Element element, Attr id) { - IdResolver.registerElementById(element, id.getNodeValue()); + element.setIdAttributeNode(id, true); } /** @@ -101,194 +58,7 @@ public class IdResolver { * @return the element obtained by the id, or null if it is not found. */ public static Element getElementById(Document doc, String id) { - - Element result = IdResolver.getElementByIdType(doc, id); - - if (result != null) { - log.log(java.util.logging.Level.FINE, - "I could find an Element using the simple getElementByIdType method: " - + result.getTagName()); - - return result; - } - - result = IdResolver.getElementByIdUsingDOM(doc, id); - - if (result != null) { - log.log(java.util.logging.Level.FINE, - "I could find an Element using the simple getElementByIdUsingDOM method: " - + result.getTagName()); - - return result; - } - // this must be done so that Xalan can catch ALL namespaces - //XMLUtils.circumventBug2650(doc); - result = IdResolver.getElementBySearching(doc, id); - - if (result != null) { - IdResolver.registerElementById(result, id); - - return result; - } - - return null; - } - - - /** - * Method getElementByIdUsingDOM - * - * @param doc the document - * @param id the value of the ID - * @return the element obtained by the id, or null if it is not found. - */ - private static Element getElementByIdUsingDOM(Document doc, String id) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "getElementByIdUsingDOM() Search for ID " + id); return doc.getElementById(id); } - /** - * Method getElementByIdType - * - * @param doc the document - * @param id the value of the ID - * @return the element obtained by the id, or null if it is not found. - */ - private static Element getElementByIdType(Document doc, String id) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "getElementByIdType() Search for ID " + id); - Map> elementMap; - synchronized (docMap) { - elementMap = docMap.get(doc); - } - if (elementMap != null) { - WeakReference weakReference = elementMap.get(id); - if (weakReference != null) { - return weakReference.get(); - } - } - return null; - } - - private static java.util.List names; - private static int namesLength; - static { - String namespaces[]={ - Constants.SignatureSpecNS, - EncryptionConstants.EncryptionSpecNS, - "http://schemas.xmlsoap.org/soap/security/2000-12", - "http://www.w3.org/2002/03/xkms#", - "urn:oasis:names:tc:SAML:1.0:assertion", - "urn:oasis:names:tc:SAML:1.0:protocol" - }; - names = Arrays.asList(namespaces); - namesLength = names.size(); - } - - - private static Element getElementBySearching(Node root,String id) { - Element []els=new Element[namesLength + 1]; - getEl(root,id,els); - for (int i=0;i2) - continue; - String value=n.getNodeValue(); - if (name.charAt(0)=='I') { - char ch=name.charAt(1); - if (ch=='d' && value.equals(id)) { - els[index]=el; - if (index==0) { - return 1; - } - } else if (ch=='D' &&value.endsWith(id)) { - if (index!=3) { - index=namesLength; - } - els[index]=el; - } - } else if ( "id".equals(name) && value.equals(id) ) { - if (index!=2) { - index=namesLength; - } - els[index]=el; - } - } - //For an element namespace search for importants - if ((elementIndex==3)&&( - el.getAttribute("OriginalRequestID").equals(id) || - el.getAttribute("RequestID").equals(id) || - el.getAttribute("ResponseID").equals(id))) { - els[3]=el; - } else if ((elementIndex==4)&&( - el.getAttribute("AssertionID").equals(id))) { - els[4]=el; - } else if ((elementIndex==5)&&( - el.getAttribute("RequestID").equals(id) || - el.getAttribute("ResponseID").equals(id))) { - els[5]=el; - } - return 0; - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java index 6eae527a570..d06a41ffd20 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java @@ -2,82 +2,80 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils; - import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; - /** - * This {@link org.xml.sax.ErrorHandler} does absulutely nothing but logging + * This {@link org.xml.sax.ErrorHandler} does absolutely nothing but log * the events. * * @author Christian Geuer-Pollmann */ public class IgnoreAllErrorHandler implements ErrorHandler { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - IgnoreAllErrorHandler.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(IgnoreAllErrorHandler.class.getName()); - /** Field throwExceptions */ - static final boolean warnOnExceptions = System.getProperty( - "com.sun.org.apache.xml.internal.security.test.warn.on.exceptions", "false").equals("true"); + /** Field throwExceptions */ + private static final boolean warnOnExceptions = + System.getProperty("com.sun.org.apache.xml.internal.security.test.warn.on.exceptions", "false").equals("true"); - /** Field throwExceptions */ - static final boolean throwExceptions = System.getProperty( - "com.sun.org.apache.xml.internal.security.test.throw.exceptions", "false").equals("true"); + /** Field throwExceptions */ + private static final boolean throwExceptions = + System.getProperty("com.sun.org.apache.xml.internal.security.test.throw.exceptions", "false").equals("true"); - /** @inheritDoc */ - public void warning(SAXParseException ex) throws SAXException { - if (IgnoreAllErrorHandler.warnOnExceptions) { - log.log(java.util.logging.Level.WARNING, "", ex); - } - if (IgnoreAllErrorHandler.throwExceptions) { - throw ex; - } + /** @inheritDoc */ + public void warning(SAXParseException ex) throws SAXException { + if (IgnoreAllErrorHandler.warnOnExceptions) { + log.log(java.util.logging.Level.WARNING, "", ex); } - - - /** @inheritDoc */ - public void error(SAXParseException ex) throws SAXException { - if (IgnoreAllErrorHandler.warnOnExceptions) { - log.log(java.util.logging.Level.SEVERE, "", ex); - } - if (IgnoreAllErrorHandler.throwExceptions) { - throw ex; - } + if (IgnoreAllErrorHandler.throwExceptions) { + throw ex; } + } - - /** @inheritDoc */ - public void fatalError(SAXParseException ex) throws SAXException { - if (IgnoreAllErrorHandler.warnOnExceptions) { - log.log(java.util.logging.Level.WARNING, "", ex); - } - if (IgnoreAllErrorHandler.throwExceptions) { - throw ex; - } + /** @inheritDoc */ + public void error(SAXParseException ex) throws SAXException { + if (IgnoreAllErrorHandler.warnOnExceptions) { + log.log(java.util.logging.Level.SEVERE, "", ex); } + if (IgnoreAllErrorHandler.throwExceptions) { + throw ex; + } + } + + + /** @inheritDoc */ + public void fatalError(SAXParseException ex) throws SAXException { + if (IgnoreAllErrorHandler.warnOnExceptions) { + log.log(java.util.logging.Level.WARNING, "", ex); + } + if (IgnoreAllErrorHandler.throwExceptions) { + throw ex; + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathAPI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathAPI.java new file mode 100644 index 00000000000..242e80ff6e9 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathAPI.java @@ -0,0 +1,132 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 com.sun.org.apache.xml.internal.security.utils; + +import javax.xml.XMLConstants; +import javax.xml.transform.TransformerException; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpression; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; +import javax.xml.xpath.XPathFactoryConfigurationException; + +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * An implementation for XPath evaluation that uses the JDK API. + */ +public class JDKXPathAPI implements XPathAPI { + + private XPathFactory xpf; + + private String xpathStr; + + private XPathExpression xpathExpression; + + /** + * Use an XPath string to select a nodelist. + * XPath namespace prefixes are resolved from the namespaceNode. + * + * @param contextNode The node to start searching from. + * @param xpathnode + * @param str + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + * @return A NodeIterator, should never be null. + * + * @throws TransformerException + */ + public NodeList selectNodeList( + Node contextNode, Node xpathnode, String str, Node namespaceNode + ) throws TransformerException { + if (!str.equals(xpathStr) || xpathExpression == null) { + if (xpf == null) { + xpf = XPathFactory.newInstance(); + try { + xpf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + } catch (XPathFactoryConfigurationException ex) { + throw new TransformerException("empty", ex); + } + } + XPath xpath = xpf.newXPath(); + xpath.setNamespaceContext(new DOMNamespaceContext(namespaceNode)); + xpathStr = str; + try { + xpathExpression = xpath.compile(xpathStr); + } catch (XPathExpressionException ex) { + throw new TransformerException("empty", ex); + } + } + try { + return (NodeList)xpathExpression.evaluate(contextNode, XPathConstants.NODESET); + } catch (XPathExpressionException ex) { + throw new TransformerException("empty", ex); + } + } + + /** + * Evaluate an XPath string and return true if the output is to be included or not. + * @param contextNode The node to start searching from. + * @param xpathnode The XPath node + * @param str The XPath expression + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + */ + public boolean evaluate(Node contextNode, Node xpathnode, String str, Node namespaceNode) + throws TransformerException { + if (!str.equals(xpathStr) || xpathExpression == null) { + if (xpf == null) { + xpf = XPathFactory.newInstance(); + try { + xpf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + } catch (XPathFactoryConfigurationException ex) { + throw new TransformerException("empty", ex); + } + } + XPath xpath = xpf.newXPath(); + xpath.setNamespaceContext(new DOMNamespaceContext(namespaceNode)); + xpathStr = str; + try { + xpathExpression = xpath.compile(xpathStr); + } catch (XPathExpressionException ex) { + throw new TransformerException("empty", ex); + } + } + try { + Boolean result = (Boolean)xpathExpression.evaluate(contextNode, XPathConstants.BOOLEAN); + return result.booleanValue(); + } catch (XPathExpressionException ex) { + throw new TransformerException("empty", ex); + } + } + + /** + * Clear any context information from this object + */ + public void clear() { + xpathStr = null; + xpathExpression = null; + xpf = null; + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathFactory.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathFactory.java new file mode 100644 index 00000000000..98c1872898a --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathFactory.java @@ -0,0 +1,37 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 com.sun.org.apache.xml.internal.security.utils; + + +/** + * A Factory to return a JDKXPathAPI instance. + */ +public class JDKXPathFactory extends XPathFactory { + + /** + * Get a new XPathAPI instance + */ + public XPathAPI newXPathAPI() { + return new JDKXPathAPI(); + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java index 540c722f45c..cf55f4088ba 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils; @@ -33,8 +35,8 @@ import java.io.InputStream; */ public class JavaUtils { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(JavaUtils.class.getName()); private JavaUtils() { @@ -45,7 +47,7 @@ public class JavaUtils { * Method getBytesFromFile * * @param fileName - * @return the bytes readed from the file + * @return the bytes read from the file * * @throws FileNotFoundException * @throws IOException @@ -55,9 +57,11 @@ public class JavaUtils { byte refBytes[] = null; - FileInputStream fisRef = new FileInputStream(fileName); + FileInputStream fisRef = null; + UnsyncByteArrayOutputStream baos = null; try { - UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream(); + fisRef = new FileInputStream(fileName); + baos = new UnsyncByteArrayOutputStream(); byte buf[] = new byte[1024]; int len; @@ -67,7 +71,12 @@ public class JavaUtils { refBytes = baos.toByteArray(); } finally { - fisRef.close(); + if (baos != null) { + baos.close(); + } + if (fisRef != null) { + fisRef.close(); + } } return refBytes; @@ -80,7 +89,6 @@ public class JavaUtils { * @param bytes */ public static void writeBytesToFilename(String filename, byte[] bytes) { - FileOutputStream fos = null; try { if (filename != null && bytes != null) { @@ -91,13 +99,19 @@ public class JavaUtils { fos.write(bytes); fos.close(); } else { - log.log(java.util.logging.Level.FINE, "writeBytesToFilename got null byte[] pointed"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "writeBytesToFilename got null byte[] pointed"); + } } } catch (IOException ex) { if (fos != null) { try { fos.close(); - } catch (IOException ioe) {} + } catch (IOException ioe) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ioe.getMessage(), ioe); + } + } } } } @@ -107,25 +121,28 @@ public class JavaUtils { * returns them as a byte array. * * @param inputStream - * @return the bytes readed from the stream + * @return the bytes read from the stream * * @throws FileNotFoundException * @throws IOException */ - public static byte[] getBytesFromStream(InputStream inputStream) - throws IOException { + public static byte[] getBytesFromStream(InputStream inputStream) throws IOException { + UnsyncByteArrayOutputStream baos = null; - byte refBytes[] = null; + byte[] retBytes = null; + try { + baos = new UnsyncByteArrayOutputStream(); + byte buf[] = new byte[4 * 1024]; + int len; - UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream(); - byte buf[] = new byte[1024]; - int len; - - while ((len = inputStream.read(buf)) > 0) { - baos.write(buf, 0, len); + while ((len = inputStream.read(buf)) > 0) { + baos.write(buf, 0, len); + } + retBytes = baos.toByteArray(); + } finally { + baos.close(); } - refBytes = baos.toByteArray(); - return refBytes; + return retBytes; } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java index 66a587511e8..1ab91701b6a 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java @@ -2,573 +2,473 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils; - - import java.io.IOException; import java.io.StringReader; - -/** - * - * @author $Author: mullan $ - */ public class RFC2253Parser { + /** + * Method rfc2253toXMLdsig + * + * @param dn + * @return normalized string + */ + public static String rfc2253toXMLdsig(String dn) { + // Transform from RFC1779 to RFC2253 + String normalized = normalize(dn, true); - /** {@link java.util.logging} logging facility */ - /* static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(RFC2253Parser.class.getName()); - */ + return rfctoXML(normalized); + } - static boolean _TOXML = true; + /** + * Method xmldsigtoRFC2253 + * + * @param dn + * @return normalized string + */ + public static String xmldsigtoRFC2253(String dn) { + // Transform from RFC1779 to RFC2253 + String normalized = normalize(dn, false); - /** - * Method rfc2253toXMLdsig - * - * @param dn - * @return normalized string - * - */ - public static String rfc2253toXMLdsig(String dn) { + return xmltoRFC(normalized); + } - _TOXML = true; + /** + * Method normalize + * + * @param dn + * @return normalized string + */ + public static String normalize(String dn) { + return normalize(dn, true); + } - // Transform from RFC1779 to RFC2253 - String normalized = normalize(dn); + /** + * Method normalize + * + * @param dn + * @param toXml + * @return normalized string + */ + public static String normalize(String dn, boolean toXml) { + //if empty string + if ((dn == null) || dn.equals("")) { + return ""; + } - return rfctoXML(normalized); - } + try { + String DN = semicolonToComma(dn); + StringBuilder sb = new StringBuilder(); + int i = 0; + int l = 0; + int k; - /** - * Method xmldsigtoRFC2253 - * - * @param dn - * @return normalized string - */ - public static String xmldsigtoRFC2253(String dn) { + //for name component + for (int j = 0; (k = DN.indexOf(',', j)) >= 0; j = k + 1) { + l += countQuotes(DN, j, k); - _TOXML = false; + if ((k > 0) && (DN.charAt(k - 1) != '\\') && (l % 2) == 0) { + sb.append(parseRDN(DN.substring(i, k).trim(), toXml) + ","); - // Transform from RFC1779 to RFC2253 - String normalized = normalize(dn); - - return xmltoRFC(normalized); - } - - /** - * Method normalize - * - * @param dn - * @return normalized string - */ - public static String normalize(String dn) { - - //if empty string - if ((dn == null) || dn.equals("")) { - return ""; - } - - try { - String _DN = semicolonToComma(dn); - StringBuffer sb = new StringBuffer(); - int i = 0; - int l = 0; - int k; - - //for name component - for (int j = 0; (k = _DN.indexOf(",", j)) >= 0; j = k + 1) { - l += countQuotes(_DN, j, k); - - if ((k > 0) && (_DN.charAt(k - 1) != '\\') && (l % 2) != 1) { - sb.append(parseRDN(_DN.substring(i, k).trim()) + ","); - - i = k + 1; - l = 0; + i = k + 1; + l = 0; + } } - } - sb.append(parseRDN(trim(_DN.substring(i)))); + sb.append(parseRDN(trim(DN.substring(i)), toXml)); - return sb.toString(); - } catch (IOException ex) { - return dn; - } - } + return sb.toString(); + } catch (IOException ex) { + return dn; + } + } - /** - * Method parseRDN - * - * @param str - * @return normalized string - * @throws IOException - */ - static String parseRDN(String str) throws IOException { + /** + * Method parseRDN + * + * @param str + * @param toXml + * @return normalized string + * @throws IOException + */ + static String parseRDN(String str, boolean toXml) throws IOException { + StringBuilder sb = new StringBuilder(); + int i = 0; + int l = 0; + int k; - StringBuffer sb = new StringBuffer(); - int i = 0; - int l = 0; - int k; + for (int j = 0; (k = str.indexOf('+', j)) >= 0; j = k + 1) { + l += countQuotes(str, j, k); - for (int j = 0; (k = str.indexOf("+", j)) >= 0; j = k + 1) { - l += countQuotes(str, j, k); + if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) == 0) { + sb.append(parseATAV(trim(str.substring(i, k)), toXml) + "+"); - if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) != 1) { - sb.append(parseATAV(trim(str.substring(i, k))) + "+"); + i = k + 1; + l = 0; + } + } - i = k + 1; - l = 0; - } - } + sb.append(parseATAV(trim(str.substring(i)), toXml)); - sb.append(parseATAV(trim(str.substring(i)))); + return sb.toString(); + } - return sb.toString(); - } + /** + * Method parseATAV + * + * @param str + * @param toXml + * @return normalized string + * @throws IOException + */ + static String parseATAV(String str, boolean toXml) throws IOException { + int i = str.indexOf('='); - /** - * Method parseATAV - * - * @param str - * @return normalized string - * @throws IOException - */ - static String parseATAV(String str) throws IOException { + if ((i == -1) || ((i > 0) && (str.charAt(i - 1) == '\\'))) { + return str; + } + String attrType = normalizeAT(str.substring(0, i)); + // only normalize if value is a String + String attrValue = null; + if (attrType.charAt(0) >= '0' && attrType.charAt(0) <= '9') { + attrValue = str.substring(i + 1); + } else { + attrValue = normalizeV(str.substring(i + 1), toXml); + } - int i = str.indexOf("="); + return attrType + "=" + attrValue; - if ((i == -1) || ((i > 0) && (str.charAt(i - 1) == '\\'))) { - return str; - } - String attrType = normalizeAT(str.substring(0, i)); - // only normalize if value is a String - String attrValue = null; - if (attrType.charAt(0) >= '0' && attrType.charAt(0) <= '9') { - attrValue = str.substring(i + 1); - } else { - attrValue = normalizeV(str.substring(i + 1)); - } + } - return attrType + "=" + attrValue; + /** + * Method normalizeAT + * + * @param str + * @return normalized string + */ + static String normalizeAT(String str) { - } + String at = str.toUpperCase().trim(); - /** - * Method normalizeAT - * - * @param str - * @return normalized string - */ - static String normalizeAT(String str) { + if (at.startsWith("OID")) { + at = at.substring(3); + } - String at = str.toUpperCase().trim(); + return at; + } - if (at.startsWith("OID")) { - at = at.substring(3); - } + /** + * Method normalizeV + * + * @param str + * @param toXml + * @return normalized string + * @throws IOException + */ + static String normalizeV(String str, boolean toXml) throws IOException { + String value = trim(str); - return at; - } + if (value.startsWith("\"")) { + StringBuilder sb = new StringBuilder(); + StringReader sr = new StringReader(value.substring(1, value.length() - 1)); + int i = 0; + char c; - /** - * Method normalizeV - * - * @param str - * @return normalized string - * @throws IOException - */ - static String normalizeV(String str) throws IOException { + while ((i = sr.read()) > -1) { + c = (char) i; - String value = trim(str); + //the following char is defined at 4.Relationship with RFC1779 and LDAPv2 inrfc2253 + if ((c == ',') || (c == '=') || (c == '+') || (c == '<') + || (c == '>') || (c == '#') || (c == ';')) { + sb.append('\\'); + } - if (value.startsWith("\"")) { - StringBuffer sb = new StringBuffer(); - StringReader sr = new StringReader(value.substring(1, - value.length() - 1)); - int i = 0; - char c; + sb.append(c); + } - for (; (i = sr.read()) > -1; ) { + value = trim(sb.toString()); + } + + if (toXml) { + if (value.startsWith("#")) { + value = '\\' + value; + } + } else { + if (value.startsWith("\\#")) { + value = value.substring(1); + } + } + + return value; + } + + /** + * Method rfctoXML + * + * @param string + * @return normalized string + */ + static String rfctoXML(String string) { + try { + String s = changeLess32toXML(string); + + return changeWStoXML(s); + } catch (Exception e) { + return string; + } + } + + /** + * Method xmltoRFC + * + * @param string + * @return normalized string + */ + static String xmltoRFC(String string) { + try { + String s = changeLess32toRFC(string); + + return changeWStoRFC(s); + } catch (Exception e) { + return string; + } + } + + /** + * Method changeLess32toRFC + * + * @param string + * @return normalized string + * @throws IOException + */ + static String changeLess32toRFC(String string) throws IOException { + StringBuilder sb = new StringBuilder(); + StringReader sr = new StringReader(string); + int i = 0; + char c; + + while ((i = sr.read()) > -1) { c = (char) i; - //the following char is defined at 4.Relationship with RFC1779 and LDAPv2 inrfc2253 - if ((c == ',') || (c == '=') || (c == '+') || (c == '<') - || (c == '>') || (c == '#') || (c == ';')) { - sb.append('\\'); - } + if (c == '\\') { + sb.append(c); - sb.append(c); - } + char c1 = (char) sr.read(); + char c2 = (char) sr.read(); - value = trim(sb.toString()); - } - - if (_TOXML == true) { - if (value.startsWith("#")) { - value = '\\' + value; - } - } else { - if (value.startsWith("\\#")) { - value = value.substring(1); - } - } - - return value; - } - - /** - * Method rfctoXML - * - * @param string - * @return normalized string - */ - static String rfctoXML(String string) { - - try { - String s = changeLess32toXML(string); - - return changeWStoXML(s); - } catch (Exception e) { - return string; - } - } - - /** - * Method xmltoRFC - * - * @param string - * @return normalized string - */ - static String xmltoRFC(String string) { - - try { - String s = changeLess32toRFC(string); - - return changeWStoRFC(s); - } catch (Exception e) { - return string; - } - } - - /** - * Method changeLess32toRFC - * - * @param string - * @return normalized string - * @throws IOException - */ - static String changeLess32toRFC(String string) throws IOException { - - StringBuffer sb = new StringBuffer(); - StringReader sr = new StringReader(string); - int i = 0; - char c; - - for (; (i = sr.read()) > -1; ) { - c = (char) i; - - if (c == '\\') { - sb.append(c); - - char c1 = (char) sr.read(); - char c2 = (char) sr.read(); - - //65 (A) 97 (a) - if ((((c1 >= 48) && (c1 <= 57)) || ((c1 >= 65) && (c1 <= 70)) || ((c1 >= 97) && (c1 <= 102))) + //65 (A) 97 (a) + if ((((c1 >= 48) && (c1 <= 57)) || ((c1 >= 65) && (c1 <= 70)) || ((c1 >= 97) && (c1 <= 102))) && (((c2 >= 48) && (c2 <= 57)) || ((c2 >= 65) && (c2 <= 70)) || ((c2 >= 97) && (c2 <= 102)))) { - char ch = (char) Byte.parseByte("" + c1 + c2, 16); + char ch = (char) Byte.parseByte("" + c1 + c2, 16); - sb.append(ch); + sb.append(ch); + } else { + sb.append(c1); + sb.append(c2); + } } else { - sb.append(c1); - sb.append(c2); + sb.append(c); } - } else { - sb.append(c); - } - } + } - return sb.toString(); - } + return sb.toString(); + } - /** - * Method changeLess32toXML - * - * @param string - * @return normalized string - * @throws IOException - */ - static String changeLess32toXML(String string) throws IOException { + /** + * Method changeLess32toXML + * + * @param string + * @return normalized string + * @throws IOException + */ + static String changeLess32toXML(String string) throws IOException { + StringBuilder sb = new StringBuilder(); + StringReader sr = new StringReader(string); + int i = 0; - StringBuffer sb = new StringBuffer(); - StringReader sr = new StringReader(string); - int i = 0; - - for (; (i = sr.read()) > -1; ) { - if (i < 32) { - sb.append('\\'); - sb.append(Integer.toHexString(i)); - } else { - sb.append((char) i); - } - } - - return sb.toString(); - } - - /** - * Method changeWStoXML - * - * @param string - * @return normalized string - * @throws IOException - */ - static String changeWStoXML(String string) throws IOException { - - StringBuffer sb = new StringBuffer(); - StringReader sr = new StringReader(string); - int i = 0; - char c; - - for (; (i = sr.read()) > -1; ) { - c = (char) i; - - if (c == '\\') { - char c1 = (char) sr.read(); - - if (c1 == ' ') { - sb.append('\\'); - - String s = "20"; - - sb.append(s); + while ((i = sr.read()) > -1) { + if (i < 32) { + sb.append('\\'); + sb.append(Integer.toHexString(i)); } else { - sb.append('\\'); - sb.append(c1); + sb.append((char) i); } - } else { - sb.append(c); - } - } + } - return sb.toString(); - } + return sb.toString(); + } - /** - * Method changeWStoRFC - * - * @param string - * @return normalized string - */ - static String changeWStoRFC(String string) { + /** + * Method changeWStoXML + * + * @param string + * @return normalized string + * @throws IOException + */ + static String changeWStoXML(String string) throws IOException { + StringBuilder sb = new StringBuilder(); + StringReader sr = new StringReader(string); + int i = 0; + char c; - StringBuffer sb = new StringBuffer(); - int i = 0; - int k; + while ((i = sr.read()) > -1) { + c = (char) i; - for (int j = 0; (k = string.indexOf("\\20", j)) >= 0; j = k + 3) { - sb.append(trim(string.substring(i, k)) + "\\ "); + if (c == '\\') { + char c1 = (char) sr.read(); - i = k + 3; - } + if (c1 == ' ') { + sb.append('\\'); - sb.append(string.substring(i)); + String s = "20"; - return sb.toString(); - } + sb.append(s); + } else { + sb.append('\\'); + sb.append(c1); + } + } else { + sb.append(c); + } + } - /** - * Method semicolonToComma - * - * @param str - * @return normalized string - */ - static String semicolonToComma(String str) { - return removeWSandReplace(str, ";", ","); - } + return sb.toString(); + } - /** - * Method removeWhiteSpace - * - * @param str - * @param symbol - * @return normalized string - */ - static String removeWhiteSpace(String str, String symbol) { - return removeWSandReplace(str, symbol, symbol); - } + /** + * Method changeWStoRFC + * + * @param string + * @return normalized string + */ + static String changeWStoRFC(String string) { + StringBuilder sb = new StringBuilder(); + int i = 0; + int k; - /** - * Method removeWSandReplace - * - * @param str - * @param symbol - * @param replace - * @return normalized string - */ - static String removeWSandReplace(String str, String symbol, String replace) { + for (int j = 0; (k = string.indexOf("\\20", j)) >= 0; j = k + 3) { + sb.append(trim(string.substring(i, k)) + "\\ "); - StringBuffer sb = new StringBuffer(); - int i = 0; - int l = 0; - int k; + i = k + 3; + } - for (int j = 0; (k = str.indexOf(symbol, j)) >= 0; j = k + 1) { - l += countQuotes(str, j, k); + sb.append(string.substring(i)); - if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) != 1) { - sb.append(trim(str.substring(i, k)) + replace); + return sb.toString(); + } - i = k + 1; - l = 0; - } - } + /** + * Method semicolonToComma + * + * @param str + * @return normalized string + */ + static String semicolonToComma(String str) { + return removeWSandReplace(str, ";", ","); + } - sb.append(trim(str.substring(i))); + /** + * Method removeWhiteSpace + * + * @param str + * @param symbol + * @return normalized string + */ + static String removeWhiteSpace(String str, String symbol) { + return removeWSandReplace(str, symbol, symbol); + } - return sb.toString(); - } + /** + * Method removeWSandReplace + * + * @param str + * @param symbol + * @param replace + * @return normalized string + */ + static String removeWSandReplace(String str, String symbol, String replace) { + StringBuilder sb = new StringBuilder(); + int i = 0; + int l = 0; + int k; - /** - * Returns the number of Quotation from i to j - * - * @param s - * @param i - * @param j - * @return number of quotes - */ - private static int countQuotes(String s, int i, int j) { + for (int j = 0; (k = str.indexOf(symbol, j)) >= 0; j = k + 1) { + l += countQuotes(str, j, k); - int k = 0; + if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) == 0) { + sb.append(trim(str.substring(i, k)) + replace); - for (int l = i; l < j; l++) { - if (s.charAt(l) == '"') { - k++; - } - } + i = k + 1; + l = 0; + } + } - return k; - } + sb.append(trim(str.substring(i))); - //only for the end of a space character occurring at the end of the string from rfc2253 + return sb.toString(); + } - /** - * Method trim - * - * @param str - * @return the string - */ - static String trim(String str) { + /** + * Returns the number of Quotation from i to j + * + * @param s + * @param i + * @param j + * @return number of quotes + */ + private static int countQuotes(String s, int i, int j) { + int k = 0; - String trimed = str.trim(); - int i = str.indexOf(trimed) + trimed.length(); + for (int l = i; l < j; l++) { + if (s.charAt(l) == '"') { + k++; + } + } - if ((str.length() > i) && trimed.endsWith("\\") - &&!trimed.endsWith("\\\\")) { - if (str.charAt(i) == ' ') { + return k; + } + + //only for the end of a space character occurring at the end of the string from rfc2253 + + /** + * Method trim + * + * @param str + * @return the string + */ + static String trim(String str) { + + String trimed = str.trim(); + int i = str.indexOf(trimed) + trimed.length(); + + if ((str.length() > i) && trimed.endsWith("\\") + && !trimed.endsWith("\\\\") && (str.charAt(i) == ' ')) { trimed = trimed + " "; - } - } + } - return trimed; - } + return trimed; + } - /** - * Method main - * - * @param args - * @throws Exception - */ - public static void main(String[] args) throws Exception { - - testToXML("CN=\"Steve, Kille\", O=Isode Limited, C=GB"); - testToXML("CN=Steve Kille , O=Isode Limited,C=GB"); - testToXML("\\ OU=Sales+CN=J. Smith,O=Widget Inc.,C=US\\ \\ "); - testToXML("CN=L. Eagle,O=Sue\\, Grabbit and Runn,C=GB"); - testToXML("CN=Before\\0DAfter,O=Test,C=GB"); - testToXML("CN=\"L. Eagle,O=Sue, = + < > # ;Grabbit and Runn\",C=GB"); - testToXML("1.3.6.1.4.1.1466.0=#04024869,O=Test,C=GB"); - - { - StringBuffer sb = new StringBuffer(); - - sb.append('L'); - sb.append('u'); - sb.append('\uc48d'); - sb.append('i'); - sb.append('\uc487'); - - String test7 = "SN=" + sb.toString(); - - testToXML(test7); - } - - testToRFC("CN=\"Steve, Kille\", O=Isode Limited, C=GB"); - testToRFC("CN=Steve Kille , O=Isode Limited,C=GB"); - testToRFC("\\20OU=Sales+CN=J. Smith,O=Widget Inc.,C=US\\20\\20 "); - testToRFC("CN=L. Eagle,O=Sue\\, Grabbit and Runn,C=GB"); - testToRFC("CN=Before\\12After,O=Test,C=GB"); - testToRFC("CN=\"L. Eagle,O=Sue, = + < > # ;Grabbit and Runn\",C=GB"); - testToRFC("1.3.6.1.4.1.1466.0=\\#04024869,O=Test,C=GB"); - - { - StringBuffer sb = new StringBuffer(); - - sb.append('L'); - sb.append('u'); - sb.append('\uc48d'); - sb.append('i'); - sb.append('\uc487'); - - String test7 = "SN=" + sb.toString(); - - testToRFC(test7); - } - } - - /** Field i */ - static int counter = 0; - - /** - * Method test - * - * @param st - */ - static void testToXML(String st) { - - System.out.println("start " + counter++ + ": " + st); - System.out.println(" " + rfc2253toXMLdsig(st)); - System.out.println(""); - } - - /** - * Method testToRFC - * - * @param st - */ - static void testToRFC(String st) { - - System.out.println("start " + counter++ + ": " + st); - System.out.println(" " + xmldsigtoRFC2253(st)); - System.out.println(""); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Signature11ElementProxy.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Signature11ElementProxy.java new file mode 100644 index 00000000000..dffcd89f47b --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Signature11ElementProxy.java @@ -0,0 +1,70 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 com.sun.org.apache.xml.internal.security.utils; + +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * Class SignatureElementProxy + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public abstract class Signature11ElementProxy extends ElementProxy { + + protected Signature11ElementProxy() { + }; + + /** + * Constructor Signature11ElementProxy + * + * @param doc + */ + public Signature11ElementProxy(Document doc) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } + + this.doc = doc; + this.constructionElement = + XMLUtils.createElementInSignature11Space(this.doc, this.getBaseLocalName()); + } + + /** + * Constructor Signature11ElementProxy + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public Signature11ElementProxy(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + + } + + /** @inheritDoc */ + public String getBaseNamespace() { + return Constants.SignatureSpec11NS; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java index d49cc676acf..3a97bd3d411 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java @@ -2,70 +2,69 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * Class SignatureElementProxy * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ + * @author $Author: coheigea $ */ public abstract class SignatureElementProxy extends ElementProxy { - protected SignatureElementProxy() { - }; - /** - * Constructor SignatureElementProxy - * - * @param doc - */ - public SignatureElementProxy(Document doc) { - if (doc == null) { - throw new RuntimeException("Document is null"); - } - this._doc = doc; - this._constructionElement = XMLUtils.createElementInSignatureSpace(this._doc, - this.getBaseLocalName()); - } + protected SignatureElementProxy() { + }; - /** - * Constructor SignatureElementProxy - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public SignatureElementProxy(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); + /** + * Constructor SignatureElementProxy + * + * @param doc + */ + public SignatureElementProxy(Document doc) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } - } + this.doc = doc; + this.constructionElement = + XMLUtils.createElementInSignatureSpace(this.doc, this.getBaseLocalName()); + } - /** @inheritDoc */ - public String getBaseNamespace() { - return Constants.SignatureSpecNS; - } + /** + * Constructor SignatureElementProxy + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public SignatureElementProxy(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + + } + + /** @inheritDoc */ + public String getBaseNamespace() { + return Constants.SignatureSpecNS; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java index 068d523bd64..c8f5747d396 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils; @@ -30,53 +32,50 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; * */ public class SignerOutputStream extends ByteArrayOutputStream { + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(SignerOutputStream.class.getName()); + final SignatureAlgorithm sa; - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger - (SignerOutputStream.class.getName()); /** * @param sa */ public SignerOutputStream(SignatureAlgorithm sa) { - this.sa=sa; + this.sa = sa; } /** @inheritDoc */ public void write(byte[] arg0) { - super.write(arg0, 0, arg0.length); try { sa.update(arg0); } catch (XMLSignatureException e) { - throw new RuntimeException(""+e); + throw new RuntimeException("" + e); } } /** @inheritDoc */ public void write(int arg0) { - super.write(arg0); try { sa.update((byte)arg0); } catch (XMLSignatureException e) { - throw new RuntimeException(""+e); + throw new RuntimeException("" + e); } } /** @inheritDoc */ public void write(byte[] arg0, int arg1, int arg2) { - super.write(arg0, arg1, arg2); if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Canonicalized SignedInfo:"); - StringBuffer sb = new StringBuffer(arg2); - for (int i=arg1; i<(arg1+arg2); i++) { - sb.append((char) arg0[i]); + StringBuilder sb = new StringBuilder(arg2); + for (int i = arg1; i < (arg1 + arg2); i++) { + sb.append((char)arg0[i]); } log.log(java.util.logging.Level.FINE, sb.toString()); } try { - sa.update(arg0,arg1,arg2); + sa.update(arg0, arg1, arg2); } catch (XMLSignatureException e) { - throw new RuntimeException(""+e); + throw new RuntimeException("" + e); } } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java index e9a7935e7ea..f424dd51b74 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils; @@ -24,75 +26,73 @@ import java.io.IOException; import java.io.OutputStream; /** - * A class that buffers writte without synchronize its methods + * A class that buffers without synchronizing its methods * @author raul - * */ public class UnsyncBufferedOutputStream extends OutputStream { - final OutputStream out; + static final int size = 8*1024; - final byte[] buf; - static final int size=8*1024; - private static ThreadLocal bufCahce = new ThreadLocal() { - protected synchronized byte[] initialValue() { - return new byte[size]; + private int pointer = 0; + private final OutputStream out; + + private final byte[] buf; + + /** + * Creates a buffered output stream without synchronization + * @param out the outputstream to buffer + */ + public UnsyncBufferedOutputStream(OutputStream out) { + buf = new byte[size]; + this.out = out; + } + + /** @inheritDoc */ + public void write(byte[] arg0) throws IOException { + write(arg0, 0, arg0.length); + } + + /** @inheritDoc */ + public void write(byte[] arg0, int arg1, int len) throws IOException { + int newLen = pointer+len; + if (newLen > size) { + flushBuffer(); + if (len > size) { + out.write(arg0, arg1,len); + return; + } + newLen = len; } - }; - int pointer=0; - /** - * Creates a buffered output stream without synchronization - * @param out the outputstream to buffer - */ - public UnsyncBufferedOutputStream(OutputStream out) { - buf=bufCahce.get(); - this.out=out; + System.arraycopy(arg0, arg1, buf, pointer, len); + pointer = newLen; + } + + private void flushBuffer() throws IOException { + if (pointer > 0) { + out.write(buf, 0, pointer); } + pointer = 0; - /** @inheritDoc */ - public void write(byte[] arg0) throws IOException { - write(arg0,0,arg0.length); + } + + /** @inheritDoc */ + public void write(int arg0) throws IOException { + if (pointer >= size) { + flushBuffer(); } + buf[pointer++] = (byte)arg0; - /** @inheritDoc */ - public void write(byte[] arg0, int arg1, int len) throws IOException { - int newLen=pointer+len; - if (newLen> size) { - flushBuffer(); - if (len>size) { - out.write(arg0,arg1,len); - return; - } - newLen=len; - } - System.arraycopy(arg0,arg1,buf,pointer,len); - pointer=newLen; - } + } - private final void flushBuffer() throws IOException { - if (pointer>0) - out.write(buf,0,pointer); - pointer=0; + /** @inheritDoc */ + public void flush() throws IOException { + flushBuffer(); + out.flush(); + } - } - - /** @inheritDoc */ - public void write(int arg0) throws IOException { - if (pointer>= size) { - flushBuffer(); - } - buf[pointer++]=(byte)arg0; - - } - - /** @inheritDoc */ - public void flush() throws IOException { - flushBuffer(); - out.flush(); - } - - /** @inheritDoc */ - public void close() throws IOException { - flush(); - } + /** @inheritDoc */ + public void close() throws IOException { + flush(); + out.close(); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java index 2a2f7ddbd03..e6f3ea7c258 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2010 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils; @@ -28,22 +30,21 @@ import java.io.OutputStream; * */ public class UnsyncByteArrayOutputStream extends OutputStream { + private static final int INITIAL_SIZE = 8192; - private static ThreadLocal bufCache = new ThreadLocal() { - protected synchronized byte[] initialValue() { - return new byte[INITIAL_SIZE]; - } - }; private byte[] buf; private int size = INITIAL_SIZE; private int pos = 0; public UnsyncByteArrayOutputStream() { - buf = bufCache.get(); + buf = new byte[INITIAL_SIZE]; } public void write(byte[] arg0) { + if ((Integer.MAX_VALUE - pos) < arg0.length) { + throw new OutOfMemoryError(); + } int newPos = pos + arg0.length; if (newPos > size) { expandSize(newPos); @@ -53,6 +54,9 @@ public class UnsyncByteArrayOutputStream extends OutputStream { } public void write(byte[] arg0, int arg1, int arg2) { + if ((Integer.MAX_VALUE - pos) < arg2) { + throw new OutOfMemoryError(); + } int newPos = pos + arg2; if (newPos > size) { expandSize(newPos); @@ -62,6 +66,9 @@ public class UnsyncByteArrayOutputStream extends OutputStream { } public void write(int arg0) { + if ((Integer.MAX_VALUE - pos) == 0) { + throw new OutOfMemoryError(); + } int newPos = pos + 1; if (newPos > size) { expandSize(newPos); @@ -82,7 +89,11 @@ public class UnsyncByteArrayOutputStream extends OutputStream { private void expandSize(int newPos) { int newSize = size; while (newPos > newSize) { - newSize = newSize<<2; + newSize = newSize << 1; + // Deal with overflow + if (newSize < 0) { + newSize = Integer.MAX_VALUE; + } } byte newBuf[] = new byte[newSize]; System.arraycopy(buf, 0, newBuf, 0, pos); diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java index dc01897cca5..620b6735b8f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java @@ -2,35 +2,34 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils; - import java.io.IOException; import java.io.OutputStream; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; -import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; -import java.util.Map; import java.util.Set; import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; @@ -42,10 +41,9 @@ import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; +import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; - - /** * DOM and XML accessibility and comfort functions. * @@ -53,28 +51,31 @@ import org.w3c.dom.Text; */ public class XMLUtils { - private static boolean ignoreLineBreaks = - AccessController.doPrivileged(new PrivilegedAction() { - public Boolean run() { - return Boolean.getBoolean - ("com.sun.org.apache.xml.internal.security.ignoreLineBreaks"); - } - }); + private static boolean ignoreLineBreaks = + AccessController.doPrivileged(new PrivilegedAction() { + public Boolean run() { + return Boolean.valueOf(Boolean.getBoolean + ("com.sun.org.apache.xml.internal.security.ignoreLineBreaks")); + } + }).booleanValue(); private static volatile String dsPrefix = "ds"; + private static volatile String ds11Prefix = "dsig11"; private static volatile String xencPrefix = "xenc"; + private static volatile String xenc11Prefix = "xenc11"; - private static final java.util.logging.Logger log = - java.util.logging.Logger.getLogger(XMLUtils.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static final java.util.logging.Logger log = + java.util.logging.Logger.getLogger(XMLUtils.class.getName()); - /** - * Constructor XMLUtils - * - */ - private XMLUtils() { - // we don't allow instantiation - } + /** + * Constructor XMLUtils + * + */ + private XMLUtils() { + // we don't allow instantiation + } /** * Set the prefix for the digital signature namespace @@ -84,6 +85,14 @@ public class XMLUtils { dsPrefix = prefix; } + /** + * Set the prefix for the digital signature 1.1 namespace + * @param prefix the new prefix for the digital signature 1.1 namespace + */ + public static void setDs11Prefix(String prefix) { + ds11Prefix = prefix; + } + /** * Set the prefix for the encryption namespace * @param prefix the new prefix for the encryption namespace @@ -92,197 +101,256 @@ public class XMLUtils { xencPrefix = prefix; } - public static Element getNextElement(Node el) { - while ((el!=null) && (el.getNodeType()!=Node.ELEMENT_NODE)) { - el=el.getNextSibling(); - } - return (Element)el; + /** + * Set the prefix for the encryption namespace 1.1 + * @param prefix the new prefix for the encryption namespace 1.1 + */ + public static void setXenc11Prefix(String prefix) { + xenc11Prefix = prefix; + } - } + public static Element getNextElement(Node el) { + Node node = el; + while ((node != null) && (node.getNodeType() != Node.ELEMENT_NODE)) { + node = node.getNextSibling(); + } + return (Element)node; + } - /** - * @param rootNode - * @param result - * @param exclude - * @param com wheather comments or not - */ - public static void getSet(Node rootNode,Set result,Node exclude ,boolean com) { - if ((exclude!=null) && isDescendantOrSelf(exclude,rootNode)){ - return; - } - getSetRec(rootNode,result,exclude,com); - } + /** + * @param rootNode + * @param result + * @param exclude + * @param com whether comments or not + */ + public static void getSet(Node rootNode, Set result, Node exclude, boolean com) { + if ((exclude != null) && isDescendantOrSelf(exclude, rootNode)) { + return; + } + getSetRec(rootNode, result, exclude, com); + } - @SuppressWarnings("fallthrough") - static final void getSetRec(final Node rootNode,final Set result, - final Node exclude ,final boolean com) { - //Set result = new HashSet(); - if (rootNode==exclude) { - return; - } - switch (rootNode.getNodeType()) { - case Node.ELEMENT_NODE: - result.add(rootNode); - Element el=(Element)rootNode; - if (el.hasAttributes()) { - NamedNodeMap nl = ((Element)rootNode).getAttributes(); - for (int i=0;i result, + final Node exclude, final boolean com) { + if (rootNode == exclude) { + return; + } + switch (rootNode.getNodeType()) { + case Node.ELEMENT_NODE: + result.add(rootNode); + Element el = (Element)rootNode; + if (el.hasAttributes()) { + NamedNodeMap nl = el.getAttributes(); + for (int i = 0;i < nl.getLength(); i++) { + result.add(nl.item(i)); } - //no return keep working - ignore fallthrough warning - case Node.DOCUMENT_NODE: - for (Node r=rootNode.getFirstChild();r!=null;r=r.getNextSibling()){ - if (r.getNodeType()==Node.TEXT_NODE) { - result.add(r); - while ((r!=null) && (r.getNodeType()==Node.TEXT_NODE)) { - r=r.getNextSibling(); - } - if (r==null) - return; - } - getSetRec(r,result,exclude,com); - } - return; - case Node.COMMENT_NODE: - if (com) { - result.add(rootNode); - } - return; - case Node.DOCUMENT_TYPE_NODE: - return; - default: - result.add(rootNode); - } - return; - } + } + //no return keep working + case Node.DOCUMENT_NODE: + for (Node r = rootNode.getFirstChild(); r != null; r = r.getNextSibling()) { + if (r.getNodeType() == Node.TEXT_NODE) { + result.add(r); + while ((r != null) && (r.getNodeType() == Node.TEXT_NODE)) { + r = r.getNextSibling(); + } + if (r == null) { + return; + } + } + getSetRec(r, result, exclude, com); + } + return; + case Node.COMMENT_NODE: + if (com) { + result.add(rootNode); + } + return; + case Node.DOCUMENT_TYPE_NODE: + return; + default: + result.add(rootNode); + } + } - /** - * Outputs a DOM tree to an {@link OutputStream}. - * - * @param contextNode root node of the DOM tree - * @param os the {@link OutputStream} - */ - public static void outputDOM(Node contextNode, OutputStream os) { - XMLUtils.outputDOM(contextNode, os, false); - } + /** + * Outputs a DOM tree to an {@link OutputStream}. + * + * @param contextNode root node of the DOM tree + * @param os the {@link OutputStream} + */ + public static void outputDOM(Node contextNode, OutputStream os) { + XMLUtils.outputDOM(contextNode, os, false); + } - /** - * Outputs a DOM tree to an {@link OutputStream}. If an Exception is - * thrown during execution, it's StackTrace is output to System.out, but the - * Exception is not re-thrown. - * - * @param contextNode root node of the DOM tree - * @param os the {@link OutputStream} - * @param addPreamble - */ - public static void outputDOM(Node contextNode, OutputStream os, - boolean addPreamble) { + /** + * Outputs a DOM tree to an {@link OutputStream}. If an Exception is + * thrown during execution, it's StackTrace is output to System.out, but the + * Exception is not re-thrown. + * + * @param contextNode root node of the DOM tree + * @param os the {@link OutputStream} + * @param addPreamble + */ + public static void outputDOM(Node contextNode, OutputStream os, boolean addPreamble) { + try { + if (addPreamble) { + os.write("\n".getBytes("UTF-8")); + } - try { - if (addPreamble) { - os.write("\n".getBytes()); - } + os.write(Canonicalizer.getInstance( + Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(contextNode) + ); + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + } + catch (InvalidCanonicalizerException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + } catch (CanonicalizationException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + } + } - os.write( - Canonicalizer.getInstance( - Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree( - contextNode)); - } catch (IOException ex) {} - catch (InvalidCanonicalizerException ex) { - ex.printStackTrace(); - } catch (CanonicalizationException ex) { - ex.printStackTrace(); - } - } + /** + * Serializes the contextNode into the OutputStream, but + * suppresses all Exceptions. + *
    + * NOTE: This should only be used for debugging purposes, + * NOT in a production environment; this method ignores all exceptions, + * so you won't notice if something goes wrong. If you're asking what is to + * be used in a production environment, simply use the code inside the + * try{} statement, but handle the Exceptions appropriately. + * + * @param contextNode + * @param os + */ + public static void outputDOMc14nWithComments(Node contextNode, OutputStream os) { + try { + os.write(Canonicalizer.getInstance( + Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(contextNode) + ); + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + // throw new RuntimeException(ex.getMessage()); + } catch (InvalidCanonicalizerException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + // throw new RuntimeException(ex.getMessage()); + } catch (CanonicalizationException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + // throw new RuntimeException(ex.getMessage()); + } + } - /** - * Serializes the contextNode into the OutputStream, but - * supresses all Exceptions. - *
    - * NOTE: This should only be used for debugging purposes, - * NOT in a production environment; this method ignores all exceptions, - * so you won't notice if something goes wrong. If you're asking what is to - * be used in a production environment, simply use the code inside the - * try{} statement, but handle the Exceptions appropriately. - * - * @param contextNode - * @param os - */ - public static void outputDOMc14nWithComments(Node contextNode, - OutputStream os) { + /** + * Method getFullTextChildrenFromElement + * + * @param element + * @return the string of children + */ + public static String getFullTextChildrenFromElement(Element element) { + StringBuilder sb = new StringBuilder(); - try { - os.write( - Canonicalizer.getInstance( - Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree( - contextNode)); - } catch (IOException ex) { + Node child = element.getFirstChild(); + while (child != null) { + if (child.getNodeType() == Node.TEXT_NODE) { + sb.append(((Text)child).getData()); + } + child = child.getNextSibling(); + } - // throw new RuntimeException(ex.getMessage()); - } catch (InvalidCanonicalizerException ex) { + return sb.toString(); + } - // throw new RuntimeException(ex.getMessage()); - } catch (CanonicalizationException ex) { + /** + * Creates an Element in the XML Signature specification namespace. + * + * @param doc the factory Document + * @param elementName the local name of the Element + * @return the Element + */ + public static Element createElementInSignatureSpace(Document doc, String elementName) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } - // throw new RuntimeException(ex.getMessage()); - } - } + if ((dsPrefix == null) || (dsPrefix.length() == 0)) { + return doc.createElementNS(Constants.SignatureSpecNS, elementName); + } + return doc.createElementNS(Constants.SignatureSpecNS, dsPrefix + ":" + elementName); + } + /** + * Creates an Element in the XML Signature 1.1 specification namespace. + * + * @param doc the factory Document + * @param elementName the local name of the Element + * @return the Element + */ + public static Element createElementInSignature11Space(Document doc, String elementName) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } - /** - * Method getFullTextChildrenFromElement - * - * @param element - * @return the string of chi;ds - */ - public static String getFullTextChildrenFromElement(Element element) { + if ((ds11Prefix == null) || (ds11Prefix.length() == 0)) { + return doc.createElementNS(Constants.SignatureSpec11NS, elementName); + } + return doc.createElementNS(Constants.SignatureSpec11NS, ds11Prefix + ":" + elementName); + } - StringBuffer sb = new StringBuffer(); - NodeList children = element.getChildNodes(); - int iMax = children.getLength(); + /** + * Creates an Element in the XML Encryption specification namespace. + * + * @param doc the factory Document + * @param elementName the local name of the Element + * @return the Element + */ + public static Element createElementInEncryptionSpace(Document doc, String elementName) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } - for (int i = 0; i < iMax; i++) { - Node curr = children.item(i); + if ((xencPrefix == null) || (xencPrefix.length() == 0)) { + return doc.createElementNS(EncryptionConstants.EncryptionSpecNS, elementName); + } + return + doc.createElementNS( + EncryptionConstants.EncryptionSpecNS, xencPrefix + ":" + elementName + ); + } - if (curr.getNodeType() == Node.TEXT_NODE) { - sb.append(((Text) curr).getData()); - } - } + /** + * Creates an Element in the XML Encryption 1.1 specification namespace. + * + * @param doc the factory Document + * @param elementName the local name of the Element + * @return the Element + */ + public static Element createElementInEncryption11Space(Document doc, String elementName) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } - return sb.toString(); - } - - static Map namePrefixes=new HashMap(); - - /** - * Creates an Element in the XML Signature specification namespace. - * - * @param doc the factory Document - * @param elementName the local name of the Element - * @return the Element - */ - public static Element createElementInSignatureSpace(Document doc, - String elementName) { - - if (doc == null) { - throw new RuntimeException("Document is null"); - } - - if ((dsPrefix == null) || (dsPrefix.length() == 0)) { - return doc.createElementNS(Constants.SignatureSpecNS, elementName); - } - String namePrefix= namePrefixes.get(elementName); - if (namePrefix==null) { - StringBuffer tag=new StringBuffer(dsPrefix); - tag.append(':'); - tag.append(elementName); - namePrefix=tag.toString(); - namePrefixes.put(elementName,namePrefix); - } - return doc.createElementNS(Constants.SignatureSpecNS, namePrefix); - } + if ((xenc11Prefix == null) || (xenc11Prefix.length() == 0)) { + return doc.createElementNS(EncryptionConstants.EncryptionSpec11NS, elementName); + } + return + doc.createElementNS( + EncryptionConstants.EncryptionSpec11NS, xenc11Prefix + ":" + elementName + ); + } /** * Returns true if the element is in XML Signature namespace and the local @@ -290,10 +358,11 @@ public class XMLUtils { * * @param element * @param localName - * @return true if the element is in XML Signature namespace and the local name equals the supplied one + * @return true if the element is in XML Signature namespace and the local name equals + * the supplied one */ public static boolean elementIsInSignatureSpace(Element element, String localName) { - if (element == null) { + if (element == null){ return false; } @@ -301,48 +370,82 @@ public class XMLUtils { && element.getLocalName().equals(localName); } + /** + * Returns true if the element is in XML Signature 1.1 namespace and the local + * name equals the supplied one. + * + * @param element + * @param localName + * @return true if the element is in XML Signature namespace and the local name equals + * the supplied one + */ + public static boolean elementIsInSignature11Space(Element element, String localName) { + if (element == null) { + return false; + } + + return Constants.SignatureSpec11NS.equals(element.getNamespaceURI()) + && element.getLocalName().equals(localName); + } + /** * Returns true if the element is in XML Encryption namespace and the local * name equals the supplied one. * * @param element * @param localName - * @return true if the element is in XML Encryption namespace and the local name equals the supplied one + * @return true if the element is in XML Encryption namespace and the local name + * equals the supplied one */ public static boolean elementIsInEncryptionSpace(Element element, String localName) { - if (element == null) { + if (element == null){ return false; } return EncryptionConstants.EncryptionSpecNS.equals(element.getNamespaceURI()) && element.getLocalName().equals(localName); } - /** - * This method returns the owner document of a particular node. - * This method is necessary because it always returns a - * {@link Document}. {@link Node#getOwnerDocument} returns null - * if the {@link Node} is a {@link Document}. - * - * @param node - * @return the owner document of the node - */ - public static Document getOwnerDocument(Node node) { + /** + * Returns true if the element is in XML Encryption 1.1 namespace and the local + * name equals the supplied one. + * + * @param element + * @param localName + * @return true if the element is in XML Encryption 1.1 namespace and the local name + * equals the supplied one + */ + public static boolean elementIsInEncryption11Space(Element element, String localName) { + if (element == null){ + return false; + } + return EncryptionConstants.EncryptionSpec11NS.equals(element.getNamespaceURI()) + && element.getLocalName().equals(localName); + } - if (node.getNodeType() == Node.DOCUMENT_NODE) { - return (Document) node; - } - try { + /** + * This method returns the owner document of a particular node. + * This method is necessary because it always returns a + * {@link Document}. {@link Node#getOwnerDocument} returns null + * if the {@link Node} is a {@link Document}. + * + * @param node + * @return the owner document of the node + */ + public static Document getOwnerDocument(Node node) { + if (node.getNodeType() == Node.DOCUMENT_NODE) { + return (Document) node; + } + try { return node.getOwnerDocument(); - } catch (NullPointerException npe) { + } catch (NullPointerException npe) { throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0") + " Original message was \"" + npe.getMessage() + "\""); - } - - } + } + } /** - * This method returns the first non-null owner document of the Node's in this Set. + * This method returns the first non-null owner document of the Nodes in this Set. * This method is necessary because it always returns a * {@link Document}. {@link Node#getOwnerDocument} returns null * if the {@link Node} is a {@link Document}. @@ -351,23 +454,23 @@ public class XMLUtils { * @return the owner document */ public static Document getOwnerDocument(Set xpathNodeSet) { - NullPointerException npe = null; - for (Node node : xpathNodeSet) { - int nodeType =node.getNodeType(); - if (nodeType == Node.DOCUMENT_NODE) { - return (Document) node; - } - try { - if (nodeType==Node.ATTRIBUTE_NODE) { + NullPointerException npe = null; + for (Node node : xpathNodeSet) { + int nodeType = node.getNodeType(); + if (nodeType == Node.DOCUMENT_NODE) { + return (Document) node; + } + try { + if (nodeType == Node.ATTRIBUTE_NODE) { return ((Attr)node).getOwnerElement().getOwnerDocument(); - } - return node.getOwnerDocument(); - } catch (NullPointerException e) { - npe = e; - } + } + return node.getOwnerDocument(); + } catch (NullPointerException e) { + npe = e; + } + } - } - throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0") + throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0") + " Original message was \"" + (npe == null ? "" : npe.getMessage()) + "\""); } @@ -380,165 +483,161 @@ public class XMLUtils { * @param namespace * @return the element. */ - public static Element createDSctx(Document doc, String prefix, - String namespace) { + public static Element createDSctx(Document doc, String prefix, String namespace) { + if ((prefix == null) || (prefix.trim().length() == 0)) { + throw new IllegalArgumentException("You must supply a prefix"); + } - if ((prefix == null) || (prefix.trim().length() == 0)) { - throw new IllegalArgumentException("You must supply a prefix"); - } + Element ctx = doc.createElementNS(null, "namespaceContext"); - Element ctx = doc.createElementNS(null, "namespaceContext"); + ctx.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix.trim(), namespace); - ctx.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix.trim(), - namespace); - - return ctx; + return ctx; } - /** - * Method addReturnToElement - * - * @param e - */ - public static void addReturnToElement(Element e) { + /** + * Method addReturnToElement + * + * @param e + */ + public static void addReturnToElement(Element e) { + if (!ignoreLineBreaks) { + Document doc = e.getOwnerDocument(); + e.appendChild(doc.createTextNode("\n")); + } + } - if (!ignoreLineBreaks) { - Document doc = e.getOwnerDocument(); - e.appendChild(doc.createTextNode("\n")); - } - } + public static void addReturnToElement(Document doc, HelperNodeList nl) { + if (!ignoreLineBreaks) { + nl.appendChild(doc.createTextNode("\n")); + } + } - public static void addReturnToElement(Document doc, HelperNodeList nl) { - if (!ignoreLineBreaks) { - nl.appendChild(doc.createTextNode("\n")); - } - } + public static void addReturnBeforeChild(Element e, Node child) { + if (!ignoreLineBreaks) { + Document doc = e.getOwnerDocument(); + e.insertBefore(doc.createTextNode("\n"), child); + } + } - public static void addReturnBeforeChild(Element e, Node child) { - if (!ignoreLineBreaks) { - Document doc = e.getOwnerDocument(); - e.insertBefore(doc.createTextNode("\n"), child); - } - } + /** + * Method convertNodelistToSet + * + * @param xpathNodeSet + * @return the set with the nodelist + */ + public static Set convertNodelistToSet(NodeList xpathNodeSet) { + if (xpathNodeSet == null) { + return new HashSet(); + } - /** - * Method convertNodelistToSet - * - * @param xpathNodeSet - * @return the set with the nodelist - */ - public static Set convertNodelistToSet(NodeList xpathNodeSet) { + int length = xpathNodeSet.getLength(); + Set set = new HashSet(length); - if (xpathNodeSet == null) { - return new HashSet(); - } + for (int i = 0; i < length; i++) { + set.add(xpathNodeSet.item(i)); + } - int length = xpathNodeSet.getLength(); - Set set = new HashSet(length); + return set; + } - for (int i = 0; i < length; i++) { - set.add(xpathNodeSet.item(i)); - } + /** + * This method spreads all namespace attributes in a DOM document to their + * children. This is needed because the XML Signature XPath transform + * must evaluate the XPath against all nodes in the input, even against + * XPath namespace nodes. Through a bug in XalanJ2, the namespace nodes are + * not fully visible in the Xalan XPath model, so we have to do this by + * hand in DOM spaces so that the nodes become visible in XPath space. + * + * @param doc + * @see + * Namespace axis resolution is not XPath compliant + */ + public static void circumventBug2650(Document doc) { - return set; - } + Element documentElement = doc.getDocumentElement(); + // if the document element has no xmlns definition, we add xmlns="" + Attr xmlnsAttr = + documentElement.getAttributeNodeNS(Constants.NamespaceSpecNS, "xmlns"); - /** - * This method spreads all namespace attributes in a DOM document to their - * children. This is needed because the XML Signature XPath transform - * must evaluate the XPath against all nodes in the input, even against - * XPath namespace nodes. Through a bug in XalanJ2, the namespace nodes are - * not fully visible in the Xalan XPath model, so we have to do this by - * hand in DOM spaces so that the nodes become visible in XPath space. - * - * @param doc - * @see Namespace axis resolution is not XPath compliant - */ - public static void circumventBug2650(Document doc) { + if (xmlnsAttr == null) { + documentElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", ""); + } - Element documentElement = doc.getDocumentElement(); + XMLUtils.circumventBug2650internal(doc); + } - // if the document element has no xmlns definition, we add xmlns="" - Attr xmlnsAttr = - documentElement.getAttributeNodeNS(Constants.NamespaceSpecNS, "xmlns"); - - if (xmlnsAttr == null) { - documentElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", ""); - } - - XMLUtils.circumventBug2650internal(doc); - } - - /** - * This is the work horse for {@link #circumventBug2650}. - * - * @param node - * @see Namespace axis resolution is not XPath compliant - */ - @SuppressWarnings("fallthrough") - private static void circumventBug2650internal(Node node) { - Node parent=null; - Node sibling=null; - final String namespaceNs=Constants.NamespaceSpecNS; - do { - switch (node.getNodeType()) { - case Node.ELEMENT_NODE : - Element element = (Element) node; - if (!element.hasChildNodes()) - break; - if (element.hasAttributes()) { - NamedNodeMap attributes = element.getAttributes(); - int attributesLength = attributes.getLength(); - - for (Node child = element.getFirstChild(); child!=null; - child=child.getNextSibling()) { - - if (child.getNodeType() != Node.ELEMENT_NODE) { - continue; + /** + * This is the work horse for {@link #circumventBug2650}. + * + * @param node + * @see + * Namespace axis resolution is not XPath compliant + */ + @SuppressWarnings("fallthrough") + private static void circumventBug2650internal(Node node) { + Node parent = null; + Node sibling = null; + final String namespaceNs = Constants.NamespaceSpecNS; + do { + switch (node.getNodeType()) { + case Node.ELEMENT_NODE : + Element element = (Element) node; + if (!element.hasChildNodes()) { + break; } - Element childElement = (Element) child; + if (element.hasAttributes()) { + NamedNodeMap attributes = element.getAttributes(); + int attributesLength = attributes.getLength(); - for (int i = 0; i < attributesLength; i++) { - Attr currentAttr = (Attr) attributes.item(i); - if (namespaceNs!=currentAttr.getNamespaceURI()) - continue; - if (childElement.hasAttributeNS(namespaceNs, - currentAttr.getLocalName())) { - continue; + for (Node child = element.getFirstChild(); child!=null; + child = child.getNextSibling()) { + + if (child.getNodeType() != Node.ELEMENT_NODE) { + continue; } - childElement.setAttributeNS(namespaceNs, - currentAttr.getName(), - currentAttr.getNodeValue()); - + Element childElement = (Element) child; + for (int i = 0; i < attributesLength; i++) { + Attr currentAttr = (Attr) attributes.item(i); + if (!namespaceNs.equals(currentAttr.getNamespaceURI())) { + continue; + } + if (childElement.hasAttributeNS(namespaceNs, + currentAttr.getLocalName())) { + continue; + } + childElement.setAttributeNS(namespaceNs, + currentAttr.getName(), + currentAttr.getNodeValue()); + } + } } - } - } - case Node.ENTITY_REFERENCE_NODE : - case Node.DOCUMENT_NODE : - parent=node; - sibling=node.getFirstChild(); - break; - } - while ((sibling==null) && (parent!=null)) { - sibling=parent.getNextSibling(); - parent=parent.getParentNode(); - }; - if (sibling==null) { - return; - } + case Node.ENTITY_REFERENCE_NODE : + case Node.DOCUMENT_NODE : + parent = node; + sibling = node.getFirstChild(); + break; + } + while ((sibling == null) && (parent != null)) { + sibling = parent.getNextSibling(); + parent = parent.getParentNode(); + } + if (sibling == null) { + return; + } - node=sibling; - sibling=node.getNextSibling(); - } while (true); - } + node = sibling; + sibling = node.getNextSibling(); + } while (true); + } /** * @param sibling * @param nodeName * @param number - * @return nodes with the constrain + * @return nodes with the constraint */ public static Element selectDsNode(Node sibling, String nodeName, int number) { while (sibling != null) { @@ -554,6 +653,26 @@ public class XMLUtils { return null; } + /** + * @param sibling + * @param nodeName + * @param number + * @return nodes with the constraint + */ + public static Element selectDs11Node(Node sibling, String nodeName, int number) { + while (sibling != null) { + if (Constants.SignatureSpec11NS.equals(sibling.getNamespaceURI()) + && sibling.getLocalName().equals(nodeName)) { + if (number == 0){ + return (Element)sibling; + } + number--; + } + sibling = sibling.getNextSibling(); + } + return null; + } + /** * @param sibling * @param nodeName @@ -574,42 +693,61 @@ public class XMLUtils { return null; } - /** - * @param sibling - * @param nodeName - * @param number - * @return nodes with the constrain - */ - public static Text selectDsNodeText(Node sibling, String nodeName, int number) { - Node n=selectDsNode(sibling,nodeName,number); - if (n==null) { - return null; + + /** + * @param sibling + * @param nodeName + * @param number + * @return nodes with the constrain + */ + public static Text selectDsNodeText(Node sibling, String nodeName, int number) { + Node n = selectDsNode(sibling,nodeName,number); + if (n == null) { + return null; } - n=n.getFirstChild(); - while (n!=null && n.getNodeType()!=Node.TEXT_NODE) { - n=n.getNextSibling(); + n = n.getFirstChild(); + while (n != null && n.getNodeType() != Node.TEXT_NODE) { + n = n.getNextSibling(); } return (Text)n; - } + } - /** - * @param sibling - * @param uri - * @param nodeName - * @param number - * @return nodes with the constrain - */ - public static Text selectNodeText(Node sibling, String uri, String nodeName, int number) { - Node n=selectNode(sibling,uri,nodeName,number); - if (n==null) { - return null; + /** + * @param sibling + * @param nodeName + * @param number + * @return nodes with the constrain + */ + public static Text selectDs11NodeText(Node sibling, String nodeName, int number) { + Node n = selectDs11Node(sibling,nodeName,number); + if (n == null) { + return null; + } + n = n.getFirstChild(); + while (n != null && n.getNodeType() != Node.TEXT_NODE) { + n = n.getNextSibling(); + } + return (Text)n; } - n=n.getFirstChild(); - while (n!=null && n.getNodeType()!=Node.TEXT_NODE) { - n=n.getNextSibling(); + + /** + * @param sibling + * @param uri + * @param nodeName + * @param number + * @return nodes with the constrain + */ + public static Text selectNodeText(Node sibling, String uri, String nodeName, int number) { + Node n = selectNode(sibling,uri,nodeName,number); + if (n == null) { + return null; + } + n = n.getFirstChild(); + while (n != null && n.getNodeType() != Node.TEXT_NODE) { + n = n.getNextSibling(); + } + return (Text)n; } - return (Text)n; - } /** * @param sibling @@ -638,16 +776,25 @@ public class XMLUtils { * @return nodes with the constrain */ public static Element[] selectDsNodes(Node sibling, String nodeName) { - return selectNodes(sibling,Constants.SignatureSpecNS, nodeName); + return selectNodes(sibling, Constants.SignatureSpecNS, nodeName); + } + + /** + * @param sibling + * @param nodeName + * @return nodes with the constrain + */ + public static Element[] selectDs11Nodes(Node sibling, String nodeName) { + return selectNodes(sibling, Constants.SignatureSpec11NS, nodeName); } /** * @param sibling * @param uri * @param nodeName - * @return nodes with the constrain + * @return nodes with the constraint */ - public static Element[] selectNodes(Node sibling, String uri, String nodeName) { + public static Element[] selectNodes(Node sibling, String uri, String nodeName) { List list = new ArrayList(); while (sibling != null) { if (sibling.getNamespaceURI() != null && sibling.getNamespaceURI().equals(uri) @@ -659,73 +806,117 @@ public class XMLUtils { return list.toArray(new Element[list.size()]); } - /** - * @param signatureElement - * @param inputSet - * @return nodes with the constrain - */ + /** + * @param signatureElement + * @param inputSet + * @return nodes with the constrain + */ public static Set excludeNodeFromSet(Node signatureElement, Set inputSet) { - Set resultSet = new HashSet(); - Iterator iterator = inputSet.iterator(); + Set resultSet = new HashSet(); + Iterator iterator = inputSet.iterator(); - while (iterator.hasNext()) { + while (iterator.hasNext()) { Node inputNode = iterator.next(); - if (!XMLUtils - .isDescendantOrSelf(signatureElement, inputNode)) { - resultSet.add(inputNode); + if (!XMLUtils.isDescendantOrSelf(signatureElement, inputNode)) { + resultSet.add(inputNode); } - } - return resultSet; - } + } + return resultSet; + } - /** - * Returns true if the descendantOrSelf is on the descendant-or-self axis - * of the context node. - * - * @param ctx - * @param descendantOrSelf - * @return true if the node is descendant - */ - static public boolean isDescendantOrSelf(Node ctx, Node descendantOrSelf) { + /** + * Method getStrFromNode + * + * @param xpathnode + * @return the string for the node. + */ + public static String getStrFromNode(Node xpathnode) { + if (xpathnode.getNodeType() == Node.TEXT_NODE) { + // we iterate over all siblings of the context node because eventually, + // the text is "polluted" with pi's or comments + StringBuilder sb = new StringBuilder(); - if (ctx == descendantOrSelf) { - return true; - } + for (Node currentSibling = xpathnode.getParentNode().getFirstChild(); + currentSibling != null; + currentSibling = currentSibling.getNextSibling()) { + if (currentSibling.getNodeType() == Node.TEXT_NODE) { + sb.append(((Text) currentSibling).getData()); + } + } - Node parent = descendantOrSelf; + return sb.toString(); + } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) { + return ((Attr) xpathnode).getNodeValue(); + } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { + return ((ProcessingInstruction) xpathnode).getNodeValue(); + } - while (true) { - if (parent == null) { - return false; - } + return null; + } - if (parent == ctx) { + /** + * Returns true if the descendantOrSelf is on the descendant-or-self axis + * of the context node. + * + * @param ctx + * @param descendantOrSelf + * @return true if the node is descendant + */ + public static boolean isDescendantOrSelf(Node ctx, Node descendantOrSelf) { + if (ctx == descendantOrSelf) { return true; - } + } - if (parent.getNodeType() == Node.ATTRIBUTE_NODE) { - parent = ((Attr) parent).getOwnerElement(); - } else { - parent = parent.getParentNode(); - } - } - } + Node parent = descendantOrSelf; + + while (true) { + if (parent == null) { + return false; + } + + if (parent == ctx) { + return true; + } + + if (parent.getNodeType() == Node.ATTRIBUTE_NODE) { + parent = ((Attr) parent).getOwnerElement(); + } else { + parent = parent.getParentNode(); + } + } + } public static boolean ignoreLineBreaks() { return ignoreLineBreaks; } /** - * This method is a tree-search to help prevent against wrapping attacks. - * It checks that no two Elements have ID Attributes that match the "value" - * argument, if this is the case then "false" is returned. Note that a - * return value of "true" does not necessarily mean that a matching Element - * has been found, just that no wrapping attack has been detected. + * Returns the attribute value for the attribute with the specified name. + * Returns null if there is no such attribute, or + * the empty string if the attribute value is empty. + * + *

    This works around a limitation of the DOM + * Element.getAttributeNode method, which does not distinguish + * between an unspecified attribute and an attribute with a value of + * "" (it returns "" for both cases). + * + * @param elem the element containing the attribute + * @param name the name of the attribute + * @return the attribute value (may be null if unspecified) */ - public static boolean protectAgainstWrappingAttack(Node startNode, - String value) - { + public static String getAttributeValue(Element elem, String name) { + Attr attr = elem.getAttributeNodeNS(null, name); + return (attr == null) ? null : attr.getValue(); + } + + /** + * This method is a tree-search to help prevent against wrapping attacks. It checks that no + * two Elements have ID Attributes that match the "value" argument, if this is the case then + * "false" is returned. Note that a return value of "true" does not necessarily mean that + * a matching Element has been found, just that no wrapping attack has been detected. + */ + public static boolean protectAgainstWrappingAttack(Node startNode, String value) { Node startParent = startNode.getParentNode(); Node processedNode = null; Element foundElement = null; @@ -780,15 +971,13 @@ public class XMLUtils { } /** - * This method is a tree-search to help prevent against wrapping attacks. - * It checks that no other Element than the given "knownElement" argument - * has an ID attribute that matches the "value" argument, which is the ID - * value of "knownElement". If this is the case then "false" is returned. + * This method is a tree-search to help prevent against wrapping attacks. It checks that no other + * Element than the given "knownElement" argument has an ID attribute that matches the "value" + * argument, which is the ID value of "knownElement". If this is the case then "false" is returned. */ - public static boolean protectAgainstWrappingAttack(Node startNode, - Element knownElement, - String value) - { + public static boolean protectAgainstWrappingAttack( + Node startNode, Element knownElement, String value + ) { Node startParent = startNode.getParentNode(); Node processedNode = null; @@ -805,9 +994,7 @@ public class XMLUtils { if (attributes != null) { for (int i = 0; i < attributes.getLength(); i++) { Attr attr = (Attr)attributes.item(i); - if (attr.isId() && id.equals(attr.getValue()) - && se != knownElement) - { + if (attr.isId() && id.equals(attr.getValue()) && se != knownElement) { log.log(java.util.logging.Level.FINE, "Multiple elements with the same 'Id' attribute value!"); return false; } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathAPI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathAPI.java new file mode 100644 index 00000000000..d5b55bac3f8 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathAPI.java @@ -0,0 +1,66 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 com.sun.org.apache.xml.internal.security.utils; + +import javax.xml.transform.TransformerException; + +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * An interface to abstract XPath evaluation + */ +public interface XPathAPI { + + /** + * Use an XPath string to select a nodelist. + * XPath namespace prefixes are resolved from the namespaceNode. + * + * @param contextNode The node to start searching from. + * @param xpathnode + * @param str + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + * @return A NodeIterator, should never be null. + * + * @throws TransformerException + */ + NodeList selectNodeList( + Node contextNode, Node xpathnode, String str, Node namespaceNode + ) throws TransformerException; + + /** + * Evaluate an XPath string and return true if the output is to be included or not. + * @param contextNode The node to start searching from. + * @param xpathnode The XPath node + * @param str The XPath expression + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + */ + boolean evaluate(Node contextNode, Node xpathnode, String str, Node namespaceNode) + throws TransformerException; + + /** + * Clear any context information from this object + */ + void clear(); + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFactory.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFactory.java new file mode 100644 index 00000000000..3de6129b935 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFactory.java @@ -0,0 +1,71 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 com.sun.org.apache.xml.internal.security.utils; + + +/** + * A Factory to return an XPathAPI instance. If Xalan is available it returns XalanXPathAPI. If not, then + * it returns JDKXPathAPI. + */ +public abstract class XPathFactory { + + private static boolean xalanInstalled; + + static { + try { + Class funcTableClass = + ClassLoaderUtils.loadClass("com.sun.org.apache.xpath.internal.compiler.FunctionTable", XPathFactory.class); + if (funcTableClass != null) { + xalanInstalled = true; + } + } catch (Exception e) { + //ignore + } + } + + protected synchronized static boolean isXalanInstalled() { + return xalanInstalled; + } + + /** + * Get a new XPathFactory instance + */ + public static XPathFactory newInstance() { + if (!isXalanInstalled()) { + return new JDKXPathFactory(); + } + // Xalan is available + if (XalanXPathAPI.isInstalled()) { + return new XalanXPathFactory(); + } + // Some problem was encountered in fixing up the Xalan FunctionTable so fall back to the + // JDK implementation + return new JDKXPathFactory(); + } + + /** + * Get a new XPathAPI instance + */ + public abstract XPathAPI newXPathAPI(); + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFuncHereAPI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFuncHereAPI.java deleted file mode 100644 index dbee521c11e..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFuncHereAPI.java +++ /dev/null @@ -1,306 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * 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 com.sun.org.apache.xml.internal.security.utils; - - - -import javax.xml.transform.TransformerException; - -import com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHereContext; -import com.sun.org.apache.xml.internal.utils.PrefixResolver; -import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault; -import com.sun.org.apache.xpath.internal.XPath; -import com.sun.org.apache.xpath.internal.objects.XObject; -import org.w3c.dom.Attr; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.ProcessingInstruction; -import org.w3c.dom.Text; -import org.w3c.dom.traversal.NodeIterator; - - - - -/** - * This class does the same as {@link com.sun.org.apache.xpath.internal.XPathAPI} except that the XPath strings - * are not supplied as Strings but as {@link Text}, {@link Attr}ibute or - * {ProcessingInstruction} nodes which contain the XPath string. This enables - * us to use the here() function. - *
    - * The methods in this class are convenience methods into the low-level XPath API. - * These functions tend to be a little slow, since a number of objects must be - * created for each evaluation. A faster way is to precompile the - * XPaths using the low-level API, and then just use the XPaths - * over and over. - * - * @author $Author: mullan $ - * @see XPath Specification - */ -public class XPathFuncHereAPI { - - /** - * Use an XPath string to select a single node. XPath namespace - * prefixes are resolved from the context node, which may not - * be what you want (see the next method). - * - * @param contextNode The node to start searching from. - * @param xpathnode A Node containing a valid XPath string. - * @return The first node found that matches the XPath, or null. - * - * @throws TransformerException - */ - public static Node selectSingleNode(Node contextNode, Node xpathnode) - throws TransformerException { - return selectSingleNode(contextNode, xpathnode, contextNode); - } - - /** - * Use an XPath string to select a single node. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return The first node found that matches the XPath, or null. - * - * @throws TransformerException - */ - public static Node selectSingleNode( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Have the XObject return its result as a NodeSetDTM. - NodeIterator nl = selectNodeIterator(contextNode, xpathnode, - namespaceNode); - - // Return the first node, or null - return nl.nextNode(); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the contextNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public static NodeIterator selectNodeIterator( - Node contextNode, Node xpathnode) throws TransformerException { - return selectNodeIterator(contextNode, xpathnode, contextNode); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public static NodeIterator selectNodeIterator( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Execute the XPath, and have it return the result - XObject list = eval(contextNode, xpathnode, namespaceNode); - - // Have the XObject return its result as a NodeSetDTM. - return list.nodeset(); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the contextNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public static NodeList selectNodeList(Node contextNode, Node xpathnode) - throws TransformerException { - return selectNodeList(contextNode, xpathnode, contextNode); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public static NodeList selectNodeList( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Execute the XPath, and have it return the result - XObject list = eval(contextNode, xpathnode, namespaceNode); - - // Return a NodeList. - return list.nodelist(); - } - - /** - * Evaluate XPath string to an XObject. Using this method, - * XPath namespace prefixes will be resolved from the namespaceNode. - * @param contextNode The node to start searching from. - * @param xpathnode - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - */ - public static XObject eval(Node contextNode, Node xpathnode) - throws TransformerException { - return eval(contextNode, xpathnode, contextNode); - } - - /** - * Evaluate XPath string to an XObject. - * XPath namespace prefixes are resolved from the namespaceNode. - * The implementation of this is a little slow, since it creates - * a number of objects each time it is called. This could be optimized - * to keep the same objects around, but then thread-safety issues would arise. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - */ - public static XObject eval( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Since we don't have a XML Parser involved here, install some default support - // for things like namespaces, etc. - // (Changed from: XPathContext xpathSupport = new XPathContext(); - // because XPathContext is weak in a number of areas... perhaps - // XPathContext should be done away with.) - FuncHereContext xpathSupport = new FuncHereContext(xpathnode); - - // Create an object to resolve namespace prefixes. - // XPath namespaces are resolved from the input context node's document element - // if it is a root node, or else the current context node (for lack of a better - // resolution space, given the simplicity of this sample code). - PrefixResolverDefault prefixResolver = - new PrefixResolverDefault((namespaceNode.getNodeType() - == Node.DOCUMENT_NODE) - ? ((Document) namespaceNode) - .getDocumentElement() - : namespaceNode); - String str = getStrFromNode(xpathnode); - - // Create the XPath object. - XPath xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null); - - // Execute the XPath, and have it return the result - // return xpath.execute(xpathSupport, contextNode, prefixResolver); - int ctxtNode = xpathSupport.getDTMHandleFromNode(contextNode); - - return xpath.execute(xpathSupport, ctxtNode, prefixResolver); - } - - /** - * Evaluate XPath string to an XObject. - * XPath namespace prefixes are resolved from the namespaceNode. - * The implementation of this is a little slow, since it creates - * a number of objects each time it is called. This could be optimized - * to keep the same objects around, but then thread-safety issues would arise. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param prefixResolver Will be called if the parser encounters namespace - * prefixes, to resolve the prefixes to URLs. - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - */ - public static XObject eval( - Node contextNode, Node xpathnode, PrefixResolver prefixResolver) - throws TransformerException { - - String str = getStrFromNode(xpathnode); - - // Since we don't have a XML Parser involved here, install some default support - // for things like namespaces, etc. - // (Changed from: XPathContext xpathSupport = new XPathContext(); - // because XPathContext is weak in a number of areas... perhaps - // XPathContext should be done away with.) - // Create the XPath object. - XPath xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null); - - // Execute the XPath, and have it return the result - FuncHereContext xpathSupport = new FuncHereContext(xpathnode); - int ctxtNode = xpathSupport.getDTMHandleFromNode(contextNode); - - return xpath.execute(xpathSupport, ctxtNode, prefixResolver); - } - - /** - * Method getStrFromNode - * - * @param xpathnode - * @return the string from the node - */ - private static String getStrFromNode(Node xpathnode) { - - if (xpathnode.getNodeType() == Node.TEXT_NODE) { - return ((Text) xpathnode).getData(); - } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) { - return ((Attr) xpathnode).getNodeValue(); - } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { - return ((ProcessingInstruction) xpathnode).getNodeValue(); - } - - return ""; - } -} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathAPI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathAPI.java new file mode 100644 index 00000000000..f9fab3033d8 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathAPI.java @@ -0,0 +1,210 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 com.sun.org.apache.xml.internal.security.utils; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +import javax.xml.transform.ErrorListener; +import javax.xml.transform.SourceLocator; +import javax.xml.transform.TransformerException; + +import com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHere; +import com.sun.org.apache.xml.internal.utils.PrefixResolver; +import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault; +import com.sun.org.apache.xpath.internal.Expression; +import com.sun.org.apache.xpath.internal.XPath; +import com.sun.org.apache.xpath.internal.XPathContext; +import com.sun.org.apache.xpath.internal.compiler.FunctionTable; +import com.sun.org.apache.xpath.internal.objects.XObject; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * An implementation of XPathAPI using Xalan. This supports the "here()" function defined in the digital + * signature spec. + */ +public class XalanXPathAPI implements XPathAPI { + + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(XalanXPathAPI.class.getName()); + + private String xpathStr = null; + + private XPath xpath = null; + + private static FunctionTable funcTable = null; + + private static boolean installed; + + private XPathContext context; + + static { + fixupFunctionTable(); + } + + + /** + * Use an XPath string to select a nodelist. + * XPath namespace prefixes are resolved from the namespaceNode. + * + * @param contextNode The node to start searching from. + * @param xpathnode + * @param str + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + * @return A NodeIterator, should never be null. + * + * @throws TransformerException + */ + public NodeList selectNodeList( + Node contextNode, Node xpathnode, String str, Node namespaceNode + ) throws TransformerException { + + // Execute the XPath, and have it return the result + XObject list = eval(contextNode, xpathnode, str, namespaceNode); + + // Return a NodeList. + return list.nodelist(); + } + + /** + * Evaluate an XPath string and return true if the output is to be included or not. + * @param contextNode The node to start searching from. + * @param xpathnode The XPath node + * @param str The XPath expression + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + */ + public boolean evaluate(Node contextNode, Node xpathnode, String str, Node namespaceNode) + throws TransformerException { + XObject object = eval(contextNode, xpathnode, str, namespaceNode); + return object.bool(); + } + + /** + * Clear any context information from this object + */ + public void clear() { + xpathStr = null; + xpath = null; + context = null; + } + + public synchronized static boolean isInstalled() { + return installed; + } + + private XObject eval(Node contextNode, Node xpathnode, String str, Node namespaceNode) + throws TransformerException { + if (context == null) { + context = new XPathContext(xpathnode); + context.setSecureProcessing(true); + } + + // Create an object to resolve namespace prefixes. + // XPath namespaces are resolved from the input context node's document element + // if it is a root node, or else the current context node (for lack of a better + // resolution space, given the simplicity of this sample code). + Node resolverNode = + (namespaceNode.getNodeType() == Node.DOCUMENT_NODE) + ? ((Document) namespaceNode).getDocumentElement() : namespaceNode; + PrefixResolverDefault prefixResolver = new PrefixResolverDefault(resolverNode); + + if (!str.equals(xpathStr)) { + if (str.indexOf("here()") > 0) { + context.reset(); + } + xpath = createXPath(str, prefixResolver); + xpathStr = str; + } + + // Execute the XPath, and have it return the result + int ctxtNode = context.getDTMHandleFromNode(contextNode); + + return xpath.execute(context, ctxtNode, prefixResolver); + } + + private XPath createXPath(String str, PrefixResolver prefixResolver) throws TransformerException { + XPath xpath = null; + Class[] classes = new Class[]{String.class, SourceLocator.class, PrefixResolver.class, int.class, + ErrorListener.class, FunctionTable.class}; + Object[] objects = + new Object[]{str, null, prefixResolver, Integer.valueOf(XPath.SELECT), null, funcTable}; + try { + Constructor constructor = XPath.class.getConstructor(classes); + xpath = (XPath) constructor.newInstance(objects); + } catch (Exception ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + } + if (xpath == null) { + xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null); + } + return xpath; + } + + private synchronized static void fixupFunctionTable() { + installed = false; + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Registering Here function"); + } + /** + * Try to register our here() implementation as internal function. + */ + try { + Class[] args = {String.class, Expression.class}; + Method installFunction = FunctionTable.class.getMethod("installFunction", args); + if ((installFunction.getModifiers() & Modifier.STATIC) != 0) { + Object[] params = {"here", new FuncHere()}; + installFunction.invoke(null, params); + installed = true; + } + } catch (Exception ex) { + log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", ex); + } + if (!installed) { + try { + funcTable = new FunctionTable(); + Class[] args = {String.class, Class.class}; + Method installFunction = FunctionTable.class.getMethod("installFunction", args); + Object[] params = {"here", FuncHere.class}; + installFunction.invoke(funcTable, params); + installed = true; + } catch (Exception ex) { + log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", ex); + } + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + if (installed) { + log.log(java.util.logging.Level.FINE, "Registered class " + FuncHere.class.getName() + + " for XPath function 'here()' function in internal table"); + } else { + log.log(java.util.logging.Level.FINE, "Unable to register class " + FuncHere.class.getName() + + " for XPath function 'here()' function in internal table"); + } + } + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathFactory.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathFactory.java new file mode 100644 index 00000000000..e6ee959d750 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathFactory.java @@ -0,0 +1,37 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 com.sun.org.apache.xml.internal.security.utils; + + +/** + * A Factory to return a XalanXPathAPI instance. + */ +public class XalanXPathFactory extends XPathFactory { + + /** + * Get a new XPathAPI instance + */ + public XPathAPI newXPathAPI() { + return new XalanXPathAPI(); + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java index 67d635cb847..7570a019064 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java @@ -85,8 +85,14 @@ public class ResourceResolver { * @throws ResourceResolverException */ public static final ResourceResolver getInstance( - Attr uri, String baseURI, boolean secureValidation + Attr uriAttr, String baseURI, boolean secureValidation ) throws ResourceResolverException { + ResourceResolverContext context = new ResourceResolverContext(uriAttr, baseURI, secureValidation); + return internalGetInstance(context); + } + + private static ResourceResolver internalGetInstance(ResourceResolverContext context) + throws ResourceResolverException { synchronized (resolverList) { for (ResourceResolver resolver : resolverList) { ResourceResolver resolverTmp = resolver; @@ -95,9 +101,9 @@ public class ResourceResolver { resolverTmp = new ResourceResolver(resolver.resolverSpi.getClass().newInstance()); } catch (InstantiationException e) { - throw new ResourceResolverException("", e, uri, baseURI); + throw new ResourceResolverException("", e, context.attr, context.baseUri); } catch (IllegalAccessException e) { - throw new ResourceResolverException("", e, uri, baseURI); + throw new ResourceResolverException("", e, context.attr, context.baseUri); } } @@ -107,15 +113,14 @@ public class ResourceResolver { ); } - resolverTmp.resolverSpi.secureValidation = secureValidation; - if ((resolverTmp != null) && resolverTmp.canResolve(uri, baseURI)) { + if ((resolverTmp != null) && resolverTmp.canResolve(context)) { // Check to see whether the Resolver is allowed - if (secureValidation + if (context.secureValidation && (resolverTmp.resolverSpi instanceof ResolverLocalFilesystem || resolverTmp.resolverSpi instanceof ResolverDirectHTTP)) { Object exArgs[] = { resolverTmp.resolverSpi.getClass().getName() }; throw new ResourceResolverException( - "signature.Reference.ForbiddenResolver", exArgs, uri, baseURI + "signature.Reference.ForbiddenResolver", exArgs, context.attr, context.baseUri ); } return resolverTmp; @@ -123,9 +128,10 @@ public class ResourceResolver { } } - Object exArgs[] = { ((uri != null) ? uri.getNodeValue() : "null"), baseURI }; + Object exArgs[] = { ((context.uriToResolve != null) + ? context.uriToResolve : "null"), context.baseUri }; - throw new ResourceResolverException("utils.resolver.noClass", exArgs, uri, baseURI); + throw new ResourceResolverException("utils.resolver.noClass", exArgs, context.attr, context.baseUri); } /** @@ -165,6 +171,8 @@ public class ResourceResolver { ); } + ResourceResolverContext context = new ResourceResolverContext(uri, baseURI, secureValidation); + // first check the individual Resolvers if (individualResolvers != null) { for (int i = 0; i < individualResolvers.size(); i++) { @@ -176,15 +184,14 @@ public class ResourceResolver { log.log(java.util.logging.Level.FINE, "check resolvability by class " + currentClass); } - resolver.resolverSpi.secureValidation = secureValidation; - if (resolver.canResolve(uri, baseURI)) { + if (resolver.canResolve(context)) { return resolver; } } } } - return getInstance(uri, baseURI, secureValidation); + return internalGetInstance(context); } /** @@ -269,6 +276,15 @@ public class ResourceResolver { } } + /** + * @deprecated New clients should use {@link #resolve(Attr, String, boolean)} + */ + @Deprecated + public XMLSignatureInput resolve(Attr uri, String baseURI) + throws ResourceResolverException { + return resolve(uri, baseURI, true); + } + /** * Method resolve * @@ -278,9 +294,10 @@ public class ResourceResolver { * * @throws ResourceResolverException */ - public XMLSignatureInput resolve(Attr uri, String baseURI) + public XMLSignatureInput resolve(Attr uri, String baseURI, boolean secureValidation) throws ResourceResolverException { - return resolverSpi.engineResolve(uri, baseURI); + ResourceResolverContext context = new ResourceResolverContext(uri, baseURI, secureValidation); + return resolverSpi.engineResolveURI(context); } /** @@ -338,7 +355,7 @@ public class ResourceResolver { * @param baseURI * @return true if it can resolve the uri */ - private boolean canResolve(Attr uri, String baseURI) { - return resolverSpi.engineCanResolve(uri, baseURI); + private boolean canResolve(ResourceResolverContext context) { + return this.resolverSpi.engineCanResolveURI(context); } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverContext.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverContext.java new file mode 100644 index 00000000000..5b8a9ce13f6 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverContext.java @@ -0,0 +1,43 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 com.sun.org.apache.xml.internal.security.utils.resolver; + +import org.w3c.dom.Attr; + +public class ResourceResolverContext { + + public ResourceResolverContext(Attr attr, String baseUri, boolean secureValidation) { + this.attr = attr; + this.baseUri = baseUri; + this.secureValidation = secureValidation; + this.uriToResolve = attr != null ? attr.getValue() : null; + } + + public final String uriToResolve; + + public final boolean secureValidation; + + public final String baseUri; + + public final Attr attr; +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java index 5fa9ea35787..cf5c8d12ea2 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java @@ -2,144 +2,137 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils.resolver; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import org.w3c.dom.Attr; - /** * This Exception is thrown if something related to the * {@link com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver} goes wrong. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class ResourceResolverException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; - /** - * Constructor ResourceResolverException - * - * @param _msgID - * @param uri - * @param BaseURI - */ - public ResourceResolverException(String _msgID, Attr uri, String BaseURI) { + private static final long serialVersionUID = 1L; - super(_msgID); + private Attr uri = null; - this._uri = uri; - this._BaseURI = BaseURI; - } + private String baseURI = null; - /** - * Constructor ResourceResolverException - * - * @param _msgID - * @param exArgs - * @param uri - * @param BaseURI - */ - public ResourceResolverException(String _msgID, Object exArgs[], Attr uri, - String BaseURI) { + /** + * Constructor ResourceResolverException + * + * @param msgID + * @param uri + * @param baseURI + */ + public ResourceResolverException(String msgID, Attr uri, String baseURI) { + super(msgID); - super(_msgID, exArgs); + this.uri = uri; + this.baseURI = baseURI; + } - this._uri = uri; - this._BaseURI = BaseURI; - } + /** + * Constructor ResourceResolverException + * + * @param msgID + * @param exArgs + * @param uri + * @param baseURI + */ + public ResourceResolverException(String msgID, Object exArgs[], Attr uri, + String baseURI) { + super(msgID, exArgs); - /** - * Constructor ResourceResolverException - * - * @param _msgID - * @param _originalException - * @param uri - * @param BaseURI - */ - public ResourceResolverException(String _msgID, Exception _originalException, - Attr uri, String BaseURI) { + this.uri = uri; + this.baseURI = baseURI; + } - super(_msgID, _originalException); + /** + * Constructor ResourceResolverException + * + * @param msgID + * @param originalException + * @param uri + * @param baseURI + */ + public ResourceResolverException(String msgID, Exception originalException, + Attr uri, String baseURI) { + super(msgID, originalException); - this._uri = uri; - this._BaseURI = BaseURI; - } + this.uri = uri; + this.baseURI = baseURI; + } - /** - * Constructor ResourceResolverException - * - * @param _msgID - * @param exArgs - * @param _originalException - * @param uri - * @param BaseURI - */ - public ResourceResolverException(String _msgID, Object exArgs[], - Exception _originalException, Attr uri, - String BaseURI) { + /** + * Constructor ResourceResolverException + * + * @param msgID + * @param exArgs + * @param originalException + * @param uri + * @param baseURI + */ + public ResourceResolverException(String msgID, Object exArgs[], + Exception originalException, Attr uri, + String baseURI) { + super(msgID, exArgs, originalException); - super(_msgID, exArgs, _originalException); + this.uri = uri; + this.baseURI = baseURI; + } - this._uri = uri; - this._BaseURI = BaseURI; - } + /** + * + * @param uri + */ + public void setURI(Attr uri) { + this.uri = uri; + } - //J- - Attr _uri = null; - /** - * - * @param uri - */ - public void setURI(Attr uri) { - this._uri = uri; - } + /** + * + * @return the uri + */ + public Attr getURI() { + return this.uri; + } - /** - * - * @return the uri - */ - public Attr getURI() { - return this._uri; - } + /** + * + * @param baseURI + */ + public void setbaseURI(String baseURI) { + this.baseURI = baseURI; + } - String _BaseURI; + /** + * + * @return the baseURI + */ + public String getbaseURI() { + return this.baseURI; + } - /** - * - * @param BaseURI - */ - public void setBaseURI(String BaseURI) { - this._BaseURI = BaseURI; - } - - /** - * - * @return the basUri - */ - public String getBaseURI() { - return this._BaseURI; - } - //J+ } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java index e9ba6d13171..0ca4523600d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java @@ -2,192 +2,239 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils.resolver; - import java.util.HashMap; import java.util.Map; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import org.w3c.dom.Attr; - /** * During reference validation, we have to retrieve resources from somewhere. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public abstract class ResourceResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - ResourceResolverSpi.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ResourceResolverSpi.class.getName()); - /** Field _properties */ - protected java.util.Map _properties = null; + /** Field properties */ + protected java.util.Map properties = null; - protected boolean secureValidation; + /** + * Deprecated - used to carry state about whether resolution was being done in a secure fashion, + * but was not thread safe, so the resolution information is now passed as parameters to methods. + * + * @deprecated Secure validation flag is now passed to methods. + */ + @Deprecated + protected final boolean secureValidation = true; - /** - * This is the workhorse method used to resolve resources. - * - * @param uri - * @param BaseURI - * @return the resource wrapped arround a XMLSignatureInput - * - * @throws ResourceResolverException - */ - public abstract XMLSignatureInput engineResolve(Attr uri, String BaseURI) - throws ResourceResolverException; + /** + * This is the workhorse method used to resolve resources. + * + * @param uri + * @param BaseURI + * @return the resource wrapped around a XMLSignatureInput + * + * @throws ResourceResolverException + * + * @deprecated New clients should override {@link #engineResolveURI(ResourceResolverContext)} + */ + @Deprecated + public XMLSignatureInput engineResolve(Attr uri, String BaseURI) + throws ResourceResolverException { + throw new UnsupportedOperationException(); + } - /** - * Method engineSetProperty - * - * @param key - * @param value - */ - public void engineSetProperty(String key, String value) { - if (_properties==null) { - _properties=new HashMap(); - } - this._properties.put(key, value); - } + /** + * This is the workhorse method used to resolve resources. + * @param context Context to use to resolve resources. + * + * @return the resource wrapped around a XMLSignatureInput + * + * @throws ResourceResolverException + */ + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) + throws ResourceResolverException { + // The default implementation, to preserve backwards compatibility in the + // test cases, calls the old resolver API. + return engineResolve(context.attr, context.baseUri); + } - /** - * Method engineGetProperty - * - * @param key - * @return the value of the property - */ - public String engineGetProperty(String key) { - if (_properties==null) { - return null; - } - return this._properties.get(key); - } + /** + * Method engineSetProperty + * + * @param key + * @param value + */ + public void engineSetProperty(String key, String value) { + if (properties == null) { + properties = new HashMap(); + } + properties.put(key, value); + } - /** - * - * @param properties - */ - public void engineAddProperies(Map properties) { - if (properties!=null) { - if (_properties==null) { - _properties=new HashMap(); - } - this._properties.putAll(properties); - } - } - /** - * Tells if the implementation does can be reused by several threads safely. - * It normally means that the implemantation does not have any member, or there is - * member change betwen engineCanResolve & engineResolve invocations. Or it mantians all - * member info in ThreadLocal methods. - */ - public boolean engineIsThreadSafe() { - return false; - } - /** - * This method helps the {@link ResourceResolver} to decide whether a - * {@link ResourceResolverSpi} is able to perform the requested action. - * - * @param uri - * @param BaseURI - * @return true if the engine can resolve the uri - */ - public abstract boolean engineCanResolve(Attr uri, String BaseURI); + /** + * Method engineGetProperty + * + * @param key + * @return the value of the property + */ + public String engineGetProperty(String key) { + if (properties == null) { + return null; + } + return properties.get(key); + } - /** - * Method engineGetPropertyKeys - * - * @return the property keys - */ - public String[] engineGetPropertyKeys() { - return new String[0]; - } - - /** - * Method understandsProperty - * - * @param propertyToTest - * @return true if understands the property - */ - public boolean understandsProperty(String propertyToTest) { - - String[] understood = this.engineGetPropertyKeys(); - - if (understood != null) { - for (int i = 0; i < understood.length; i++) { - if (understood[i].equals(propertyToTest)) { - return true; + /** + * + * @param newProperties + */ + public void engineAddProperies(Map newProperties) { + if (newProperties != null && !newProperties.isEmpty()) { + if (properties == null) { + properties = new HashMap(); } - } - } + properties.putAll(newProperties); + } + } - return false; - } + /** + * Tells if the implementation does can be reused by several threads safely. + * It normally means that the implementation does not have any member, or there is + * member change between engineCanResolve & engineResolve invocations. Or it maintains all + * member info in ThreadLocal methods. + */ + public boolean engineIsThreadSafe() { + return false; + } + + /** + * This method helps the {@link ResourceResolver} to decide whether a + * {@link ResourceResolverSpi} is able to perform the requested action. + * + * @param uri + * @param BaseURI + * @return true if the engine can resolve the uri + * + * @deprecated See {@link #engineCanResolveURI(ResourceResolverContext)} + */ + @Deprecated + public boolean engineCanResolve(Attr uri, String BaseURI) { + // This method used to be abstract, so any calls to "super" are bogus. + throw new UnsupportedOperationException(); + } + + /** + * This method helps the {@link ResourceResolver} to decide whether a + * {@link ResourceResolverSpi} is able to perform the requested action. + * + *

    New clients should override this method, and not override {@link #engineCanResolve(Attr, String)} + *

    + * @param context Context in which to do resolution. + * @return true if the engine can resolve the uri + */ + public boolean engineCanResolveURI(ResourceResolverContext context) { + // To preserve backward compatibility with existing resolvers that might override the old method, + // call the old deprecated API. + return engineCanResolve( context.attr, context.baseUri ); + } + + /** + * Method engineGetPropertyKeys + * + * @return the property keys + */ + public String[] engineGetPropertyKeys() { + return new String[0]; + } + + /** + * Method understandsProperty + * + * @param propertyToTest + * @return true if understands the property + */ + public boolean understandsProperty(String propertyToTest) { + String[] understood = this.engineGetPropertyKeys(); + + if (understood != null) { + for (int i = 0; i < understood.length; i++) { + if (understood[i].equals(propertyToTest)) { + return true; + } + } + } + + return false; + } - /** - * Fixes a platform dependent filename to standard URI form. - * - * @param str The string to fix. - * - * @return Returns the fixed URI string. - */ - public static String fixURI(String str) { + /** + * Fixes a platform dependent filename to standard URI form. + * + * @param str The string to fix. + * + * @return Returns the fixed URI string. + */ + public static String fixURI(String str) { - // handle platform dependent strings - str = str.replace(java.io.File.separatorChar, '/'); + // handle platform dependent strings + str = str.replace(java.io.File.separatorChar, '/'); - if (str.length() >= 4) { + if (str.length() >= 4) { - // str =~ /^\W:\/([^/])/ # to speak perl ;-)) - char ch0 = Character.toUpperCase(str.charAt(0)); - char ch1 = str.charAt(1); - char ch2 = str.charAt(2); - char ch3 = str.charAt(3); - boolean isDosFilename = ((('A' <= ch0) && (ch0 <= 'Z')) - && (ch1 == ':') && (ch2 == '/') - && (ch3 != '/')); - - if (isDosFilename) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Found DOS filename: " + str); - } - } - - // Windows fix - if (str.length() >= 2) { - char ch1 = str.charAt(1); - - if (ch1 == ':') { + // str =~ /^\W:\/([^/])/ # to speak perl ;-)) char ch0 = Character.toUpperCase(str.charAt(0)); + char ch1 = str.charAt(1); + char ch2 = str.charAt(2); + char ch3 = str.charAt(3); + boolean isDosFilename = ((('A' <= ch0) && (ch0 <= 'Z')) + && (ch1 == ':') && (ch2 == '/') + && (ch3 != '/')); - if (('A' <= ch0) && (ch0 <= 'Z')) { - str = "/" + str; + if (isDosFilename && log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found DOS filename: " + str); } - } - } + } - // done - return str; - } + // Windows fix + if (str.length() >= 2) { + char ch1 = str.charAt(1); + + if (ch1 == ':') { + char ch0 = Character.toUpperCase(str.charAt(0)); + + if (('A' <= ch0) && (ch0 <= 'Z')) { + str = "/" + str; + } + } + } + + // done + return str; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java index 0bd0c59120b..22aba4083b8 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils.resolver.implementations; @@ -27,51 +29,56 @@ import java.io.IOException; import java.io.InputStream; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; -import org.w3c.dom.Attr; /** - * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ - public class ResolverAnonymous extends ResourceResolverSpi { - private XMLSignatureInput _input = null; + private InputStream inStream = null; - /** - * @param filename + @Override + public boolean engineIsThreadSafe() { + return true; + } + + /** + * @param filename * @throws FileNotFoundException * @throws IOException */ - public ResolverAnonymous(String filename) throws FileNotFoundException, IOException { - this._input = new XMLSignatureInput(new FileInputStream(filename)); - } + public ResolverAnonymous(String filename) throws FileNotFoundException, IOException { + inStream = new FileInputStream(filename); + } - /** - * @param is + /** + * @param is */ - public ResolverAnonymous(InputStream is) { - this._input = new XMLSignatureInput(is); - } + public ResolverAnonymous(InputStream is) { + inStream = is; + } - /** @inheritDoc */ - public XMLSignatureInput engineResolve(Attr uri, String BaseURI) { - return this._input; - } + /** @inheritDoc */ + @Override + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) { + return new XMLSignatureInput(inStream); + } - /** - * @inheritDoc - */ - public boolean engineCanResolve(Attr uri, String BaseURI) { - if (uri == null) { - return true; - } - return false; - } + /** + * @inheritDoc + */ + @Override + public boolean engineCanResolveURI(ResourceResolverContext context) { + if (context.uriToResolve == null) { + return true; + } + return false; + } - /** @inheritDoc */ - public String[] engineGetPropertyKeys() { - return new String[0]; - } + /** @inheritDoc */ + public String[] engineGetPropertyKeys() { + return new String[0]; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java index 706cccc6a4d..cd0967215a7 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java @@ -2,38 +2,42 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils.resolver.implementations; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import java.net.InetSocketAddress; import java.net.MalformedURLException; +import java.net.Proxy; +import java.net.URISyntaxException; +import java.net.URI; import java.net.URL; import java.net.URLConnection; -import com.sun.org.apache.xml.internal.utils.URI; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.utils.Base64; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; -import org.w3c.dom.Attr; - /** * A simple ResourceResolver for HTTP requests. This class handles only 'pure' @@ -51,253 +55,219 @@ import org.w3c.dom.Attr; * resourceResolver.setProperty("http.proxy.password", "secretca"); *
    * - * - * @author $Author: mullan $ * @see Java Tip 42: Write Java apps that work with proxy-based firewalls * @see SUN J2SE docs for network properties * @see The JAVA FAQ Question 9.5: How do I make Java work with a proxy server? - * $todo$ the proxy behaviour seems not to work; if a on-existing proxy is set, it works ?!? */ public class ResolverDirectHTTP extends ResourceResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - ResolverDirectHTTP.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ResolverDirectHTTP.class.getName()); - /** Field properties[] */ - private static final String properties[] = - { "http.proxy.host", "http.proxy.port", - "http.proxy.username", - "http.proxy.password", - "http.basic.username", - "http.basic.password" }; + /** Field properties[] */ + private static final String properties[] = { + "http.proxy.host", "http.proxy.port", + "http.proxy.username", "http.proxy.password", + "http.basic.username", "http.basic.password" + }; - /** Field HttpProxyHost */ - private static final int HttpProxyHost = 0; + /** Field HttpProxyHost */ + private static final int HttpProxyHost = 0; - /** Field HttpProxyPort */ - private static final int HttpProxyPort = 1; + /** Field HttpProxyPort */ + private static final int HttpProxyPort = 1; - /** Field HttpProxyUser */ - private static final int HttpProxyUser = 2; + /** Field HttpProxyUser */ + private static final int HttpProxyUser = 2; - /** Field HttpProxyPass */ - private static final int HttpProxyPass = 3; + /** Field HttpProxyPass */ + private static final int HttpProxyPass = 3; - /** Field HttpProxyUser */ - private static final int HttpBasicUser = 4; + /** Field HttpProxyUser */ + private static final int HttpBasicUser = 4; - /** Field HttpProxyPass */ - private static final int HttpBasicPass = 5; + /** Field HttpProxyPass */ + private static final int HttpBasicPass = 5; - public boolean engineIsThreadSafe() { - return true; - } - /** - * Method resolve - * - * @param uri - * @param BaseURI - * - * @throws ResourceResolverException - * @return - * $todo$ calculate the correct URI from the attribute and the BaseURI - */ - public XMLSignatureInput engineResolve(Attr uri, String BaseURI) - throws ResourceResolverException { + @Override + public boolean engineIsThreadSafe() { + return true; + } - try { - boolean useProxy = false; - String proxyHost = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpProxyHost]); - String proxyPort = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpProxyPort]); + /** + * Method resolve + * + * @param uri + * @param baseURI + * + * @throws ResourceResolverException + * @return + * $todo$ calculate the correct URI from the attribute and the baseURI + */ + @Override + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) + throws ResourceResolverException { + try { - if ((proxyHost != null) && (proxyPort != null)) { - useProxy = true; - } - - String oldProxySet = null; - String oldProxyHost = null; - String oldProxyPort = null; - // switch on proxy usage - if (useProxy) { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Use of HTTP proxy enabled: " + proxyHost + ":" - + proxyPort); - } - oldProxySet = System.getProperty("http.proxySet"); - oldProxyHost = System.getProperty("http.proxyHost"); - oldProxyPort = System.getProperty("http.proxyPort"); - System.setProperty("http.proxySet", "true"); - System.setProperty("http.proxyHost", proxyHost); - System.setProperty("http.proxyPort", proxyPort); - } - - boolean switchBackProxy = ((oldProxySet != null) - && (oldProxyHost != null) - && (oldProxyPort != null)); - - // calculate new URI - URI uriNew = getNewURI(uri.getNodeValue(), BaseURI); - - // if the URI contains a fragment, ignore it - URI uriNewNoFrag = new URI(uriNew); - - uriNewNoFrag.setFragment(null); - - URL url = new URL(uriNewNoFrag.toString()); - URLConnection urlConnection = url.openConnection(); - - { - - // set proxy pass - String proxyUser = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpProxyUser]); - String proxyPass = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpProxyPass]); - - if ((proxyUser != null) && (proxyPass != null)) { - String password = proxyUser + ":" + proxyPass; - String encodedPassword = Base64.encode(password.getBytes()); - - // or was it Proxy-Authenticate ? - urlConnection.setRequestProperty("Proxy-Authorization", - encodedPassword); - } - } - - { + // calculate new URI + URI uriNew = getNewURI(context.uriToResolve, context.baseUri); + URL url = uriNew.toURL(); + URLConnection urlConnection; + urlConnection = openConnection(url); // check if Basic authentication is required String auth = urlConnection.getHeaderField("WWW-Authenticate"); - if (auth != null) { + if (auth != null && auth.startsWith("Basic")) { + // do http basic authentication + String user = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpBasicUser]); + String pass = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpBasicPass]); - // do http basic authentication - if (auth.startsWith("Basic")) { - String user = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpBasicUser]); - String pass = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpBasicPass]); + if ((user != null) && (pass != null)) { + urlConnection = openConnection(url); - if ((user != null) && (pass != null)) { - urlConnection = url.openConnection(); + String password = user + ":" + pass; + String encodedPassword = Base64.encode(password.getBytes("ISO-8859-1")); - String password = user + ":" + pass; - String encodedPassword = - Base64.encode(password.getBytes()); - - // set authentication property in the http header - urlConnection.setRequestProperty("Authorization", - "Basic " - + encodedPassword); - } - } + // set authentication property in the http header + urlConnection.setRequestProperty("Authorization", + "Basic " + encodedPassword); + } } - } - String mimeType = urlConnection.getHeaderField("Content-Type"); - InputStream inputStream = urlConnection.getInputStream(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - byte buf[] = new byte[4096]; - int read = 0; - int summarized = 0; + String mimeType = urlConnection.getHeaderField("Content-Type"); + InputStream inputStream = urlConnection.getInputStream(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte buf[] = new byte[4096]; + int read = 0; + int summarized = 0; - while ((read = inputStream.read(buf)) >= 0) { - baos.write(buf, 0, read); + while ((read = inputStream.read(buf)) >= 0) { + baos.write(buf, 0, read); + summarized += read; + } - summarized += read; - } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Fetched " + summarized + " bytes from URI " + uriNew.toString()); + } - log.log(java.util.logging.Level.FINE, "Fetched " + summarized + " bytes from URI " - + uriNew.toString()); + XMLSignatureInput result = new XMLSignatureInput(baos.toByteArray()); - XMLSignatureInput result = new XMLSignatureInput(baos.toByteArray()); + result.setSourceURI(uriNew.toString()); + result.setMIMEType(mimeType); - // XMLSignatureInput result = new XMLSignatureInput(inputStream); - result.setSourceURI(uriNew.toString()); - result.setMIMEType(mimeType); + return result; + } catch (URISyntaxException ex) { + throw new ResourceResolverException("generic.EmptyMessage", ex, context.attr, context.baseUri); + } catch (MalformedURLException ex) { + throw new ResourceResolverException("generic.EmptyMessage", ex, context.attr, context.baseUri); + } catch (IOException ex) { + throw new ResourceResolverException("generic.EmptyMessage", ex, context.attr, context.baseUri); + } catch (IllegalArgumentException e) { + throw new ResourceResolverException("generic.EmptyMessage", e, context.attr, context.baseUri); + } + } - // switch off proxy usage - if (useProxy && switchBackProxy) { - System.setProperty("http.proxySet", oldProxySet); - System.setProperty("http.proxyHost", oldProxyHost); - System.setProperty("http.proxyPort", oldProxyPort); - } + private URLConnection openConnection(URL url) throws IOException { - return result; - } catch (MalformedURLException ex) { - throw new ResourceResolverException("generic.EmptyMessage", ex, uri, - BaseURI); - } catch (IOException ex) { - throw new ResourceResolverException("generic.EmptyMessage", ex, uri, - BaseURI); - } - } + String proxyHostProp = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyHost]); + String proxyPortProp = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyPort]); + String proxyUser = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyUser]); + String proxyPass = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyPass]); - /** - * We resolve http URIs without fragment... - * - * @param uri - * @param BaseURI - * @return true if can be resolved - */ - public boolean engineCanResolve(Attr uri, String BaseURI) { - if (uri == null) { - log.log(java.util.logging.Level.FINE, "quick fail, uri == null"); + Proxy proxy = null; + if ((proxyHostProp != null) && (proxyPortProp != null)) { + int port = Integer.parseInt(proxyPortProp); + proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHostProp, port)); + } - return false; - } + URLConnection urlConnection; + if (proxy != null) { + urlConnection = url.openConnection(proxy); - String uriNodeValue = uri.getNodeValue(); + if ((proxyUser != null) && (proxyPass != null)) { + String password = proxyUser + ":" + proxyPass; + String authString = "Basic " + Base64.encode(password.getBytes("ISO-8859-1")); - if (uriNodeValue.equals("") || (uriNodeValue.charAt(0)=='#')) { - log.log(java.util.logging.Level.FINE, "quick fail for empty URIs and local ones"); + urlConnection.setRequestProperty("Proxy-Authorization", authString); + } + } else { + urlConnection = url.openConnection(); + } - return false; - } + return urlConnection; + } - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + uriNodeValue); - } + /** + * We resolve http URIs without fragment... + * + * @param uri + * @param baseURI + * @return true if can be resolved + */ + public boolean engineCanResolveURI(ResourceResolverContext context) { + if (context.uriToResolve == null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "quick fail, uri == null"); + } + return false; + } - if ( uriNodeValue.startsWith("http:") || - (BaseURI!=null && BaseURI.startsWith("http:") )) { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "I state that I can resolve " + uriNodeValue); - } + if (context.uriToResolve.equals("") || (context.uriToResolve.charAt(0)=='#')) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "quick fail for empty URIs and local ones"); + } + return false; + } - return true; - } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + context.uriToResolve); + } - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "I state that I can't resolve " + uriNodeValue); - } + if (context.uriToResolve.startsWith("http:") || + (context.baseUri != null && context.baseUri.startsWith("http:") )) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I state that I can resolve " + context.uriToResolve); + } + return true; + } - return false; - } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I state that I can't resolve " + context.uriToResolve); + } - /** - * @inheritDoc - */ - public String[] engineGetPropertyKeys() { - return ResolverDirectHTTP.properties.clone(); - } + return false; + } - private URI getNewURI(String uri, String BaseURI) - throws URI.MalformedURIException { + /** + * @inheritDoc + */ + public String[] engineGetPropertyKeys() { + return ResolverDirectHTTP.properties.clone(); + } + + private static URI getNewURI(String uri, String baseURI) throws URISyntaxException { + URI newUri = null; + if (baseURI == null || "".equals(baseURI)) { + newUri = new URI(uri); + } else { + newUri = new URI(baseURI).resolve(uri); + } + + // if the URI contains a fragment, ignore it + if (newUri.getFragment() != null) { + URI uriNewNoFrag = + new URI(newUri.getScheme(), newUri.getSchemeSpecificPart(), null); + return uriNewNoFrag; + } + return newUri; + } - if ((BaseURI == null) || "".equals(BaseURI)) { - return new URI(uri); - } - return new URI(new URI(BaseURI), uri); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java index d2750c84903..49eb0407382 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java @@ -2,148 +2,148 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils.resolver.implementations; - - import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; -import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; - /** * This resolver is used for resolving same-document URIs like URI="" of URI="#id". * - * @author $Author: mullan $ + * @author $Author: coheigea $ * @see The Reference processing model in the XML Signature spec * @see Same-Document URI-References in the XML Signature spec * @see Section 4.2 of RFC 2396 */ public class ResolverFragment extends ResourceResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - ResolverFragment.class.getName()); - public boolean engineIsThreadSafe() { - return true; - } - /** - * Method engineResolve - * - * @inheritDoc - * @param uri - * @param baseURI - */ - public XMLSignatureInput engineResolve(Attr uri, String baseURI) - throws ResourceResolverException - { - String uriNodeValue = uri.getNodeValue(); - Document doc = uri.getOwnerElement().getOwnerDocument(); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ResolverFragment.class.getName()); + + @Override + public boolean engineIsThreadSafe() { + return true; + } + + /** + * Method engineResolve + * + * @inheritDoc + * @param uri + * @param baseURI + */ + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) + throws ResourceResolverException { + + Document doc = context.attr.getOwnerElement().getOwnerDocument(); Node selectedElem = null; - if (uriNodeValue.equals("")) { - - /* - * Identifies the node-set (minus any comment nodes) of the XML - * resource containing the signature - */ - - log.log(java.util.logging.Level.FINE, "ResolverFragment with empty URI (means complete document)"); + if (context.uriToResolve.equals("")) { + /* + * Identifies the node-set (minus any comment nodes) of the XML + * resource containing the signature + */ + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "ResolverFragment with empty URI (means complete document)"); + } selectedElem = doc; } else { - /* * URI="#chapter1" * Identifies a node-set containing the element with ID attribute * value 'chapter1' of the XML resource containing the signature. * XML Signature (and its applications) modify this node-set to - * include the element plus all descendents including namespaces and + * include the element plus all descendants including namespaces and * attributes -- but not comments. */ - String id = uriNodeValue.substring(1); + String id = context.uriToResolve.substring(1); selectedElem = doc.getElementById(id); if (selectedElem == null) { Object exArgs[] = { id }; throw new ResourceResolverException( - "signature.Verification.MissingID", exArgs, uri, baseURI); + "signature.Verification.MissingID", exArgs, context.attr, context.baseUri + ); } - if (secureValidation) { - Element start = uri.getOwnerDocument().getDocumentElement(); + if (context.secureValidation) { + Element start = context.attr.getOwnerDocument().getDocumentElement(); if (!XMLUtils.protectAgainstWrappingAttack(start, id)) { Object exArgs[] = { id }; throw new ResourceResolverException( - "signature.Verification.MultipleIDs", exArgs, - uri, baseURI); + "signature.Verification.MultipleIDs", exArgs, context.attr, context.baseUri + ); } } - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Try to catch an Element with ID " + id + " and Element was " + selectedElem); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, + "Try to catch an Element with ID " + id + " and Element was " + selectedElem + ); + } } XMLSignatureInput result = new XMLSignatureInput(selectedElem); result.setExcludeComments(true); result.setMIMEType("text/xml"); - if (baseURI != null && baseURI.length() > 0) { - result.setSourceURI(baseURI.concat(uri.getNodeValue())); + if (context.baseUri != null && context.baseUri.length() > 0) { + result.setSourceURI(context.baseUri.concat(context.uriToResolve)); } else { - result.setSourceURI(uri.getNodeValue()); + result.setSourceURI(context.uriToResolve); } return result; } - /** - * Method engineCanResolve - * @inheritDoc - * @param uri - * @param BaseURI - * - */ - public boolean engineCanResolve(Attr uri, String BaseURI) { + /** + * Method engineCanResolve + * @inheritDoc + * @param uri + * @param baseURI + */ + public boolean engineCanResolveURI(ResourceResolverContext context) { + if (context.uriToResolve == null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Quick fail for null uri"); + } + return false; + } - if (uri == null) { - log.log(java.util.logging.Level.FINE, "Quick fail for null uri"); - return false; - } - - String uriNodeValue = uri.getNodeValue(); - - if (uriNodeValue.equals("") || - ( - (uriNodeValue.charAt(0)=='#') - && !((uriNodeValue.charAt(1)=='x') && uriNodeValue.startsWith("#xpointer(")) - ) - ){ - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "State I can resolve reference: \"" + uriNodeValue + "\""); - return true; - } - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Do not seem to be able to resolve reference: \"" + uriNodeValue + "\""); - return false; - } + if (context.uriToResolve.equals("") || + ((context.uriToResolve.charAt(0) == '#') && !context.uriToResolve.startsWith("#xpointer(")) + ) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "State I can resolve reference: \"" + context.uriToResolve + "\""); + } + return true; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Do not seem to be able to resolve reference: \"" + context.uriToResolve + "\""); + } + return false; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java index 07af53db296..c526286462d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java @@ -2,156 +2,160 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils.resolver.implementations; import java.io.FileInputStream; +import java.net.URI; +import java.net.URISyntaxException; -import com.sun.org.apache.xml.internal.utils.URI; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; -import org.w3c.dom.Attr; /** * A simple ResourceResolver for requests into the local filesystem. - * - * @author $Author: mullan $ */ public class ResolverLocalFilesystem extends ResourceResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - ResolverLocalFilesystem.class.getName()); + private static final int FILE_URI_LENGTH = "file:/".length(); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ResolverLocalFilesystem.class.getName()); + + @Override public boolean engineIsThreadSafe() { - return true; - } - /** - * @inheritDoc - */ - public XMLSignatureInput engineResolve(Attr uri, String BaseURI) - throws ResourceResolverException { + return true; + } - try { - URI uriNew = getNewURI(uri.getNodeValue(), BaseURI); + /** + * @inheritDoc + */ + @Override + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) + throws ResourceResolverException { + try { + // calculate new URI + URI uriNew = getNewURI(context.uriToResolve, context.baseUri); + + String fileName = + ResolverLocalFilesystem.translateUriToFilename(uriNew.toString()); + FileInputStream inputStream = new FileInputStream(fileName); + XMLSignatureInput result = new XMLSignatureInput(inputStream); + + result.setSourceURI(uriNew.toString()); + + return result; + } catch (Exception e) { + throw new ResourceResolverException("generic.EmptyMessage", e, context.attr, context.baseUri); + } + } + + /** + * Method translateUriToFilename + * + * @param uri + * @return the string of the filename + */ + private static String translateUriToFilename(String uri) { + + String subStr = uri.substring(FILE_URI_LENGTH); + + if (subStr.indexOf("%20") > -1) { + int offset = 0; + int index = 0; + StringBuilder temp = new StringBuilder(subStr.length()); + do { + index = subStr.indexOf("%20",offset); + if (index == -1) { + temp.append(subStr.substring(offset)); + } else { + temp.append(subStr.substring(offset, index)); + temp.append(' '); + offset = index + 3; + } + } while(index != -1); + subStr = temp.toString(); + } + + if (subStr.charAt(1) == ':') { + // we're running M$ Windows, so this works fine + return subStr; + } + // we're running some UNIX, so we have to prepend a slash + return "/" + subStr; + } + + /** + * @inheritDoc + */ + public boolean engineCanResolveURI(ResourceResolverContext context) { + if (context.uriToResolve == null) { + return false; + } + + if (context.uriToResolve.equals("") || (context.uriToResolve.charAt(0)=='#') || + context.uriToResolve.startsWith("http:")) { + return false; + } + + try { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + context.uriToResolve); + } + + if (context.uriToResolve.startsWith("file:") || context.baseUri.startsWith("file:")) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I state that I can resolve " + context.uriToResolve); + } + return true; + } + } catch (Exception e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + } + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "But I can't"); + } + + return false; + } + + private static URI getNewURI(String uri, String baseURI) throws URISyntaxException { + URI newUri = null; + if (baseURI == null || "".equals(baseURI)) { + newUri = new URI(uri); + } else { + newUri = new URI(baseURI).resolve(uri); + } // if the URI contains a fragment, ignore it - URI uriNewNoFrag = new URI(uriNew); - - uriNewNoFrag.setFragment(null); - - String fileName = - ResolverLocalFilesystem - .translateUriToFilename(uriNewNoFrag.toString()); - FileInputStream inputStream = new FileInputStream(fileName); - XMLSignatureInput result = new XMLSignatureInput(inputStream); - - result.setSourceURI(uriNew.toString()); - - return result; - } catch (Exception e) { - throw new ResourceResolverException("generic.EmptyMessage", e, uri, - BaseURI); - } - } - - private static int FILE_URI_LENGTH="file:/".length(); - /** - * Method translateUriToFilename - * - * @param uri - * @return the string of the filename - */ - private static String translateUriToFilename(String uri) { - - String subStr = uri.substring(FILE_URI_LENGTH); - - if (subStr.indexOf("%20") > -1) - { - int offset = 0; - int index = 0; - StringBuffer temp = new StringBuffer(subStr.length()); - do - { - index = subStr.indexOf("%20",offset); - if (index == -1) temp.append(subStr.substring(offset)); - else - { - temp.append(subStr.substring(offset,index)); - temp.append(' '); - offset = index+3; - } + if (newUri.getFragment() != null) { + URI uriNewNoFrag = + new URI(newUri.getScheme(), newUri.getSchemeSpecificPart(), null); + return uriNewNoFrag; } - while(index != -1); - subStr = temp.toString(); - } - - if (subStr.charAt(1) == ':') { - // we're running M$ Windows, so this works fine - return subStr; - } - // we're running some UNIX, so we have to prepend a slash - return "/" + subStr; - } - - /** - * @inheritDoc - */ - public boolean engineCanResolve(Attr uri, String BaseURI) { - - if (uri == null) { - return false; - } - - String uriNodeValue = uri.getNodeValue(); - - if (uriNodeValue.equals("") || (uriNodeValue.charAt(0)=='#') || - uriNodeValue.startsWith("http:")) { - return false; - } - - try { - //URI uriNew = new URI(new URI(BaseURI), uri.getNodeValue()); - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + uriNodeValue/*uriNew.toString()*/); - - if ( uriNodeValue.startsWith("file:") || - BaseURI.startsWith("file:")/*uriNew.getScheme().equals("file")*/) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "I state that I can resolve " + uriNodeValue/*uriNew.toString()*/); - - return true; - } - } catch (Exception e) {} - - log.log(java.util.logging.Level.FINE, "But I can't"); - - return false; - } - - private static URI getNewURI(String uri, String BaseURI) - throws URI.MalformedURIException { - - if ((BaseURI == null) || "".equals(BaseURI)) { - return new URI(uri); - } - return new URI(new URI(BaseURI), uri); - } + return newUri; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java index 0f931f44193..345087bbcec 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java @@ -2,36 +2,35 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 * - * 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. + * 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 com.sun.org.apache.xml.internal.security.utils.resolver.implementations; - - import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; -import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; - /** * Handles barename XPointer Reference URIs. *
    @@ -45,15 +44,18 @@ import org.w3c.dom.Node; * nodes of the parse tree (all descendants, plus all attributes, * plus all namespaces nodes). * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class ResolverXPointer extends ResourceResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - ResolverXPointer.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ResolverXPointer.class.getName()); + private static final String XP = "#xpointer(id("; + private static final int XP_LENGTH = XP.length(); + + @Override public boolean engineIsThreadSafe() { return true; } @@ -61,139 +63,118 @@ public class ResolverXPointer extends ResourceResolverSpi { /** * @inheritDoc */ - public XMLSignatureInput engineResolve(Attr uri, String baseURI) - throws ResourceResolverException { + @Override + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) + throws ResourceResolverException { Node resultNode = null; - Document doc = uri.getOwnerElement().getOwnerDocument(); + Document doc = context.attr.getOwnerElement().getOwnerDocument(); - String uriStr = uri.getNodeValue(); - if (isXPointerSlash(uriStr)) { + if (isXPointerSlash(context.uriToResolve)) { resultNode = doc; - - } else if (isXPointerId(uriStr)) { - String id = getXPointerId(uriStr); + } else if (isXPointerId(context.uriToResolve)) { + String id = getXPointerId(context.uriToResolve); resultNode = doc.getElementById(id); - if (secureValidation) { - Element start = uri.getOwnerDocument().getDocumentElement(); + if (context.secureValidation) { + Element start = context.attr.getOwnerDocument().getDocumentElement(); if (!XMLUtils.protectAgainstWrappingAttack(start, id)) { Object exArgs[] = { id }; throw new ResourceResolverException( - "signature.Verification.MultipleIDs", exArgs, - uri, baseURI); + "signature.Verification.MultipleIDs", exArgs, context.attr, context.baseUri + ); } } if (resultNode == null) { - Object exArgs[] = { id }; + Object exArgs[] = { id }; - throw new ResourceResolverException( - "signature.Verification.MissingID", exArgs, uri, baseURI); + throw new ResourceResolverException( + "signature.Verification.MissingID", exArgs, context.attr, context.baseUri + ); } } XMLSignatureInput result = new XMLSignatureInput(resultNode); result.setMIMEType("text/xml"); - if (baseURI != null && baseURI.length() > 0) { - result.setSourceURI(baseURI.concat(uri.getNodeValue())); + if (context.baseUri != null && context.baseUri.length() > 0) { + result.setSourceURI(context.baseUri.concat(context.uriToResolve)); } else { - result.setSourceURI(uri.getNodeValue()); + result.setSourceURI(context.uriToResolve); } return result; } - /** - * @inheritDoc - */ - public boolean engineCanResolve(Attr uri, String BaseURI) { - - if (uri == null) { - return false; - } - String uriStr =uri.getNodeValue(); - if (isXPointerSlash(uriStr) || isXPointerId(uriStr)) { - return true; - } - - return false; - } - - /** - * Method isXPointerSlash - * - * @param uri - * @return true if begins with xpointer - */ - private static boolean isXPointerSlash(String uri) { - - if (uri.equals("#xpointer(/)")) { - return true; - } - - return false; - } - - - private static final String XP="#xpointer(id("; - private static final int XP_LENGTH=XP.length(); - /** - * Method isXPointerId - * - * @param uri - * @return it it has an xpointer id - * - */ - private static boolean isXPointerId(String uri) { - - - if (uri.startsWith(XP) - && uri.endsWith("))")) { - String idPlusDelim = uri.substring(XP_LENGTH, - uri.length() - - 2); - - // log.log(java.util.logging.Level.FINE, "idPlusDelim=" + idPlusDelim); - int idLen=idPlusDelim.length() -1; - if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim - .charAt(idLen) == '"')) || ((idPlusDelim - .charAt(0) == '\'') && (idPlusDelim - .charAt(idLen) == '\''))) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Id=" - + idPlusDelim.substring(1, idLen)); - + /** + * @inheritDoc + */ + public boolean engineCanResolveURI(ResourceResolverContext context) { + if (context.uriToResolve == null) { + return false; + } + if (isXPointerSlash(context.uriToResolve) || isXPointerId(context.uriToResolve)) { return true; - } - } + } - return false; - } + return false; + } - /** - * Method getXPointerId - * - * @param uri - * @return xpointerId to search. - */ - private static String getXPointerId(String uri) { + /** + * Method isXPointerSlash + * + * @param uri + * @return true if begins with xpointer + */ + private static boolean isXPointerSlash(String uri) { + if (uri.equals("#xpointer(/)")) { + return true; + } + return false; + } - if (uri.startsWith(XP) - && uri.endsWith("))")) { - String idPlusDelim = uri.substring(XP_LENGTH,uri.length() - - 2); - int idLen=idPlusDelim.length() -1; - if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim - .charAt(idLen) == '"')) || ((idPlusDelim - .charAt(0) == '\'') && (idPlusDelim - .charAt(idLen) == '\''))) { - return idPlusDelim.substring(1, idLen); - } - } + /** + * Method isXPointerId + * + * @param uri + * @return whether it has an xpointer id + */ + private static boolean isXPointerId(String uri) { + if (uri.startsWith(XP) && uri.endsWith("))")) { + String idPlusDelim = uri.substring(XP_LENGTH, uri.length() - 2); - return null; - } + int idLen = idPlusDelim.length() -1; + if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim.charAt(idLen) == '"')) + || ((idPlusDelim.charAt(0) == '\'') && (idPlusDelim.charAt(idLen) == '\''))) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Id = " + idPlusDelim.substring(1, idLen)); + } + return true; + } + } + + return false; + } + + /** + * Method getXPointerId + * + * @param uri + * @return xpointerId to search. + */ + private static String getXPointerId(String uri) { + if (uri.startsWith(XP) && uri.endsWith("))")) { + String idPlusDelim = uri.substring(XP_LENGTH,uri.length() - 2); + + int idLen = idPlusDelim.length() -1; + if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim.charAt(idLen) == '"')) + || ((idPlusDelim.charAt(0) == '\'') && (idPlusDelim.charAt(idLen) == '\''))) { + return idPlusDelim.substring(1, idLen); + } + } + + return null; + } } diff --git a/jdk/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java b/jdk/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java index 17bab9c9c70..93901d4b41f 100644 --- a/jdk/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java +++ b/jdk/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java @@ -252,13 +252,12 @@ public abstract class AbstractSaslImpl { /** - * Outputs a byte array and converts + * Outputs a byte array. Can be null. */ protected static final void traceOutput(String srcClass, String srcMethod, String traceTag, byte[] output) { - if (output != null) { - traceOutput(srcClass, srcMethod, traceTag, output, 0, output.length); - } + traceOutput(srcClass, srcMethod, traceTag, output, 0, + output == null ? 0 : output.length); } protected static final void traceOutput(String srcClass, String srcMethod, @@ -274,13 +273,20 @@ public abstract class AbstractSaslImpl { lev = Level.FINEST; } - ByteArrayOutputStream out = new ByteArrayOutputStream(len); - new HexDumpEncoder().encodeBuffer( - new ByteArrayInputStream(output, offset, len), out); + String content; + + if (output != null) { + ByteArrayOutputStream out = new ByteArrayOutputStream(len); + new HexDumpEncoder().encodeBuffer( + new ByteArrayInputStream(output, offset, len), out); + content = out.toString(); + } else { + content = "NULL"; + } // Message id supplied by caller as part of traceTag logger.logp(lev, srcClass, srcMethod, "{0} ( {1} ): {2}", - new Object[] {traceTag, new Integer(origlen), out.toString()}); + new Object[] {traceTag, new Integer(origlen), content}); } catch (Exception e) { logger.logp(Level.WARNING, srcClass, srcMethod, "SASLIMPL09:Error generating trace output: {0}", e); diff --git a/jdk/src/share/classes/java/awt/GraphicsDevice.java b/jdk/src/share/classes/java/awt/GraphicsDevice.java index b99d7ef8def..c619a2aee19 100644 --- a/jdk/src/share/classes/java/awt/GraphicsDevice.java +++ b/jdk/src/share/classes/java/awt/GraphicsDevice.java @@ -296,6 +296,12 @@ public abstract class GraphicsDevice { bgColor.getBlue(), 255); w.setBackground(bgColor); } + // Check if this window is in fullscreen mode on another device. + final GraphicsConfiguration gc = w.getGraphicsConfiguration(); + if (gc != null && gc.getDevice() != this + && gc.getDevice().getFullScreenWindow() == w) { + gc.getDevice().setFullScreenWindow(null); + } } if (fullScreenWindow != null && windowedModeBounds != null) { // if the window went into fs mode before it was realized it may diff --git a/jdk/src/share/classes/java/beans/Introspector.java b/jdk/src/share/classes/java/beans/Introspector.java index 65d95eb4e80..783fcbef315 100644 --- a/jdk/src/share/classes/java/beans/Introspector.java +++ b/jdk/src/share/classes/java/beans/Introspector.java @@ -652,11 +652,12 @@ public class Introspector { } } else { if (pd.getReadMethod() != null) { + String pdName = pd.getReadMethod().getName(); if (gpd != null) { // Don't replace the existing read // method if it starts with "is" - Method method = gpd.getReadMethod(); - if (!method.getName().startsWith(IS_PREFIX)) { + String gpdName = gpd.getReadMethod().getName(); + if (gpdName.equals(pdName) || !gpdName.startsWith(IS_PREFIX)) { gpd = new PropertyDescriptor(gpd, pd); } } else { diff --git a/jdk/src/share/classes/java/io/BufferedReader.java b/jdk/src/share/classes/java/io/BufferedReader.java index ebf398078bf..98fe47c7a59 100644 --- a/jdk/src/share/classes/java/io/BufferedReader.java +++ b/jdk/src/share/classes/java/io/BufferedReader.java @@ -587,6 +587,6 @@ public class BufferedReader extends Reader { } } }; - return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iter, Spliterator.ORDERED)); + return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iter, Spliterator.ORDERED), false); } } diff --git a/jdk/src/share/classes/java/io/DataInput.java b/jdk/src/share/classes/java/io/DataInput.java index 1480c9f0485..4dad59d55f3 100644 --- a/jdk/src/share/classes/java/io/DataInput.java +++ b/jdk/src/share/classes/java/io/DataInput.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -66,10 +66,10 @@ package java.io; * summary="Bit values and bytes"> * * - * Bit Values + * Bit Values * * - * Byte 1 + * Byte 1 * * * @@ -92,10 +92,10 @@ package java.io; * summary="Bit values and bytes"> * * - * + * * * - * + * *
    Bit ValuesBit Values
    Byte 1Byte 1 * * @@ -108,7 +108,7 @@ package java.io; * * * - * + * *
    Byte 2Byte 2 * * @@ -131,10 +131,10 @@ package java.io; * summary="Bit values and bytes"> * * - * + * * * - * + * *
    Bit ValuesBit Values
    Byte 1Byte 1 * * @@ -148,7 +148,7 @@ package java.io; * * * - * + * *
    Byte 2Byte 2 * * diff --git a/jdk/src/share/classes/java/io/File.java b/jdk/src/share/classes/java/io/File.java index 4bc75fe5099..6bab9bb21fe 100644 --- a/jdk/src/share/classes/java/io/File.java +++ b/jdk/src/share/classes/java/io/File.java @@ -1910,7 +1910,7 @@ public class File } String name = prefix + Long.toString(n) + suffix; File f = new File(dir, name); - if (!name.equals(f.getName())) + if (!name.equals(f.getName()) || f.isInvalid()) throw new IOException("Unable to create temporary file"); return f; } @@ -1996,19 +1996,26 @@ public class File File tmpdir = (directory != null) ? directory : TempDirectory.location(); + SecurityManager sm = System.getSecurityManager(); File f; - try { - do { - f = TempDirectory.generateFile(prefix, suffix, tmpdir); - } while (f.exists()); - if (!f.createNewFile()) - throw new IOException("Unable to create temporary file"); - } catch (SecurityException se) { - // don't reveal temporary directory location - if (directory == null) - throw new SecurityException("Unable to create temporary file"); - throw se; - } + do { + f = TempDirectory.generateFile(prefix, suffix, tmpdir); + + if (sm != null) { + try { + sm.checkWrite(f.getPath()); + } catch (SecurityException se) { + // don't reveal temporary directory location + if (directory == null) + throw new SecurityException("Unable to create temporary file"); + throw se; + } + } + } while ((fs.getBooleanAttributes(f) & FileSystem.BA_EXISTS) != 0); + + if (!fs.createFileExclusively(f.getPath())) + throw new IOException("Unable to create temporary file"); + return f; } diff --git a/jdk/src/share/classes/java/io/FileInputStream.java b/jdk/src/share/classes/java/io/FileInputStream.java index 90d1ad5cc3e..3e67fb85515 100644 --- a/jdk/src/share/classes/java/io/FileInputStream.java +++ b/jdk/src/share/classes/java/io/FileInputStream.java @@ -331,7 +331,7 @@ class FileInputStream extends InputStream * object associated with this file input stream. * *

    The initial {@link java.nio.channels.FileChannel#position() - * position} of the returned channel will be equal to the + * position} of the returned channel will be equal to the * number of bytes read from the file so far. Reading bytes from this * stream will increment the channel's position. Changing the channel's * position, either explicitly or by reading, will change this stream's diff --git a/jdk/src/share/classes/java/io/FileOutputStream.java b/jdk/src/share/classes/java/io/FileOutputStream.java index 928e4f3cf15..44f472870ec 100644 --- a/jdk/src/share/classes/java/io/FileOutputStream.java +++ b/jdk/src/share/classes/java/io/FileOutputStream.java @@ -358,10 +358,10 @@ class FileOutputStream extends OutputStream /** * Returns the unique {@link java.nio.channels.FileChannel FileChannel} - * object associated with this file output stream.

    + * object associated with this file output stream. * *

    The initial {@link java.nio.channels.FileChannel#position() - * position} of the returned channel will be equal to the + * position} of the returned channel will be equal to the * number of bytes written to the file so far unless this stream is in * append mode, in which case it will be equal to the size of the file. * Writing bytes to this stream will increment the channel's position diff --git a/jdk/src/share/classes/java/io/InputStreamReader.java b/jdk/src/share/classes/java/io/InputStreamReader.java index 1f6d5f6113b..e131dca304a 100644 --- a/jdk/src/share/classes/java/io/InputStreamReader.java +++ b/jdk/src/share/classes/java/io/InputStreamReader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,7 +33,7 @@ import sun.nio.cs.StreamDecoder; /** * An InputStreamReader is a bridge from byte streams to character streams: It * reads bytes and decodes them into characters using a specified {@link - * java.nio.charset.Charset charset}. The charset that it uses + * java.nio.charset.Charset charset}. The charset that it uses * may be specified by name or may be given explicitly, or the platform's * default charset may be accepted. * @@ -101,7 +101,7 @@ public class InputStreamReader extends Reader { } /** - * Creates an InputStreamReader that uses the given charset.

    + * Creates an InputStreamReader that uses the given charset. * * @param in An InputStream * @param cs A charset @@ -117,7 +117,7 @@ public class InputStreamReader extends Reader { } /** - * Creates an InputStreamReader that uses the given charset decoder.

    + * Creates an InputStreamReader that uses the given charset decoder. * * @param in An InputStream * @param dec A charset decoder diff --git a/jdk/src/share/classes/java/io/OutputStreamWriter.java b/jdk/src/share/classes/java/io/OutputStreamWriter.java index b4e4b9e320b..5f7b9e34bca 100644 --- a/jdk/src/share/classes/java/io/OutputStreamWriter.java +++ b/jdk/src/share/classes/java/io/OutputStreamWriter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,7 +33,7 @@ import sun.nio.cs.StreamEncoder; /** * An OutputStreamWriter is a bridge from character streams to byte streams: * Characters written to it are encoded into bytes using a specified {@link - * java.nio.charset.Charset charset}. The charset that it uses + * java.nio.charset.Charset charset}. The charset that it uses * may be specified by name or may be given explicitly, or the platform's * default charset may be accepted. * @@ -86,7 +86,7 @@ public class OutputStreamWriter extends Writer { * * @param charsetName * The name of a supported - * {@link java.nio.charset.Charset
    charset} + * {@link java.nio.charset.Charset charset} * * @exception UnsupportedEncodingException * If the named encoding is not supported @@ -115,7 +115,7 @@ public class OutputStreamWriter extends Writer { } /** - * Creates an OutputStreamWriter that uses the given charset.

    + * Creates an OutputStreamWriter that uses the given charset. * * @param out * An OutputStream @@ -134,7 +134,7 @@ public class OutputStreamWriter extends Writer { } /** - * Creates an OutputStreamWriter that uses the given charset encoder.

    + * Creates an OutputStreamWriter that uses the given charset encoder. * * @param out * An OutputStream diff --git a/jdk/src/share/classes/java/io/PipedInputStream.java b/jdk/src/share/classes/java/io/PipedInputStream.java index 4ad8fbd81d8..af07de5b4e6 100644 --- a/jdk/src/share/classes/java/io/PipedInputStream.java +++ b/jdk/src/share/classes/java/io/PipedInputStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,7 +39,7 @@ package java.io; * The piped input stream contains a buffer, * decoupling read operations from write operations, * within limits. - * A pipe is said to be broken if a + * A pipe is said to be broken if a * thread that was providing data bytes to the connected * piped output stream is no longer alive. * @@ -193,7 +193,7 @@ public class PipedInputStream extends InputStream { * Receives a byte of data. This method will block if no input is * available. * @param b the byte being received - * @exception IOException If the pipe is broken, + * @exception IOException If the pipe is broken, * {@link #connect(java.io.PipedOutputStream) unconnected}, * closed, or if an I/O error occurs. * @since JDK1.1 @@ -219,7 +219,7 @@ public class PipedInputStream extends InputStream { * @param b the buffer into which the data is received * @param off the start offset of the data * @param len the maximum number of bytes received - * @exception IOException If the pipe is broken, + * @exception IOException If the pipe is broken, * {@link #connect(java.io.PipedOutputStream) unconnected}, * closed,or if an I/O error occurs. */ @@ -298,7 +298,7 @@ public class PipedInputStream extends InputStream { * stream is reached. * @exception IOException if the pipe is * {@link #connect(java.io.PipedOutputStream) unconnected}, - * broken, closed, + * broken, closed, * or if an I/O error occurs. */ public synchronized int read() throws IOException { @@ -361,7 +361,7 @@ public class PipedInputStream extends InputStream { * @exception IndexOutOfBoundsException If off is negative, * len is negative, or len is greater than * b.length - off - * @exception IOException if the pipe is broken, + * @exception IOException if the pipe is broken, * {@link #connect(java.io.PipedOutputStream) unconnected}, * closed, or if an I/O error occurs. */ @@ -419,7 +419,7 @@ public class PipedInputStream extends InputStream { * without blocking, or {@code 0} if this input stream has been * closed by invoking its {@link #close()} method, or if the pipe * is {@link #connect(java.io.PipedOutputStream) unconnected}, or - * broken. + * broken. * * @exception IOException if an I/O error occurs. * @since JDK1.0.2 diff --git a/jdk/src/share/classes/java/io/RandomAccessFile.java b/jdk/src/share/classes/java/io/RandomAccessFile.java index adccfbc757a..5e32ad5dba1 100644 --- a/jdk/src/share/classes/java/io/RandomAccessFile.java +++ b/jdk/src/share/classes/java/io/RandomAccessFile.java @@ -123,11 +123,11 @@ public class RandomAccessFile implements DataOutput, DataInput, Closeable { * write to, the file specified by the {@link File} argument. A new {@link * FileDescriptor} object is created to represent this file connection. * - *

    The mode argument specifies the access mode + *

    The mode argument specifies the access mode * in which the file is to be opened. The permitted values and their * meanings are: * - *

    + *
    * * * - *

    Value

    Meaning

    "r" Open for reading only. Invoking any of the write @@ -144,7 +144,7 @@ public class RandomAccessFile implements DataOutput, DataInput, Closeable { * Open for reading and writing, as with "rw", and also * require that every update to the file's content be written * synchronously to the underlying storage device.
    + *
    * * The "rws" and "rwd" modes work much like the {@link * java.nio.channels.FileChannel#force(boolean) force(boolean)} method of @@ -158,13 +158,13 @@ public class RandomAccessFile implements DataOutput, DataInput, Closeable { * event of a system crash. If the file does not reside on a local device * then no such guarantee is made. * - *

    The "rwd" mode can be used to reduce the number of I/O + *

    The "rwd" mode can be used to reduce the number of I/O * operations performed. Using "rwd" only requires updates to the * file's content to be written to storage; using "rws" requires * updates to both the file's content and its metadata to be written, which * generally requires at least one more low-level I/O operation. * - *

    If there is a security manager, its {@code checkRead} method is + *

    If there is a security manager, its {@code checkRead} method is * called with the pathname of the {@code file} argument as its * argument to see if read access to the file is allowed. If the mode * allows writing, the security manager's {@code checkWrite} method is @@ -238,7 +238,7 @@ public class RandomAccessFile implements DataOutput, DataInput, Closeable { /** * Returns the opaque file descriptor object associated with this - * stream.

    + * stream. * * @return the file descriptor object associated with this stream. * @exception IOException if an I/O error occurs. diff --git a/jdk/src/share/classes/java/lang/CharSequence.java b/jdk/src/share/classes/java/lang/CharSequence.java index 30a23590875..ac80b22f066 100644 --- a/jdk/src/share/classes/java/lang/CharSequence.java +++ b/jdk/src/share/classes/java/lang/CharSequence.java @@ -60,7 +60,7 @@ public interface CharSequence { /** * Returns the length of this character sequence. The length is the number - * of 16-bit chars in the sequence.

    + * of 16-bit chars in the sequence. * * @return the number of chars in this sequence */ @@ -70,7 +70,7 @@ public interface CharSequence { * Returns the char value at the specified index. An index ranges from zero * to length() - 1. The first char value of the sequence is at * index zero, the next at index one, and so on, as for array - * indexing.

    + * indexing. * *

    If the char value specified by the index is a * surrogate, the surrogate @@ -92,7 +92,7 @@ public interface CharSequence { * ends with the char value at index end - 1. The length * (in chars) of the * returned sequence is end - start, so if start == end - * then an empty sequence is returned.

    + * then an empty sequence is returned. * * @param start the start index, inclusive * @param end the end index, exclusive @@ -109,7 +109,7 @@ public interface CharSequence { /** * Returns a string containing the characters in this sequence in the same * order as this sequence. The length of the string will be the length of - * this sequence.

    + * this sequence. * * @return a string consisting of exactly this sequence of characters */ @@ -156,7 +156,8 @@ public interface CharSequence { new CharIterator(), length(), Spliterator.ORDERED), - Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED); + Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED, + false); } /** @@ -227,6 +228,7 @@ public interface CharSequence { Spliterators.spliteratorUnknownSize( new CodePointIterator(), Spliterator.ORDERED), - Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED); + Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED, + false); } } diff --git a/jdk/src/share/classes/java/lang/Character.java b/jdk/src/share/classes/java/lang/Character.java index e512e582612..41576cca8d8 100644 --- a/jdk/src/share/classes/java/lang/Character.java +++ b/jdk/src/share/classes/java/lang/Character.java @@ -54,7 +54,7 @@ import java.util.Locale; *
  • http://www.unicode.org * * - *

    Unicode Character Representations

    + *

    Unicode Character Representations

    * *

    The {@code char} data type (and therefore the value that a * {@code Character} object encapsulates) are based on the @@ -68,7 +68,7 @@ import java.util.Locale; * definition of the U+n notation in the Unicode * Standard.) * - *

    The set of characters from U+0000 to U+FFFF is + *

    The set of characters from U+0000 to U+FFFF is * sometimes referred to as the Basic Multilingual Plane (BMP). * Characters whose code points are greater * than U+FFFF are called supplementary characters. The Java @@ -4599,6 +4599,7 @@ class Character implements java.io.Serializable, Comparable { * * @since 1.8 * + * @param value The {@code char} for which to return a hash code. * @return a hash code value for a {@code char} value. */ public static int hashCode(char value) { @@ -6637,7 +6638,7 @@ class Character implements java.io.Serializable, Comparable { * Determines if the specified character is ISO-LATIN-1 white space. * This method returns {@code true} for the following five * characters only: - * + *
    * * * @@ -7174,6 +7175,7 @@ class Character implements java.io.Serializable, Comparable { * Returns the value obtained by reversing the order of the bytes in the * specified char value. * + * @param ch The {@code char} of which to reverse the byte order. * @return the value obtained by reversing (or, equivalently, swapping) * the bytes in the specified char value. * @since 1.5 diff --git a/jdk/src/share/classes/java/lang/Class.java b/jdk/src/share/classes/java/lang/Class.java index df4d457367d..2e47377996f 100644 --- a/jdk/src/share/classes/java/lang/Class.java +++ b/jdk/src/share/classes/java/lang/Class.java @@ -360,36 +360,24 @@ public final class Class implements java.io.Serializable, * any exception thrown by the constructor in a (checked) {@link * java.lang.reflect.InvocationTargetException}. * - * @return a newly allocated instance of the class represented by this - * object. - * @exception IllegalAccessException if the class or its nullary - * constructor is not accessible. - * @exception InstantiationException - * if this {@code Class} represents an abstract class, - * an interface, an array class, a primitive type, or void; - * or if the class has no nullary constructor; - * or if the instantiation fails for some other reason. - * @exception ExceptionInInitializerError if the initialization - * provoked by this method fails. - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *
      - * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * creation of new instances of this class - * - *
    • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
    - * + * @return a newly allocated instance of the class represented by this + * object. + * @throws IllegalAccessException if the class or its nullary + * constructor is not accessible. + * @throws InstantiationException + * if this {@code Class} represents an abstract class, + * an interface, an array class, a primitive type, or void; + * or if the class has no nullary constructor; + * or if the instantiation fails for some other reason. + * @throws ExceptionInInitializerError if the initialization + * provoked by this method fails. + * @throws SecurityException + * If a security manager, s, is present and + * the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class. */ @CallerSensitive public T newInstance() @@ -981,24 +969,27 @@ public final class Class implements java.io.Serializable, * * @return the immediately enclosing method of the underlying class, if * that class is a local or anonymous class; otherwise {@code null}. - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: * - *
      + * @throws SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(enclosingClass, Member.DECLARED)} denies - * access to the methods within the enclosing class + *
        * - *
      • the caller's class loader is not the same as or an - * ancestor of the class loader for the enclosing class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of the enclosing class + *
      • the caller's class loader is not the same as the + * class loader of the enclosing class and invocation of + * {@link SecurityManager#checkPermission + * s.checkPermission} method with + * {@code RuntimePermission("accessDeclaredMembers")} + * denies access to the methods within the enclosing class * - *
      + *
    • the caller's class loader is not the same as or an + * ancestor of the class loader for the enclosing class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of the enclosing class + * + *
    * @since 1.5 */ @CallerSensitive @@ -1025,11 +1016,6 @@ public final class Class implements java.io.Serializable, // Perform access check Class enclosingCandidate = enclosingInfo.getEnclosingClass(); - // be very careful not to change the stack depth of this - // checkMemberAccess call for security reasons - // see java.lang.SecurityManager.checkMemberAccess - // - // Note that we need to do this on the enclosing class enclosingCandidate.checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); /* @@ -1137,24 +1123,26 @@ public final class Class implements java.io.Serializable, * * @return the immediately enclosing constructor of the underlying class, if * that class is a local or anonymous class; otherwise {@code null}. - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: + * @throws SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: * - *
      + *
        * - *
      • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(enclosingClass, Member.DECLARED)} denies - * access to the constructors within the enclosing class + *
      • the caller's class loader is not the same as the + * class loader of the enclosing class and invocation of + * {@link SecurityManager#checkPermission + * s.checkPermission} method with + * {@code RuntimePermission("accessDeclaredMembers")} + * denies access to the constructors within the enclosing class * - *
      • the caller's class loader is not the same as or an - * ancestor of the class loader for the enclosing class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of the enclosing class + *
      • the caller's class loader is not the same as or an + * ancestor of the class loader for the enclosing class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of the enclosing class * - *
      + *
    * @since 1.5 */ @CallerSensitive @@ -1180,11 +1168,6 @@ public final class Class implements java.io.Serializable, // Perform access check Class enclosingCandidate = enclosingInfo.getEnclosingClass(); - // be very careful not to change the stack depth of this - // checkMemberAccess call for security reasons - // see java.lang.SecurityManager.checkMemberAccess - // - // Note that we need to do this on the enclosing class enclosingCandidate.checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); /* @@ -1457,25 +1440,14 @@ public final class Class implements java.io.Serializable, * class, or void. * * @return the array of {@code Class} objects representing the public - * members of this class - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *
      - * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} method - * denies access to the classes within this class - * - *
    • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
    + * members of this class + * @throws SecurityException + * If a security manager, s, is present and + * the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class. * * @since JDK1.1 */ @@ -1530,25 +1502,14 @@ public final class Class implements java.io.Serializable, *

    See The Java Language Specification, sections 8.2 and 8.3. * * @return the array of {@code Field} objects representing the - * public fields - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *

      - * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the fields within this class - * - *
    • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
    + * public fields + * @throws SecurityException + * If a security manager, s, is present and + * the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class. * * @since JDK1.1 */ @@ -1579,25 +1540,14 @@ public final class Class implements java.io.Serializable, *

    See The Java Language Specification, sections 8.2 and 8.4. * * @return the array of {@code Method} objects representing the - * public methods of this class - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *

      - * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the methods within this class - * - *
    • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
    + * public methods of this class + * @throws SecurityException + * If a security manager, s, is present and + * the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class. * * @since JDK1.1 */ @@ -1626,25 +1576,14 @@ public final class Class implements java.io.Serializable, * {@code Constructor[]}. * * @return the array of {@code Constructor} objects representing the - * public constructors of this class - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *
      - * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the constructors within this class - * - *
    • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
    + * public constructors of this class + * @throws SecurityException + * If a security manager, s, is present and + * the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class. * * @since JDK1.1 */ @@ -1678,29 +1617,18 @@ public final class Class implements java.io.Serializable, *

    See The Java Language Specification, sections 8.2 and 8.3. * * @param name the field name - * @return the {@code Field} object of this class specified by - * {@code name} - * @exception NoSuchFieldException if a field with the specified name is - * not found. - * @exception NullPointerException if {@code name} is {@code null} - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *

      - * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the field - * - *
    • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
    + * @return the {@code Field} object of this class specified by + * {@code name} + * @throws NoSuchFieldException if a field with the specified name is + * not found. + * @throws NullPointerException if {@code name} is {@code null} + * @throws SecurityException + * If a security manager, s, is present and + * the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class. * * @since JDK1.1 */ @@ -1762,28 +1690,17 @@ public final class Class implements java.io.Serializable, * @param name the name of the method * @param parameterTypes the list of parameters * @return the {@code Method} object that matches the specified - * {@code name} and {@code parameterTypes} - * @exception NoSuchMethodException if a matching method is not found - * or if the name is "<init>"or "<clinit>". - * @exception NullPointerException if {@code name} is {@code null} - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *
      - * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the method - * - *
    • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
    + * {@code name} and {@code parameterTypes} + * @throws NoSuchMethodException if a matching method is not found + * or if the name is "<init>"or "<clinit>". + * @throws NullPointerException if {@code name} is {@code null} + * @throws SecurityException + * If a security manager, s, is present and + * the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class. * * @since JDK1.1 */ @@ -1816,26 +1733,15 @@ public final class Class implements java.io.Serializable, * * @param parameterTypes the parameter array * @return the {@code Constructor} object of the public constructor that - * matches the specified {@code parameterTypes} - * @exception NoSuchMethodException if a matching method is not found. - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *
      - * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the constructor - * - *
    • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
    + * matches the specified {@code parameterTypes} + * @throws NoSuchMethodException if a matching method is not found. + * @throws SecurityException + * If a security manager, s, is present and + * the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class. * * @since JDK1.1 */ @@ -1858,25 +1764,27 @@ public final class Class implements java.io.Serializable, * primitive type, an array class, or void. * * @return the array of {@code Class} objects representing all the - * declared members of this class - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: + * declared members of this class + * @throws SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: * - *
      + *
        * - *
      • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared classes within this class + *
      • the caller's class loader is not the same as the + * class loader of this class and invocation of + * {@link SecurityManager#checkPermission + * s.checkPermission} method with + * {@code RuntimePermission("accessDeclaredMembers")} + * denies access to the declared classes within this class * - *
      • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class + *
      • the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class * - *
      + *
    * * @since JDK1.1 */ @@ -1899,26 +1807,28 @@ public final class Class implements java.io.Serializable, * *

    See The Java Language Specification, sections 8.2 and 8.3. * - * @return the array of {@code Field} objects representing all the - * declared fields of this class - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: + * @return the array of {@code Field} objects representing all the + * declared fields of this class + * @throws SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: * - *

      + *
        * - *
      • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared fields within this class + *
      • the caller's class loader is not the same as the + * class loader of this class and invocation of + * {@link SecurityManager#checkPermission + * s.checkPermission} method with + * {@code RuntimePermission("accessDeclaredMembers")} + * denies access to the declared fields within this class * - *
      • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class + *
      • the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class * - *
      + *
    * * @since JDK1.1 */ @@ -1945,26 +1855,28 @@ public final class Class implements java.io.Serializable, * *

    See The Java Language Specification, section 8.2. * - * @return the array of {@code Method} objects representing all the - * declared methods of this class - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: + * @return the array of {@code Method} objects representing all the + * declared methods of this class + * @throws SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: * - *

      + *
        * - *
      • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared methods within this class + *
      • the caller's class loader is not the same as the + * class loader of this class and invocation of + * {@link SecurityManager#checkPermission + * s.checkPermission} method with + * {@code RuntimePermission("accessDeclaredMembers")} + * denies access to the declared methods within this class * - *
      • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class + *
      • the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class * - *
      + *
    * * @since JDK1.1 */ @@ -1988,26 +1900,28 @@ public final class Class implements java.io.Serializable, * *

    See The Java Language Specification, section 8.2. * - * @return the array of {@code Constructor} objects representing all the - * declared constructors of this class - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: + * @return the array of {@code Constructor} objects representing all the + * declared constructors of this class + * @throws SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: * - *

      + *
        * - *
      • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared constructors within this class + *
      • the caller's class loader is not the same as the + * class loader of this class and invocation of + * {@link SecurityManager#checkPermission + * s.checkPermission} method with + * {@code RuntimePermission("accessDeclaredMembers")} + * denies access to the declared constructors within this class * - *
      • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class + *
      • the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class * - *
      + *
    * * @since JDK1.1 */ @@ -2026,29 +1940,31 @@ public final class Class implements java.io.Serializable, * will not reflect the {@code length} field of an array class. * * @param name the name of the field - * @return the {@code Field} object for the specified field in this - * class - * @exception NoSuchFieldException if a field with the specified name is - * not found. - * @exception NullPointerException if {@code name} is {@code null} - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: + * @return the {@code Field} object for the specified field in this + * class + * @throws NoSuchFieldException if a field with the specified name is + * not found. + * @throws NullPointerException if {@code name} is {@code null} + * @throws SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: * - *
      + *
        * - *
      • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared field + *
      • the caller's class loader is not the same as the + * class loader of this class and invocation of + * {@link SecurityManager#checkPermission + * s.checkPermission} method with + * {@code RuntimePermission("accessDeclaredMembers")} + * denies access to the declared field * - *
      • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class + *
      • the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class * - *
      + *
    * * @since JDK1.1 */ @@ -2080,28 +1996,30 @@ public final class Class implements java.io.Serializable, * * @param name the name of the method * @param parameterTypes the parameter array - * @return the {@code Method} object for the method of this class - * matching the specified name and parameters - * @exception NoSuchMethodException if a matching method is not found. - * @exception NullPointerException if {@code name} is {@code null} - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: + * @return the {@code Method} object for the method of this class + * matching the specified name and parameters + * @throws NoSuchMethodException if a matching method is not found. + * @throws NullPointerException if {@code name} is {@code null} + * @throws SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: * - *
      + *
        * - *
      • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared method + *
      • the caller's class loader is not the same as the + * class loader of this class and invocation of + * {@link SecurityManager#checkPermission + * s.checkPermission} method with + * {@code RuntimePermission("accessDeclaredMembers")} + * denies access to the declared method * - *
      • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class + *
      • the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class * - *
      + *
    * * @since JDK1.1 */ @@ -2129,27 +2047,29 @@ public final class Class implements java.io.Serializable, * include the explicit enclosing instance as the first parameter. * * @param parameterTypes the parameter array - * @return The {@code Constructor} object for the constructor with the - * specified parameter list - * @exception NoSuchMethodException if a matching method is not found. - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: + * @return The {@code Constructor} object for the constructor with the + * specified parameter list + * @throws NoSuchMethodException if a matching method is not found. + * @throws SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: * - *
      + *
        * - *
      • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared constructor + *
      • the caller's class loader is not the same as the + * class loader of this class and invocation of + * {@link SecurityManager#checkPermission + * s.checkPermission} method with + * {@code RuntimePermission("accessDeclaredMembers")} + * denies access to the declared constructor * - *
      • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class + *
      • the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class * - *
      + *
    * * @since JDK1.1 */ @@ -2306,14 +2226,6 @@ public final class Class implements java.io.Serializable, */ static native Class getPrimitiveClass(String name); - private static boolean isCheckMemberAccessOverridden(SecurityManager smgr) { - if (smgr.getClass() == SecurityManager.class) return false; - - Class[] paramTypes = new Class[] {Class.class, int.class}; - return smgr.getClass().getMethod0("checkMemberAccess", paramTypes). - getDeclaringClass() != SecurityManager.class; - } - /* * Check if client is allowed to access members. If access is denied, * throw a SecurityException. @@ -2326,19 +2238,17 @@ public final class Class implements java.io.Serializable, private void checkMemberAccess(int which, Class caller, boolean checkProxyInterfaces) { final SecurityManager s = System.getSecurityManager(); if (s != null) { + /* Default policy allows access to all {@link Member#PUBLIC} members, + * as well as access to classes that have the same class loader as the caller. + * In all other cases, it requires RuntimePermission("accessDeclaredMembers") + * permission. + */ final ClassLoader ccl = ClassLoader.getClassLoader(caller); final ClassLoader cl = getClassLoader0(); - if (!isCheckMemberAccessOverridden(s)) { - // Inlined SecurityManager.checkMemberAccess - if (which != Member.PUBLIC) { - if (ccl != cl) { - s.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); - } + if (which != Member.PUBLIC) { + if (ccl != cl) { + s.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); } - } else { - // Don't refactor; otherwise break the stack depth for - // checkMemberAccess of subclasses of SecurityManager as specified. - s.checkMemberAccess(this, which); } this.checkPackageAccess(ccl, checkProxyInterfaces); } @@ -2397,6 +2307,45 @@ public final class Class implements java.io.Serializable, return name; } + /** + * Atomic operations support. + */ + private static class Atomic { + // initialize Unsafe machinery here, since we need to call Class.class instance method + // and have to avoid calling it in the static initializer of the Class class... + private static final Unsafe unsafe = Unsafe.getUnsafe(); + // offset of Class.reflectionData instance field + private static final long reflectionDataOffset; + // offset of Class.annotationType instance field + private static final long annotationTypeOffset; + + static { + Field[] fields = Class.class.getDeclaredFields0(false); // bypass caches + reflectionDataOffset = objectFieldOffset(fields, "reflectionData"); + annotationTypeOffset = objectFieldOffset(fields, "annotationType"); + } + + private static long objectFieldOffset(Field[] fields, String fieldName) { + Field field = searchFields(fields, fieldName); + if (field == null) { + throw new Error("No " + fieldName + " field found in java.lang.Class"); + } + return unsafe.objectFieldOffset(field); + } + + static boolean casReflectionData(Class clazz, + SoftReference> oldData, + SoftReference> newData) { + return unsafe.compareAndSwapObject(clazz, reflectionDataOffset, oldData, newData); + } + + static boolean casAnnotationType(Class clazz, + AnnotationType oldType, + AnnotationType newType) { + return unsafe.compareAndSwapObject(clazz, annotationTypeOffset, oldType, newType); + } + } + /** * Reflection support. */ @@ -2423,29 +2372,6 @@ public final class Class implements java.io.Serializable, ReflectionData(int redefinedCount) { this.redefinedCount = redefinedCount; } - - // initialize Unsafe machinery here, since we need to call Class.class instance method - // and have to avoid calling it in the static initializer of the Class class... - private static final Unsafe unsafe; - // offset of Class.reflectionData instance field - private static final long reflectionDataOffset; - - static { - unsafe = Unsafe.getUnsafe(); - // bypass caches - Field reflectionDataField = searchFields(Class.class.getDeclaredFields0(false), - "reflectionData"); - if (reflectionDataField == null) { - throw new Error("No reflectionData field found in java.lang.Class"); - } - reflectionDataOffset = unsafe.objectFieldOffset(reflectionDataField); - } - - static boolean compareAndSwap(Class clazz, - SoftReference> oldData, - SoftReference> newData) { - return unsafe.compareAndSwapObject(clazz, reflectionDataOffset, oldData, newData); - } } private volatile transient SoftReference> reflectionData; @@ -2477,7 +2403,7 @@ public final class Class implements java.io.Serializable, while (true) { ReflectionData rd = new ReflectionData<>(classRedefinedCount); // try to CAS it... - if (ReflectionData.compareAndSwap(this, oldReflectionData, new SoftReference<>(rd))) { + if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) { return rd; } // else retry @@ -2520,7 +2446,7 @@ public final class Class implements java.io.Serializable, } // Annotations handling - private native byte[] getRawAnnotations(); + native byte[] getRawAnnotations(); // Since 1.8 native byte[] getRawTypeAnnotations(); static byte[] getExecutableTypeAnnotationBytes(Executable ex) { @@ -3380,10 +3306,11 @@ public final class Class implements java.io.Serializable, // Annotation types cache their internal (AnnotationType) form - private AnnotationType annotationType; + @SuppressWarnings("UnusedDeclaration") + private volatile transient AnnotationType annotationType; - void setAnnotationType(AnnotationType type) { - annotationType = type; + boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) { + return Atomic.casAnnotationType(this, oldType, newType); } AnnotationType getAnnotationType() { diff --git a/jdk/src/share/classes/java/lang/ClassLoader.java b/jdk/src/share/classes/java/lang/ClassLoader.java index f26eafd980a..c3f2aa20458 100644 --- a/jdk/src/share/classes/java/lang/ClassLoader.java +++ b/jdk/src/share/classes/java/lang/ClassLoader.java @@ -157,7 +157,7 @@ import sun.security.util.SecurityConstants; * } * * - *

    Binary names

    + *

    Binary names

    * *

    Any class name provided as a {@link String} parameter to methods in * ClassLoader must be a binary name as defined by @@ -342,7 +342,7 @@ public abstract class ClassLoader { * #loadClass(String, boolean)} method. It is invoked by the Java virtual * machine to resolve class references. Invoking this method is equivalent * to invoking {@link #loadClass(String, boolean) loadClass(name, - * false)}.

    + * false)}. * * @param name * The binary name of the class @@ -441,7 +441,7 @@ public abstract class ClassLoader { * behaves as follows. If this ClassLoader object is registered as * parallel capable, the method returns a dedicated object associated * with the specified class name. Otherwise, the method returns this - * ClassLoader object.

    + * ClassLoader object. * * @param className * The name of the to-be-loaded class @@ -506,7 +506,7 @@ public abstract class ClassLoader { * follow the delegation model for loading classes, and will be invoked by * the {@link #loadClass loadClass} method after checking the * parent class loader for the requested class. The default implementation - * throws a ClassNotFoundException.

    + * throws a ClassNotFoundException. * * @param name * The binary name of the class @@ -772,16 +772,16 @@ public abstract class ClassLoader { * bBuffer, pd) yields exactly the same * result as the statements * - *
    + *

    * ...
    - * byte[] temp = new byte[
    bBuffer.{@link + * byte[] temp = new byte[bBuffer.{@link * java.nio.ByteBuffer#remaining remaining}()];
    - *
    bBuffer.{@link java.nio.ByteBuffer#get(byte[]) + * bBuffer.{@link java.nio.ByteBuffer#get(byte[]) * get}(temp);
    * return {@link #defineClass(String, byte[], int, int, ProtectionDomain) - *
    cl.defineClass}(name, temp, 0, - * temp.length, pd);
    - *

    + * cl.defineClass}(name, temp, 0, + * temp.length, pd);
    + *

    * * @param name * The expected binary name. of the class, or @@ -940,7 +940,6 @@ public abstract class ClassLoader { * already been linked, then this method simply returns. Otherwise, the * class is linked as described in the "Execution" chapter of * The Java™ Language Specification. - *

    * * @param c * The class to link @@ -1012,7 +1011,7 @@ public abstract class ClassLoader { * Returns the class with the given binary name if this * loader has been recorded by the Java virtual machine as an initiating * loader of a class with that binary name. Otherwise - * null is returned.

    + * null is returned. * * @param name * The binary name of the class @@ -1032,7 +1031,7 @@ public abstract class ClassLoader { /** * Sets the signers of a class. This should be invoked after defining a - * class.

    + * class. * * @param c * The Class object @@ -1125,7 +1124,7 @@ public abstract class ClassLoader { /** * Finds the resource with the given name. Class loader implementations - * should override this method to specify where to find resources.

    + * should override this method to specify where to find resources. * * @param name * The resource name @@ -1143,7 +1142,7 @@ public abstract class ClassLoader { * Returns an enumeration of {@link java.net.URL URL} objects * representing all the resources with the given name. Class loader * implementations should override this method to specify where to load - * resources from.

    + * resources from. * * @param name * The resource name @@ -1161,14 +1160,16 @@ public abstract class ClassLoader { } /** - * Registers the caller as parallel capable.

    + * Registers the caller as parallel capable. * The registration succeeds if and only if all of the following - * conditions are met:
    - * 1. no instance of the caller has been created

    - * 2. all of the super classes (except class Object) of the caller are - * registered as parallel capable

    - * Note that once a class loader is registered as parallel capable, there - * is no way to change it back.

    + * conditions are met: + *
      + *
    1. no instance of the caller has been created
    2. + *
    3. all of the super classes (except class Object) of the caller are + * registered as parallel capable
    4. + *
    + *

    Note that once a class loader is registered as parallel capable, there + * is no way to change it back.

    * * @return true if the caller is successfully registered as * parallel capable and false if otherwise. @@ -1185,7 +1186,7 @@ public abstract class ClassLoader { /** * Find a resource of the specified name from the search path used to load * classes. This method locates the resource through the system class - * loader (see {@link #getSystemClassLoader()}).

    + * loader (see {@link #getSystemClassLoader()}). * * @param name * The resource name @@ -1292,7 +1293,7 @@ public abstract class ClassLoader { /** * Open for reading, a resource of the specified name from the search path * used to load classes. This method locates the resource through the - * system class loader (see {@link #getSystemClassLoader()}).

    + * system class loader (see {@link #getSystemClassLoader()}). * * @param name * The resource name @@ -1515,7 +1516,7 @@ public abstract class ClassLoader { * class loaders to define the packages for their classes. Packages must * be created before the class is defined, and package names must be * unique within a class loader and cannot be redefined or changed once - * created.

    + * created. * * @param name * The package name @@ -1572,7 +1573,7 @@ public abstract class ClassLoader { /** * Returns a Package that has been defined by this class loader - * or any of its ancestors.

    + * or any of its ancestors. * * @param name * The package name @@ -1609,7 +1610,7 @@ public abstract class ClassLoader { /** * Returns all of the Packages defined by this class loader and - * its ancestors.

    + * its ancestors. * * @return The array of Package objects defined by this * ClassLoader @@ -1646,7 +1647,7 @@ public abstract class ClassLoader { * method to locate the native libraries that belong to classes loaded with * this class loader. If this method returns null, the VM * searches the library along the path specified as the - * "java.library.path" property.

    + * "java.library.path" property. * * @param libname * The library name @@ -1966,7 +1967,7 @@ public abstract class ClassLoader { * in the future will have assertions enabled or disabled by default. * This setting may be overridden on a per-package or per-class basis by * invoking {@link #setPackageAssertionStatus(String, boolean)} or {@link - * #setClassAssertionStatus(String, boolean)}.

    + * #setClassAssertionStatus(String, boolean)}. * * @param enabled * true if classes loaded by this class loader will @@ -2068,7 +2069,6 @@ public abstract class ClassLoader { * status settings associated with the class loader. This method is * provided so that class loaders can be made to ignore any command line or * persistent assertion status settings and "start with a clean slate." - *

    * * @since 1.4 */ diff --git a/jdk/src/share/classes/java/lang/Double.java b/jdk/src/share/classes/java/lang/Double.java index 113cdf81a4c..1b1aece8122 100644 --- a/jdk/src/share/classes/java/lang/Double.java +++ b/jdk/src/share/classes/java/lang/Double.java @@ -256,7 +256,7 @@ public final class Double extends Number implements Comparable { * * *
    {@code '\t'} {@code U+0009}{@code HORIZONTAL TABULATION}
    {@code '\n'} {@code U+000A}
    - * + * * * * diff --git a/jdk/src/share/classes/java/lang/Float.java b/jdk/src/share/classes/java/lang/Float.java index 2f2b6b22444..e130e92314e 100644 --- a/jdk/src/share/classes/java/lang/Float.java +++ b/jdk/src/share/classes/java/lang/Float.java @@ -258,7 +258,7 @@ public final class Float extends Number implements Comparable { * * *

    Examples

    Examples
    Floating-point ValueHexadecimal String
    {@code 1.0} {@code 0x1.0p0}
    {@code -1.0} {@code -0x1.0p0}
    - * + * * * * diff --git a/jdk/src/share/classes/java/lang/Iterable.java b/jdk/src/share/classes/java/lang/Iterable.java index 8d46dbfe5ff..fe9086f6874 100644 --- a/jdk/src/share/classes/java/lang/Iterable.java +++ b/jdk/src/share/classes/java/lang/Iterable.java @@ -26,6 +26,8 @@ package java.lang; import java.util.Iterator; import java.util.Objects; +import java.util.Spliterator; +import java.util.Spliterators; import java.util.function.Consumer; /** @@ -72,5 +74,30 @@ public interface Iterable { action.accept(t); } } + + /** + * Creates a {@link Spliterator} over the elements described by this + * {@code Iterable}. + * + * @implSpec + * The default implementation creates an + * early-binding + * spliterator from the iterable's {@code Iterator}. The spliterator + * inherits the fail-fast properties of the iterable's iterator. + * + * @implNote + * The default implementation should usually be overridden. The + * spliterator returned by the default implementation has poor splitting + * capabilities, is unsized, and does not report any spliterator + * characteristics. Implementing classes can nearly always provide a + * better implementation. + * + * @return a {@code Spliterator} over the elements described by this + * {@code Iterable}. + * @since 1.8 + */ + default Spliterator spliterator() { + return Spliterators.spliteratorUnknownSize(iterator(), 0); + } } diff --git a/jdk/src/share/classes/java/lang/ProcessBuilder.java b/jdk/src/share/classes/java/lang/ProcessBuilder.java index b467f45c351..0cb7febe533 100644 --- a/jdk/src/share/classes/java/lang/ProcessBuilder.java +++ b/jdk/src/share/classes/java/lang/ProcessBuilder.java @@ -65,7 +65,7 @@ import java.util.Map; * working directory of the current process, usually the directory * named by the system property {@code user.dir}. * - *
  • a source of standard input. + *
  • a source of standard input. * By default, the subprocess reads input from a pipe. Java code * can access this pipe via the output stream returned by * {@link Process#getOutputStream()}. However, standard input may @@ -81,7 +81,7 @@ import java.util.Map; * * *
  • a destination for standard output - * and standard error. By default, the subprocess writes standard + * and standard error. By default, the subprocess writes standard * output and standard error to pipes. Java code can access these pipes * via the input streams returned by {@link Process#getInputStream()} and * {@link Process#getErrorStream()}. However, standard output and @@ -554,6 +554,7 @@ public final class ProcessBuilder * Redirect.from(file).type() == Redirect.Type.READ * } * + * @param file The {@code File} for the {@code Redirect}. * @throws NullPointerException if the specified file is null * @return a redirect to read from the specified file */ @@ -580,6 +581,7 @@ public final class ProcessBuilder * Redirect.to(file).type() == Redirect.Type.WRITE * } * + * @param file The {@code File} for the {@code Redirect}. * @throws NullPointerException if the specified file is null * @return a redirect to write to the specified file */ @@ -610,6 +612,7 @@ public final class ProcessBuilder * Redirect.appendTo(file).type() == Redirect.Type.APPEND * } * + * @param file The {@code File} for the {@code Redirect}. * @throws NullPointerException if the specified file is null * @return a redirect to append to the specified file */ diff --git a/jdk/src/share/classes/java/lang/Runtime.java b/jdk/src/share/classes/java/lang/Runtime.java index 5ff1aac0bce..9e53dc939ec 100644 --- a/jdk/src/share/classes/java/lang/Runtime.java +++ b/jdk/src/share/classes/java/lang/Runtime.java @@ -661,7 +661,7 @@ public class Runtime { /** * Returns the maximum amount of memory that the Java virtual machine will * attempt to use. If there is no inherent limit then the value {@link - * java.lang.Long#MAX_VALUE} will be returned.

    + * java.lang.Long#MAX_VALUE} will be returned. * * @return the maximum amount of memory that the virtual machine will * attempt to use, measured in bytes diff --git a/jdk/src/share/classes/java/lang/SecurityManager.java b/jdk/src/share/classes/java/lang/SecurityManager.java index ca187630528..34be905bd02 100644 --- a/jdk/src/share/classes/java/lang/SecurityManager.java +++ b/jdk/src/share/classes/java/lang/SecurityManager.java @@ -1675,10 +1675,18 @@ class SecurityManager { * permission to access members. * @exception NullPointerException if the clazz argument is * null. + * + * @deprecated This method relies on the caller being at a stack depth + * of 4 which is error-prone and cannot be enforced by the runtime. + * Users of this method should instead invoke {@link #checkPermission} + * directly. This method will be changed in a future release + * to check the permission {@code java.security.AllPermission}. + * * @see java.lang.reflect.Member * @since JDK1.1 * @see #checkPermission(java.security.Permission) checkPermission */ + @Deprecated @CallerSensitive public void checkMemberAccess(Class clazz, int which) { if (clazz == null) { diff --git a/jdk/src/share/classes/java/lang/System.java b/jdk/src/share/classes/java/lang/System.java index 52a5e0de823..79eb6434433 100644 --- a/jdk/src/share/classes/java/lang/System.java +++ b/jdk/src/share/classes/java/lang/System.java @@ -1220,12 +1220,15 @@ public final class System { public sun.reflect.ConstantPool getConstantPool(Class klass) { return klass.getConstantPool(); } - public void setAnnotationType(Class klass, AnnotationType type) { - klass.setAnnotationType(type); + public boolean casAnnotationType(Class klass, AnnotationType oldType, AnnotationType newType) { + return klass.casAnnotationType(oldType, newType); } public AnnotationType getAnnotationType(Class klass) { return klass.getAnnotationType(); } + public byte[] getRawClassAnnotations(Class klass) { + return klass.getRawAnnotations(); + } public byte[] getRawClassTypeAnnotations(Class klass) { return klass.getRawTypeAnnotations(); } diff --git a/jdk/src/share/classes/java/lang/Thread.java b/jdk/src/share/classes/java/lang/Thread.java index eb89670d149..d8a9ee2a582 100644 --- a/jdk/src/share/classes/java/lang/Thread.java +++ b/jdk/src/share/classes/java/lang/Thread.java @@ -865,8 +865,8 @@ class Thread implements Runnable { * will receive an {@link InterruptedException}. * *

    If this thread is blocked in an I/O operation upon an {@link - * java.nio.channels.InterruptibleChannel interruptible - * channel} then the channel will be closed, the thread's interrupt + * java.nio.channels.InterruptibleChannel InterruptibleChannel} + * then the channel will be closed, the thread's interrupt * status will be set, and the thread will receive a {@link * java.nio.channels.ClosedByInterruptException}. * @@ -1883,6 +1883,7 @@ class Thread implements Runnable { * there is no default. * @since 1.5 * @see #setDefaultUncaughtExceptionHandler + * @return the default uncaught exception handler for all threads */ public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){ return defaultUncaughtExceptionHandler; @@ -1895,6 +1896,7 @@ class Thread implements Runnable { * ThreadGroup object is returned, unless this thread * has terminated, in which case null is returned. * @since 1.5 + * @return the uncaught exception handler for this thread */ public UncaughtExceptionHandler getUncaughtExceptionHandler() { return uncaughtExceptionHandler != null ? diff --git a/jdk/src/share/classes/java/lang/ThreadLocal.java b/jdk/src/share/classes/java/lang/ThreadLocal.java index b337fc5f2e6..91d3df940d6 100644 --- a/jdk/src/share/classes/java/lang/ThreadLocal.java +++ b/jdk/src/share/classes/java/lang/ThreadLocal.java @@ -131,12 +131,13 @@ public class ThreadLocal { * Creates a thread local variable. The initial value of the variable is * determined by invoking the {@code get} method on the {@code Supplier}. * + * @param the type of the thread local's value * @param supplier the supplier to be used to determine the initial value * @return a new thread local variable * @throws NullPointerException if the specified supplier is null * @since 1.8 */ - public static ThreadLocal withInitial(Supplier supplier) { + public static ThreadLocal withInitial(Supplier supplier) { return new SuppliedThreadLocal<>(supplier); } diff --git a/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java b/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java index 8efbda80614..04eda964966 100644 --- a/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java +++ b/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java @@ -747,7 +747,8 @@ import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP; GuardWithCatch gguard = new GuardWithCatch(gtarget, exType, gcatcher); if (gtarget == null || gcatcher == null) throw new InternalError(); MethodHandle ginvoker = GuardWithCatch.VARARGS_INVOKE.bindReceiver(gguard); - return makeCollectArguments(ginvoker, ValueConversions.varargsArray(nargs), 0, false); + MethodHandle gcollect = makeCollectArguments(ginvoker, ValueConversions.varargsArray(nargs), 0, false); + return makePairwiseConvert(gcollect, type, 2); } } diff --git a/jdk/src/share/classes/java/lang/invoke/MethodHandles.java b/jdk/src/share/classes/java/lang/invoke/MethodHandles.java index 3bf24bc8503..78b01215636 100644 --- a/jdk/src/share/classes/java/lang/invoke/MethodHandles.java +++ b/jdk/src/share/classes/java/lang/invoke/MethodHandles.java @@ -41,6 +41,7 @@ import sun.reflect.misc.ReflectUtil; import sun.security.util.SecurityConstants; import static java.lang.invoke.MethodHandleStatics.*; import static java.lang.invoke.MethodHandleNatives.Constants.*; +import sun.security.util.SecurityConstants; /** * This class consists exclusively of static methods that operate on or return @@ -305,36 +306,30 @@ public class MethodHandles { * * If a security manager is present, member lookups are subject to * additional checks. - * From one to four calls are made to the security manager. + * From one to three calls are made to the security manager. * Any of these calls can refuse access by throwing a * {@link java.lang.SecurityException SecurityException}. * Define {@code smgr} as the security manager, + * {@code lookc} as the lookup class of the current lookup object, * {@code refc} as the containing class in which the member * is being sought, and {@code defc} as the class in which the * member is actually defined. + * The value {@code lookc} is defined as not present + * if the current lookup object does not have + * {@linkplain java.lang.invoke.MethodHandles.Lookup#PRIVATE private access}. * The calls are made according to the following rules: *

      - *
    • In all cases, {@link SecurityManager#checkMemberAccess - * smgr.checkMemberAccess(refc, Member.PUBLIC)} is called. - *
    • If the class loader of the lookup class is not + *
    • If {@code lookc} is not present, or if its class loader is not * the same as or an ancestor of the class loader of {@code refc}, * then {@link SecurityManager#checkPackageAccess * smgr.checkPackageAccess(refcPkg)} is called, * where {@code refcPkg} is the package of {@code refc}. + *
    • If the retrieved member is not public and + * {@code lookc} is not present, then + * {@link SecurityManager#checkPermission smgr.checkPermission} + * with {@code RuntimePermission("accessDeclaredMembers")} is called. *
    • If the retrieved member is not public, - * {@link SecurityManager#checkMemberAccess - * smgr.checkMemberAccess(defc, Member.DECLARED)} is called. - * (Note that {@code defc} might be the same as {@code refc}.) - * The default implementation of this security manager method - * inspects the stack to determine the original caller of - * the reflective request (such as {@code findStatic}), - * and performs additional permission checks if the - * class loader of {@code defc} differs from the class - * loader of the class from which the reflective request came. - *
    • If the retrieved member is not public, - * and if {@code defc} and {@code refc} are in different class loaders, - * and if the class loader of the lookup class is not - * the same as or an ancestor of the class loader of {@code defc}, + * and if {@code defc} and {@code refc} are different, * then {@link SecurityManager#checkPackageAccess * smgr.checkPackageAccess(defcPkg)} is called, * where {@code defcPkg} is the package of {@code defc}. @@ -1053,22 +1048,6 @@ return mh1; return (allowedModes & PRIVATE) != 0; } - /** - * Determine whether a security manager has an overridden - * SecurityManager.checkMemberAccess method. - */ - private boolean isCheckMemberAccessOverridden(SecurityManager sm) { - final Class cls = sm.getClass(); - if (cls == SecurityManager.class) return false; - - try { - return cls.getMethod("checkMemberAccess", Class.class, int.class). - getDeclaringClass() != SecurityManager.class; - } catch (NoSuchMethodException e) { - throw new InternalError("should not reach here"); - } - } - /** * Perform necessary access checks. * Determines a trustable caller class to compare with refc, the symbolic reference class. @@ -1079,45 +1058,22 @@ return mh1; if (smgr == null) return; if (allowedModes == TRUSTED) return; - final boolean overridden = isCheckMemberAccessOverridden(smgr); // Step 1: - { - // Default policy is to allow Member.PUBLIC; no need to check - // permission if SecurityManager is the default implementation - final int which = Member.PUBLIC; - final Class clazz = refc; - if (overridden) { - // Don't refactor; otherwise break the stack depth for - // checkMemberAccess of subclasses of SecurityManager as specified. - smgr.checkMemberAccess(clazz, which); - } - } - - // Step 2: if (!isFullPowerLookup() || !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { ReflectUtil.checkPackageAccess(refc); } - // Step 3: + // Step 2: if (m.isPublic()) return; Class defc = m.getDeclaringClass(); { - // Inline SecurityManager.checkMemberAccess - final int which = Member.DECLARED; - final Class clazz = defc; - if (!overridden) { - if (!isFullPowerLookup()) { - smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); - } - } else { - // Don't refactor; otherwise break the stack depth for - // checkMemberAccess of subclasses of SecurityManager as specified. - smgr.checkMemberAccess(clazz, which); + if (!isFullPowerLookup()) { + smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); } } - // Step 4: + // Step 3: if (defc != refc) { ReflectUtil.checkPackageAccess(defc); } diff --git a/jdk/src/share/classes/java/lang/management/LockInfo.java b/jdk/src/share/classes/java/lang/management/LockInfo.java index 4c05ee84f0c..b08bc046c33 100644 --- a/jdk/src/share/classes/java/lang/management/LockInfo.java +++ b/jdk/src/share/classes/java/lang/management/LockInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ import sun.management.LockInfoCompositeData; * {@link ReentrantReadWriteLock ReentrantReadWriteLock} are * two examples of ownable synchronizers provided by the platform. * - *

      MXBean Mapping

      + *

      MXBean Mapping

      * LockInfo is mapped to a {@link CompositeData CompositeData} * as specified in the {@link #from from} method. * @@ -105,7 +105,7 @@ public class LockInfo { * given {@code CompositeData}. * The given {@code CompositeData} must contain the following attributes: *
      - *
  • Examples

    Examples
    Floating-point ValueHexadecimal String
    {@code 1.0} {@code 0x1.0p0}
    {@code -1.0} {@code -0x1.0p0}
    + *
    * * * diff --git a/jdk/src/share/classes/java/lang/management/ManagementFactory.java b/jdk/src/share/classes/java/lang/management/ManagementFactory.java index 384cf4cda06..6e00706ccd0 100644 --- a/jdk/src/share/classes/java/lang/management/ManagementFactory.java +++ b/jdk/src/share/classes/java/lang/management/ManagementFactory.java @@ -61,7 +61,7 @@ import sun.management.ManagementFactoryHelper; * the management interface of a component of the Java virtual * machine. *

    - *

    Platform MXBeans

    + *

    Platform MXBeans

    *

    * A platform MXBean is a managed bean that * conforms to the JMX @@ -87,7 +87,7 @@ import sun.management.ManagementFactoryHelper; * *

    * An application can access a platform MXBean in the following ways: - *

    1. Direct access to an MXBean interface
    + *

    1. Direct access to an MXBean interface

    *
    *
      *
    • Get an MXBean instance by calling the @@ -107,7 +107,7 @@ import sun.management.ManagementFactoryHelper; * an MXBean of another running virtual machine. *
    • *
    - *
    2. Indirect access to an MXBean interface via MBeanServer
    + *

    2. Indirect access to an MXBean interface via MBeanServer

    *
      *
    • Go through the platform {@code MBeanServer} to access MXBeans * locally or a specific MBeanServerConnection to access @@ -135,7 +135,7 @@ import sun.management.ManagementFactoryHelper; * interfaces: * *
      - *
    Attribute NameType
    + *
    * * * @@ -178,7 +178,7 @@ import sun.management.ManagementFactoryHelper; * the following management interfaces. * *
    - *
    Management InterfaceObjectName
    + *
    * * * @@ -195,7 +195,7 @@ import sun.management.ManagementFactoryHelper; * A Java virtual machine may have one or more instances of the following * management interfaces. *
    - *
    Management InterfaceObjectName
    + *
    * * * @@ -561,6 +561,12 @@ public class ManagementFactory { * in the format of {@link ObjectName ObjectName}. * @param mxbeanInterface the MXBean interface to be implemented * by the proxy. + * @param an {@code mxbeanInterface} type parameter + * + * @return a proxy for a platform MXBean interface of a + * given MXBean name + * that forwards its method calls through the given + * MBeanServerConnection, or {@code null} if not exist. * * @throws IllegalArgumentException if *
      @@ -635,6 +641,7 @@ public class ManagementFactory { * @param mxbeanInterface a management interface for a platform * MXBean with one single instance in the Java virtual machine * if implemented. + * @param an {@code mxbeanInterface} type parameter * * @return the platform MXBean that implements * {@code mxbeanInterface}, or {@code null} if not exist. @@ -670,6 +677,7 @@ public class ManagementFactory { * * @param mxbeanInterface a management interface for a platform * MXBean + * @param an {@code mxbeanInterface} type parameter * * @return the list of platform MXBeans that implement * {@code mxbeanInterface}. @@ -707,6 +715,7 @@ public class ManagementFactory { * @param mxbeanInterface a management interface for a platform * MXBean with one single instance in the Java virtual machine * being monitored, if implemented. + * @param an {@code mxbeanInterface} type parameter * * @return the platform MXBean proxy for * forwarding the method calls of the {@code mxbeanInterface} @@ -750,6 +759,7 @@ public class ManagementFactory { * @param connection the {@code MBeanServerConnection} to forward to. * @param mxbeanInterface a management interface for a platform * MXBean + * @param an {@code mxbeanInterface} type parameter * * @return the list of platform MXBean proxies for * forwarding the method calls of the {@code mxbeanInterface} diff --git a/jdk/src/share/classes/java/lang/management/MemoryMXBean.java b/jdk/src/share/classes/java/lang/management/MemoryMXBean.java index a18748991c1..356873d842c 100644 --- a/jdk/src/share/classes/java/lang/management/MemoryMXBean.java +++ b/jdk/src/share/classes/java/lang/management/MemoryMXBean.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -49,11 +49,11 @@ import javax.management.openmbean.CompositeData; * It can be obtained by calling the * {@link PlatformManagedObject#getObjectName} method. * - *

      Memory

      + *

      Memory

      * The memory system of the Java virtual machine manages * the following kinds of memory: * - *

      1. Heap

      + *

      1. Heap

      * The Java virtual machine has a heap that is the runtime * data area from which memory for all class instances and arrays * are allocated. It is created at the Java virtual machine start-up. @@ -63,7 +63,7 @@ import javax.management.openmbean.CompositeData; *

      The heap may be of a fixed size or may be expanded and shrunk. * The memory for the heap does not need to be contiguous. * - *

      2. Non-Heap Memory

      + *

      2. Non-Heap Memory

      * The Java virtual machine manages memory other than the heap * (referred as non-heap memory). * @@ -87,7 +87,7 @@ import javax.management.openmbean.CompositeData; * machine code translated from the Java virtual machine code for * high performance. * - *

      Memory Pools and Memory Managers

      + *

      Memory Pools and Memory Managers

      * {@link MemoryPoolMXBean Memory pools} and * {@link MemoryManagerMXBean memory managers} are the abstract entities * that monitor and manage the memory system @@ -105,7 +105,7 @@ import javax.management.openmbean.CompositeData; * add or remove memory managers during execution. * A memory pool can be managed by more than one memory manager. * - *

      Memory Usage Monitoring

      + *

      Memory Usage Monitoring

      * * Memory usage is a very important monitoring attribute for the memory system. * The memory usage, for example, could indicate: @@ -131,7 +131,7 @@ import javax.management.openmbean.CompositeData; * certain threshold. It is not intended for an application to detect * and recover from a low memory condition. * - *

      Notifications

      + *

      Notifications

      * *

      This MemoryMXBean is a * {@link javax.management.NotificationEmitter NotificationEmitter} @@ -169,7 +169,7 @@ import javax.management.openmbean.CompositeData; * MemoryNotificationInfo}. * *


      - *

      NotificationEmitter

      + *

      NotificationEmitter

      * The MemoryMXBean object returned by * {@link ManagementFactory#getMemoryMXBean} implements * the {@link javax.management.NotificationEmitter NotificationEmitter} diff --git a/jdk/src/share/classes/java/lang/management/MemoryNotificationInfo.java b/jdk/src/share/classes/java/lang/management/MemoryNotificationInfo.java index 3b0b156ee30..0c45555ee2e 100644 --- a/jdk/src/share/classes/java/lang/management/MemoryNotificationInfo.java +++ b/jdk/src/share/classes/java/lang/management/MemoryNotificationInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -212,7 +212,7 @@ public class MemoryNotificationInfo { * The given CompositeData must contain * the following attributes: *
      - *
    Management InterfaceObjectName
    + *
    * * * diff --git a/jdk/src/share/classes/java/lang/management/MemoryPoolMXBean.java b/jdk/src/share/classes/java/lang/management/MemoryPoolMXBean.java index bcd7c5559b0..82aa1fcda87 100644 --- a/jdk/src/share/classes/java/lang/management/MemoryPoolMXBean.java +++ b/jdk/src/share/classes/java/lang/management/MemoryPoolMXBean.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -49,7 +49,7 @@ package java.lang.management; * It can be obtained by calling the * {@link PlatformManagedObject#getObjectName} method. * - *

    Memory Type

    + *

    Memory Type

    *

    The Java virtual machine has a heap for object allocation and also * maintains non-heap memory for the method area and the Java virtual * machine execution. The Java virtual machine can have one or more @@ -60,7 +60,7 @@ package java.lang.management; *

  • {@link MemoryType#NON_HEAP non-heap}
  • * * - *

    Memory Usage Monitoring

    + *

    Memory Usage Monitoring

    * * A memory pool has the following attributes: *
      @@ -71,7 +71,7 @@ package java.lang.management; * (only supported by some garbage-collected memory pools) *
    * - *

    1. Memory Usage

    + *

    1. Memory Usage

    * * The {@link #getUsage} method provides an estimate * of the current usage of a memory pool. @@ -86,14 +86,14 @@ package java.lang.management; * the current memory usage. An implementation should document when * this is the case. * - *

    2. Peak Memory Usage

    + *

    2. Peak Memory Usage

    * * The Java virtual machine maintains the peak memory usage of a memory * pool since the virtual machine was started or the peak was reset. * The peak memory usage is returned by the {@link #getPeakUsage} method * and reset by calling the {@link #resetPeakUsage} method. * - *

    3. Usage Threshold

    + *

    3. Usage Threshold

    * * Each memory pool has a manageable attribute * called the usage threshold which has a default value supplied @@ -304,7 +304,7 @@ package java.lang.management; * * * - *

    4. Collection Usage Threshold

    + *

    4. Collection Usage Threshold

    * * Collection usage threshold is a manageable attribute only applicable * to some garbage-collected memory pools. diff --git a/jdk/src/share/classes/java/lang/management/MemoryUsage.java b/jdk/src/share/classes/java/lang/management/MemoryUsage.java index 4dc23c0fe46..bbb75a26484 100644 --- a/jdk/src/share/classes/java/lang/management/MemoryUsage.java +++ b/jdk/src/share/classes/java/lang/management/MemoryUsage.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,8 +36,7 @@ import sun.management.MemoryUsageCompositeData; * the heap or non-heap memory of the Java virtual machine as a whole. * *

    A MemoryUsage object contains four values: - *

      - *
    Attribute NameType
    + *
    * * * * *
    init represents the initial amount of memory (in bytes) that @@ -78,7 +77,6 @@ import sun.management.MemoryUsageCompositeData; *
    - * * * Below is a picture showing an example of a memory pool: *

    @@ -98,7 +96,7 @@ import sun.management.MemoryUsageCompositeData; * max * * - *

    MXBean Mapping

    + *

    MXBean Mapping

    * MemoryUsage is mapped to a {@link CompositeData CompositeData} * with attributes as specified in the {@link #from from} method. * @@ -254,7 +252,7 @@ public class MemoryUsage { * must contain the following attributes: *

    *

    - * + *
    * * * diff --git a/jdk/src/share/classes/java/lang/management/MonitorInfo.java b/jdk/src/share/classes/java/lang/management/MonitorInfo.java index 658be133fda..e97a3173b9e 100644 --- a/jdk/src/share/classes/java/lang/management/MonitorInfo.java +++ b/jdk/src/share/classes/java/lang/management/MonitorInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,7 +32,7 @@ import sun.management.MonitorInfoCompositeData; * Information about an object monitor lock. An object monitor is locked * when entering a synchronization block or method on that object. * - *

    MXBean Mapping

    + *

    MXBean Mapping

    * MonitorInfo is mapped to a {@link CompositeData CompositeData} * with attributes as specified in * the {@link #from from} method. @@ -106,7 +106,7 @@ public class MonitorInfo extends LockInfo { * * mapped type for the {@link LockInfo} class: *
    - *
    Attribute NameType
    + *
    * * * diff --git a/jdk/src/share/classes/java/lang/management/RuntimeMXBean.java b/jdk/src/share/classes/java/lang/management/RuntimeMXBean.java index e4142d3e439..0e680fdf04e 100644 --- a/jdk/src/share/classes/java/lang/management/RuntimeMXBean.java +++ b/jdk/src/share/classes/java/lang/management/RuntimeMXBean.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -272,7 +272,7 @@ public interface RuntimeMXBean extends PlatformManagedObject { * *

    * MBeanServer access:
    - * The mapped type of List is String[]. + * The mapped type of {@code List} is String[]. * * @return a list of String objects; each element * is an argument passed to the Java virtual machine. @@ -312,7 +312,7 @@ public interface RuntimeMXBean extends PlatformManagedObject { * {@link javax.management.openmbean.TabularData TabularData} * with two items in each row as follows: *

    - *
    Attribute NameType
    + *
    * * * diff --git a/jdk/src/share/classes/java/lang/management/ThreadInfo.java b/jdk/src/share/classes/java/lang/management/ThreadInfo.java index 676b698f5a2..e6f80b2eb23 100644 --- a/jdk/src/share/classes/java/lang/management/ThreadInfo.java +++ b/jdk/src/share/classes/java/lang/management/ThreadInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,13 +33,13 @@ import static java.lang.Thread.State.*; /** * Thread information. ThreadInfo contains the information * about a thread including: - *

    General thread information

    + *

    General thread information

    *
      *
    • Thread ID.
    • *
    • Name of the thread.
    • *
    * - *

    Execution information

    + *

    Execution information

    *
      *
    • Thread state.
    • *
    • The object upon which the thread is blocked due to: @@ -652,7 +652,7 @@ public class ThreadInfo { * The given CompositeData must contain the following attributes * unless otherwise specified below: *
      - *
    Item NameItem Type
    + *
    * * * @@ -722,7 +722,7 @@ public class ThreadInfo { * Each element is a CompositeData representing * StackTraceElement containing the following attributes: *
    - *
    Attribute NameType
    + *
    * * * diff --git a/jdk/src/share/classes/java/lang/management/ThreadMXBean.java b/jdk/src/share/classes/java/lang/management/ThreadMXBean.java index 30251d51f60..02a87dcf6d3 100644 --- a/jdk/src/share/classes/java/lang/management/ThreadMXBean.java +++ b/jdk/src/share/classes/java/lang/management/ThreadMXBean.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -49,7 +49,7 @@ import java.util.Map; * It can be obtained by calling the * {@link PlatformManagedObject#getObjectName} method. * - *

    Thread ID

    + *

    Thread ID

    * Thread ID is a positive long value returned by calling the * {@link java.lang.Thread#getId} method for a thread. * The thread ID is unique during its lifetime. When a thread @@ -58,7 +58,7 @@ import java.util.Map; *

    Some methods in this interface take a thread ID or an array * of thread IDs as the input parameter and return per-thread information. * - *

    Thread CPU time

    + *

    Thread CPU time

    * A Java virtual machine implementation may support measuring * the CPU time for the current thread, for any thread, or for no threads. * @@ -83,7 +83,7 @@ import java.util.Map; * Enabling thread CPU measurement could be expensive in some * Java virtual machine implementations. * - *

    Thread Contention Monitoring

    + *

    Thread Contention Monitoring

    * Some Java virtual machines may support thread contention monitoring. * When thread contention monitoring is enabled, the accumulated elapsed * time that the thread has blocked for synchronization or waited for @@ -96,7 +96,7 @@ import java.util.Map; * {@link #setThreadContentionMonitoringEnabled} method can be used to enable * thread contention monitoring. * - *

    Synchronization Information and Deadlock Detection

    + *

    Synchronization Information and Deadlock Detection

    * Some Java virtual machines may support monitoring of * {@linkplain #isObjectMonitorUsageSupported object monitor usage} and * {@linkplain #isSynchronizerUsageSupported ownable synchronizer usage}. diff --git a/jdk/src/share/classes/java/lang/ref/Reference.java b/jdk/src/share/classes/java/lang/ref/Reference.java index bc24e9df026..1cdeefd992b 100644 --- a/jdk/src/share/classes/java/lang/ref/Reference.java +++ b/jdk/src/share/classes/java/lang/ref/Reference.java @@ -89,7 +89,7 @@ public abstract class Reference { private T referent; /* Treated specially by GC */ - ReferenceQueue queue; + volatile ReferenceQueue queue; /* When active: NULL * pending: this @@ -225,9 +225,7 @@ public abstract class Reference { * been enqueued */ public boolean isEnqueued() { - synchronized (this) { - return (this.next != null && this.queue == ReferenceQueue.ENQUEUED); - } + return (this.queue == ReferenceQueue.ENQUEUED); } /** diff --git a/jdk/src/share/classes/java/lang/ref/ReferenceQueue.java b/jdk/src/share/classes/java/lang/ref/ReferenceQueue.java index 00ca9b3e0ed..a2fad1cbce3 100644 --- a/jdk/src/share/classes/java/lang/ref/ReferenceQueue.java +++ b/jdk/src/share/classes/java/lang/ref/ReferenceQueue.java @@ -55,25 +55,29 @@ public class ReferenceQueue { private long queueLength = 0; boolean enqueue(Reference r) { /* Called only by Reference class */ - synchronized (r) { - if (r.queue == ENQUEUED) return false; - synchronized (lock) { - r.queue = ENQUEUED; - r.next = (head == null) ? r : head; - head = r; - queueLength++; - if (r instanceof FinalReference) { - sun.misc.VM.addFinalRefCount(1); - } - lock.notifyAll(); - return true; + synchronized (lock) { + // Check that since getting the lock this reference hasn't already been + // enqueued (and even then removed) + ReferenceQueue queue = r.queue; + if ((queue == NULL) || (queue == ENQUEUED)) { + return false; } + assert queue == this; + r.queue = ENQUEUED; + r.next = (head == null) ? r : head; + head = r; + queueLength++; + if (r instanceof FinalReference) { + sun.misc.VM.addFinalRefCount(1); + } + lock.notifyAll(); + return true; } } private Reference reallyPoll() { /* Must hold lock */ - if (head != null) { - Reference r = head; + Reference r = head; + if (r != null) { head = (r.next == r) ? null : r.next; r.queue = NULL; r.next = r; diff --git a/jdk/src/share/classes/java/lang/reflect/AnnotatedElement.java b/jdk/src/share/classes/java/lang/reflect/AnnotatedElement.java index 6bc894efaba..50a7e6af904 100644 --- a/jdk/src/share/classes/java/lang/reflect/AnnotatedElement.java +++ b/jdk/src/share/classes/java/lang/reflect/AnnotatedElement.java @@ -32,49 +32,101 @@ import java.lang.annotation.AnnotationFormatError; * Represents an annotated element of the program currently running in this * VM. This interface allows annotations to be read reflectively. All * annotations returned by methods in this interface are immutable and - * serializable. It is permissible for the caller to modify the - * arrays returned by accessors for array-valued enum members; it will - * have no affect on the arrays returned to other callers. + * serializable. The arrays returned by methods of this interface may be modified + * by callers without affecting the arrays returned to other callers. * *

    The {@link #getAnnotationsByType(Class)} and {@link * #getDeclaredAnnotationsByType(Class)} methods support multiple - * annotations of the same type on an element. If the argument to either method - * is a repeatable annotation type (JLS 9.6), then the method will "look - * through" a container annotation (JLS 9.7) which was generated at - * compile-time to wrap multiple annotations of the argument type. + * annotations of the same type on an element. If the argument to + * either method is a repeatable annotation type (JLS 9.6), then the + * method will "look through" a container annotation (JLS 9.7), if + * present, and return any annotations inside the container. Container + * annotations may be generated at compile-time to wrap multiple + * annotations of the argument type. * - *

    The terms directly present and present are used - * throughout this interface to describe precisely which annotations are - * returned by methods: + *

    The terms directly present, indirectly present, + * present, and associated are used throughout this + * interface to describe precisely which annotations are returned by + * methods: * *

      - *
    • An annotation A is directly present on an element E if E is - * associated with a RuntimeVisibleAnnotations or - * RuntimeVisibleParameterAnnotations attribute, and: + * + *
    • An annotation A is directly present on an + * element E if E has a {@code + * RuntimeVisibleAnnotations} or {@code + * RuntimeVisibleParameterAnnotations} or {@code + * RuntimeVisibleTypeAnnotations} attribute, and the attribute + * contains A. + * + *
    • An annotation A is indirectly present on an + * element E if E has a {@code RuntimeVisibleAnnotations} or + * {@code RuntimeVisibleParameterAnnotations} or {@code RuntimeVisibleTypeAnnotations} + * attribute, and A 's type is repeatable, and the attribute contains + * exactly one annotation whose value element contains A and whose + * type is the containing annotation type of A 's type. + * + *
    • An annotation A is present on an element E if either: * *
        - *
      • for an invocation of {@code get[Declared]Annotation(Class)} or - * {@code get[Declared]Annotations()}, the attribute contains A. * - *
      • for an invocation of {@code get[Declared]AnnotationsByType(Class)}, the - * attribute either contains A or, if the type of A is repeatable, contains - * exactly one annotation whose value element contains A and whose type is the - * containing annotation type of A's type (JLS 9.6). + *
      • A is directly present on E; or + * + *
      • No annotation of A 's type is directly present on + * E, and E is a class, and A 's type is + * inheritable, and A is present on the superclass of E. + * *
      * - *

      - *

    • An annotation A is present on an element E if either: + *
    • An annotation A is associated with an element E + * if either: * *
        - *
      • A is directly present on E; or * - *
      • A is not directly present on E, and E is a class, and A's type - * is inheritable (JLS 9.6.3.3), and A is present on the superclass of - * E. + *
      • A is directly or indirectly present on E; or + * + *
      • No annotation of A 's type is directly or indirectly + * present on E, and E is a class, and A's type + * is inheritable, and A is associated with the superclass of + * E. + * *
      * *
    * + *

    The table below summarizes which kind of annotation presence + * different methods in this interface examine. + * + *

    Attribute NameType
    + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    Overview of kind of presence detected by different AnnotatedElement methods
    Kind of Presence
    MethodDirectly PresentIndirectly PresentPresentAssociated
    {@code T}{@link #getAnnotation(Class) getAnnotation(Class<T>)} + * X
    {@code Annotation[]}{@link #getAnnotations getAnnotations()} + * X
    {@code T[]}{@link #getAnnotationsByType(Class) getAnnotationsByType(Class<T>)} + * X
    {@code T}{@link #getDeclaredAnnotation(Class) getDeclaredAnnotation(Class<T>)} + * X
    {@code Annotation[]}{@link #getDeclaredAnnotations getDeclaredAnnotations()} + * X
    {@code T[]}{@link #getDeclaredAnnotationsByType(Class) getDeclaredAnnotationsByType(Class<T>)} + * XX
    + * + *

    For an invocation of {@code get[Declared]AnnotationsByType( Class < + * T >)}, the order of annotations which are directly or indirectly + * present on an element E is computed as if indirectly present + * annotations on E are directly present on E in place + * of their container annotation, in the order in which they appear in + * the value element of the container annotation. + *

    If an annotation returned by a method in this interface contains * (directly or indirectly) a {@link Class}-valued member referring to * a class that is not accessible in this VM, attempting to read the class @@ -85,10 +137,11 @@ import java.lang.annotation.AnnotationFormatError; * a {@link EnumConstantNotPresentException} if the enum constant in the * annotation is no longer present in the enum type. * - *

    Attempting to read annotations of a repeatable annotation type T - * that are contained in an annotation whose type is not, in fact, the - * containing annotation type of T, will result in an {@link - * AnnotationFormatError}. + *

    If an annotation type T is (meta-)annotated with an + * {@code @Repeatable} annotation whose value element indicates a type + * TC, but TC does not declare a {@code value()} method + * with a return type of T{@code []}, then an exception of type + * {@link java.lang.annotation.AnnotationFormatError} is thrown. * *

    Finally, attempting to read a member whose definition has evolved * incompatibly will result in a {@link @@ -106,7 +159,7 @@ import java.lang.annotation.AnnotationFormatError; public interface AnnotatedElement { /** * Returns true if an annotation for the specified type - * is present on this element, else false. This method + * is present on this element, else false. This method * is designed primarily for convenient access to marker annotations. * *

    The truth value returned by this method is equivalent to: @@ -128,7 +181,7 @@ public interface AnnotatedElement { /** * Returns this element's annotation for the specified type if - * such an annotation is present, else null. + * such an annotation is present, else null. * * @param the type of the annotation to query for and return if present * @param annotationClass the Class object corresponding to the @@ -146,6 +199,20 @@ public interface AnnotatedElement { * If there are no annotations present on this element, the return * value is an array of length 0. * + * The caller of this method is free to modify the returned array; it will + * have no effect on the arrays returned to other callers. + * + * @return annotations present on this element + * @since 1.5 + */ + Annotation[] getAnnotations(); + + /** + * Returns annotations that are associated with this element. + * + * If there are no annotations associated with this element, the return + * value is an array of length 0. + * * The difference between this method and {@link #getAnnotation(Class)} * is that this method detects if its argument is a repeatable * annotation type (JLS 9.6), and if so, attempts to find one or @@ -159,65 +226,54 @@ public interface AnnotatedElement { * @param annotationClass the Class object corresponding to the * annotation type * @return all this element's annotations for the specified annotation type if - * present on this element, else an array of length zero + * associated with this element, else an array of length zero * @throws NullPointerException if the given annotation class is null * @since 1.8 */ T[] getAnnotationsByType(Class annotationClass); - /** - * Returns annotations that are present on this element. - * - * If there are no annotations present on this element, the return - * value is an array of length 0. - * - * The caller of this method is free to modify the returned array; it will - * have no effect on the arrays returned to other callers. - * - * @return annotations present on this element - * @since 1.5 - */ - Annotation[] getAnnotations(); - /** * Returns this element's annotation for the specified type if - * such an annotation is present, else null. + * such an annotation is directly present, else null. * * This method ignores inherited annotations. (Returns null if no * annotations are directly present on this element.) * - * @param the type of the annotation to query for and return if present + * @param the type of the annotation to query for and return if directly present * @param annotationClass the Class object corresponding to the * annotation type * @return this element's annotation for the specified annotation type if - * present on this element, else null + * directly present on this element, else null * @throws NullPointerException if the given annotation class is null * @since 1.8 */ T getDeclaredAnnotation(Class annotationClass); /** - * Returns annotations that are directly present on this element. - * This method ignores inherited annotations. + * Returns this element's annotation(s) for the specified type if + * such annotations are either directly present or + * indirectly present. This method ignores inherited + * annotations. * - * If there are no annotations directly present on this element, - * the return value is an array of length 0. + * If there are no specified annotations directly or indirectly + * present on this element, the return value is an array of length + * 0. * * The difference between this method and {@link * #getDeclaredAnnotation(Class)} is that this method detects if its * argument is a repeatable annotation type (JLS 9.6), and if so, * attempts to find one or more annotations of that type by "looking - * through" a container annotation. + * through" a container annotation if one is present. * * The caller of this method is free to modify the returned array; it will * have no effect on the arrays returned to other callers. * * @param the type of the annotation to query for and return - * if directly present + * if directly or indirectly present * @param annotationClass the Class object corresponding to the * annotation type * @return all this element's annotations for the specified annotation type if - * present on this element, else an array of length zero + * directly or indirectly present on this element, else an array of length zero * @throws NullPointerException if the given annotation class is null * @since 1.8 */ diff --git a/jdk/src/share/classes/java/lang/reflect/Executable.java b/jdk/src/share/classes/java/lang/reflect/Executable.java index 2501fd68d5d..aa8820fd2d7 100644 --- a/jdk/src/share/classes/java/lang/reflect/Executable.java +++ b/jdk/src/share/classes/java/lang/reflect/Executable.java @@ -326,8 +326,12 @@ public abstract class Executable extends AccessibleObject tmp = getParameters0(); // If we get back nothing, then synthesize parameters - if (tmp == null) + if (tmp == null) { + hasRealParameterData = false; tmp = synthesizeAllParams(); + } else { + hasRealParameterData = true; + } parameters = tmp; } @@ -335,6 +339,16 @@ public abstract class Executable extends AccessibleObject return tmp; } + boolean hasRealParameterData() { + // If this somehow gets called before parameters gets + // initialized, force it into existence. + if (parameters == null) { + privateGetParameters(); + } + return hasRealParameterData; + } + + private transient volatile boolean hasRealParameterData; private transient volatile Parameter[] parameters; private native Parameter[] getParameters0(); diff --git a/jdk/src/share/classes/java/lang/reflect/Member.java b/jdk/src/share/classes/java/lang/reflect/Member.java index 5d3ab3dd8b3..a539cb54614 100644 --- a/jdk/src/share/classes/java/lang/reflect/Member.java +++ b/jdk/src/share/classes/java/lang/reflect/Member.java @@ -42,14 +42,12 @@ interface Member { /** * Identifies the set of all public members of a class or interface, * including inherited members. - * @see java.lang.SecurityManager#checkMemberAccess */ public static final int PUBLIC = 0; /** * Identifies the set of declared members of a class or interface. * Inherited members are not included. - * @see java.lang.SecurityManager#checkMemberAccess */ public static final int DECLARED = 1; diff --git a/jdk/src/share/classes/java/lang/reflect/Parameter.java b/jdk/src/share/classes/java/lang/reflect/Parameter.java index 20969347255..f49c1daa436 100644 --- a/jdk/src/share/classes/java/lang/reflect/Parameter.java +++ b/jdk/src/share/classes/java/lang/reflect/Parameter.java @@ -94,6 +94,19 @@ public final class Parameter implements AnnotatedElement { return executable.hashCode() ^ index; } + /** + * Returns true if the parameter has a name according to the class + * file; returns false otherwise. Whether a parameter has a name + * is determined by the {@literal MethodParameters} attribute of + * the method which declares the parameter. + * + * @return true if and only if the parameter has a name according + * to the class file. + */ + public boolean isNamePresent() { + return executable.hasRealParameterData(); + } + /** * Returns a string describing this parameter. The format is the * modifiers for the parameter, if any, in canonical order as @@ -149,11 +162,15 @@ public final class Parameter implements AnnotatedElement { /** * Returns the name of the parameter. If the parameter's name is - * defined in a class file, then that name will be returned by - * this method. Otherwise, this method will synthesize a name of - * the form argN, where N is the index of the parameter. + * {@linkplain isNamePresent() present}, then this method returns + * the name provided by the class file. Otherwise, this method + * synthesizes a name of the form argN, where N is the index of + * the parameter in the descriptor of the method which declares + * the parameter. * - * @return the name of the parameter + * @return The name of the parameter, either provided by the class + * file or synthesized if the class file does not provide + * a name. */ public String getName() { // Note: empty strings as paramete names are now outlawed. diff --git a/jdk/src/share/classes/java/math/BigDecimal.java b/jdk/src/share/classes/java/math/BigDecimal.java index 944f8a79fbe..1a7ca811226 100644 --- a/jdk/src/share/classes/java/math/BigDecimal.java +++ b/jdk/src/share/classes/java/math/BigDecimal.java @@ -2592,14 +2592,18 @@ public class BigDecimal extends Number implements Comparable { * the {@code BigDecimal} value {@code 600.0}, which has * [{@code BigInteger}, {@code scale}] components equals to * [6000, 1], yields {@code 6E2} with [{@code BigInteger}, - * {@code scale}] components equals to [6, -2] + * {@code scale}] components equals to [6, -2]. If + * this BigDecimal is numerically equal to zero, then + * {@code BigDecimal.ZERO} is returned. * * @return a numerically equal {@code BigDecimal} with any * trailing zeros removed. * @since 1.5 */ public BigDecimal stripTrailingZeros() { - if(intCompact!=INFLATED) { + if (intCompact == 0 || (intVal != null && intVal.signum() == 0)) { + return BigDecimal.ZERO; + } else if (intCompact != INFLATED) { return createAndStripZerosToMatchScale(intCompact, scale, Long.MIN_VALUE); } else { return createAndStripZerosToMatchScale(intVal, scale, Long.MIN_VALUE); diff --git a/jdk/src/share/classes/java/net/CookieStore.java b/jdk/src/share/classes/java/net/CookieStore.java index a8232d2930c..89b9c41dd01 100644 --- a/jdk/src/share/classes/java/net/CookieStore.java +++ b/jdk/src/share/classes/java/net/CookieStore.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -75,6 +75,8 @@ public interface CookieStore { * @return an immutable list of HttpCookie, * return empty list if no cookies match the given URI * + * @param uri the uri associated with the cookies to be returned + * * @throws NullPointerException if uri is null * * @see #add diff --git a/jdk/src/share/classes/java/net/HttpURLPermission.java b/jdk/src/share/classes/java/net/HttpURLPermission.java index 55d37fda8ca..4e038bc739e 100644 --- a/jdk/src/share/classes/java/net/HttpURLPermission.java +++ b/jdk/src/share/classes/java/net/HttpURLPermission.java @@ -47,6 +47,7 @@ import java.security.Permission; * in {@link java.io.FilePermission}. There are three different ways * as the following examples show: * + * * * * @@ -57,7 +58,7 @@ import java.security.Permission; * which only differ in the final path component, represented by the '*'. * * - * *
    URL Examples
    Example urlDescription
    http://www.oracle.com/a/b/c.htmlA url which identifies a specific (single) resource
    http://www.oracle.com/a/b/- + *
    http://www.oracle.com/a/b/-The '-' character refers to all resources recursively below the * preceding path (eg. http://www.oracle.com/a/b/c/d/e.html matches this * example). @@ -164,6 +165,8 @@ public final class HttpURLPermission extends Permission { * methods and request headers by invoking the two argument * constructor as follows: HttpURLPermission(url, "*:*") * + * @param url the url string + * * @throws IllegalArgumentException if url does not result in a valid {@link URI} */ public HttpURLPermission(String url) { @@ -204,11 +207,10 @@ public final class HttpURLPermission extends Permission { *
  • if the path or paths specified by p's url are contained in the * set of paths specified by this's url, then return true *
  • otherwise, return false
  • - * - *

    - * Some examples of how paths are matched are shown below: - *

    - * + * + *

    Some examples of how paths are matched are shown below: + *

    + * * * * diff --git a/jdk/src/share/classes/java/net/Inet4Address.java b/jdk/src/share/classes/java/net/Inet4Address.java index 529257fa90d..6c59a692f82 100644 --- a/jdk/src/share/classes/java/net/Inet4Address.java +++ b/jdk/src/share/classes/java/net/Inet4Address.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,7 +36,7 @@ import java.io.ObjectStreamException; * and RFC 2365: * Administratively Scoped IP Multicast * - *

    Textual representation of IP addresses

    + *

    Textual representation of IP addresses

    * * Textual representation of IPv4 address used as input to methods * takes one of the following forms: diff --git a/jdk/src/share/classes/java/net/Inet6Address.java b/jdk/src/share/classes/java/net/Inet6Address.java index 4a2d4e22473..169a180de11 100644 --- a/jdk/src/share/classes/java/net/Inet6Address.java +++ b/jdk/src/share/classes/java/net/Inet6Address.java @@ -35,7 +35,7 @@ import java.util.Enumeration; * Defined by * RFC 2373: IP Version 6 Addressing Architecture. * - *

    Textual representation of IP addresses

    + *

    Textual representation of IP addresses

    * * Textual representation of IPv6 address used as input to methods * takes one of the following forms: @@ -156,7 +156,7 @@ import java.util.Enumeration; * system. Usually, the numeric values can be determined through administration * tools on the system. Each interface may have multiple values, one for each * scope. If the scope is unspecified, then the default value used is zero. - *

  • As a string. This must be the exact string that is returned by + *
  • As a string. This must be the exact string that is returned by * {@link java.net.NetworkInterface#getName()} for the particular interface in * question. When an Inet6Address is created in this way, the numeric scope-id * is determined at the time the object is created by querying the relevant diff --git a/jdk/src/share/classes/java/net/InetAddress.java b/jdk/src/share/classes/java/net/InetAddress.java index 1154c9a80f4..aa5ef16705d 100644 --- a/jdk/src/share/classes/java/net/InetAddress.java +++ b/jdk/src/share/classes/java/net/InetAddress.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -65,7 +65,7 @@ import sun.net.spi.nameservice.*; * with a host name or whether it has already done reverse host name * resolution). * - *

    Address types

    + *

    Address types

    * *
  • Examples of Path Matching
    this's pathp's pathmatch
    /a/b/a/byes
    /a/b/*/a/b/cyes
    * @@ -165,7 +165,6 @@ import sun.net.spi.nameservice.*; *

    * A value of -1 indicates "cache forever". * - *

    *

    networkaddress.cache.negative.ttl (default: 10)
    *
    Indicates the caching policy for un-successful name lookups * from the name service. The value is specified as as integer to diff --git a/jdk/src/share/classes/java/net/ProtocolFamily.java b/jdk/src/share/classes/java/net/ProtocolFamily.java index c6aa95b1861..5d02326db18 100644 --- a/jdk/src/share/classes/java/net/ProtocolFamily.java +++ b/jdk/src/share/classes/java/net/ProtocolFamily.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,6 +34,8 @@ package java.net; public interface ProtocolFamily { /** * Returns the name of the protocol family. + * + * @return the name of the protocol family */ String name(); } diff --git a/jdk/src/share/classes/java/net/SocketOption.java b/jdk/src/share/classes/java/net/SocketOption.java index cfa4616bcef..2ccf57f5f33 100644 --- a/jdk/src/share/classes/java/net/SocketOption.java +++ b/jdk/src/share/classes/java/net/SocketOption.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -45,11 +45,15 @@ public interface SocketOption { /** * Returns the name of the socket option. + * + * @return the name of the socket option */ String name(); /** * Returns the type of the socket option value. + * + * @return the type of the socket option value */ Class type(); } diff --git a/jdk/src/share/classes/java/net/URI.java b/jdk/src/share/classes/java/net/URI.java index ed90f090c29..643c8af8a71 100644 --- a/jdk/src/share/classes/java/net/URI.java +++ b/jdk/src/share/classes/java/net/URI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -61,13 +61,13 @@ import java.lang.NullPointerException; // for javadoc * and relativizing URI instances. Instances of this class are immutable. * * - *

    URI syntax and components

    + *

    URI syntax and components

    * * At the highest level a URI reference (hereinafter simply "URI") in string * form has the syntax * *
    - * [scheme:]scheme-specific-part[#fragment] + * [scheme:]scheme-specific-part[#fragment] *
    * * where square brackets [...] delineate optional components and the characters @@ -334,14 +334,14 @@ import java.lang.NullPointerException; // for javadoc * *
      * - *
    • The {@link #URI(java.lang.String) single-argument - * constructor} requires any illegal characters in its argument to be + *

    • The {@linkplain #URI(java.lang.String) single-argument + * constructor} requires any illegal characters in its argument to be * quoted and preserves any escaped octets and other characters that * are present.

    • * - *
    • The {@link + *

    • The {@linkplain * #URI(java.lang.String,java.lang.String,java.lang.String,int,java.lang.String,java.lang.String,java.lang.String) - * multi-argument constructors} quote illegal characters as + * multi-argument constructors} quote illegal characters as * required by the components in which they appear. The percent character * ('%') is always quoted by these constructors. Any other * characters are preserved.

    • diff --git a/jdk/src/share/classes/java/nio/X-Buffer.java.template b/jdk/src/share/classes/java/nio/X-Buffer.java.template index 03a7255c16a..60f0733c9ab 100644 --- a/jdk/src/share/classes/java/nio/X-Buffer.java.template +++ b/jdk/src/share/classes/java/nio/X-Buffer.java.template @@ -1495,7 +1495,7 @@ public abstract class $Type$Buffer #end[char] public $Streamtype$Stream $type$s() { return StreamSupport.$streamtype$Stream(() -> new $Type$BufferSpliterator(this), - Buffer.SPLITERATOR_CHARACTERISTICS); + Buffer.SPLITERATOR_CHARACTERISTICS, false); } #end[streamableType] diff --git a/jdk/src/share/classes/java/nio/file/Files.java b/jdk/src/share/classes/java/nio/file/Files.java index ca0263d0660..586859f17dc 100644 --- a/jdk/src/share/classes/java/nio/file/Files.java +++ b/jdk/src/share/classes/java/nio/file/Files.java @@ -3269,9 +3269,10 @@ public final class Files { } }; - return new DelegatingCloseableStream<>(ds, - StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, - Spliterator.DISTINCT))); + Stream s = StreamSupport.stream( + Spliterators.spliteratorUnknownSize(it, Spliterator.DISTINCT), + false); + return new DelegatingCloseableStream<>(ds, s); } /** @@ -3358,9 +3359,12 @@ public final class Files { throws IOException { FileTreeIterator iterator = new FileTreeIterator(start, maxDepth, options); - return new DelegatingCloseableStream<>(iterator, - StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT)) - .map(entry -> entry.file())); + + Stream s = StreamSupport.stream( + Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT), + false). + map(entry -> entry.file()); + return new DelegatingCloseableStream<>(iterator, s); } /** @@ -3455,10 +3459,13 @@ public final class Files { throws IOException { FileTreeIterator iterator = new FileTreeIterator(start, maxDepth, options); - return new DelegatingCloseableStream<>(iterator, - StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT)) - .filter(entry -> matcher.test(entry.file(), entry.attributes())) - .map(entry -> entry.file())); + + Stream s = StreamSupport.stream( + Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT), + false). + filter(entry -> matcher.test(entry.file(), entry.attributes())). + map(entry -> entry.file()); + return new DelegatingCloseableStream<>(iterator, s); } /** diff --git a/jdk/src/share/classes/java/security/AuthProvider.java b/jdk/src/share/classes/java/security/AuthProvider.java index a5310aa9f42..571a1fe085f 100644 --- a/jdk/src/share/classes/java/security/AuthProvider.java +++ b/jdk/src/share/classes/java/security/AuthProvider.java @@ -41,6 +41,8 @@ import javax.security.auth.callback.CallbackHandler; */ public abstract class AuthProvider extends Provider { + private static final long serialVersionUID = 4197859053084546461L; + /** * Constructs a provider with the specified name, version number, * and information. diff --git a/jdk/src/share/classes/java/util/AbstractMap.java b/jdk/src/share/classes/java/util/AbstractMap.java index fdca2aa7993..7c5153fc3bb 100644 --- a/jdk/src/share/classes/java/util/AbstractMap.java +++ b/jdk/src/share/classes/java/util/AbstractMap.java @@ -543,6 +543,8 @@ public abstract class AbstractMap implements Map { /** * Utility method for SimpleEntry and SimpleImmutableEntry. * Test for equality, checking for nulls. + * + * NB: Do not replace with Object.equals until JDK-8015417 is resolved. */ private static boolean eq(Object o1, Object o2) { return o1 == null ? o2 == null : o1.equals(o2); diff --git a/jdk/src/share/classes/java/util/ArrayList.java b/jdk/src/share/classes/java/util/ArrayList.java index 2211cc8f10d..b7d5349cc00 100644 --- a/jdk/src/share/classes/java/util/ArrayList.java +++ b/jdk/src/share/classes/java/util/ArrayList.java @@ -70,9 +70,9 @@ import java.util.function.UnaryOperator; * unsynchronized access to the list:
        *   List list = Collections.synchronizedList(new ArrayList(...));
      * - *

      + *

      * The iterators returned by this class's {@link #iterator() iterator} and - * {@link #listIterator(int) listIterator} methods are fail-fast: + * {@link #listIterator(int) listIterator} methods are fail-fast: * if the list is structurally modified at any time after the iterator is * created, in any way except through the iterator's own * {@link ListIterator#remove() remove} or diff --git a/jdk/src/share/classes/java/util/Arrays.java b/jdk/src/share/classes/java/util/Arrays.java index 196a31e5767..47c99ef7f82 100644 --- a/jdk/src/share/classes/java/util/Arrays.java +++ b/jdk/src/share/classes/java/util/Arrays.java @@ -984,6 +984,7 @@ public class Arrays { * {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to * execute any parallel tasks. * + * @param the class of the objects to be sorted * @param a the array to be sorted * * @throws ClassCastException if the array contains elements that are not @@ -1035,6 +1036,7 @@ public class Arrays { * array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is * used to execute any parallel tasks. * + * @param the class of the objects to be sorted * @param a the array to be sorted * @param fromIndex the index of the first element (inclusive) to be * sorted @@ -1087,6 +1089,7 @@ public class Arrays { * {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to * execute any parallel tasks. * + * @param the class of the objects to be sorted * @param a the array to be sorted * @param cmp the comparator to determine the order of the array. A * {@code null} value indicates that the elements' @@ -1138,6 +1141,7 @@ public class Arrays { * array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is * used to execute any parallel tasks. * + * @param the class of the objects to be sorted * @param a the array to be sorted * @param fromIndex the index of the first element (inclusive) to be * sorted @@ -1412,6 +1416,7 @@ public class Arrays { * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, * January 1993. * + * @param the class of the objects to be sorted * @param a the array to be sorted * @param c the comparator to determine the order of the array. A * {@code null} value indicates that the elements' @@ -1475,6 +1480,7 @@ public class Arrays { * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, * January 1993. * + * @param the class of the objects to be sorted * @param a the array to be sorted * @param fromIndex the index of the first element (inclusive) to be * sorted @@ -1569,6 +1575,7 @@ public class Arrays { * Parallel prefix computation is usually more efficient than * sequential loops for large arrays. * + * @param the class of the objects in the array * @param array the array, which is modified in-place by this method * @param op a side-effect-free, associative function to perform the * cumulation @@ -1585,6 +1592,7 @@ public class Arrays { * Performs {@link #parallelPrefix(Object[], BinaryOperator)} * for the given subrange of the array. * + * @param the class of the objects in the array * @param array the array * @param fromIndex the index of the first element, inclusive * @param toIndex the index of the last element, exclusive @@ -2437,6 +2445,7 @@ public class Arrays { * elements equal to the specified object, there is no guarantee which one * will be found. * + * @param the class of the objects in the array * @param a the array to be searched * @param key the value to be searched for * @param c the comparator by which the array is ordered. A @@ -2472,6 +2481,7 @@ public class Arrays { * If the range contains multiple elements equal to the specified object, * there is no guarantee which one will be found. * + * @param the class of the objects in the array * @param a the array to be searched * @param fromIndex the index of the first element (inclusive) to be * searched @@ -3143,6 +3153,7 @@ public class Arrays { * is greater than that of the original array. * The resulting array is of exactly the same class as the original array. * + * @param the class of the objects in the array * @param original the array to be copied * @param newLength the length of the copy to be returned * @return a copy of the original array, truncated or padded with nulls @@ -3166,6 +3177,8 @@ public class Arrays { * is greater than that of the original array. * The resulting array is of the class newType. * + * @param the class of the objects in the original array + * @param the class of the objects in the returned array * @param original the array to be copied * @param newLength the length of the copy to be returned * @param newType the class of the copy to be returned @@ -3396,6 +3409,7 @@ public class Arrays { *

      * The resulting array is of exactly the same class as the original array. * + * @param the class of the objects in the array * @param original the array from which a range is to be copied * @param from the initial index of the range to be copied, inclusive * @param to the final index of the range to be copied, exclusive. @@ -3428,6 +3442,8 @@ public class Arrays { * of the returned array will be to - from. * The resulting array is of the class newType. * + * @param the class of the objects in the original array + * @param the class of the objects in the returned array * @param original the array from which a range is to be copied * @param from the initial index of the range to be copied, inclusive * @param to the final index of the range to be copied, exclusive. @@ -3760,6 +3776,7 @@ public class Arrays { * List<String> stooges = Arrays.asList("Larry", "Moe", "Curly"); * * + * @param the class of the objects in the array * @param a the array by which the list will be backed * @return a list view of the specified array */ @@ -4966,7 +4983,7 @@ public class Arrays { * @since 1.8 */ public static Stream stream(T[] array, int startInclusive, int endExclusive) { - return StreamSupport.stream(spliterator(array, startInclusive, endExclusive)); + return StreamSupport.stream(spliterator(array, startInclusive, endExclusive), false); } /** @@ -4996,7 +5013,7 @@ public class Arrays { * @since 1.8 */ public static IntStream stream(int[] array, int startInclusive, int endExclusive) { - return StreamSupport.intStream(spliterator(array, startInclusive, endExclusive)); + return StreamSupport.intStream(spliterator(array, startInclusive, endExclusive), false); } /** @@ -5026,7 +5043,7 @@ public class Arrays { * @since 1.8 */ public static LongStream stream(long[] array, int startInclusive, int endExclusive) { - return StreamSupport.longStream(spliterator(array, startInclusive, endExclusive)); + return StreamSupport.longStream(spliterator(array, startInclusive, endExclusive), false); } /** @@ -5056,6 +5073,6 @@ public class Arrays { * @since 1.8 */ public static DoubleStream stream(double[] array, int startInclusive, int endExclusive) { - return StreamSupport.doubleStream(spliterator(array, startInclusive, endExclusive)); + return StreamSupport.doubleStream(spliterator(array, startInclusive, endExclusive), false); } } diff --git a/jdk/src/share/classes/java/util/Base64.java b/jdk/src/share/classes/java/util/Base64.java index 2dbaf921a52..39da03b7e3c 100644 --- a/jdk/src/share/classes/java/util/Base64.java +++ b/jdk/src/share/classes/java/util/Base64.java @@ -42,24 +42,21 @@ import java.nio.charset.StandardCharsets; * *

      *

        - * - *
      • Basic + *
      • Basic *

        Uses "The Base64 Alphabet" as specified in Table 1 of * RFC 4648 and RFC 2045 for encoding and decoding operation. * The encoder does not add any line feed (line separator) * character. The decoder rejects data that contains characters * outside the base64 alphabet.

      • * - * - *
      • URL and Filename safe + *
      • URL and Filename safe *

        Uses the "URL and Filename safe Base64 Alphabet" as specified * in Table 2 of RFC 4648 for encoding and decoding. The * encoder does not add any line feed (line separator) character. * The decoder rejects data that contains characters outside the * base64 alphabet.

      • * - * - *
      • MIME + *
      • MIME *

        Uses the "The Base64 Alphabet" as specified in Table 1 of * RFC 2045 for encoding and decoding operation. The encoded output * must be represented in lines of no more than 76 characters each diff --git a/jdk/src/share/classes/java/util/BitSet.java b/jdk/src/share/classes/java/util/BitSet.java index 56faccc66fb..c7c3143221f 100644 --- a/jdk/src/share/classes/java/util/BitSet.java +++ b/jdk/src/share/classes/java/util/BitSet.java @@ -189,6 +189,7 @@ public class BitSet implements Cloneable, java.io.Serializable { * @param longs a long array containing a little-endian representation * of a sequence of bits to be used as the initial bits of the * new bit set + * @return a {@code BitSet} containing all the bits in the long array * @since 1.7 */ public static BitSet valueOf(long[] longs) { @@ -212,6 +213,8 @@ public class BitSet implements Cloneable, java.io.Serializable { * @param lb a long buffer containing a little-endian representation * of a sequence of bits between its position and limit, to be * used as the initial bits of the new bit set + * @return a {@code BitSet} containing all the bits in the buffer in the + * specified range * @since 1.7 */ public static BitSet valueOf(LongBuffer lb) { @@ -237,6 +240,7 @@ public class BitSet implements Cloneable, java.io.Serializable { * @param bytes a byte array containing a little-endian * representation of a sequence of bits to be used as the * initial bits of the new bit set + * @return a {@code BitSet} containing all the bits in the byte array * @since 1.7 */ public static BitSet valueOf(byte[] bytes) { @@ -257,6 +261,8 @@ public class BitSet implements Cloneable, java.io.Serializable { * @param bb a byte buffer containing a little-endian representation * of a sequence of bits between its position and limit, to be * used as the initial bits of the new bit set + * @return a {@code BitSet} containing all the bits in the buffer in the + * specified range * @since 1.7 */ public static BitSet valueOf(ByteBuffer bb) { @@ -1231,6 +1237,7 @@ public class BitSet implements Cloneable, java.io.Serializable { new BitSetIterator(), cardinality(), Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED), Spliterator.SIZED | Spliterator.SUBSIZED | - Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED); + Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED, + false); } } diff --git a/jdk/src/share/classes/java/util/Calendar.java b/jdk/src/share/classes/java/util/Calendar.java index 566b8b090be..076b59db52c 100644 --- a/jdk/src/share/classes/java/util/Calendar.java +++ b/jdk/src/share/classes/java/util/Calendar.java @@ -96,7 +96,7 @@ import sun.util.spi.CalendarProvider; * concrete subclass, such as ERA. See individual field * documentation and subclass documentation for details. * - *

        Getting and Setting Calendar Field Values

        + *

        Getting and Setting Calendar Field Values

        * *

        The calendar field values can be set by calling the set * methods. Any field values set in a Calendar will not be @@ -207,7 +207,7 @@ import sun.util.spi.CalendarProvider; *

        Field Manipulation

        * * The calendar fields can be changed using three methods: - * set(), add(), and roll().

        + * set(), add(), and roll(). * *

        set(f, value) changes calendar field * f to value. In addition, it sets an @@ -2024,6 +2024,7 @@ public abstract class Calendar implements Serializable, Cloneable, Comparableget method call. * + * @param field the calendar field to test * @return true if the given calendar field has a value set; * false otherwise. */ diff --git a/jdk/src/share/classes/java/util/Collection.java b/jdk/src/share/classes/java/util/Collection.java index 249be10f0ea..7fe7a75bc44 100644 --- a/jdk/src/share/classes/java/util/Collection.java +++ b/jdk/src/share/classes/java/util/Collection.java @@ -64,9 +64,9 @@ import java.util.stream.StreamSupport; * but is not required to, throw the exception if the collection to be added * is empty. * - *

        + *

        * Some collection implementations have restrictions on the elements that - * they may contain. For example, some implementations prohibit null elements, + * they may contain. For example, some implementations prohibit null elements, * and some have restrictions on the types of their elements. Attempting to * add an ineligible element throws an unchecked exception, typically * NullPointerException or ClassCastException. Attempting @@ -232,6 +232,7 @@ public interface Collection extends Iterable { * Note that toArray(new Object[0]) is identical in function to * toArray(). * + * @param the runtime type of the array to contain the collection * @param a the array into which the elements of this collection are to be * stored, if it is big enough; otherwise, a new array of the same * runtime type is allocated for this purpose. @@ -557,7 +558,7 @@ public interface Collection extends Iterable { * @since 1.8 */ default Stream stream() { - return StreamSupport.stream(spliterator()); + return StreamSupport.stream(spliterator(), false); } /** @@ -578,6 +579,6 @@ public interface Collection extends Iterable { * @since 1.8 */ default Stream parallelStream() { - return StreamSupport.parallelStream(spliterator()); + return StreamSupport.stream(spliterator(), true); } } diff --git a/jdk/src/share/classes/java/util/Collections.java b/jdk/src/share/classes/java/util/Collections.java index ad4540db14a..43ce42eeea6 100644 --- a/jdk/src/share/classes/java/util/Collections.java +++ b/jdk/src/share/classes/java/util/Collections.java @@ -27,6 +27,7 @@ package java.util; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.IOException; +import java.io.InvalidObjectException; import java.lang.reflect.Array; import java.util.function.BiConsumer; import java.util.function.BiFunction; @@ -34,6 +35,8 @@ import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.UnaryOperator; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; /** * This class consists exclusively of static methods that operate on or return @@ -136,7 +139,7 @@ public class Collections { * *

        The implementation was adapted from Tim Peters's list sort for Python * ( - * TimSort). It uses techiques from Peter McIlroy's "Optimistic + * TimSort). It uses techniques from Peter McIlroy's "Optimistic * Sorting and Information Theoretic Complexity", in Proceedings of the * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, * January 1993. @@ -147,6 +150,7 @@ public class Collections { * n2 log(n) performance that would result from attempting * to sort a linked list in place. * + * @param the class of the objects in the list * @param list the list to be sorted. * @throws ClassCastException if the list contains elements that are not * mutually comparable (for example, strings and integers). @@ -197,7 +201,7 @@ public class Collections { * *

        The implementation was adapted from Tim Peters's list sort for Python * ( - * TimSort). It uses techiques from Peter McIlroy's "Optimistic + * TimSort). It uses techniques from Peter McIlroy's "Optimistic * Sorting and Information Theoretic Complexity", in Proceedings of the * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, * January 1993. @@ -208,6 +212,7 @@ public class Collections { * n2 log(n) performance that would result from attempting * to sort a linked list in place. * + * @param the class of the objects in the list * @param list the list to be sorted. * @param c the comparator to determine the order of the list. A * {@code null} value indicates that the elements' natural @@ -246,6 +251,7 @@ public class Collections { * this method will do an iterator-based binary search that performs * O(n) link traversals and O(log n) element comparisons. * + * @param the class of the objects in the list * @param list the list to be searched. * @param key the key to be searched for. * @return the index of the search key, if it is contained in the list; @@ -346,6 +352,7 @@ public class Collections { * this method will do an iterator-based binary search that performs * O(n) link traversals and O(log n) element comparisons. * + * @param the class of the objects in the list * @param list the list to be searched. * @param key the key to be searched for. * @param c the comparator by which the list is ordered. @@ -565,6 +572,7 @@ public class Collections { * * This method runs in linear time. * + * @param the class of the objects in the list * @param list the list to be filled with the specified element. * @param obj The element with which to fill the specified list. * @throws UnsupportedOperationException if the specified list or its @@ -594,6 +602,7 @@ public class Collections { * * This method runs in linear time. * + * @param the class of the objects in the lists * @param dest The destination list. * @param src The source list. * @throws IndexOutOfBoundsException if the destination list is too small @@ -632,6 +641,7 @@ public class Collections { * This method iterates over the entire collection, hence it requires * time proportional to the size of the collection. * + * @param the class of the objects in the collection * @param coll the collection whose minimum element is to be determined. * @return the minimum element of the given collection, according * to the natural ordering of its elements. @@ -664,6 +674,7 @@ public class Collections { * This method iterates over the entire collection, hence it requires * time proportional to the size of the collection. * + * @param the class of the objects in the collection * @param coll the collection whose minimum element is to be determined. * @param comp the comparator with which to determine the minimum element. * A null value indicates that the elements' natural @@ -703,6 +714,7 @@ public class Collections { * This method iterates over the entire collection, hence it requires * time proportional to the size of the collection. * + * @param the class of the objects in the collection * @param coll the collection whose maximum element is to be determined. * @return the maximum element of the given collection, according * to the natural ordering of its elements. @@ -735,6 +747,7 @@ public class Collections { * This method iterates over the entire collection, hence it requires * time proportional to the size of the collection. * + * @param the class of the objects in the collection * @param coll the collection whose maximum element is to be determined. * @param comp the comparator with which to determine the maximum element. * A null value indicates that the elements' natural @@ -869,6 +882,7 @@ public class Collections { * (oldVal==null ? e==null : oldVal.equals(e)). * (This method has no effect on the size of the list.) * + * @param the class of the objects in the list * @param list the list in which replacement is to occur. * @param oldVal the old value to be replaced. * @param newVal the new value with which oldVal is to be @@ -1050,6 +1064,7 @@ public class Collections { * The returned collection will be serializable if the specified collection * is serializable. * + * @param the class of the objects in the collection * @param c the collection for which an unmodifiable view is to be * returned. * @return an unmodifiable view of the specified collection. @@ -1145,6 +1160,7 @@ public class Collections { * The returned set will be serializable if the specified set * is serializable. * + * @param the class of the objects in the set * @param s the set for which an unmodifiable view is to be returned. * @return an unmodifiable view of the specified set. */ @@ -1176,6 +1192,7 @@ public class Collections { * The returned sorted set will be serializable if the specified sorted set * is serializable. * + * @param the class of the objects in the set * @param s the sorted set for which an unmodifiable view is to be * returned. * @return an unmodifiable view of the specified sorted set. @@ -1211,6 +1228,95 @@ public class Collections { public E last() {return ss.last();} } + /** + * Returns an unmodifiable view of the specified navigable set. This method + * allows modules to provide users with "read-only" access to internal + * navigable sets. Query operations on the returned navigable set "read + * through" to the specified navigable set. Attempts to modify the returned + * navigable set, whether direct, via its iterator, or via its + * {@code subSet}, {@code headSet}, or {@code tailSet} views, result in + * an {@code UnsupportedOperationException}.

        + * + * The returned navigable set will be serializable if the specified + * navigable set is serializable. + * + * @param the class of the objects in the set + * @param s the navigable set for which an unmodifiable view is to be + * returned + * @return an unmodifiable view of the specified navigable set + * @since 1.8 + */ + public static NavigableSet unmodifiableNavigableSet(NavigableSet s) { + return new UnmodifiableNavigableSet<>(s); + } + + /** + * Wraps a navigable set and disables all of the mutative operations. + * + * @param type of elements + * @serial include + */ + static class UnmodifiableNavigableSet + extends UnmodifiableSortedSet + implements NavigableSet, Serializable { + + private static final long serialVersionUID = -6027448201786391929L; + + /** + * A singleton empty unmodifiable navigable set used for + * {@link #emptyNavigableSet()}. + * + * @param type of elements, if there were any, and bounds + */ + private static class EmptyNavigableSet extends UnmodifiableNavigableSet + implements Serializable { + private static final long serialVersionUID = -6291252904449939134L; + + public EmptyNavigableSet() { + super(new TreeSet()); + } + + private Object readResolve() { return EMPTY_NAVIGABLE_SET; } + } + + @SuppressWarnings("rawtypes") + private static final NavigableSet EMPTY_NAVIGABLE_SET = + new EmptyNavigableSet<>(); + + /** + * The instance we are protecting. + */ + private final NavigableSet ns; + + UnmodifiableNavigableSet(NavigableSet s) {super(s); ns = s;} + + public E lower(E e) { return ns.lower(e); } + public E floor(E e) { return ns.floor(e); } + public E ceiling(E e) { return ns.ceiling(e); } + public E higher(E e) { return ns.higher(e); } + public E pollFirst() { throw new UnsupportedOperationException(); } + public E pollLast() { throw new UnsupportedOperationException(); } + public NavigableSet descendingSet() + { return new UnmodifiableNavigableSet<>(ns.descendingSet()); } + public Iterator descendingIterator() + { return descendingSet().iterator(); } + + public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { + return new UnmodifiableNavigableSet<>( + ns.subSet(fromElement, fromInclusive, toElement, toInclusive)); + } + + public NavigableSet headSet(E toElement, boolean inclusive) { + return new UnmodifiableNavigableSet<>( + ns.headSet(toElement, inclusive)); + } + + public NavigableSet tailSet(E fromElement, boolean inclusive) { + return new UnmodifiableNavigableSet<>( + ns.tailSet(fromElement, inclusive)); + } + } + /** * Returns an unmodifiable view of the specified list. This method allows * modules to provide users with "read-only" access to internal @@ -1223,6 +1329,7 @@ public class Collections { * is serializable. Similarly, the returned list will implement * {@link RandomAccess} if the specified list does. * + * @param the class of the objects in the list * @param list the list for which an unmodifiable view is to be returned. * @return an unmodifiable view of the specified list. */ @@ -1238,6 +1345,7 @@ public class Collections { static class UnmodifiableList extends UnmodifiableCollection implements List { private static final long serialVersionUID = -283967356065247728L; + final List list; UnmodifiableList(List list) { @@ -1366,6 +1474,8 @@ public class Collections { * The returned map will be serializable if the specified map * is serializable. * + * @param the class of the map keys + * @param the class of the map values * @param m the map for which an unmodifiable view is to be returned. * @return an unmodifiable view of the specified map. */ @@ -1510,6 +1620,86 @@ public class Collections { // Need to cast to raw in order to work around a limitation in the type system super((Set)s); } + + static Consumer> entryConsumer(Consumer> action) { + return e -> action.accept(new UnmodifiableEntry<>(e)); + } + + public void forEach(Consumer> action) { + Objects.requireNonNull(action); + c.forEach(entryConsumer(action)); + } + + static final class UnmodifiableEntrySetSpliterator + implements Spliterator> { + final Spliterator> s; + + UnmodifiableEntrySetSpliterator(Spliterator> s) { + this.s = s; + } + + @Override + public boolean tryAdvance(Consumer> action) { + Objects.requireNonNull(action); + return s.tryAdvance(entryConsumer(action)); + } + + @Override + public void forEachRemaining(Consumer> action) { + Objects.requireNonNull(action); + s.forEachRemaining(entryConsumer(action)); + } + + @Override + public Spliterator> trySplit() { + Spliterator> split = s.trySplit(); + return split == null + ? null + : new UnmodifiableEntrySetSpliterator<>(split); + } + + @Override + public long estimateSize() { + return s.estimateSize(); + } + + @Override + public long getExactSizeIfKnown() { + return s.getExactSizeIfKnown(); + } + + @Override + public int characteristics() { + return s.characteristics(); + } + + @Override + public boolean hasCharacteristics(int characteristics) { + return s.hasCharacteristics(characteristics); + } + + @Override + public Comparator> getComparator() { + return s.getComparator(); + } + } + + @SuppressWarnings("unchecked") + public Spliterator> spliterator() { + return new UnmodifiableEntrySetSpliterator<>( + (Spliterator>) c.spliterator()); + } + + @Override + public Stream> stream() { + return StreamSupport.stream(spliterator(), false); + } + + @Override + public Stream> parallelStream() { + return StreamSupport.stream(spliterator(), true); + } + public Iterator> iterator() { return new Iterator>() { private final Iterator> i = c.iterator(); @@ -1600,7 +1790,8 @@ public class Collections { private static class UnmodifiableEntry implements Map.Entry { private Map.Entry e; - UnmodifiableEntry(Map.Entry e) {this.e = e;} + UnmodifiableEntry(Map.Entry e) + {this.e = Objects.requireNonNull(e);} public K getKey() {return e.getKey();} public V getValue() {return e.getValue();} @@ -1634,6 +1825,8 @@ public class Collections { * The returned sorted map will be serializable if the specified sorted map * is serializable. * + * @param the class of the map keys + * @param the class of the map values * @param m the sorted map for which an unmodifiable view is to be * returned. * @return an unmodifiable view of the specified sorted map. @@ -1652,24 +1845,153 @@ public class Collections { private final SortedMap sm; - UnmodifiableSortedMap(SortedMap m) {super(m); sm = m;} - - public Comparator comparator() {return sm.comparator();} - - public SortedMap subMap(K fromKey, K toKey) { - return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey)); - } - public SortedMap headMap(K toKey) { - return new UnmodifiableSortedMap<>(sm.headMap(toKey)); - } - public SortedMap tailMap(K fromKey) { - return new UnmodifiableSortedMap<>(sm.tailMap(fromKey)); - } - - public K firstKey() {return sm.firstKey();} - public K lastKey() {return sm.lastKey();} + UnmodifiableSortedMap(SortedMap m) {super(m); sm = m; } + public Comparator comparator() { return sm.comparator(); } + public SortedMap subMap(K fromKey, K toKey) + { return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey)); } + public SortedMap headMap(K toKey) + { return new UnmodifiableSortedMap<>(sm.headMap(toKey)); } + public SortedMap tailMap(K fromKey) + { return new UnmodifiableSortedMap<>(sm.tailMap(fromKey)); } + public K firstKey() { return sm.firstKey(); } + public K lastKey() { return sm.lastKey(); } } + /** + * Returns an unmodifiable view of the specified navigable map. This method + * allows modules to provide users with "read-only" access to internal + * navigable maps. Query operations on the returned navigable map "read + * through" to the specified navigable map. Attempts to modify the returned + * navigable map, whether direct, via its collection views, or via its + * {@code subMap}, {@code headMap}, or {@code tailMap} views, result in + * an {@code UnsupportedOperationException}.

        + * + * The returned navigable map will be serializable if the specified + * navigable map is serializable. + * + * @param the class of the map keys + * @param the class of the map values + * @param m the navigable map for which an unmodifiable view is to be + * returned + * @return an unmodifiable view of the specified navigable map + * @since 1.8 + */ + public static NavigableMap unmodifiableNavigableMap(NavigableMap m) { + return new UnmodifiableNavigableMap<>(m); + } + + /** + * @serial include + */ + static class UnmodifiableNavigableMap + extends UnmodifiableSortedMap + implements NavigableMap, Serializable { + private static final long serialVersionUID = -4858195264774772197L; + + /** + * A class for the {@link EMPTY_NAVIGABLE_MAP} which needs readResolve + * to preserve singleton property. + * + * @param type of keys, if there were any, and of bounds + * @param type of values, if there were any + */ + private static class EmptyNavigableMap extends UnmodifiableNavigableMap + implements Serializable { + + private static final long serialVersionUID = -2239321462712562324L; + + EmptyNavigableMap() { super(new TreeMap()); } + + @Override + public NavigableSet navigableKeySet() + { return emptyNavigableSet(); } + + private Object readResolve() { return EMPTY_NAVIGABLE_MAP; } + } + + /** + * Singleton for {@link emptyNavigableMap()} which is also immutable. + */ + private static final EmptyNavigableMap EMPTY_NAVIGABLE_MAP = + new EmptyNavigableMap<>(); + + /** + * The instance we wrap and protect. + */ + private final NavigableMap nm; + + UnmodifiableNavigableMap(NavigableMap m) + {super(m); nm = m;} + + public K lowerKey(K key) { return nm.lowerKey(key); } + public K floorKey(K key) { return nm.floorKey(key); } + public K ceilingKey(K key) { return nm.ceilingKey(key); } + public K higherKey(K key) { return nm.higherKey(key); } + + public Entry lowerEntry(K key) { + Entry lower = (Entry) nm.lowerEntry(key); + return (null != lower) + ? new UnmodifiableEntrySet.UnmodifiableEntry(lower) + : null; + } + + public Entry floorEntry(K key) { + Entry floor = (Entry) nm.floorEntry(key); + return (null != floor) + ? new UnmodifiableEntrySet.UnmodifiableEntry(floor) + : null; + } + + public Entry ceilingEntry(K key) { + Entry ceiling = (Entry) nm.ceilingEntry(key); + return (null != ceiling) + ? new UnmodifiableEntrySet.UnmodifiableEntry(ceiling) + : null; + } + + + public Entry higherEntry(K key) { + Entry higher = (Entry) nm.higherEntry(key); + return (null != higher) + ? new UnmodifiableEntrySet.UnmodifiableEntry(higher) + : null; + } + + public Entry firstEntry() { + Entry first = (Entry) nm.firstEntry(); + return (null != first) + ? new UnmodifiableEntrySet.UnmodifiableEntry(first) + : null; + } + + public Entry lastEntry() { + Entry last = (Entry) nm.lastEntry(); + return (null != last) + ? new UnmodifiableEntrySet.UnmodifiableEntry(last) + : null; + } + + public Entry pollFirstEntry() + { throw new UnsupportedOperationException(); } + public Entry pollLastEntry() + { throw new UnsupportedOperationException(); } + public NavigableMap descendingMap() + { return unmodifiableNavigableMap(nm.descendingMap()); } + public NavigableSet navigableKeySet() + { return unmodifiableNavigableSet(nm.navigableKeySet()); } + public NavigableSet descendingKeySet() + { return unmodifiableNavigableSet(nm.descendingKeySet()); } + + public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { + return unmodifiableNavigableMap( + nm.subMap(fromKey, fromInclusive, toKey, toInclusive)); + } + + public NavigableMap headMap(K toKey, boolean inclusive) + { return unmodifiableNavigableMap(nm.headMap(toKey, inclusive)); } + public NavigableMap tailMap(K fromKey, boolean inclusive) + { return unmodifiableNavigableMap(nm.tailMap(fromKey, inclusive)); } + } // Synch Wrappers @@ -1702,6 +2024,7 @@ public class Collections { * The returned collection will be serializable if the specified collection * is serializable. * + * @param the class of the objects in the collection * @param c the collection to be "wrapped" in a synchronized collection. * @return a synchronized view of the specified collection. */ @@ -1723,14 +2046,13 @@ public class Collections { final Object mutex; // Object on which to synchronize SynchronizedCollection(Collection c) { - if (c==null) - throw new NullPointerException(); - this.c = c; + this.c = Objects.requireNonNull(c); mutex = this; } + SynchronizedCollection(Collection c, Object mutex) { - this.c = c; - this.mutex = mutex; + this.c = Objects.requireNonNull(c); + this.mutex = Objects.requireNonNull(mutex); } public int size() { @@ -1818,6 +2140,7 @@ public class Collections { *

        The returned set will be serializable if the specified set is * serializable. * + * @param the class of the objects in the set * @param s the set to be "wrapped" in a synchronized set. * @return a synchronized view of the specified set. */ @@ -1888,6 +2211,7 @@ public class Collections { *

        The returned sorted set will be serializable if the specified * sorted set is serializable. * + * @param the class of the objects in the set * @param s the sorted set to be "wrapped" in a synchronized sorted set. * @return a synchronized view of the specified sorted set. */ @@ -1944,6 +2268,121 @@ public class Collections { } } + /** + * Returns a synchronized (thread-safe) navigable set backed by the + * specified navigable set. In order to guarantee serial access, it is + * critical that all access to the backing navigable set is + * accomplished through the returned navigable set (or its views).

        + * + * It is imperative that the user manually synchronize on the returned + * navigable set when iterating over it or any of its {@code subSet}, + * {@code headSet}, or {@code tailSet} views. + *

        +     *  NavigableSet s = Collections.synchronizedNavigableSet(new TreeSet());
        +     *      ...
        +     *  synchronized (s) {
        +     *      Iterator i = s.iterator(); // Must be in the synchronized block
        +     *      while (i.hasNext())
        +     *          foo(i.next());
        +     *  }
        +     * 
        + * or: + *
        +     *  NavigableSet s = Collections.synchronizedNavigableSet(new TreeSet());
        +     *  NavigableSet s2 = s.headSet(foo, true);
        +     *      ...
        +     *  synchronized (s) {  // Note: s, not s2!!!
        +     *      Iterator i = s2.iterator(); // Must be in the synchronized block
        +     *      while (i.hasNext())
        +     *          foo(i.next());
        +     *  }
        +     * 
        + * Failure to follow this advice may result in non-deterministic behavior. + * + *

        The returned navigable set will be serializable if the specified + * navigable set is serializable. + * + * @param the class of the objects in the set + * @param s the navigable set to be "wrapped" in a synchronized navigable + * set + * @return a synchronized view of the specified navigable set + * @since 1.8 + */ + public static NavigableSet synchronizedNavigableSet(NavigableSet s) { + return new SynchronizedNavigableSet<>(s); + } + + /** + * @serial include + */ + static class SynchronizedNavigableSet + extends SynchronizedSortedSet + implements NavigableSet + { + private static final long serialVersionUID = -5505529816273629798L; + + private final NavigableSet ns; + + SynchronizedNavigableSet(NavigableSet s) { + super(s); + ns = s; + } + + SynchronizedNavigableSet(NavigableSet s, Object mutex) { + super(s, mutex); + ns = s; + } + public E lower(E e) { synchronized (mutex) {return ns.lower(e);} } + public E floor(E e) { synchronized (mutex) {return ns.floor(e);} } + public E ceiling(E e) { synchronized (mutex) {return ns.ceiling(e);} } + public E higher(E e) { synchronized (mutex) {return ns.higher(e);} } + public E pollFirst() { synchronized (mutex) {return ns.pollFirst();} } + public E pollLast() { synchronized (mutex) {return ns.pollLast();} } + + public NavigableSet descendingSet() { + synchronized (mutex) { + return new SynchronizedNavigableSet<>(ns.descendingSet(), mutex); + } + } + + public Iterator descendingIterator() + { synchronized (mutex) { return descendingSet().iterator(); } } + + public NavigableSet subSet(E fromElement, E toElement) { + synchronized (mutex) { + return new SynchronizedNavigableSet<>(ns.subSet(fromElement, true, toElement, false), mutex); + } + } + public NavigableSet headSet(E toElement) { + synchronized (mutex) { + return new SynchronizedNavigableSet<>(ns.headSet(toElement, false), mutex); + } + } + public NavigableSet tailSet(E fromElement) { + synchronized (mutex) { + return new SynchronizedNavigableSet(ns.tailSet(fromElement, true), mutex); + } + } + + public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { + synchronized (mutex) { + return new SynchronizedNavigableSet<>(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), mutex); + } + } + + public NavigableSet headSet(E toElement, boolean inclusive) { + synchronized (mutex) { + return new SynchronizedNavigableSet<>(ns.headSet(toElement, inclusive), mutex); + } + } + + public NavigableSet tailSet(E fromElement, boolean inclusive) { + synchronized (mutex) { + return new SynchronizedNavigableSet<>(ns.tailSet(fromElement, inclusive)); + } + } + } + /** * Returns a synchronized (thread-safe) list backed by the specified * list. In order to guarantee serial access, it is critical that @@ -1966,6 +2405,7 @@ public class Collections { *

        The returned list will be serializable if the specified list is * serializable. * + * @param the class of the objects in the list * @param list the list to be "wrapped" in a synchronized list. * @return a synchronized view of the specified list. */ @@ -2135,6 +2575,8 @@ public class Collections { *

        The returned map will be serializable if the specified map is * serializable. * + * @param the class of the map keys + * @param the class of the map values * @param m the map to be "wrapped" in a synchronized map. * @return a synchronized view of the specified map. */ @@ -2153,9 +2595,7 @@ public class Collections { final Object mutex; // Object on which to synchronize SynchronizedMap(Map m) { - if (m==null) - throw new NullPointerException(); - this.m = m; + this.m = Objects.requireNonNull(m); mutex = this; } @@ -2327,6 +2767,8 @@ public class Collections { *

        The returned sorted map will be serializable if the specified * sorted map is serializable. * + * @param the class of the map keys + * @param the class of the map values * @param m the sorted map to be "wrapped" in a synchronized sorted map. * @return a synchronized view of the specified sorted map. */ @@ -2334,7 +2776,6 @@ public class Collections { return new SynchronizedSortedMap<>(m); } - /** * @serial include */ @@ -2384,6 +2825,166 @@ public class Collections { } } + /** + * Returns a synchronized (thread-safe) navigable map backed by the + * specified navigable map. In order to guarantee serial access, it is + * critical that all access to the backing navigable map is + * accomplished through the returned navigable map (or its views).

        + * + * It is imperative that the user manually synchronize on the returned + * navigable map when iterating over any of its collection views, or the + * collections views of any of its {@code subMap}, {@code headMap} or + * {@code tailMap} views. + *

        +     *  NavigableMap m = Collections.synchronizedNavigableMap(new TreeMap());
        +     *      ...
        +     *  Set s = m.keySet();  // Needn't be in synchronized block
        +     *      ...
        +     *  synchronized (m) {  // Synchronizing on m, not s!
        +     *      Iterator i = s.iterator(); // Must be in synchronized block
        +     *      while (i.hasNext())
        +     *          foo(i.next());
        +     *  }
        +     * 
        + * or: + *
        +     *  NavigableMap m = Collections.synchronizedNavigableMap(new TreeMap());
        +     *  NavigableMap m2 = m.subMap(foo, true, bar, false);
        +     *      ...
        +     *  Set s2 = m2.keySet();  // Needn't be in synchronized block
        +     *      ...
        +     *  synchronized (m) {  // Synchronizing on m, not m2 or s2!
        +     *      Iterator i = s.iterator(); // Must be in synchronized block
        +     *      while (i.hasNext())
        +     *          foo(i.next());
        +     *  }
        +     * 
        + * Failure to follow this advice may result in non-deterministic behavior. + * + *

        The returned navigable map will be serializable if the specified + * navigable map is serializable. + * + * @param the class of the map keys + * @param the class of the map values + * @param m the navigable map to be "wrapped" in a synchronized navigable + * map + * @return a synchronized view of the specified navigable map. + * @since 1.8 + */ + public static NavigableMap synchronizedNavigableMap(NavigableMap m) { + return new SynchronizedNavigableMap<>(m); + } + + /** + * A synchronized NavigableMap. + * + * @serial include + */ + static class SynchronizedNavigableMap + extends SynchronizedSortedMap + implements NavigableMap + { + private static final long serialVersionUID = 699392247599746807L; + + private final NavigableMap nm; + + SynchronizedNavigableMap(NavigableMap m) { + super(m); + nm = m; + } + SynchronizedNavigableMap(NavigableMap m, Object mutex) { + super(m, mutex); + nm = m; + } + + public Entry lowerEntry(K key) + { synchronized (mutex) { return nm.lowerEntry(key); } } + public K lowerKey(K key) + { synchronized (mutex) { return nm.lowerKey(key); } } + public Entry floorEntry(K key) + { synchronized (mutex) { return nm.floorEntry(key); } } + public K floorKey(K key) + { synchronized (mutex) { return nm.floorKey(key); } } + public Entry ceilingEntry(K key) + { synchronized (mutex) { return nm.ceilingEntry(key); } } + public K ceilingKey(K key) + { synchronized (mutex) { return nm.ceilingKey(key); } } + public Entry higherEntry(K key) + { synchronized (mutex) { return nm.higherEntry(key); } } + public K higherKey(K key) + { synchronized (mutex) { return nm.higherKey(key); } } + public Entry firstEntry() + { synchronized (mutex) { return nm.firstEntry(); } } + public Entry lastEntry() + { synchronized (mutex) { return nm.lastEntry(); } } + public Entry pollFirstEntry() + { synchronized (mutex) { return nm.pollFirstEntry(); } } + public Entry pollLastEntry() + { synchronized (mutex) { return nm.pollLastEntry(); } } + + public NavigableMap descendingMap() { + synchronized (mutex) { + return + new SynchronizedNavigableMap(nm.descendingMap(), mutex); + } + } + + public NavigableSet keySet() { + return navigableKeySet(); + } + + public NavigableSet navigableKeySet() { + synchronized (mutex) { + return new SynchronizedNavigableSet(nm.navigableKeySet(), mutex); + } + } + + public NavigableSet descendingKeySet() { + synchronized (mutex) { + return new SynchronizedNavigableSet(nm.descendingKeySet(), mutex); + } + } + + + public SortedMap subMap(K fromKey, K toKey) { + synchronized (mutex) { + return new SynchronizedNavigableMap<>( + nm.subMap(fromKey, true, toKey, false), mutex); + } + } + public SortedMap headMap(K toKey) { + synchronized (mutex) { + return new SynchronizedNavigableMap<>(nm.headMap(toKey, false), mutex); + } + } + public SortedMap tailMap(K fromKey) { + synchronized (mutex) { + return new SynchronizedNavigableMap<>(nm.tailMap(fromKey, true),mutex); + } + } + + public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { + synchronized (mutex) { + return new SynchronizedNavigableMap( + nm.subMap(fromKey, fromInclusive, toKey, toInclusive), mutex); + } + } + + public NavigableMap headMap(K toKey, boolean inclusive) { + synchronized (mutex) { + return new SynchronizedNavigableMap( + nm.headMap(toKey, inclusive), mutex); + } + } + + public NavigableMap tailMap(K fromKey, boolean inclusive) { + synchronized (mutex) { + return new SynchronizedNavigableMap( + nm.tailMap(fromKey, inclusive), mutex); + } + } + } + // Dynamically typesafe collection wrappers /** @@ -2415,12 +3016,12 @@ public class Collections { * program to wrap the collection with a dynamically typesafe view. * For example, this declaration: *

         {@code
        -     *     Collection c = new HashSet();
        +     *     Collection c = new HashSet<>();
              * }
        * may be replaced temporarily by this one: *
         {@code
              *     Collection c = Collections.checkedCollection(
        -     *         new HashSet(), String.class);
        +     *         new HashSet<>(), String.class);
              * }
        * Running the program again will cause it to fail at the point where * an incorrectly typed element is inserted into the collection, clearly @@ -2440,6 +3041,7 @@ public class Collections { * type, the returned collection permits insertion of null elements * whenever the backing collection does. * + * @param the class of the objects in the collection * @param c the collection for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code c} is permitted to hold @@ -2585,6 +3187,7 @@ public class Collections { * type, the returned queue permits insertion of {@code null} elements * whenever the backing queue does. * + * @param the class of the objects in the queue * @param queue the queue for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code queue} is permitted to hold @@ -2643,6 +3246,7 @@ public class Collections { * type, the returned set permits insertion of null elements whenever * the backing set does. * + * @param the class of the objects in the set * @param s the set for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code s} is permitted to hold @@ -2688,6 +3292,7 @@ public class Collections { * type, the returned sorted set permits insertion of null elements * whenever the backing sorted set does. * + * @param the class of the objects in the set * @param s the sorted set for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code s} is permitted to hold @@ -2706,6 +3311,7 @@ public class Collections { implements SortedSet, Serializable { private static final long serialVersionUID = 1599911165492914959L; + private final SortedSet ss; CheckedSortedSet(SortedSet s, Class type) { @@ -2728,6 +3334,88 @@ public class Collections { } } +/** + * Returns a dynamically typesafe view of the specified navigable set. + * Any attempt to insert an element of the wrong type will result in an + * immediate {@link ClassCastException}. Assuming a navigable set + * contains no incorrectly typed elements prior to the time a + * dynamically typesafe view is generated, and that all subsequent + * access to the navigable set takes place through the view, it is + * guaranteed that the navigable set cannot contain an incorrectly + * typed element. + * + *

        A discussion of the use of dynamically typesafe views may be + * found in the documentation for the {@link #checkedCollection + * checkedCollection} method. + * + *

        The returned navigable set will be serializable if the specified + * navigable set is serializable. + * + *

        Since {@code null} is considered to be a value of any reference + * type, the returned navigable set permits insertion of null elements + * whenever the backing sorted set does. + * + * @param the class of the objects in the set + * @param s the navigable set for which a dynamically typesafe view is to be + * returned + * @param type the type of element that {@code s} is permitted to hold + * @return a dynamically typesafe view of the specified navigable set + * @since 1.8 + */ + public static NavigableSet checkedNavigableSet(NavigableSet s, + Class type) { + return new CheckedNavigableSet<>(s, type); + } + + /** + * @serial include + */ + static class CheckedNavigableSet extends CheckedSortedSet + implements NavigableSet, Serializable + { + private static final long serialVersionUID = -5429120189805438922L; + + private final NavigableSet ns; + + CheckedNavigableSet(NavigableSet s, Class type) { + super(s, type); + ns = s; + } + + public E lower(E e) { return ns.lower(e); } + public E floor(E e) { return ns.floor(e); } + public E ceiling(E e) { return ns.ceiling(e); } + public E higher(E e) { return ns.higher(e); } + public E pollFirst() { return ns.pollFirst(); } + public E pollLast() {return ns.pollLast(); } + public NavigableSet descendingSet() + { return checkedNavigableSet(ns.descendingSet(), type); } + public Iterator descendingIterator() + {return checkedNavigableSet(ns.descendingSet(), type).iterator(); } + + public NavigableSet subSet(E fromElement, E toElement) { + return checkedNavigableSet(ns.subSet(fromElement, true, toElement, false), type); + } + public NavigableSet headSet(E toElement) { + return checkedNavigableSet(ns.headSet(toElement, false), type); + } + public NavigableSet tailSet(E fromElement) { + return checkedNavigableSet(ns.tailSet(fromElement, true), type); + } + + public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { + return checkedNavigableSet(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), type); + } + + public NavigableSet headSet(E toElement, boolean inclusive) { + return checkedNavigableSet(ns.headSet(toElement, inclusive), type); + } + + public NavigableSet tailSet(E fromElement, boolean inclusive) { + return checkedNavigableSet(ns.tailSet(fromElement, inclusive), type); + } + } + /** * Returns a dynamically typesafe view of the specified list. * Any attempt to insert an element of the wrong type will result in @@ -2748,6 +3436,7 @@ public class Collections { * type, the returned list permits insertion of null elements whenever * the backing list does. * + * @param the class of the objects in the list * @param list the list for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code list} is permitted to hold @@ -2885,6 +3574,8 @@ public class Collections { * type, the returned map permits insertion of null keys or values * whenever the backing map does. * + * @param the class of the map keys + * @param the class of the map values * @param m the map for which a dynamically typesafe view is to be * returned * @param keyType the type of key that {@code m} is permitted to hold @@ -2940,11 +3631,9 @@ public class Collections { } CheckedMap(Map m, Class keyType, Class valueType) { - if (m == null || keyType == null || valueType == null) - throw new NullPointerException(); - this.m = m; - this.keyType = keyType; - this.valueType = valueType; + this.m = Objects.requireNonNull(m); + this.keyType = Objects.requireNonNull(keyType); + this.valueType = Objects.requireNonNull(valueType); } public int size() { return m.size(); } @@ -3221,8 +3910,8 @@ public class Collections { private final Class valueType; CheckedEntry(Map.Entry e, Class valueType) { - this.e = e; - this.valueType = valueType; + this.e = Objects.requireNonNull(e); + this.valueType = Objects.requireNonNull(valueType); } public K getKey() { return e.getKey(); } @@ -3280,6 +3969,8 @@ public class Collections { * type, the returned map permits insertion of null keys or values * whenever the backing map does. * + * @param the class of the map keys + * @param the class of the map values * @param m the map for which a dynamically typesafe view is to be * returned * @param keyType the type of key that {@code m} is permitted to hold @@ -3325,27 +4016,195 @@ public class Collections { } } + /** + * Returns a dynamically typesafe view of the specified navigable map. + * Any attempt to insert a mapping whose key or value have the wrong + * type will result in an immediate {@link ClassCastException}. + * Similarly, any attempt to modify the value currently associated with + * a key will result in an immediate {@link ClassCastException}, + * whether the modification is attempted directly through the map + * itself, or through a {@link Map.Entry} instance obtained from the + * map's {@link Map#entrySet() entry set} view. + * + *

        Assuming a map contains no incorrectly typed keys or values + * prior to the time a dynamically typesafe view is generated, and + * that all subsequent access to the map takes place through the view + * (or one of its collection views), it is guaranteed that the + * map cannot contain an incorrectly typed key or value. + * + *

        A discussion of the use of dynamically typesafe views may be + * found in the documentation for the {@link #checkedCollection + * checkedCollection} method. + * + *

        The returned map will be serializable if the specified map is + * serializable. + * + *

        Since {@code null} is considered to be a value of any reference + * type, the returned map permits insertion of null keys or values + * whenever the backing map does. + * + * @param type of map keys + * @param type of map values + * @param m the map for which a dynamically typesafe view is to be + * returned + * @param keyType the type of key that {@code m} is permitted to hold + * @param valueType the type of value that {@code m} is permitted to hold + * @return a dynamically typesafe view of the specified map + * @since 1.8 + */ + public static NavigableMap checkedNavigableMap(NavigableMap m, + Class keyType, + Class valueType) { + return new CheckedNavigableMap<>(m, keyType, valueType); + } + + /** + * @serial include + */ + static class CheckedNavigableMap extends CheckedSortedMap + implements NavigableMap, Serializable + { + private static final long serialVersionUID = -4852462692372534096L; + + private final NavigableMap nm; + + CheckedNavigableMap(NavigableMap m, + Class keyType, Class valueType) { + super(m, keyType, valueType); + nm = m; + } + + public Comparator comparator() { return nm.comparator(); } + public K firstKey() { return nm.firstKey(); } + public K lastKey() { return nm.lastKey(); } + + public Entry lowerEntry(K key) { + Entry lower = nm.lowerEntry(key); + return (null != lower) + ? new CheckedMap.CheckedEntrySet.CheckedEntry(lower, valueType) + : null; + } + + public K lowerKey(K key) { return nm.lowerKey(key); } + + public Entry floorEntry(K key) { + Entry floor = nm.floorEntry(key); + return (null != floor) + ? new CheckedMap.CheckedEntrySet.CheckedEntry(floor, valueType) + : null; + } + + public K floorKey(K key) { return nm.floorKey(key); } + + public Entry ceilingEntry(K key) { + Entry ceiling = nm.ceilingEntry(key); + return (null != ceiling) + ? new CheckedMap.CheckedEntrySet.CheckedEntry(ceiling, valueType) + : null; + } + + public K ceilingKey(K key) { return nm.ceilingKey(key); } + + public Entry higherEntry(K key) { + Entry higher = nm.higherEntry(key); + return (null != higher) + ? new CheckedMap.CheckedEntrySet.CheckedEntry(higher, valueType) + : null; + } + + public K higherKey(K key) { return nm.higherKey(key); } + + public Entry firstEntry() { + Entry first = nm.firstEntry(); + return (null != first) + ? new CheckedMap.CheckedEntrySet.CheckedEntry(first, valueType) + : null; + } + + public Entry lastEntry() { + Entry last = nm.lastEntry(); + return (null != last) + ? new CheckedMap.CheckedEntrySet.CheckedEntry(last, valueType) + : null; + } + + public Entry pollFirstEntry() { + Entry entry = nm.pollFirstEntry(); + return (null == entry) + ? null + : new CheckedMap.CheckedEntrySet.CheckedEntry(entry, valueType); + } + + public Entry pollLastEntry() { + Entry entry = nm.pollLastEntry(); + return (null == entry) + ? null + : new CheckedMap.CheckedEntrySet.CheckedEntry(entry, valueType); + } + + public NavigableMap descendingMap() { + return checkedNavigableMap(nm.descendingMap(), keyType, valueType); + } + + public NavigableSet keySet() { + return navigableKeySet(); + } + + public NavigableSet navigableKeySet() { + return checkedNavigableSet(nm.navigableKeySet(), keyType); + } + + public NavigableSet descendingKeySet() { + return checkedNavigableSet(nm.descendingKeySet(), keyType); + } + + @Override + public NavigableMap subMap(K fromKey, K toKey) { + return checkedNavigableMap(nm.subMap(fromKey, true, toKey, false), + keyType, valueType); + } + + @Override + public NavigableMap headMap(K toKey) { + return checkedNavigableMap(nm.headMap(toKey, false), keyType, valueType); + } + + @Override + public NavigableMap tailMap(K fromKey) { + return checkedNavigableMap(nm.tailMap(fromKey, true), keyType, valueType); + } + + public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { + return checkedNavigableMap(nm.subMap(fromKey, fromInclusive, toKey, toInclusive), keyType, valueType); + } + + public NavigableMap headMap(K toKey, boolean inclusive) { + return checkedNavigableMap(nm.headMap(toKey, inclusive), keyType, valueType); + } + + public NavigableMap tailMap(K fromKey, boolean inclusive) { + return checkedNavigableMap(nm.tailMap(fromKey, inclusive), keyType, valueType); + } + } + // Empty collections /** * Returns an iterator that has no elements. More precisely, * - *

          - * + *
            *
          • {@link Iterator#hasNext hasNext} always returns {@code - * false}. - * + * false}.
          • *
          • {@link Iterator#next next} always throws {@link - * NoSuchElementException}. - * + * NoSuchElementException}.
          • *
          • {@link Iterator#remove remove} always throws {@link - * IllegalStateException}. - * + * IllegalStateException}.
          • *
          * *

          Implementations of this method are permitted, but not * required, to return the same object from multiple invocations. * + * @param type of elements, if there were any, in the iterator * @return an empty iterator * @since 1.7 */ @@ -3370,32 +4229,26 @@ public class Collections { /** * Returns a list iterator that has no elements. More precisely, * - *

            - * + *
              *
            • {@link Iterator#hasNext hasNext} and {@link * ListIterator#hasPrevious hasPrevious} always return {@code - * false}. - * + * false}.
            • *
            • {@link Iterator#next next} and {@link ListIterator#previous - * previous} always throw {@link NoSuchElementException}. - * + * previous} always throw {@link NoSuchElementException}.
            • *
            • {@link Iterator#remove remove} and {@link ListIterator#set - * set} always throw {@link IllegalStateException}. - * + * set} always throw {@link IllegalStateException}.
            • *
            • {@link ListIterator#add add} always throws {@link - * UnsupportedOperationException}. - * + * UnsupportedOperationException}.
            • *
            • {@link ListIterator#nextIndex nextIndex} always returns - * {@code 0} . - * + * {@code 0}.
            • *
            • {@link ListIterator#previousIndex previousIndex} always - * returns {@code -1}. - * + * returns {@code -1}.
            • *
            * *

            Implementations of this method are permitted, but not * required, to return the same object from multiple invocations. * + * @param type of elements, if there were any, in the iterator * @return an empty list iterator * @since 1.7 */ @@ -3422,19 +4275,17 @@ public class Collections { /** * Returns an enumeration that has no elements. More precisely, * - *

              - * + *
                *
              • {@link Enumeration#hasMoreElements hasMoreElements} always - * returns {@code false}. - * + * returns {@code false}.
              • *
              • {@link Enumeration#nextElement nextElement} always throws - * {@link NoSuchElementException}. - * + * {@link NoSuchElementException}.
              • *
              * *

              Implementations of this method are permitted, but not * required, to return the same object from multiple invocations. * + * @param the class of the objects in the enumeration * @return an empty enumeration * @since 1.7 */ @@ -3460,17 +4311,20 @@ public class Collections { public static final Set EMPTY_SET = new EmptySet<>(); /** - * Returns the empty set (immutable). This set is serializable. + * Returns an empty set (immutable). This set is serializable. * Unlike the like-named field, this method is parameterized. * *

              This example illustrates the type-safe way to obtain an empty set: *

                    *     Set<String> s = Collections.emptySet();
                    * 
              - * Implementation note: Implementations of this method need not - * create a separate Set object for each call. Using this - * method is likely to have comparable cost to using the like-named - * field. (Unlike this method, the field does not provide type safety.) + * @implNote Implementations of this method need not create a separate + * {@code Set} object for each call. Using this method is likely to have + * comparable cost to using the like-named field. (Unlike this method, the + * field does not provide type safety.) + * + * @param the class of the objects in the set + * @return the empty set * * @see #EMPTY_SET * @since 1.5 @@ -3525,121 +4379,45 @@ public class Collections { } /** - * Returns the empty sorted set (immutable). This set is serializable. + * Returns an empty sorted set (immutable). This set is serializable. * - *

              This example illustrates the type-safe way to obtain an empty sorted - * set: - *

              -     *     SortedSet<String> s = Collections.emptySortedSet();
              -     * 
              - * Implementation note: Implementations of this method need not - * create a separate SortedSet object for each call. + *

              This example illustrates the type-safe way to obtain an empty + * sorted set: + *

               {@code
              +     *     SortedSet s = Collections.emptySortedSet();
              +     * }
              * + * @implNote Implementations of this method need not create a separate + * {@code SortedSet} object for each call. + * + * @param type of elements, if there were any, in the set + * @return the empty sorted set * @since 1.8 */ @SuppressWarnings("unchecked") - public static final SortedSet emptySortedSet() { - return (SortedSet) new EmptySortedSet<>(); + public static SortedSet emptySortedSet() { + return (SortedSet) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET; } /** - * @serial include + * Returns an empty navigable set (immutable). This set is serializable. + * + *

              This example illustrates the type-safe way to obtain an empty + * navigable set: + *

               {@code
              +     *     NavigableSet s = Collections.emptyNavigableSet();
              +     * }
              + * + * @implNote Implementations of this method need not + * create a separate {@code NavigableSet} object for each call. + * + * @param type of elements, if there were any, in the set + * @return the empty navigable set + * @since 1.8 */ - private static class EmptySortedSet - extends AbstractSet - implements SortedSet, Serializable - { - private static final long serialVersionUID = 6316515401502265487L; - public Iterator iterator() { return emptyIterator(); } - public int size() {return 0;} - public boolean isEmpty() {return true;} - public boolean contains(Object obj) {return false;} - public boolean containsAll(Collection c) { return c.isEmpty(); } - public Object[] toArray() { return new Object[0]; } - - public E[] toArray(E[] a) { - if (a.length > 0) - a[0] = null; - return a; - } - - // Preserves singleton property - private Object readResolve() { - return new EmptySortedSet<>(); - } - - @Override - public Comparator comparator() { - return null; - } - - @Override - @SuppressWarnings("unchecked") - public SortedSet subSet(Object fromElement, Object toElement) { - Objects.requireNonNull(fromElement); - Objects.requireNonNull(toElement); - - if (!(fromElement instanceof Comparable) || - !(toElement instanceof Comparable)) - { - throw new ClassCastException(); - } - - if ((((Comparable)fromElement).compareTo(toElement) >= 0) || - (((Comparable)toElement).compareTo(fromElement) < 0)) - { - throw new IllegalArgumentException(); - } - - return emptySortedSet(); - } - - @Override - public SortedSet headSet(Object toElement) { - Objects.requireNonNull(toElement); - - if (!(toElement instanceof Comparable)) { - throw new ClassCastException(); - } - - return emptySortedSet(); - } - - @Override - public SortedSet tailSet(Object fromElement) { - Objects.requireNonNull(fromElement); - - if (!(fromElement instanceof Comparable)) { - throw new ClassCastException(); - } - - return emptySortedSet(); - } - - @Override - public E first() { - throw new NoSuchElementException(); - } - - @Override - public E last() { - throw new NoSuchElementException(); - } - - // Override default methods in Collection - @Override - public void forEach(Consumer action) { - Objects.requireNonNull(action); - } - - @Override - public boolean removeIf(Predicate filter) { - Objects.requireNonNull(filter); - return false; - } - - @Override - public Spliterator spliterator() { return Spliterators.emptySpliterator(); } + @SuppressWarnings("unchecked") + public static NavigableSet emptyNavigableSet() { + return (NavigableSet) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET; } /** @@ -3651,7 +4429,7 @@ public class Collections { public static final List EMPTY_LIST = new EmptyList<>(); /** - * Returns the empty list (immutable). This list is serializable. + * Returns an empty list (immutable). This list is serializable. * *

              This example illustrates the type-safe way to obtain an empty list: *

              @@ -3662,6 +4440,9 @@ public class Collections {
                    * method is likely to have comparable cost to using the like-named
                    * field.  (Unlike this method, the field does not provide type safety.)
                    *
              +     * @param  type of elements, if there were any, in the list
              +     * @return an empty immutable list
              +     *
                    * @see #EMPTY_LIST
                    * @since 1.5
                    */
              @@ -3748,17 +4529,20 @@ public class Collections {
                   public static final Map EMPTY_MAP = new EmptyMap<>();
               
                   /**
              -     * Returns the empty map (immutable).  This map is serializable.
              +     * Returns an empty map (immutable).  This map is serializable.
                    *
              -     * 

              This example illustrates the type-safe way to obtain an empty set: + *

              This example illustrates the type-safe way to obtain an empty map: *

                    *     Map<String, Date> s = Collections.emptyMap();
                    * 
              - * Implementation note: Implementations of this method need not - * create a separate Map object for each call. Using this - * method is likely to have comparable cost to using the like-named - * field. (Unlike this method, the field does not provide type safety.) + * @implNote Implementations of this method need not create a separate + * {@code Map} object for each call. Using this method is likely to have + * comparable cost to using the like-named field. (Unlike this method, the + * field does not provide type safety.) * + * @param the class of the map keys + * @param the class of the map values + * @return an empty map * @see #EMPTY_MAP * @since 1.5 */ @@ -3767,6 +4551,48 @@ public class Collections { return (Map) EMPTY_MAP; } + /** + * Returns an empty sorted map (immutable). This map is serializable. + * + *

              This example illustrates the type-safe way to obtain an empty map: + *

               {@code
              +     *     SortedMap s = Collections.emptySortedMap();
              +     * }
              + * + * @implNote Implementations of this method need not create a separate + * {@code SortedMap} object for each call. + * + * @param the class of the map keys + * @param the class of the map values + * @return an empty sorted map + * @since 1.8 + */ + @SuppressWarnings("unchecked") + public static final SortedMap emptySortedMap() { + return (SortedMap) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP; + } + + /** + * Returns an empty navigable map (immutable). This map is serializable. + * + *

              This example illustrates the type-safe way to obtain an empty map: + *

               {@code
              +     *     NavigableMap s = Collections.emptyNavigableMap();
              +     * }
              + * + * @implNote Implementations of this method need not create a separate + * {@code NavigableMap} object for each call. + * + * @param the class of the map keys + * @param the class of the map values + * @return an empty navigable map + * @since 1.8 + */ + @SuppressWarnings("unchecked") + public static final NavigableMap emptyNavigableMap() { + return (NavigableMap) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP; + } + /** * @serial include */ @@ -3864,6 +4690,7 @@ public class Collections { * Returns an immutable set containing only the specified object. * The returned set is serializable. * + * @param the class of the objects in the set * @param o the sole object to be stored in the returned set. * @return an immutable set containing only the specified object. */ @@ -3984,6 +4811,7 @@ public class Collections { * Returns an immutable list containing only the specified object. * The returned list is serializable. * + * @param the class of the objects in the list * @param o the sole object to be stored in the returned list. * @return an immutable list containing only the specified object. * @since 1.3 @@ -4045,6 +4873,8 @@ public class Collections { * Returns an immutable map, mapping only the specified key to the * specified value. The returned map is serializable. * + * @param the class of the map keys + * @param the class of the map values * @param key the sole key to be stored in the returned map. * @param value the value to which the returned map maps key. * @return an immutable map containing only the specified key-value @@ -4071,15 +4901,11 @@ public class Collections { v = value; } - public int size() {return 1;} - - public boolean isEmpty() {return false;} - - public boolean containsKey(Object key) {return eq(key, k);} - - public boolean containsValue(Object value) {return eq(value, v);} - - public V get(Object key) {return (eq(key, k) ? v : null);} + public int size() {return 1;} + public boolean isEmpty() {return false;} + public boolean containsKey(Object key) {return eq(key, k);} + public boolean containsValue(Object value) {return eq(value, v);} + public V get(Object key) {return (eq(key, k) ? v : null);} private transient Set keySet = null; private transient Set> entrySet = null; @@ -4174,6 +5000,8 @@ public class Collections { * combination with the List.addAll method to grow lists. * The returned list is serializable. * + * @param the class of the object to copy and of the objects + * in the returned list. * @param n the number of elements in the returned list. * @param o the element to appear repeatedly in the returned list. * @return an immutable list consisting of n copies of the @@ -4278,6 +5106,7 @@ public class Collections { * * The returned comparator is serializable. * + * @param the class of the objects compared by the comparator * @return A comparator that imposes the reverse of the natural * ordering on a collection of objects that implement * the Comparable interface. @@ -4321,6 +5150,7 @@ public class Collections { *

              The returned comparator is serializable (assuming the specified * comparator is also serializable or {@code null}). * + * @param the class of the objects compared by the comparator * @param cmp a comparator who's ordering is to be reversed by the returned * comparator or {@code null} * @return A comparator that imposes the reverse ordering of the @@ -4384,6 +5214,7 @@ public class Collections { * interoperability with legacy APIs that require an enumeration * as input. * + * @param the class of the objects in the collection * @param c the collection for which an enumeration is to be returned. * @return an enumeration over the specified collection. * @see Enumeration @@ -4409,6 +5240,7 @@ public class Collections { * legacy APIs that return enumerations and new APIs that require * collections. * + * @param the class of the objects returned by the enumeration * @param e enumeration providing elements for the returned * array list * @return an array list containing the elements returned @@ -4426,6 +5258,8 @@ public class Collections { /** * Returns true if the specified arguments are equal, or both null. + * + * NB: Do not replace with Object.equals until JDK-8015417 is resolved. */ static boolean eq(Object o1, Object o2) { return o1==null ? o2==null : o1.equals(o2); @@ -4440,6 +5274,7 @@ public class Collections { * @param c the collection in which to determine the frequency * of o * @param o the object whose frequency is to be determined + * @return the number of elements in {@code c} equal to {@code o} * @throws NullPointerException if c is null * @since 1.5 */ @@ -4560,6 +5395,7 @@ public class Collections { * Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon"); *

              * + * @param the class of the elements to add and of the collection * @param c the collection into which elements are to be inserted * @param elements the elements to insert into c * @return true if the collection changed as a result of the call @@ -4605,6 +5441,8 @@ public class Collections { * new WeakHashMap<Object, Boolean>()); * * + * @param the class of the map keys and of the objects in the + * returned set * @param map the backing map * @return the set backed by the map * @throws IllegalArgumentException if map is not empty @@ -4683,6 +5521,7 @@ public class Collections { * implemented as a sequence of {@link Deque#addFirst addFirst} * invocations on the backing deque. * + * @param the class of the objects in the deque * @param deque the deque * @return the queue * @since 1.6 diff --git a/jdk/src/share/classes/java/util/ConcurrentModificationException.java b/jdk/src/share/classes/java/util/ConcurrentModificationException.java index 3683fb399cf..d5256538f04 100644 --- a/jdk/src/share/classes/java/util/ConcurrentModificationException.java +++ b/jdk/src/share/classes/java/util/ConcurrentModificationException.java @@ -57,6 +57,7 @@ package java.util; * @author Josh Bloch * @see Collection * @see Iterator + * @see Spliterator * @see ListIterator * @see Vector * @see LinkedList diff --git a/jdk/src/share/classes/java/util/EnumSet.java b/jdk/src/share/classes/java/util/EnumSet.java index 039d772094e..6aff2994ebe 100644 --- a/jdk/src/share/classes/java/util/EnumSet.java +++ b/jdk/src/share/classes/java/util/EnumSet.java @@ -100,8 +100,10 @@ public abstract class EnumSet> extends AbstractSet /** * Creates an empty enum set with the specified element type. * + * @param The class of the elements in the set * @param elementType the class object of the element type for this enum * set + * @return An empty enum set of the specified type. * @throws NullPointerException if elementType is null */ public static > EnumSet noneOf(Class elementType) { @@ -119,8 +121,10 @@ public abstract class EnumSet> extends AbstractSet * Creates an enum set containing all of the elements in the specified * element type. * + * @param The class of the elements in the set * @param elementType the class object of the element type for this enum * set + * @return An enum set containing all the elements in the specified type. * @throws NullPointerException if elementType is null */ public static > EnumSet allOf(Class elementType) { @@ -139,7 +143,9 @@ public abstract class EnumSet> extends AbstractSet * Creates an enum set with the same element type as the specified enum * set, initially containing the same elements (if any). * + * @param The class of the elements in the set * @param s the enum set from which to initialize this enum set + * @return A copy of the specified enum set. * @throws NullPointerException if s is null */ public static > EnumSet copyOf(EnumSet s) { @@ -153,7 +159,9 @@ public abstract class EnumSet> extends AbstractSet * Otherwise, the specified collection must contain at least one element * (in order to determine the new enum set's element type). * + * @param The class of the elements in the collection * @param c the collection from which to initialize this enum set + * @return An enum set initialized from the given collection. * @throws IllegalArgumentException if c is not an * EnumSet instance and contains no elements * @throws NullPointerException if c is null @@ -178,7 +186,9 @@ public abstract class EnumSet> extends AbstractSet * set, initially containing all the elements of this type that are * not contained in the specified set. * + * @param The class of the elements in the enum set * @param s the enum set from whose complement to initialize this enum set + * @return The complement of the specified set in this set * @throws NullPointerException if s is null */ public static > EnumSet complementOf(EnumSet s) { @@ -196,6 +206,7 @@ public abstract class EnumSet> extends AbstractSet * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * + * @param The class of the specified element and of the set * @param e the element that this set is to contain initially * @throws NullPointerException if e is null * @return an enum set initially containing the specified element @@ -215,6 +226,7 @@ public abstract class EnumSet> extends AbstractSet * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * + * @param The class of the parameter elements and of the set * @param e1 an element that this set is to contain initially * @param e2 another element that this set is to contain initially * @throws NullPointerException if any parameters are null @@ -236,6 +248,7 @@ public abstract class EnumSet> extends AbstractSet * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * + * @param The class of the parameter elements and of the set * @param e1 an element that this set is to contain initially * @param e2 another element that this set is to contain initially * @param e3 another element that this set is to contain initially @@ -259,6 +272,7 @@ public abstract class EnumSet> extends AbstractSet * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * + * @param The class of the parameter elements and of the set * @param e1 an element that this set is to contain initially * @param e2 another element that this set is to contain initially * @param e3 another element that this set is to contain initially @@ -284,6 +298,7 @@ public abstract class EnumSet> extends AbstractSet * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * + * @param The class of the parameter elements and of the set * @param e1 an element that this set is to contain initially * @param e2 another element that this set is to contain initially * @param e3 another element that this set is to contain initially @@ -311,6 +326,7 @@ public abstract class EnumSet> extends AbstractSet * number of elements, but it is likely to run slower than the overloadings * that do not use varargs. * + * @param The class of the parameter elements and of the set * @param first an element that the set is to contain initially * @param rest the remaining elements the set is to contain initially * @throws NullPointerException if any of the specified elements are null, @@ -332,6 +348,7 @@ public abstract class EnumSet> extends AbstractSet * contain the endpoints themselves, which may be identical but must not * be out of order. * + * @param The class of the parameter elements and of the set * @param from the first element in the range * @param to the last element in the range * @throws NullPointerException if {@code from} or {@code to} are null diff --git a/jdk/src/share/classes/java/util/Formattable.java b/jdk/src/share/classes/java/util/Formattable.java index 28b788c340a..6f3fd1ab080 100644 --- a/jdk/src/share/classes/java/util/Formattable.java +++ b/jdk/src/share/classes/java/util/Formattable.java @@ -36,7 +36,7 @@ import java.io.IOException; * For example, the following class prints out different representations of a * stock's name depending on the flags and length constraints: * - *
              + * {@code
                *   import java.nio.CharBuffer;
                *   import java.util.Formatter;
                *   import java.util.Formattable;
              @@ -89,12 +89,12 @@ import java.io.IOException;
                *           return String.format("%s - %s", symbol, companyName);
                *       }
                *   }
              - * 
              + * } * *

              When used in conjunction with the {@link java.util.Formatter}, the above * class produces the following output for various format strings. * - *

              + * {@code
                *   Formatter fmt = new Formatter();
                *   StockName sn = new StockName("HUGE", "Huge Fruit, Inc.",
                *                                "Fruit Titanesque, Inc.");
              @@ -104,7 +104,7 @@ import java.io.IOException;
                *   fmt.format("%-10.8s", sn);              //   -> "HUGE      "
                *   fmt.format("%.12s", sn);                //   -> "Huge Fruit,*"
                *   fmt.format(Locale.FRANCE, "%25s", sn);  //   -> "   Fruit Titanesque, Inc."
              - * 
              + * } * *

              Formattables are not necessarily safe for multithreaded access. Thread * safety is optional and may be enforced by classes that extend and implement diff --git a/jdk/src/share/classes/java/util/Formatter.java b/jdk/src/share/classes/java/util/Formatter.java index 7906c763fe2..5c096c63acf 100644 --- a/jdk/src/share/classes/java/util/Formatter.java +++ b/jdk/src/share/classes/java/util/Formatter.java @@ -190,7 +190,7 @@ import sun.misc.FormattedFloatingDecimal; *

              The optional flags is a set of characters that modify the output * format. The set of valid flags depends on the conversion. * - *

              The optional width is a non-negative decimal integer indicating + *

              The optional width is a positive decimal integer indicating * the minimum number of characters to be written to the output. * *

              The optional precision is a non-negative decimal integer usually @@ -841,7 +841,7 @@ import sun.misc.FormattedFloatingDecimal; * *

              Numeric types will be formatted according to the following algorithm: * - *

              Number Localization Algorithm + *

              Number Localization Algorithm * *

              After digits are obtained for the integer part, fractional part, and * exponent (as appropriate for the data type), the following transformation @@ -860,7 +860,7 @@ import sun.misc.FormattedFloatingDecimal; * substituted. * *

            • If the {@code ','} ('\u002c') - * flag is given, then the locale-specific {@linkplain + * flag is given, then the locale-specific {@linkplain * java.text.DecimalFormatSymbols#getGroupingSeparator grouping separator} is * inserted by scanning the integer part of the string from least significant * to most significant digits and inserting a separator at intervals defined by @@ -902,7 +902,7 @@ import sun.misc.FormattedFloatingDecimal; *
    unicast
    {@code 'd'} * '\u0054' * Formats the argument as a decimal integer. The localization algorithm is applied. + * href="#L10nAlgorithm">localization algorithm is applied. * *

    If the {@code '0'} flag is given and the value is negative, then * the zero padding will occur after the sign. @@ -1011,7 +1011,7 @@ import sun.misc.FormattedFloatingDecimal; *

    '\u002c' * Requires the output to include the locale-specific {@linkplain * java.text.DecimalFormatSymbols#getGroupingSeparator group separators} as - * described in the "group" section of the + * described in the "group" section of the * localization algorithm. * *
    {@code '('} @@ -1060,7 +1060,7 @@ import sun.misc.FormattedFloatingDecimal; *
    {@code 'd'} * '\u0054' * Requires the output to be formatted as a decimal integer. The localization algorithm is applied. + * href="#L10nAlgorithm">localization algorithm is applied. * *

    If the {@code '#'} flag is given {@link * FormatFlagsConversionMismatchException} will be thrown. @@ -1155,7 +1155,7 @@ import sun.misc.FormattedFloatingDecimal; *

    '\u0065' * Requires the output to be formatted using computerized scientific notation. The localization algorithm is applied. + * href="#L10nAlgorithm">localization algorithm is applied. * *

    The formatting of the magnitude m depends upon its value. * @@ -1168,7 +1168,7 @@ import sun.misc.FormattedFloatingDecimal; * *

    Otherwise, the result is a string that represents the sign and * magnitude (absolute value) of the argument. The formatting of the sign - * is described in the localization + * is described in the localization * algorithm. The formatting of the magnitude m depends upon its * value. * @@ -1207,7 +1207,7 @@ import sun.misc.FormattedFloatingDecimal; *

    {@code 'g'} * '\u0067' * Requires the output to be formatted in general scientific notation - * as described below. The localization + * as described below. The localization * algorithm is applied. * *

    After rounding for the precision, the formatting of the resulting @@ -1236,12 +1236,12 @@ import sun.misc.FormattedFloatingDecimal; *

    {@code 'f'} * '\u0066' * Requires the output to be formatted using decimal - * format. The localization algorithm is + * format. The localization algorithm is * applied. * *

    The result is a string that represents the sign and magnitude * (absolute value) of the argument. The formatting of the sign is - * described in the localization + * described in the localization * algorithm. The formatting of the magnitude m depends upon its * value. * @@ -1382,7 +1382,7 @@ import sun.misc.FormattedFloatingDecimal; *

    '\u0065' * Requires the output to be formatted using computerized scientific notation. The localization algorithm is applied. + * href="#L10nAlgorithm">localization algorithm is applied. * *

    The formatting of the magnitude m depends upon its value. * @@ -1391,7 +1391,7 @@ import sun.misc.FormattedFloatingDecimal; * *

    Otherwise, the result is a string that represents the sign and * magnitude (absolute value) of the argument. The formatting of the sign - * is described in the localization + * is described in the localization * algorithm. The formatting of the magnitude m depends upon its * value. * @@ -1428,7 +1428,7 @@ import sun.misc.FormattedFloatingDecimal; *

    {@code 'g'} * '\u0067' * Requires the output to be formatted in general scientific notation - * as described below. The localization + * as described below. The localization * algorithm is applied. * *

    After rounding for the precision, the formatting of the resulting @@ -1457,12 +1457,12 @@ import sun.misc.FormattedFloatingDecimal; *

    {@code 'f'} * '\u0066' * Requires the output to be formatted using decimal - * format. The localization algorithm is + * format. The localization algorithm is * applied. * *

    The result is a string that represents the sign and magnitude * (absolute value) of the argument. The formatting of the sign is - * described in the localization + * described in the localization * algorithm. The formatting of the magnitude m depends upon its * value. * @@ -1721,7 +1721,7 @@ import sun.misc.FormattedFloatingDecimal; * conversions applies. If the {@code '#'} flag is given, then a {@link * FormatFlagsConversionMismatchException} will be thrown. * - *

    The width is the minimum number of characters to + *

    The width is the minimum number of characters to * be written to the output. If the length of the converted value is less than * the {@code width} then the output will be padded by spaces * ('\u0020') until the total number of characters equals width. @@ -1741,7 +1741,7 @@ import sun.misc.FormattedFloatingDecimal; *

    {@code '%'} * The result is a literal {@code '%'} ('\u0025') * - *

    The width is the minimum number of characters to + *

    The width is the minimum number of characters to * be written to the output including the {@code '%'}. If the length of the * converted value is less than the {@code width} then the output will be * padded by spaces ('\u0020') until the total number of @@ -2590,7 +2590,20 @@ public final class Formatter implements Closeable, Flushable { public String toString() { return s; } } - public enum BigDecimalLayoutForm { SCIENTIFIC, DECIMAL_FLOAT }; + /** + * Enum for {@code BigDecimal} formatting. + */ + public enum BigDecimalLayoutForm { + /** + * Format the {@code BigDecimal} in computerized scientific notation. + */ + SCIENTIFIC, + + /** + * Format the {@code BigDecimal} as a decimal number. + */ + DECIMAL_FLOAT + }; private class FormatSpecifier implements FormatString { private int index = -1; diff --git a/jdk/src/share/classes/java/util/GregorianCalendar.java b/jdk/src/share/classes/java/util/GregorianCalendar.java index 1f818ed6f64..8381a4fab4b 100644 --- a/jdk/src/share/classes/java/util/GregorianCalendar.java +++ b/jdk/src/share/classes/java/util/GregorianCalendar.java @@ -94,7 +94,7 @@ import sun.util.calendar.ZoneInfo; * adjustment may be made if desired for dates that are prior to the Gregorian * changeover and which fall between January 1 and March 24. * - *

    Week Of Year and Week Year

    + *

    Week Of Year and Week Year

    * *

    Values calculated for the {@link Calendar#WEEK_OF_YEAR * WEEK_OF_YEAR} field range from 1 to 53. The first week of a diff --git a/jdk/src/share/classes/java/util/HashMap.java b/jdk/src/share/classes/java/util/HashMap.java index eab47e3776d..c2aace9db8f 100644 --- a/jdk/src/share/classes/java/util/HashMap.java +++ b/jdk/src/share/classes/java/util/HashMap.java @@ -1013,7 +1013,7 @@ public class HashMap */ @SuppressWarnings("unchecked") final Entry getEntry(Object key) { - if (isEmpty()) { + if (size == 0) { return null; } if (key == null) { @@ -1468,7 +1468,7 @@ public class HashMap @Override public boolean remove(Object key, Object value) { - if (isEmpty()) { + if (size == 0) { return false; } if (key == null) { @@ -1531,7 +1531,7 @@ public class HashMap @Override public boolean replace(K key, V oldValue, V newValue) { - if (isEmpty()) { + if (size == 0) { return false; } if (key == null) { @@ -1574,7 +1574,7 @@ public class HashMap @Override public V replace(K key, V value) { - if (isEmpty()) { + if (size == 0) { return null; } if (key == null) { @@ -1694,7 +1694,7 @@ public class HashMap @Override public V computeIfPresent(K key, BiFunction remappingFunction) { - if (isEmpty()) { + if (size == 0) { return null; } if (key == null) { @@ -1980,7 +1980,7 @@ public class HashMap * TreeNode in a TreeBin. */ final Entry removeEntryForKey(Object key) { - if (isEmpty()) { + if (size == 0) { return null; } if (key == null) { @@ -2040,7 +2040,7 @@ public class HashMap * for matching. */ final Entry removeMapping(Object o) { - if (isEmpty() || !(o instanceof Map.Entry)) + if (size == 0 || !(o instanceof Map.Entry)) return null; Map.Entry entry = (Map.Entry) o; diff --git a/jdk/src/share/classes/java/util/LinkedList.java b/jdk/src/share/classes/java/util/LinkedList.java index 54297d96232..4d0f6dbca92 100644 --- a/jdk/src/share/classes/java/util/LinkedList.java +++ b/jdk/src/share/classes/java/util/LinkedList.java @@ -1195,12 +1195,7 @@ public class LinkedList n = s; if (n > MAX_BATCH) n = MAX_BATCH; - Object[] a; - try { - a = new Object[n]; - } catch (OutOfMemoryError oome) { - return null; - } + Object[] a = new Object[n]; int j = 0; do { a[j++] = p.item; } while ((p = p.next) != null && j < n); current = p; diff --git a/jdk/src/share/classes/java/util/Locale.java b/jdk/src/share/classes/java/util/Locale.java index 69f277659ab..6ecd39393fd 100644 --- a/jdk/src/share/classes/java/util/Locale.java +++ b/jdk/src/share/classes/java/util/Locale.java @@ -84,7 +84,7 @@ import sun.util.locale.provider.ResourceBundleBasedAdapter; * described below. * *

    - *
    language
    + *
    language
    * *
    ISO 639 alpha-2 or alpha-3 language code, or registered * language subtags up to 8 alpha letters (for future enhancements). @@ -92,51 +92,51 @@ import sun.util.locale.provider.ResourceBundleBasedAdapter; * alpha-2 code must be used. You can find a full list of valid * language codes in the IANA Language Subtag Registry (search for * "Type: language"). The language field is case insensitive, but - * Locale always canonicalizes to lower case.

    + * Locale always canonicalizes to lower case. * *
    Well-formed language values have the form * [a-zA-Z]{2,8}. Note that this is not the the full * BCP47 language production, since it excludes extlang. They are * not needed since modern three-letter language codes replace - * them.

    + * them. * - *
    Example: "en" (English), "ja" (Japanese), "kok" (Konkani)

    + *
    Example: "en" (English), "ja" (Japanese), "kok" (Konkani)
    * - *
    script
    + *
    script
    * *
    ISO 15924 alpha-4 script code. You can find a full list of * valid script codes in the IANA Language Subtag Registry (search * for "Type: script"). The script field is case insensitive, but * Locale always canonicalizes to title case (the first * letter is upper case and the rest of the letters are lower - * case).

    + * case). * *
    Well-formed script values have the form - * [a-zA-Z]{4}

    + * [a-zA-Z]{4} * - *
    Example: "Latn" (Latin), "Cyrl" (Cyrillic)

    + *
    Example: "Latn" (Latin), "Cyrl" (Cyrillic)
    * - *
    country (region)
    + *
    country (region)
    * *
    ISO 3166 alpha-2 country code or UN M.49 numeric-3 area code. * You can find a full list of valid country and region codes in the * IANA Language Subtag Registry (search for "Type: region"). The * country (region) field is case insensitive, but - * Locale always canonicalizes to upper case.

    + * Locale always canonicalizes to upper case. * *
    Well-formed country/region values have - * the form [a-zA-Z]{2} | [0-9]{3}

    + * the form [a-zA-Z]{2} | [0-9]{3} * *
    Example: "US" (United States), "FR" (France), "029" - * (Caribbean)

    + * (Caribbean) * - *
    variant
    + *
    variant
    * *
    Any arbitrary value used to indicate a variation of a * Locale. Where there are two or more variant values * each indicating its own semantics, these values should be ordered * by importance, with most important first, separated by - * underscore('_'). The variant field is case sensitive.

    + * underscore('_'). The variant field is case sensitive. * *
    Note: IETF BCP 47 places syntactic restrictions on variant * subtags. Also BCP 47 subtags are strictly used to indicate @@ -152,16 +152,16 @@ import sun.util.locale.provider.ResourceBundleBasedAdapter; * cultural behaviors such as calendar type or number script. In * BCP 47 this kind of information, which does not identify the * language, is supported by extension subtags or private use - * subtags.

    + * subtags. * *
    Well-formed variant values have the form SUBTAG * (('_'|'-') SUBTAG)* where SUBTAG = * [0-9][0-9a-zA-Z]{3} | [0-9a-zA-Z]{5,8}. (Note: BCP 47 only - * uses hyphen ('-') as a delimiter, this is more lenient).

    + * uses hyphen ('-') as a delimiter, this is more lenient). * - *
    Example: "polyton" (Polytonic Greek), "POSIX"

    + *
    Example: "polyton" (Polytonic Greek), "POSIX"
    * - *
    extensions
    + *
    extensions
    * *
    A map from single character keys to string values, indicating * extensions apart from language identification. The extensions in @@ -169,14 +169,14 @@ import sun.util.locale.provider.ResourceBundleBasedAdapter; * extension subtags and private use subtags. The extensions are * case insensitive, but Locale canonicalizes all * extension keys and values to lower case. Note that extensions - * cannot have empty values.

    + * cannot have empty values. * *
    Well-formed keys are single characters from the set * [0-9a-zA-Z]. Well-formed values have the form * SUBTAG ('-' SUBTAG)* where for the key 'x' * SUBTAG = [0-9a-zA-Z]{1,8} and for other keys * SUBTAG = [0-9a-zA-Z]{2,8} (that is, 'x' allows - * single-character subtags).

    + * single-character subtags). * *
    Example: key="u"/value="ca-japanese" (Japanese Calendar), * key="x"/value="java-1-7"
    @@ -189,7 +189,7 @@ import sun.util.locale.provider.ResourceBundleBasedAdapter; * requirement (is well-formed), but does not validate the value * itself. See {@link Builder} for details. * - *

    Unicode locale/language extension

    + *

    Unicode locale/language extension

    * *

    UTS#35, "Unicode Locale Data Markup Language" defines optional * attributes and keywords to override or refine the default behavior @@ -409,7 +409,7 @@ import sun.util.locale.provider.ResourceBundleBasedAdapter; * Clients desiring a string representation of the complete locale can * then always rely on toLanguageTag for this purpose. * - *

    Special cases
    + *
    Special cases
    * *

    For compatibility reasons, two * non-conforming locales are treated as special cases. These are @@ -1007,6 +1007,8 @@ public final class Locale implements Cloneable, Serializable { * country (region), such as 3-letter numeric UN M.49 area codes. * Therefore, the list returned by this method does not contain ALL valid * codes that can be used to create Locales. + * + * @return An array of ISO 3166 two-letter country codes. */ public static String[] getISOCountries() { if (isoCountries == null) { @@ -1030,6 +1032,8 @@ public final class Locale implements Cloneable, Serializable { * 8 characters in length. Therefore, the list returned by this method does * not contain ALL valid codes that can be used to create Locales. * + * + * @return Am array of ISO 639 two-letter language codes. */ public static String[] getISOLanguages() { if (isoLanguages == null) { @@ -1268,15 +1272,15 @@ public final class Locale implements Cloneable, Serializable { * fields only. To represent a Locale as a String for interchange purposes, use * {@link #toLanguageTag}. * - *

    Examples:

      - *
    • en - *
    • de_DE - *
    • _GB - *
    • en_US_WIN - *
    • de__POSIX - *
    • zh_CN_#Hans - *
    • zh_TW_#Hant-x-java - *
    • th_TH_TH_#u-nu-thai
    + *

    Examples:

      + *
    • en
    • + *
    • de_DE
    • + *
    • _GB
    • + *
    • en_US_WIN
    • + *
    • de__POSIX
    • + *
    • zh_CN_#Hans
    • + *
    • zh_TW_#Hant-x-java
    • + *
    • th_TH_TH_#u-nu-thai
    * * @return A string representation of the Locale, for debugging. * @see #getDisplayName @@ -1506,7 +1510,7 @@ public final class Locale implements Cloneable, Serializable { * *

    Grandfathered tags with canonical replacements are as follows: * - * + *
    * * * @@ -1535,7 +1539,7 @@ public final class Locale implements Cloneable, Serializable { *

    Grandfathered tags with no modern replacement will be * converted as follows: * - *

    grandfathered tag modern replacement
    art-lojban jbo
    + *
    * * * @@ -1659,6 +1663,8 @@ public final class Locale implements Cloneable, Serializable { * (say, we don't have a Japanese name for Croatian), * this function falls back on the English name, and uses the ISO code as a last-resort * value. If the locale doesn't specify a language, this function returns the empty string. + * + * @return The name of the display language. */ public final String getDisplayLanguage() { return getDisplayLanguage(getDefault(Category.DISPLAY)); @@ -1677,6 +1683,8 @@ public final class Locale implements Cloneable, Serializable { * on the ISO code as a last-resort value. If the locale doesn't specify a language, * this function returns the empty string. * + * @param inLocale The locale for which to retrieve the display language. + * @return The name of the display language appropriate to the given locale. * @exception NullPointerException if inLocale is null */ public String getDisplayLanguage(Locale inLocale) { @@ -1703,6 +1711,7 @@ public final class Locale implements Cloneable, Serializable { * localized for the given locale. Returns the empty string if * this locale doesn't specify a script code. * + * @param inLocale The locale for which to retrieve the display script. * @return the display name of the script code for the current default * {@link Locale.Category#DISPLAY DISPLAY} locale * @throws NullPointerException if inLocale is null @@ -1727,6 +1736,8 @@ public final class Locale implements Cloneable, Serializable { * (say, we don't have a Japanese name for Croatia), * this function falls back on the English name, and uses the ISO code as a last-resort * value. If the locale doesn't specify a country, this function returns the empty string. + * + * @return The name of the country appropriate to the locale. */ public final String getDisplayCountry() { return getDisplayCountry(getDefault(Category.DISPLAY)); @@ -1745,6 +1756,8 @@ public final class Locale implements Cloneable, Serializable { * on the ISO code as a last-resort value. If the locale doesn't specify a country, * this function returns the empty string. * + * @param inLocale The locale for which to retrieve the display country. + * @return The name of the country appropriate to the given locale. * @exception NullPointerException if inLocale is null */ public String getDisplayCountry(Locale inLocale) { @@ -1778,6 +1791,8 @@ public final class Locale implements Cloneable, Serializable { * user. If possible, the name will be localized for the default * {@link Locale.Category#DISPLAY DISPLAY} locale. If the locale * doesn't specify a variant code, this function returns the empty string. + * + * @return The name of the display variant code appropriate to the locale. */ public final String getDisplayVariant() { return getDisplayVariant(getDefault(Category.DISPLAY)); @@ -1788,6 +1803,8 @@ public final class Locale implements Cloneable, Serializable { * user. If possible, the name will be localized for inLocale. If the locale * doesn't specify a variant code, this function returns the empty string. * + * @param inLocale The locale for which to retrieve the display variant code. + * @return The name of the display variant code appropriate to the given locale. * @exception NullPointerException if inLocale is null */ public String getDisplayVariant(Locale inLocale) { @@ -1821,6 +1838,8 @@ public final class Locale implements Cloneable, Serializable { * depending on which fields are specified in the locale. If the * language, sacript, country, and variant fields are all empty, * this function returns the empty string. + * + * @return The name of the locale appropriate to display. */ public final String getDisplayName() { return getDisplayName(getDefault(Category.DISPLAY)); @@ -1844,6 +1863,8 @@ public final class Locale implements Cloneable, Serializable { * language, script, country, and variant fields are all empty, * this function returns the empty string. * + * @param inLocale The locale for which to retrieve the display name. + * @return The name of the locale appropriate to display. * @throws NullPointerException if inLocale is null */ public String getDisplayName(Locale inLocale) { @@ -2672,7 +2693,7 @@ public final class Locale implements Cloneable, Serializable { * * The filtering method will behave as follows: * - *
    grandfathered tag converts to
    cel-gaulish xtg-x-cel-gaulish
    + *
    * * * diff --git a/jdk/src/share/classes/java/util/NavigableSet.java b/jdk/src/share/classes/java/util/NavigableSet.java index 26fcd3a7c35..4dbb1c1cc45 100644 --- a/jdk/src/share/classes/java/util/NavigableSet.java +++ b/jdk/src/share/classes/java/util/NavigableSet.java @@ -303,7 +303,7 @@ public interface NavigableSet extends SortedSet { * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} -na */ + */ SortedSet headSet(E toElement); /** diff --git a/jdk/src/share/classes/java/util/Optional.java b/jdk/src/share/classes/java/util/Optional.java index b51a4d26122..4e95e18684b 100644 --- a/jdk/src/share/classes/java/util/Optional.java +++ b/jdk/src/share/classes/java/util/Optional.java @@ -25,6 +25,8 @@ package java.util; import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; import java.util.function.Supplier; /** @@ -52,7 +54,7 @@ public final class Optional { private final T value; /** - * Construct an empty instance. + * Constructs an empty instance. * * @implNote Generally only one empty instance, {@link Optional#EMPTY}, * should exist per VM. @@ -80,7 +82,7 @@ public final class Optional { } /** - * Construct an instance with the value present. + * Constructs an instance with the value present. * * @param value the non-null value to be present */ @@ -89,7 +91,7 @@ public final class Optional { } /** - * Return an {@code Optional} with the specified present value. + * Returns an {@code Optional} with the specified present non-null value. * * @param value the value to be present, which must be non-null * @return an {@code Optional} with the value present @@ -98,6 +100,18 @@ public final class Optional { return new Optional<>(value); } + /** + * Returns an {@code Optional} describing the specified value, if non-null, + * otherwise returns an empty {@code Optional}. + * + * @param value the possibly-null value to describe + * @return an {@code Optional} with a present value if the specified value + * is non-null, otherwise an empty {@code Optional} + */ + public static Optional ofNullable(T value) { + return value == null ? empty() : of(value); + } + /** * If a value is present in this {@code Optional}, returns the value, * otherwise throws {@code NoSuchElementException}. @@ -124,7 +138,7 @@ public final class Optional { } /** - * Have the specified consumer accept the value if a value is present, + * If a value is present, invoke the specified consumer with the value, * otherwise do nothing. * * @param consumer block to be executed if a value is present @@ -136,6 +150,89 @@ public final class Optional { consumer.accept(value); } + /** + * If a value is present, and the value matches the given predicate, + * return an {@code Optional} describing the value, otherwise return an + * empty {@code Optional}. + * + * @param predicate a predicate to apply to the value, if present + * @return an {@code Optional} describing the value of this {@code Optional} + * if a value is present and the value matches the given predicate, + * otherwise an empty {@code Optional} + * @throws NullPointerException if the predicate is null + */ + public Optional filter(Predicate predicate) { + Objects.requireNonNull(predicate); + if (!isPresent()) + return this; + else + return predicate.test(value) ? this : empty(); + } + + /** + * If a value is present, apply the provided mapping function to it, + * and if the result is non-null, return an {@code Optional} describing the + * result. Otherwise return an empty {@code Optional}. + * + * @apiNote This method supports post-processing on optional values, without + * the need to explicitly check for a return status. For example, the + * following code traverses a stream of file names, selects one that has + * not yet been processed, and then opens that file, returning an + * {@code Optional}: + * + *
    {@code
    +     *     Optional fis =
    +     *         names.stream().filter(name -> !isProcessedYet(name))
    +     *                       .findFirst()
    +     *                       .map(name -> new FileInputStream(name));
    +     * }
    + * + * Here, {@code findFirst} returns an {@code Optional}, and then + * {@code map} returns an {@code Optional} for the desired + * file if one exists. + * + * @param The type of the result of the mapping function + * @param mapper a mapping function to apply to the value, if present + * @return an {@code Optional} describing the result of applying a mapping + * function to the value of this {@code Optional}, if a value is present, + * otherwise an empty {@code Optional} + * @throws NullPointerException if the mapping function is null + */ + public Optional map(Function mapper) { + Objects.requireNonNull(mapper); + if (!isPresent()) + return empty(); + else { + return Optional.ofNullable(mapper.apply(value)); + } + } + + /** + * If a value is present, apply the provided {@code Optional}-bearing + * mapping function to it, return that result, otherwise return an empty + * {@code Optional}. This method is similar to {@link #map(Function)}, + * but the provided mapper is one whose result is already an {@code Optional}, + * and if invoked, {@code flatMap} does not wrap it with an additional + * {@code Optional}. + * + * @param The type parameter to the {@code Optional} returned by + * @param mapper a mapping function to apply to the value, if present + * the mapping function + * @return the result of applying an {@code Optional}-bearing mapping + * function to the value of this {@code Optional}, if a value is present, + * otherwise an empty {@code Optional} + * @throws NullPointerException if the mapping function is null or returns + * a null result + */ + public Optional flatMap(Function> mapper) { + Objects.requireNonNull(mapper); + if (!isPresent()) + return empty(); + else { + return Objects.requireNonNull(mapper.apply(value)); + } + } + /** * Return the value if present, otherwise return {@code other}. * diff --git a/jdk/src/share/classes/java/util/OptionalDouble.java b/jdk/src/share/classes/java/util/OptionalDouble.java index 118a4b8d017..eda306cf7d4 100644 --- a/jdk/src/share/classes/java/util/OptionalDouble.java +++ b/jdk/src/share/classes/java/util/OptionalDouble.java @@ -186,10 +186,10 @@ public final class OptionalDouble { } /** - * Indicates whether some other object is "equal to" this Optional. The + * Indicates whether some other object is "equal to" this OptionalDouble. The * other object is considered equal if: *
      - *
    • it is also an {@code OptionalInt} and; + *
    • it is also an {@code OptionalDouble} and; *
    • both instances have no value present or; *
    • the present values are "equal to" each other via {@code Double.compare() == 0}. *
    @@ -226,12 +226,14 @@ public final class OptionalDouble { } /** - * Returns a non-empty string representation of this OptionalDouble suitable for + * {@inheritDoc} + * + * Returns a non-empty string representation of this object suitable for * debugging. The exact presentation format is unspecified and may vary * between implementations and versions. * * @implSpec If a value is present the result must include its string - * representation in the result. Empty and present OptionalDoubless must be + * representation in the result. Empty and present instances must be * unambiguously differentiable. * * @return the string representation of this instance diff --git a/jdk/src/share/classes/java/util/OptionalInt.java b/jdk/src/share/classes/java/util/OptionalInt.java index 755c2870b73..66478ce4713 100644 --- a/jdk/src/share/classes/java/util/OptionalInt.java +++ b/jdk/src/share/classes/java/util/OptionalInt.java @@ -186,7 +186,7 @@ public final class OptionalInt { } /** - * Indicates whether some other object is "equal to" this Optional. The + * Indicates whether some other object is "equal to" this OptionalInt. The * other object is considered equal if: *
      *
    • it is also an {@code OptionalInt} and; @@ -226,12 +226,14 @@ public final class OptionalInt { } /** - * Returns a non-empty string representation of this OptionalInt suitable for + * {@inheritDoc} + * + * Returns a non-empty string representation of this object suitable for * debugging. The exact presentation format is unspecified and may vary * between implementations and versions. * * @implSpec If a value is present the result must include its string - * representation in the result. Empty and present OptionalInts must be + * representation in the result. Empty and present instances must be * unambiguously differentiable. * * @return the string representation of this instance diff --git a/jdk/src/share/classes/java/util/OptionalLong.java b/jdk/src/share/classes/java/util/OptionalLong.java index fbb1661cc25..f07cc0d3d3a 100644 --- a/jdk/src/share/classes/java/util/OptionalLong.java +++ b/jdk/src/share/classes/java/util/OptionalLong.java @@ -186,10 +186,10 @@ public final class OptionalLong { } /** - * Indicates whether some other object is "equal to" this Optional. The + * Indicates whether some other object is "equal to" this OptionalLong. The * other object is considered equal if: *
        - *
      • it is also an {@code OptionalInt} and; + *
      • it is also an {@code OptionalLong} and; *
      • both instances have no value present or; *
      • the present values are "equal to" each other via {@code ==}. *
      @@ -226,12 +226,14 @@ public final class OptionalLong { } /** - * Returns a non-empty string representation of this OptionalLong suitable for + * {@inheritDoc} + * + * Returns a non-empty string representation of this object suitable for * debugging. The exact presentation format is unspecified and may vary * between implementations and versions. * * @implSpec If a value is present the result must include its string - * representation in the result. Empty and present OptionalLongs must be + * representation in the result. Empty and present instances must be * unambiguously differentiable. * * @return the string representation of this instance diff --git a/jdk/src/share/classes/java/util/ResourceBundle.java b/jdk/src/share/classes/java/util/ResourceBundle.java index 1d9d80b90a4..b16174d30b7 100644 --- a/jdk/src/share/classes/java/util/ResourceBundle.java +++ b/jdk/src/share/classes/java/util/ResourceBundle.java @@ -74,7 +74,7 @@ import sun.util.locale.LocaleObjectCache; * *

      * This allows you to write programs that can: - *

        + *
          *
        • be easily localized, or translated, into different languages *
        • handle multiple locales at once *
        • be easily modified later to support even more locales @@ -184,7 +184,7 @@ import sun.util.locale.LocaleObjectCache; * subclass. Your subclasses must override two methods: handleGetObject * and getKeys(). * - *

          ResourceBundle.Control

          + *

          ResourceBundle.Control

          * * The {@link ResourceBundle.Control} class provides information necessary * to perform the bundle loading process by the getBundle @@ -195,7 +195,7 @@ import sun.util.locale.LocaleObjectCache; * {@link #getBundle(String, Locale, ClassLoader, Control) getBundle} * factory method for details. * - *

          For the {@code getBundle} factory + *

          For the {@code getBundle} factory * methods that take no {@link Control} instance, their default behavior of resource bundle loading * can be modified with installed {@link @@ -206,7 +206,7 @@ import sun.util.locale.LocaleObjectCache; * more than one service provider installed for supporting the same base name, * the first one returned from {@link ServiceLoader} will be used. * - *

          Cache Management

          + *

          Cache Management

          * * Resource bundle instances created by the getBundle factory * methods are cached by default, and the factory methods return the same @@ -222,7 +222,7 @@ import sun.util.locale.LocaleObjectCache; * Control#needsReload(String, Locale, String, ClassLoader, ResourceBundle, * long) ResourceBundle.Control.needsReload} for details. * - *

          Example

          + *

          Example

          * * The following is a very simple example of a ResourceBundle * subclass, MyResources, that manages two resources (for a larger number of @@ -878,8 +878,8 @@ public abstract class ResourceBundle { * description of modifying the default * behavior. * - *

          The following describes the default - * behavior. + *

          The following describes the default + * behavior. * *

          getBundle uses the base name, the specified locale, and * the default locale (obtained from {@link java.util.Locale#getDefault() @@ -974,8 +974,8 @@ public abstract class ResourceBundle { *

          If still no result bundle is found, the base name alone is looked up. If * this still fails, a MissingResourceException is thrown. * - *

          Once a result resource bundle has been found, - * its parent chain is instantiated. If the result bundle already + *

          Once a result resource bundle has been found, + * its parent chain is instantiated. If the result bundle already * has a parent (perhaps because it was returned from a cache) the chain is * complete. * @@ -1004,8 +1004,8 @@ public abstract class ResourceBundle { * path name (using "/") instead of a fully qualified class name (using * "."). * - *

          - * Example: + *

          + * Example: *

          * The following class and property files are provided: *

          @@ -1026,7 +1026,7 @@ public abstract class ResourceBundle {
                * 

          Calling getBundle with the locale arguments below will * instantiate resource bundles as follows: * - *

    Filtering ModeLanguage Priority List: {@code "de-DE"}
    + *
    * * * @@ -1106,45 +1106,45 @@ public abstract class ResourceBundle { * control.newBundle. * *
    Locale("fr", "CH")MyResources_fr_CH.class, parent MyResources_fr.properties, parent MyResources.class
    Locale("fr", "FR")MyResources_fr.properties, parent MyResources.class
    Locale("de", "DE")MyResources_en.properties, parent MyResources.class
    - * + * border="0" cellpadding="2" cellspacing="2" summary="locale-format combinations for newBundle"> + * * * * * * - * - * * * - * - * + * * * - * - * + * + * * * - * - * + * + * * * - * - * + * * * - * - * + * + * * - * + * *
    Locale
    + * style="vertical-align: top; text-align: left; font-weight: bold; width: 50%;">Locale
    *
    format
    + * style="vertical-align: top; text-align: left; font-weight: bold; width: 50%;">format
    *
    Locale("de", "DE")
    + *
    Locale("de", "DE")
    *
    java.class
    + *
    java.class
    *
    Locale("de", "DE")java.properties
    + *
    Locale("de", "DE")java.properties
    *
    Locale("de")java.classLocale("de")java.class
    Locale("de")java.propertiesLocale("de")java.properties
    Locale("")
    + *
    Locale("")
    *
    java.classjava.class
    Locale("")java.propertiesLocale("")java.properties
    * * @@ -2199,11 +2199,11 @@ public abstract class ResourceBundle { * one by one as below: * *

      - *
    • [L, C, V] - *
    • [L, C] - *
    • [L] - *
    • Locale.ROOT - *
    + *
  • [L, C, V]
  • + *
  • [L, C]
  • + *
  • [L]
  • + *
  • Locale.ROOT
  • + * * *
  • For an input Locale with a non-empty script value, * append candidate Locales by omitting the final component @@ -2211,14 +2211,14 @@ public abstract class ResourceBundle { * Locale with country and variant restored: * *
      - *
    • [L, S, C, V] - *
    • [L, S, C] - *
    • [L, S] - *
    • [L, C, V] - *
    • [L, C] - *
    • [L] - *
    • Locale.ROOT - *
    + *
  • [L, S, C, V]
  • + *
  • [L, S, C]
  • + *
  • [L, S]
  • + *
  • [L, C, V]
  • + *
  • [L, C]
  • + *
  • [L]
  • + *
  • Locale.ROOT
  • + * * *
  • For an input Locale with a variant value consisting * of multiple subtags separated by underscore, generate candidate @@ -2228,16 +2228,16 @@ public abstract class ResourceBundle { * the variant consists of two subtags V1 and V2: * *
      - *
    • [L, S, C, V1, V2] - *
    • [L, S, C, V1] - *
    • [L, S, C] - *
    • [L, S] - *
    • [L, C, V1, V2] - *
    • [L, C, V1] - *
    • [L, C] - *
    • [L] - *
    • Locale.ROOT - *
    + *
  • [L, S, C, V1, V2]
  • + *
  • [L, S, C, V1]
  • + *
  • [L, S, C]
  • + *
  • [L, S]
  • + *
  • [L, C, V1, V2]
  • + *
  • [L, C, V1]
  • + *
  • [L, C]
  • + *
  • [L]
  • + *
  • Locale.ROOT
  • + * * *
  • Special cases for Chinese. When an input Locale has the * language "zh" (Chinese) and an empty script value, either "Hans" (Simplified) or @@ -2248,21 +2248,21 @@ public abstract class ResourceBundle { * is empty, no script is supplied. For example, for Locale("zh", "CN") * , the candidate list will be: *
      - *
    • [L("zh"), S("Hans"), C("CN")] - *
    • [L("zh"), S("Hans")] - *
    • [L("zh"), C("CN")] - *
    • [L("zh")] - *
    • Locale.ROOT + *
    • [L("zh"), S("Hans"), C("CN")]
    • + *
    • [L("zh"), S("Hans")]
    • + *
    • [L("zh"), C("CN")]
    • + *
    • [L("zh")]
    • + *
    • Locale.ROOT
    • *
    * * For Locale("zh", "TW"), the candidate list will be: *
      - *
    • [L("zh"), S("Hant"), C("TW")] - *
    • [L("zh"), S("Hant")] - *
    • [L("zh"), C("TW")] - *
    • [L("zh")] - *
    • Locale.ROOT - *
    + *
  • [L("zh"), S("Hant"), C("TW")]
  • + *
  • [L("zh"), S("Hant")]
  • + *
  • [L("zh"), C("TW")]
  • + *
  • [L("zh")]
  • + *
  • Locale.ROOT
  • + * * *
  • Special cases for Norwegian. Both Locale("no", "NO", * "NY") and Locale("nn", "NO") represent Norwegian @@ -2270,10 +2270,10 @@ public abstract class ResourceBundle { * list is generated up to [L("nn")], and then the following * candidates are added: * - *