This commit is contained in:
J. Duke 2017-07-05 19:04:43 +02:00
commit e9facbae15
899 changed files with 70243 additions and 38134 deletions

View File

@ -220,3 +220,4 @@ cb51fb4789ac0b8be4056482077ddfb8f3bd3805 jdk8-b91
c156084add486f941c12d886a0b1b2854795d557 jdk8-b96 c156084add486f941c12d886a0b1b2854795d557 jdk8-b96
a1c1e8bf71f354f3aec0214cf13d6668811e021d jdk8-b97 a1c1e8bf71f354f3aec0214cf13d6668811e021d jdk8-b97
0d0c983a817bbe8518a5ff201306334a8de267f2 jdk8-b98 0d0c983a817bbe8518a5ff201306334a8de267f2 jdk8-b98
59dc9da813794c924a0383c2a6241af94defdfed jdk8-b99

View File

@ -220,3 +220,4 @@ c8286839d0df04aba819ec4bef12b86babccf30e jdk8-b90
3357c2776431d51a8de326a85e0f41420e40774f jdk8-b96 3357c2776431d51a8de326a85e0f41420e40774f jdk8-b96
469995a8e97424f450c880606d689bf345277b19 jdk8-b97 469995a8e97424f450c880606d689bf345277b19 jdk8-b97
3370fb6146e47a6cc05a213fc213e12fc0a38d07 jdk8-b98 3370fb6146e47a6cc05a213fc213e12fc0a38d07 jdk8-b98
3f67804ab61303782df57e54989ef5e0e4629beb jdk8-b99

View File

@ -359,3 +359,5 @@ d197d377ab2e016d024e8c86cb06a57bd7eae590 jdk8-b97
c9dd82da51ed34a28f7c6b3245163ee962e94572 hs25-b40 c9dd82da51ed34a28f7c6b3245163ee962e94572 hs25-b40
30b5b75c42ac5174b640fbef8aa87527668e8400 jdk8-b98 30b5b75c42ac5174b640fbef8aa87527668e8400 jdk8-b98
2b9946e10587f74ef75ae8145bea484df4a2738b hs25-b41 2b9946e10587f74ef75ae8145bea484df4a2738b hs25-b41
81b6cb70717c66375846b78bb174594ec3aa998e jdk8-b99
9f71e36a471ae4a668e08827d33035963ed10c08 hs25-b42

View File

@ -35,7 +35,7 @@ HOTSPOT_VM_COPYRIGHT=Copyright 2013
HS_MAJOR_VER=25 HS_MAJOR_VER=25
HS_MINOR_VER=0 HS_MINOR_VER=0
HS_BUILD_NUMBER=41 HS_BUILD_NUMBER=42
JDK_MAJOR_VER=1 JDK_MAJOR_VER=1
JDK_MINOR_VER=8 JDK_MINOR_VER=8

View File

@ -46,6 +46,7 @@ ifeq ($(findstring true, $(JVM_VARIANT_ZERO) $(JVM_VARIANT_ZEROSHARK)), true)
include $(MAKEFILES_DIR)/zeroshark.make include $(MAKEFILES_DIR)/zeroshark.make
else else
include $(MAKEFILES_DIR)/$(BUILDARCH).make include $(MAKEFILES_DIR)/$(BUILDARCH).make
-include $(HS_ALT_MAKE)/$(Platform_os_family)/makefiles/$(BUILDARCH).make
endif endif
# set VPATH so make knows where to look for source files # 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 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

View File

@ -410,6 +410,51 @@ class StubGenerator: public StubCodeGenerator {
return start; 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 // 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 // Don't initialize the platform math functions since sparc
// doesn't have intrinsics for these operations. // 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);
} }

View File

@ -2766,6 +2766,39 @@ class StubGenerator: public StubCodeGenerator {
return start; 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: public:
// Information about frame layout at time of blocking runtime call. // 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_encryptAESCrypt = generate_cipherBlockChaining_encryptAESCrypt();
StubRoutines::_cipherBlockChaining_decryptAESCrypt = generate_cipherBlockChaining_decryptAESCrypt(); 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;
} }

View File

@ -3357,7 +3357,45 @@ class StubGenerator: public StubCodeGenerator {
return start; 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 // This is a version of CBC/AES Decrypt which does 4 blocks in a loop at a time
// to hide instruction latency // to hide instruction latency
@ -3833,6 +3871,14 @@ class StubGenerator: public StubCodeGenerator {
StubRoutines::_cipherBlockChaining_encryptAESCrypt = generate_cipherBlockChaining_encryptAESCrypt(); StubRoutines::_cipherBlockChaining_encryptAESCrypt = generate_cipherBlockChaining_encryptAESCrypt();
StubRoutines::_cipherBlockChaining_decryptAESCrypt = generate_cipherBlockChaining_decryptAESCrypt_Parallel(); 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: public:

View File

@ -2323,6 +2323,11 @@ LONG WINAPI topLevelExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo) {
#endif #endif
Thread* t = ThreadLocalStorage::get_thread_slow(); // slow & steady 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 #ifndef _WIN64
// Execution protection violation - win32 running on AMD64 only // Execution protection violation - win32 running on AMD64 only
// Handled first to avoid misdiagnosis as a "normal" access violation; // Handled first to avoid misdiagnosis as a "normal" access violation;

View File

@ -63,24 +63,6 @@ SYMBOL(fixcw):
popl %eax popl %eax
ret 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) .globl SYMBOL(SpinPause)
ELF_TYPE(SpinPause,@function) ELF_TYPE(SpinPause,@function)
.p2align 4,,15 .p2align 4,,15

View File

@ -46,28 +46,6 @@
.text .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) .globl SYMBOL(SpinPause)
.p2align 4,,15 .p2align 4,,15
ELF_TYPE(SpinPause,@function) ELF_TYPE(SpinPause,@function)

View File

@ -385,13 +385,6 @@ enum {
trap_page_fault = 0xE 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 extern "C" JNIEXPORT int
JVM_handle_bsd_signal(int sig, JVM_handle_bsd_signal(int sig,
siginfo_t* info, siginfo_t* info,
@ -454,16 +447,10 @@ JVM_handle_bsd_signal(int sig,
if (info != NULL && uc != NULL && thread != NULL) { if (info != NULL && uc != NULL && thread != NULL) {
pc = (address) os::Bsd::ucontext_get_pc(uc); pc = (address) os::Bsd::ucontext_get_pc(uc);
if (pc == (address) Fetch32PFI) { if (StubRoutines::is_safefetch_fault(pc)) {
uc->context_pc = intptr_t(Fetch32Resume) ; uc->context_pc = intptr_t(StubRoutines::continuation_for_safefetch_fault(pc));
return 1 ; return 1;
} }
#ifdef AMD64
if (pc == (address) FetchNPFI) {
uc->context_pc = intptr_t (FetchNResume) ;
return 1 ;
}
#endif // AMD64
// Handle ALL stack overflow variations here // Handle ALL stack overflow variations here
if (sig == SIGSEGV || sig == SIGBUS) { if (sig == SIGSEGV || sig == SIGBUS) {

View File

@ -21,42 +21,6 @@
# questions. # 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: # Possibilities:
# -- membar # -- membar
# -- CAS (SP + BIAS, G0, G0) # -- CAS (SP + BIAS, G0, G0)

View File

@ -366,18 +366,9 @@ intptr_t* os::Linux::ucontext_get_fp(ucontext_t *uc) {
// Utility functions // 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) { inline static bool checkPrefetch(sigcontext* uc, address pc) {
if (pc == (address) Fetch32PFI) { if (StubRoutines::is_safefetch_fault(pc)) {
set_cont_address(uc, address(Fetch32Resume)); set_cont_address(uc, address(StubRoutines::continuation_for_safefetch_fault(pc)));
return true;
}
if (pc == (address) FetchNPFI) {
set_cont_address(uc, address(FetchNResume));
return true; return true;
} }
return false; return false;

View File

@ -42,24 +42,6 @@
.text .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 .globl SpinPause
.type SpinPause,@function .type SpinPause,@function
.p2align 4,,15 .p2align 4,,15

View File

@ -38,28 +38,6 @@
.text .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 .globl SpinPause
.align 16 .align 16
.type SpinPause,@function .type SpinPause,@function

View File

@ -209,13 +209,6 @@ enum {
trap_page_fault = 0xE 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 extern "C" JNIEXPORT int
JVM_handle_linux_signal(int sig, JVM_handle_linux_signal(int sig,
siginfo_t* info, siginfo_t* info,
@ -278,16 +271,10 @@ JVM_handle_linux_signal(int sig,
if (info != NULL && uc != NULL && thread != NULL) { if (info != NULL && uc != NULL && thread != NULL) {
pc = (address) os::Linux::ucontext_get_pc(uc); pc = (address) os::Linux::ucontext_get_pc(uc);
if (pc == (address) Fetch32PFI) { if (StubRoutines::is_safefetch_fault(pc)) {
uc->uc_mcontext.gregs[REG_PC] = intptr_t(Fetch32Resume) ; uc->uc_mcontext.gregs[REG_PC] = intptr_t(StubRoutines::continuation_for_safefetch_fault(pc));
return 1 ; return 1;
} }
#ifdef AMD64
if (pc == (address) FetchNPFI) {
uc->uc_mcontext.gregs[REG_PC] = intptr_t (FetchNResume) ;
return 1 ;
}
#endif // AMD64
#ifndef AMD64 #ifndef AMD64
// Halt if SI_KERNEL before more crashes get misdiagnosed as Java bugs // Halt if SI_KERNEL before more crashes get misdiagnosed as Java bugs

View File

@ -303,11 +303,6 @@ bool os::is_allocatable(size_t bytes) {
#endif #endif
} }
extern "C" void Fetch32PFI () ;
extern "C" void Fetch32Resume () ;
extern "C" void FetchNPFI () ;
extern "C" void FetchNResume () ;
extern "C" JNIEXPORT int extern "C" JNIEXPORT int
JVM_handle_solaris_signal(int sig, siginfo_t* info, void* ucVoid, JVM_handle_solaris_signal(int sig, siginfo_t* info, void* ucVoid,
int abort_if_unrecognized) { 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]; npc = (address) uc->uc_mcontext.gregs[REG_nPC];
// SafeFetch() support // SafeFetch() support
// Implemented with either a fixed set of addresses such if (StubRoutines::is_safefetch_fault(pc)) {
// as Fetch32*, or with Thread._OnTrap. uc->uc_mcontext.gregs[REG_PC] = intptr_t(StubRoutines::continuation_for_safefetch_fault(pc));
if (uc->uc_mcontext.gregs[REG_PC] == intptr_t(Fetch32PFI)) { uc->uc_mcontext.gregs[REG_nPC] = uc->uc_mcontext.gregs[REG_PC] + 4;
uc->uc_mcontext.gregs [REG_PC] = intptr_t(Fetch32Resume) ; return 1;
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 ;
} }
// Handle ALL stack overflow variations here // Handle ALL stack overflow variations here

View File

@ -21,47 +21,6 @@
!! questions. !! 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: !! Possibilities:
!! -- membar !! -- membar
!! -- CAS (SP + BIAS, G0, G0) !! -- CAS (SP + BIAS, G0, G0)

View File

@ -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 extern "C" JNIEXPORT int
JVM_handle_solaris_signal(int sig, siginfo_t* info, void* ucVoid, JVM_handle_solaris_signal(int sig, siginfo_t* info, void* ucVoid,
int abort_if_unrecognized) { int abort_if_unrecognized) {
@ -436,17 +429,10 @@ JVM_handle_solaris_signal(int sig, siginfo_t* info, void* ucVoid,
// factor me: getPCfromContext // factor me: getPCfromContext
pc = (address) uc->uc_mcontext.gregs[REG_PC]; pc = (address) uc->uc_mcontext.gregs[REG_PC];
// SafeFetch32() support if (StubRoutines::is_safefetch_fault(pc)) {
if (pc == (address) Fetch32PFI) { uc->uc_mcontext.gregs[REG_PC] = intptr_t(StubRoutines::continuation_for_safefetch_fault(pc));
uc->uc_mcontext.gregs[REG_PC] = intptr_t(Fetch32Resume) ; return true;
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 // Handle ALL stack overflow variations here
if (sig == SIGSEGV && info->si_code == SEGV_ACCERR) { if (sig == SIGSEGV && info->si_code == SEGV_ACCERR) {

View File

@ -54,20 +54,6 @@ fixcw:
popl %eax popl %eax
ret 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 .align 16
.globl SpinPause .globl SpinPause
SpinPause: SpinPause:

View File

@ -51,26 +51,6 @@ fs_thread:
movq %fs:0x0,%rax movq %fs:0x0,%rax
ret ret
.globl SafeFetch32, Fetch32PFI, Fetch32Resume
.align 16
// Prototype: int SafeFetch32 (int * Adr, int ErrValue)
SafeFetch32:
movl %esi, %eax
Fetch32PFI:
movl (%rdi), %eax
Fetch32Resume:
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:
ret
.globl SpinPause .globl SpinPause
.align 16 .align 16
SpinPause: SpinPause:

View File

@ -518,24 +518,6 @@ void os::print_register_info(outputStream *st, void *context) {
st->cr(); 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 () { extern "C" int SpinPause () {
#ifdef AMD64 #ifdef AMD64
return 0 ; return 0 ;

View File

@ -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; size_t alloc_byte_size = alloc_word_size * HeapWordSize;
if ((cur_used_bytes + alloc_byte_size) > marking_initiating_used_threshold) { 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, ergo_verbose5(ErgoConcCycles,
"request concurrent cycle initiation", "request concurrent cycle initiation",
ergo_format_reason("occupancy higher than threshold") 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(); last_pause_included_initial_mark = during_initial_mark_pause();
if (last_pause_included_initial_mark) { if (last_pause_included_initial_mark) {
record_concurrent_mark_init_end(0.0); 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 // Note: this might have already been set, if during the last
// pause we decided to start a cycle but at the beginning of // pause we decided to start a cycle but at the beginning of
// this pause we decided to postpone it. That's OK. // this pause we decided to postpone it. That's OK.

View File

@ -915,8 +915,6 @@ class os: AllStatic {
// of the global SpinPause() with C linkage. // of the global SpinPause() with C linkage.
// It'd also be eligible for inlining on many platforms. // It'd also be eligible for inlining on many platforms.
extern "C" int SpinPause () ; extern "C" int SpinPause();
extern "C" int SafeFetch32 (int * adr, int errValue) ;
extern "C" intptr_t SafeFetchN (intptr_t * adr, intptr_t errValue) ;
#endif // SHARE_VM_RUNTIME_OS_HPP #endif // SHARE_VM_RUNTIME_OS_HPP

View File

@ -136,6 +136,13 @@ double (* StubRoutines::_intrinsic_sin )(double) = NULL;
double (* StubRoutines::_intrinsic_cos )(double) = NULL; double (* StubRoutines::_intrinsic_cos )(double) = NULL;
double (* StubRoutines::_intrinsic_tan )(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 // Initialization
// //
// Note: to break cycle with universe initialization, stubs are generated in two phases. // Note: to break cycle with universe initialization, stubs are generated in two phases.

View File

@ -221,6 +221,14 @@ class StubRoutines: AllStatic {
static double (*_intrinsic_cos)(double); static double (*_intrinsic_cos)(double);
static double (*_intrinsic_tan)(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: public:
// Initialization/Testing // Initialization/Testing
static void initialize1(); // must happen before universe::genesis static void initialize1(); // must happen before universe::genesis
@ -381,6 +389,34 @@ class StubRoutines: AllStatic {
return _intrinsic_tan(d); 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 // Default versions of the above arraycopy functions for platforms which do
// not have specialized versions // not have specialized versions
@ -400,4 +436,15 @@ class StubRoutines: AllStatic {
static void arrayof_oop_copy_uninit(HeapWord* src, HeapWord* dest, size_t count); 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 #endif // SHARE_VM_RUNTIME_STUBROUTINES_HPP

View File

@ -81,13 +81,13 @@ void MemTracker::init_tracking_options(const char* option_line) {
} else if (strcmp(option_line, "=detail") == 0) { } else if (strcmp(option_line, "=detail") == 0) {
// detail relies on a stack-walking ability that may not // detail relies on a stack-walking ability that may not
// be available depending on platform and/or compiler flags // be available depending on platform and/or compiler flags
if (PLATFORM_NMT_DETAIL_SUPPORTED) { #if PLATFORM_NATIVE_STACK_WALKING_SUPPORTED
_tracking_level = NMT_detail; _tracking_level = NMT_detail;
} else { #else
jio_fprintf(defaultStream::error_stream(), 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; _tracking_level = NMT_summary;
} #endif
} else if (strcmp(option_line, "=off") != 0) { } else if (strcmp(option_line, "=off") != 0) {
vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL); vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
} }

View File

@ -381,12 +381,12 @@ const uint64_t KlassEncodingMetaspaceMax = (uint64_t(max_juint) + 1) << LogKlass
#endif #endif
/* /*
* If a platform does not support NMT_detail * If a platform does not support native stack walking
* the platform specific globalDefinitions (above) * 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 #ifndef PLATFORM_NATIVE_STACK_WALKING_SUPPORTED
#define PLATFORM_NMT_DETAIL_SUPPORTED true #define PLATFORM_NATIVE_STACK_WALKING_SUPPORTED 1
#endif #endif
// The byte alignment to be used by Arena::Amalloc. See bugid 4169348. // The byte alignment to be used by Arena::Amalloc. See bugid 4169348.

View File

@ -220,3 +220,4 @@ a2a2a91075ad85becbe10a39d7fd04ef9bea8df5 jdk8-b92
4a5d3cf2b3af1660db0237e8da324c140e534fa4 jdk8-b96 4a5d3cf2b3af1660db0237e8da324c140e534fa4 jdk8-b96
978a95239044f26dcc8a6d59246be07ad6ca6be2 jdk8-b97 978a95239044f26dcc8a6d59246be07ad6ca6be2 jdk8-b97
c4908732fef5235f1b98cafe0ce507771ef7892c jdk8-b98 c4908732fef5235f1b98cafe0ce507771ef7892c jdk8-b98
6a099a36589bd933957272ba63e5263bede29971 jdk8-b99

View File

@ -102,7 +102,7 @@ SUNWprivate_1.1 {
Java_sun_security_pkcs11_Secmod_nssGetLibraryHandle; Java_sun_security_pkcs11_Secmod_nssGetLibraryHandle;
Java_sun_security_pkcs11_Secmod_nssLoadLibrary; Java_sun_security_pkcs11_Secmod_nssLoadLibrary;
Java_sun_security_pkcs11_Secmod_nssVersionCheck; Java_sun_security_pkcs11_Secmod_nssVersionCheck;
Java_sun_security_pkcs11_Secmod_nssInit; Java_sun_security_pkcs11_Secmod_nssInitialize;
Java_sun_security_pkcs11_Secmod_nssGetModuleList; Java_sun_security_pkcs11_Secmod_nssGetModuleList;
local: local:

View File

@ -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. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
# #
# This code is free software; you can redistribute it and/or modify it # 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_nssGetLibraryHandle;
Java_sun_security_pkcs11_Secmod_nssLoadLibrary; Java_sun_security_pkcs11_Secmod_nssLoadLibrary;
Java_sun_security_pkcs11_Secmod_nssVersionCheck; Java_sun_security_pkcs11_Secmod_nssVersionCheck;
Java_sun_security_pkcs11_Secmod_nssInit; Java_sun_security_pkcs11_Secmod_nssInitialize;
Java_sun_security_pkcs11_Secmod_nssGetModuleList; Java_sun_security_pkcs11_Secmod_nssGetModuleList;
local: local:

View File

@ -32,6 +32,7 @@ import java.util.List;
import javax.swing.RootPaneContainer; import javax.swing.RootPaneContainer;
import com.apple.eawt.AppEvent.FullScreenEvent; import com.apple.eawt.AppEvent.FullScreenEvent;
import sun.awt.SunToolkit;
import java.lang.annotation.Native; import java.lang.annotation.Native;
@ -75,7 +76,7 @@ final class FullScreenHandler {
static void handleFullScreenEventFromNative(final Window window, final int type) { static void handleFullScreenEventFromNative(final Window window, final int type) {
if (!(window instanceof RootPaneContainer)) return; // handles null if (!(window instanceof RootPaneContainer)) return; // handles null
EventQueue.invokeLater(new Runnable() { SunToolkit.executeOnEventHandlerThread(window, new Runnable() {
public void run() { public void run() {
final FullScreenHandler handler = getHandlerFor((RootPaneContainer)window); final FullScreenHandler handler = getHandlerFor((RootPaneContainer)window);
if (handler != null) handler.notifyListener(new FullScreenEvent(window), type); if (handler != null) handler.notifyListener(new FullScreenEvent(window), type);

View File

@ -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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * 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.net.*;
import java.util.*; import java.util.*;
import java.util.List; import java.util.List;
import sun.awt.AppContext;
import sun.awt.SunToolkit;
import com.apple.eawt.AppEvent.*; import com.apple.eawt.AppEvent.*;
@ -269,13 +271,11 @@ class _AppEventHandler {
} }
class _AppReOpenedDispatcher extends _AppEventMultiplexor<AppReOpenedListener> { class _AppReOpenedDispatcher extends _AppEventMultiplexor<AppReOpenedListener> {
void performOnListeners(final List<AppReOpenedListener> listeners, final _NativeEvent event) { void performOnListener(AppReOpenedListener listener, final _NativeEvent event) {
final AppReOpenedEvent e = new AppReOpenedEvent(); final AppReOpenedEvent e = new AppReOpenedEvent();
for (final AppReOpenedListener listener : listeners) {
listener.appReOpened(e); listener.appReOpened(e);
} }
} }
}
class _AppForegroundDispatcher extends _BooleanAppEventMultiplexor<AppForegroundListener, AppForegroundEvent> { class _AppForegroundDispatcher extends _BooleanAppEventMultiplexor<AppForegroundListener, AppForegroundEvent> {
AppForegroundEvent createEvent(final boolean isTrue) { return new AppForegroundEvent(); } AppForegroundEvent createEvent(final boolean isTrue) { return new AppForegroundEvent(); }
@ -415,50 +415,67 @@ class _AppEventHandler {
} }
abstract class _AppEventMultiplexor<L> { abstract class _AppEventMultiplexor<L> {
final List<L> _listeners = new ArrayList<L>(0); private final Map<L, AppContext> listenerToAppContext =
new IdentityHashMap<L, AppContext>();
boolean nativeListenerRegistered; boolean nativeListenerRegistered;
// called from AppKit Thread-0 // called from AppKit Thread-0
void dispatch(final _NativeEvent event, final Object... args) { void dispatch(final _NativeEvent event, final Object... args) {
// grab a local ref to the listeners // grab a local ref to the listeners and its contexts as an array of the map's entries
final List<L> localListeners; final ArrayList<Map.Entry<L, AppContext>> localEntries;
synchronized (this) { synchronized (this) {
if (_listeners.size() == 0) return; if (listenerToAppContext.size() == 0) {
localListeners = new ArrayList<L>(_listeners); return;
}
localEntries = new ArrayList<Map.Entry<L, AppContext>>(listenerToAppContext.size());
localEntries.addAll(listenerToAppContext.entrySet());
} }
EventQueue.invokeLater(new Runnable() { for (final Map.Entry<L, AppContext> e : localEntries) {
final L listener = e.getKey();
final AppContext listenerContext = e.getValue();
SunToolkit.invokeLaterOnAppContext(listenerContext, new Runnable() {
public void run() { public void run() {
performOnListeners(localListeners, event); performOnListener(listener, event);
} }
}); });
} }
}
synchronized void addListener(final L listener) { synchronized void addListener(final L listener) {
setListenerContext(listener, AppContext.getAppContext());
if (!nativeListenerRegistered) { if (!nativeListenerRegistered) {
registerNativeListener(); registerNativeListener();
nativeListenerRegistered = true; nativeListenerRegistered = true;
} }
_listeners.add(listener);
} }
synchronized void removeListener(final L listener) { synchronized void removeListener(final L listener) {
_listeners.remove(listener); listenerToAppContext.remove(listener);
} }
abstract void performOnListeners(final List<L> listeners, final _NativeEvent event); abstract void performOnListener(L listener, final _NativeEvent event);
void registerNativeListener() { } 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<L, E> extends _AppEventMultiplexor<L> { abstract class _BooleanAppEventMultiplexor<L, E> extends _AppEventMultiplexor<L> {
@Override @Override
void performOnListeners(final List<L> listeners, final _NativeEvent event) { void performOnListener(L listener, final _NativeEvent event) {
final boolean isTrue = Boolean.TRUE.equals(event.get(0)); final boolean isTrue = Boolean.TRUE.equals(event.get(0));
final E e = createEvent(isTrue); final E e = createEvent(isTrue);
if (isTrue) { if (isTrue) {
for (final L listener : listeners) performTrueEventOn(listener, e); performTrueEventOn(listener, e);
} else { } else {
for (final L listener : listeners) performFalseEventOn(listener, e); performFalseEventOn(listener, e);
} }
} }
@ -479,30 +496,34 @@ class _AppEventHandler {
*/ */
abstract class _AppEventDispatcher<H> { abstract class _AppEventDispatcher<H> {
H _handler; H _handler;
AppContext handlerContext;
// called from AppKit Thread-0 // called from AppKit Thread-0
void dispatch(final _NativeEvent event) { void dispatch(final _NativeEvent event) {
EventQueue.invokeLater(new Runnable() {
public void run() {
// grab a local ref to the handler // grab a local ref to the handler
final H localHandler; final H localHandler;
final AppContext localHandlerContext;
synchronized (_AppEventDispatcher.this) { synchronized (_AppEventDispatcher.this) {
localHandler = _handler; localHandler = _handler;
localHandlerContext = handlerContext;
} }
// invoke the handler outside of the synchronized block
if (localHandler == null) { if (localHandler == null) {
performDefaultAction(event); performDefaultAction(event);
} else { } else {
SunToolkit.invokeLaterOnAppContext(localHandlerContext, new Runnable() {
public void run() {
performUsing(localHandler, event); performUsing(localHandler, event);
} }
}
}); });
} }
}
synchronized void setHandler(final H handler) { synchronized void setHandler(final H handler) {
this._handler = handler; this._handler = handler;
setHandlerContext(AppContext.getAppContext());
// if a new handler is installed, block addition of legacy ApplicationListeners // if a new handler is installed, block addition of legacy ApplicationListeners
if (handler == legacyHandler) return; if (handler == legacyHandler) return;
legacyHandler.blockLegacyAPI(); legacyHandler.blockLegacyAPI();
@ -510,6 +531,15 @@ class _AppEventHandler {
void performDefaultAction(final _NativeEvent event) { } // by default, do nothing void performDefaultAction(final _NativeEvent event) { } // by default, do nothing
abstract void performUsing(final H handler, final _NativeEvent event); 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<H> extends _AppEventDispatcher<H> { abstract class _QueuingAppEventDispatcher<H> extends _AppEventDispatcher<H> {
@ -531,6 +561,8 @@ class _AppEventHandler {
synchronized void setHandler(final H handler) { synchronized void setHandler(final H handler) {
this._handler = handler; this._handler = handler;
setHandlerContext(AppContext.getAppContext());
// dispatch any events in the queue // dispatch any events in the queue
if (queuedEvents != null) { if (queuedEvents != null) {
// grab a local ref to the queue, so the real one can be nulled out // grab a local ref to the queue, so the real one can be nulled out

View File

@ -25,6 +25,8 @@
package com.apple.eawt.event; package com.apple.eawt.event;
import sun.awt.SunToolkit;
import java.awt.*; import java.awt.*;
import java.util.*; import java.util.*;
import java.util.List; 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) { 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... if (window == null) return; // should never happen...
EventQueue.invokeLater(new Runnable() { SunToolkit.executeOnEventHandlerThread(window, new Runnable() {
public void run() { public void run() {
final Component component = SwingUtilities.getDeepestComponentAt(window, (int)x, (int)y); final Component component = SwingUtilities.getDeepestComponentAt(window, (int)x, (int)y);

View File

@ -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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * 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 javax.swing.*;
import sun.awt.SunToolkit;
import sun.lwawt.LWToolkit; import sun.lwawt.LWToolkit;
import sun.lwawt.macosx.*; import sun.lwawt.macosx.*;
@ -144,7 +145,7 @@ class ScreenMenu extends Menu implements ContainerListener, ComponentListener, S
updateItems(); updateItems();
fItemBounds = new Rectangle[invoker.getMenuComponentCount()]; fItemBounds = new Rectangle[invoker.getMenuComponentCount()];
} }
}, null); }, invoker);
} catch (final Exception e) { } catch (final Exception e) {
System.err.println(e); System.err.println(e);
e.printStackTrace(); e.printStackTrace();
@ -172,7 +173,7 @@ class ScreenMenu extends Menu implements ContainerListener, ComponentListener, S
fItemBounds = null; fItemBounds = null;
} }
}, null); }, invoker);
} catch (final Exception e) { } catch (final Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -200,7 +201,7 @@ class ScreenMenu extends Menu implements ContainerListener, ComponentListener, S
if (kind == 0) return; if (kind == 0) return;
if (fItemBounds == null) return; if (fItemBounds == null) return;
SwingUtilities.invokeLater(new Runnable() { SunToolkit.executeOnEventHandlerThread(fInvoker, new Runnable() {
@Override @Override
public void run() { public void run() {
Component target = null; Component target = null;

View File

@ -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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * 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) { public void handleAction(final boolean state) {
final CheckboxMenuItem target = (CheckboxMenuItem)getTarget(); final CheckboxMenuItem target = (CheckboxMenuItem)getTarget();
EventQueue.invokeLater(new Runnable() { SunToolkit.executeOnEventHandlerThread(target, new Runnable() {
public void run() { public void run() {
target.setState(state); target.setState(state);
} }

View File

@ -107,10 +107,6 @@ public final class CDragSourceContextPeer extends SunDragSourceContextPeer {
loc = rootComponent.getLocation(); 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 there isn't any drag image make one of default appearance:
if (fDragImage == null) if (fDragImage == null)
this.setDefaultDragImage(component); this.setDefaultDragImage(component);
@ -137,6 +133,11 @@ public final class CDragSourceContextPeer extends SunDragSourceContextPeer {
} }
try { 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: // Create native dragging source:
final long nativeDragSource = createNativeDragSource(component, nativeViewPtr, transferable, triggerEvent, final long nativeDragSource = createNativeDragSource(component, nativeViewPtr, transferable, triggerEvent,
(int) (dragOrigin.getX()), (int) (dragOrigin.getY()), extModifiers, (int) (dragOrigin.getX()), (int) (dragOrigin.getY()), extModifiers,

View File

@ -52,6 +52,8 @@ public final class CDropTarget {
fPeer = peer; fPeer = peer;
long nativePeer = CPlatformWindow.getNativeViewPtr(((LWComponentPeer) peer).getPlatformWindow()); long nativePeer = CPlatformWindow.getNativeViewPtr(((LWComponentPeer) peer).getPlatformWindow());
if (nativePeer == 0L) return; // Unsupported for a window without a native view (plugin)
// Create native dragging destination: // Create native dragging destination:
fNativeDropTarget = this.createNativeDropTarget(dropTarget, component, peer, nativePeer); fNativeDropTarget = this.createNativeDropTarget(dropTarget, component, peer, nativePeer);
if (fNativeDropTarget == 0) { if (fNativeDropTarget == 0) {

View File

@ -479,12 +479,14 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo
deliverZoom(true); deliverZoom(true);
this.normalBounds = peer.getBounds(); this.normalBounds = peer.getBounds();
long screen = CWrapper.NSWindow.screen(getNSWindowPtr());
Rectangle toBounds = CWrapper.NSScreen.visibleFrame(screen).getBounds(); GraphicsConfiguration config = getPeer().getGraphicsConfiguration();
// Flip the y coordinate Insets i = ((CGraphicsDevice)config.getDevice()).getScreenInsets();
Rectangle frame = CWrapper.NSScreen.frame(screen).getBounds(); Rectangle toBounds = config.getBounds();
toBounds.y = frame.height - toBounds.y - toBounds.height; setBounds(toBounds.x + i.left,
setBounds(toBounds.x, toBounds.y, toBounds.width, toBounds.height); 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 // the move/size notification from the underlying system comes
// but it contains a bounds smaller than the whole screen // but it contains a bounds smaller than the whole screen
// and therefore we need to create the synthetic notifications // and therefore we need to create the synthetic notifications
Rectangle screenBounds; Rectangle screenBounds = getPeer().getGraphicsConfiguration().getBounds();
final long screenPtr = CWrapper.NSWindow.screen(getNSWindowPtr());
try {
screenBounds = CWrapper.NSScreen.frame(screenPtr).getBounds();
} finally {
CWrapper.NSObject.release(screenPtr);
}
peer.notifyReshape(screenBounds.x, screenBounds.y, screenBounds.width, peer.notifyReshape(screenBounds.x, screenBounds.y, screenBounds.width,
screenBounds.height); screenBounds.height);
} }
@ -900,8 +896,6 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo
nativePeer = ((CPlatformWindow) platformWindow).getContentView().getAWTView(); nativePeer = ((CPlatformWindow) platformWindow).getContentView().getAWTView();
} else if (platformWindow instanceof CViewPlatformEmbeddedFrame){ } else if (platformWindow instanceof CViewPlatformEmbeddedFrame){
nativePeer = ((CViewPlatformEmbeddedFrame) platformWindow).getNSViewPtr(); nativePeer = ((CViewPlatformEmbeddedFrame) platformWindow).getNSViewPtr();
} else {
throw new IllegalArgumentException("Unsupported platformWindow implementation");
} }
return nativePeer; return nativePeer;
} }
@ -932,27 +926,21 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo
final Rectangle oldB = nativeBounds; final Rectangle oldB = nativeBounds;
nativeBounds = new Rectangle(x, y, width, height); nativeBounds = new Rectangle(x, y, width, height);
final GraphicsConfiguration oldGC = peer.getGraphicsConfiguration();
final GraphicsConfiguration newGC = peer.getGraphicsConfiguration();
// System-dependent appearance optimization.
if (peer != null) { if (peer != null) {
peer.notifyReshape(x, y, width, height); peer.notifyReshape(x, y, width, height);
} // System-dependent appearance optimization.
if ((byUser && !oldB.getSize().equals(nativeBounds.getSize())) if ((byUser && !oldB.getSize().equals(nativeBounds.getSize()))
|| isFullScreenAnimationOn || !Objects.equals(newGC, oldGC)) { || isFullScreenAnimationOn) {
flushBuffers(); flushBuffers();
} }
} }
}
private void deliverWindowClosingEvent() { private void deliverWindowClosingEvent() {
if (peer != null) { if (peer != null && peer.getBlocker() == null) {
if (peer.getBlocker() == null) {
peer.postEvent(new WindowEvent(target, WindowEvent.WINDOW_CLOSING)); peer.postEvent(new WindowEvent(target, WindowEvent.WINDOW_CLOSING));
} }
} }
}
private void deliverIconify(final boolean iconify) { private void deliverIconify(final boolean iconify) {
if (peer != null) { if (peer != null) {

View File

@ -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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -96,7 +96,7 @@ public class CViewEmbeddedFrame extends EmbeddedFrame {
validate(); validate();
setVisible(true); setVisible(true);
} }
}, null); }, this);
} catch (InterruptedException | InvocationTargetException ex) {} } catch (InterruptedException | InvocationTargetException ex) {}
} }
} }

View File

@ -71,8 +71,6 @@ public final class CWrapper {
public static native void zoom(long window); public static native void zoom(long window);
public static native void makeFirstResponder(long window, long responder); public static native void makeFirstResponder(long window, long responder);
public static native long screen(long window);
} }
public static final class NSView { public static final class NSView {
@ -95,12 +93,6 @@ public final class CWrapper {
public static native void release(long object); 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 final class NSColor {
public static native long clearColor(); public static native long clearColor();
} }

View File

@ -82,8 +82,13 @@ JNF_COCOA_ENTER(env);
// keys, so we need to do the same translation here that we do // keys, so we need to do the same translation here that we do
// for the regular key down events // for the regular key down events
if ([eventKey length] == 1) { if ([eventKey length] == 1) {
unichar ch = NsCharToJavaChar([eventKey characterAtIndex:0], 0); unichar origChar = [eventKey characterAtIndex:0];
eventKey = [NSString stringWithCharacters: &ch length: 1]; 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]) { if ([menuKey isEqualToString:eventKey]) {

View File

@ -396,31 +396,6 @@ JNF_COCOA_ENTER(env);
JNF_COCOA_EXIT(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 * Method: miniaturize
* Signature: (J)V * Signature: (J)V
@ -690,92 +665,6 @@ JNF_COCOA_ENTER(env);
JNF_COCOA_EXIT(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 * Class: sun_lwawt_macosx_CWrapper$NSColor
* Method: clearColor * Method: clearColor

View File

@ -102,7 +102,7 @@ horizontal=horizontal
# #
# accessible actions # accessible actions
# #
toggle expand=toggle expand toggleexpand=toggle expand
# new relations, roles and states for J2SE 1.5.0 # new relations, roles and states for J2SE 1.5.0

View File

@ -102,7 +102,7 @@ horizontal=horizontal
# #
# accessible actions # accessible actions
# #
toggle expand=ein-/ausblenden toggleexpand=ein-/ausblenden
# new relations, roles and states for J2SE 1.5.0 # new relations, roles and states for J2SE 1.5.0

View File

@ -102,7 +102,7 @@ horizontal=horizontal
# #
# accessible actions # accessible actions
# #
toggle expand=activar/desactivar ampliaci\u00F3n toggleexpand=activar/desactivar ampliaci\u00F3n
# new relations, roles and states for J2SE 1.5.0 # new relations, roles and states for J2SE 1.5.0

View File

@ -102,7 +102,7 @@ horizontal=horizontal
# #
# accessible actions # accessible actions
# #
toggle expand=basculer le d\u00E9veloppement toggleexpand=basculer le d\u00E9veloppement
# new relations, roles and states for J2SE 1.5.0 # new relations, roles and states for J2SE 1.5.0

View File

@ -102,7 +102,7 @@ horizontal=orizzontale
# #
# accessible actions # accessible actions
# #
toggle expand=abilita/disabilita espansione toggleexpand=abilita/disabilita espansione
# new relations, roles and states for J2SE 1.5.0 # new relations, roles and states for J2SE 1.5.0

View File

@ -102,7 +102,7 @@ horizontal=\u6C34\u5E73
# #
# accessible actions # 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 # new relations, roles and states for J2SE 1.5.0

View File

@ -102,7 +102,7 @@ horizontal=\uAC00\uB85C
# #
# accessible actions # accessible actions
# #
toggle expand=\uD1A0\uAE00 \uD655\uC7A5 toggleexpand=\uD1A0\uAE00 \uD655\uC7A5
# new relations, roles and states for J2SE 1.5.0 # new relations, roles and states for J2SE 1.5.0

View File

@ -102,7 +102,7 @@ horizontal=horizontal
# #
# accessible actions # accessible actions
# #
toggle expand=alternar expans\u00E3o toggleexpand=alternar expans\u00E3o
# new relations, roles and states for J2SE 1.5.0 # new relations, roles and states for J2SE 1.5.0

View File

@ -102,7 +102,7 @@ horizontal=horisontell
# #
# accessible actions # accessible actions
# #
toggle expand=v\u00E4xla ut\u00F6ka toggleexpand=v\u00E4xla ut\u00F6ka
# new relations, roles and states for J2SE 1.5.0 # new relations, roles and states for J2SE 1.5.0

View File

@ -102,7 +102,7 @@ horizontal=\u6C34\u5E73
# #
# accessible actions # accessible actions
# #
toggle expand=\u5207\u6362\u5C55\u5F00 toggleexpand=\u5207\u6362\u5C55\u5F00
# new relations, roles and states for J2SE 1.5.0 # new relations, roles and states for J2SE 1.5.0

View File

@ -102,7 +102,7 @@ horizontal=\u6C34\u5E73
# #
# accessible actions # accessible actions
# #
toggle expand=\u5207\u63DB\u64F4\u5C55 toggleexpand=\u5207\u63DB\u64F4\u5C55
# new relations, roles and states for J2SE 1.5.0 # new relations, roles and states for J2SE 1.5.0

View File

@ -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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * 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.InvalidKeyException;
import java.security.spec.KeySpec; import java.security.spec.KeySpec;
import java.security.spec.InvalidKeySpecException; import java.security.spec.InvalidKeySpecException;
import javax.crypto.spec.SecretKeySpec;
/** /**
* This class implements the DES key factory of the Sun provider. * 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) protected SecretKey engineGenerateSecret(KeySpec keySpec)
throws InvalidKeySpecException { throws InvalidKeySpecException {
DESKey desKey = null;
try { try {
if (!(keySpec instanceof DESKeySpec)) { if (keySpec instanceof DESKeySpec) {
throw new InvalidKeySpecException return new DESKey(((DESKeySpec)keySpec).getKey());
("Inappropriate key specification");
} }
else {
DESKeySpec desKeySpec = (DESKeySpec)keySpec; if (keySpec instanceof SecretKeySpec) {
desKey = new DESKey(desKeySpec.getKey()); return new DESKey(((SecretKeySpec)keySpec).getEncoded());
} }
throw new InvalidKeySpecException(
"Inappropriate key specification");
} catch (InvalidKeyException e) { } catch (InvalidKeyException e) {
throw new InvalidKeySpecException(e.getMessage());
} }
return desKey;
} }
/** /**

View File

@ -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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * 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.InvalidKeyException;
import java.security.spec.KeySpec; import java.security.spec.KeySpec;
import java.security.spec.InvalidKeySpecException; import java.security.spec.InvalidKeySpecException;
import javax.crypto.spec.SecretKeySpec;
/** /**
* This class implements the DES-EDE key factory of the Sun provider. * 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) protected SecretKey engineGenerateSecret(KeySpec keySpec)
throws InvalidKeySpecException { throws InvalidKeySpecException {
DESedeKey desEdeKey = null;
try { try {
if (keySpec instanceof DESedeKeySpec) { if (keySpec instanceof DESedeKeySpec) {
DESedeKeySpec desEdeKeySpec = (DESedeKeySpec)keySpec; return new DESedeKey(((DESedeKeySpec)keySpec).getKey());
desEdeKey = new DESedeKey(desEdeKeySpec.getKey()); }
if (keySpec instanceof SecretKeySpec) {
return new DESedeKey(((SecretKeySpec)keySpec).getEncoded());
} else { }
throw new InvalidKeySpecException throw new InvalidKeySpecException
("Inappropriate key specification"); ("Inappropriate key specification");
}
} catch (InvalidKeyException e) { } catch (InvalidKeyException e) {
throw new InvalidKeySpecException(e.getMessage());
} }
return desEdeKey;
} }
/** /**

View File

@ -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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * 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) { } catch (InvalidKeyException e) {
throw new InvalidKeySpecException throw new InvalidKeySpecException
("Inappropriate key specification"); ("Inappropriate key specification", e);
} }
} }
@ -118,7 +118,7 @@ public final class DHKeyFactory extends KeyFactorySpi {
} }
} catch (InvalidKeyException e) { } catch (InvalidKeyException e) {
throw new InvalidKeySpecException throw new InvalidKeySpecException
("Inappropriate key specification"); ("Inappropriate key specification", e);
} }
} }
@ -227,7 +227,7 @@ public final class DHKeyFactory extends KeyFactorySpi {
} }
} catch (InvalidKeySpecException e) { } catch (InvalidKeySpecException e) {
throw new InvalidKeyException("Cannot translate key"); throw new InvalidKeyException("Cannot translate key", e);
} }
} }
} }

View File

@ -167,15 +167,16 @@ public final class DHKeyPairGenerator extends KeyPairGeneratorSpi {
BigInteger pMinus2 = p.subtract(BigInteger.valueOf(2)); BigInteger pMinus2 = p.subtract(BigInteger.valueOf(2));
// //
// Handbook of Applied Cryptography: Menezes, et.al. // PKCS#3 section 7.1 "Private-value generation"
// Repeat if the following does not hold: // Repeat if either of the followings does not hold:
// 1 <= x <= p-2 // 0 < x < p-1
// 2^(lSize-1) <= x < 2^(lSize)
// //
do { do {
// generate random x up to 2^lSize bits long // generate random x up to 2^lSize bits long
x = new BigInteger(lSize, random); x = new BigInteger(lSize, random);
} while ((x.compareTo(BigInteger.ONE) < 0) || } while ((x.compareTo(BigInteger.ONE) < 0) ||
((x.compareTo(pMinus2) > 0))); ((x.compareTo(pMinus2) > 0)) || (x.bitLength() != lSize));
// calculate public value y // calculate public value y
BigInteger y = g.modPow(x, p); BigInteger y = g.modPow(x, p);

View File

@ -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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -26,6 +26,7 @@
package com.sun.crypto.provider; package com.sun.crypto.provider;
import java.io.*; import java.io.*;
import java.util.Objects;
import java.math.BigInteger; import java.math.BigInteger;
import java.security.KeyRep; import java.security.KeyRep;
import java.security.PrivateKey; import java.security.PrivateKey;
@ -67,7 +68,7 @@ javax.crypto.interfaces.DHPrivateKey, Serializable {
// the base generator // the base generator
private BigInteger g; private BigInteger g;
// the private-value length // the private-value length (optional)
private int l; private int l;
private int DH_data[] = { 1, 2, 840, 113549, 1, 3, 1 }; 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(); this.key = val.data.getOctetString();
parseKeyBits(); parseKeyBits();
// ignore OPTIONAL attributes
this.encodedKey = encodedKey.clone(); this.encodedKey = encodedKey.clone();
} catch (IOException | NumberFormatException e) {
} catch (NumberFormatException e) { throw new InvalidKeyException("Error parsing key encoding", 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;
} }
} }
@ -234,8 +224,9 @@ javax.crypto.interfaces.DHPrivateKey, Serializable {
DerOutputStream params = new DerOutputStream(); DerOutputStream params = new DerOutputStream();
params.putInteger(this.p); params.putInteger(this.p);
params.putInteger(this.g); params.putInteger(this.g);
if (this.l != 0) if (this.l != 0) {
params.putInteger(this.l); params.putInteger(this.l);
}
// wrap parameters into SEQUENCE // wrap parameters into SEQUENCE
DerValue paramSequence = new DerValue(DerValue.tag_Sequence, DerValue paramSequence = new DerValue(DerValue.tag_Sequence,
params.toByteArray()); params.toByteArray());
@ -273,11 +264,12 @@ javax.crypto.interfaces.DHPrivateKey, Serializable {
* @return the key parameters * @return the key parameters
*/ */
public DHParameterSpec getParams() { public DHParameterSpec getParams() {
if (this.l != 0) if (this.l != 0) {
return new DHParameterSpec(this.p, this.g, this.l); return new DHParameterSpec(this.p, this.g, this.l);
else } else {
return new DHParameterSpec(this.p, this.g); return new DHParameterSpec(this.p, this.g);
} }
}
public String toString() { public String toString() {
String LINE_SEP = System.getProperty("line.separator"); String LINE_SEP = System.getProperty("line.separator");
@ -312,26 +304,21 @@ javax.crypto.interfaces.DHPrivateKey, Serializable {
* Objects that are equal will also have the same hashcode. * Objects that are equal will also have the same hashcode.
*/ */
public int hashCode() { public int hashCode() {
int retval = 0; return Objects.hash(x, p, g);
byte[] enc = getEncoded();
for (int i = 1; i < enc.length; i++) {
retval += enc[i] * i;
}
return(retval);
} }
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) if (this == obj) return true;
return true;
if (!(obj instanceof PrivateKey)) if (!(obj instanceof javax.crypto.interfaces.DHPrivateKey)) {
return false; return false;
}
byte[] thisEncoded = this.getEncoded(); javax.crypto.interfaces.DHPrivateKey other =
byte[] thatEncoded = ((PrivateKey)obj).getEncoded(); (javax.crypto.interfaces.DHPrivateKey) obj;
DHParameterSpec otherParams = other.getParams();
return java.util.Arrays.equals(thisEncoded, thatEncoded); return ((this.x.compareTo(other.getX()) == 0) &&
(this.p.compareTo(otherParams.getP()) == 0) &&
(this.g.compareTo(otherParams.getG()) == 0));
} }
/** /**

View File

@ -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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -26,6 +26,7 @@
package com.sun.crypto.provider; package com.sun.crypto.provider;
import java.io.*; import java.io.*;
import java.util.Objects;
import java.math.BigInteger; import java.math.BigInteger;
import java.security.KeyRep; import java.security.KeyRep;
import java.security.InvalidKeyException; import java.security.InvalidKeyException;
@ -64,7 +65,7 @@ javax.crypto.interfaces.DHPublicKey, Serializable {
// the base generator // the base generator
private BigInteger g; private BigInteger g;
// the private-value length // the private-value length (optional)
private int l; private int l;
private int DH_data[] = { 1, 2, 840, 113549, 1, 3, 1 }; private int DH_data[] = { 1, 2, 840, 113549, 1, 3, 1 };
@ -173,13 +174,8 @@ javax.crypto.interfaces.DHPublicKey, Serializable {
} }
this.encodedKey = encodedKey.clone(); this.encodedKey = encodedKey.clone();
} catch (IOException | NumberFormatException e) {
} catch (NumberFormatException e) { throw new InvalidKeyException("Error parsing key encoding", e);
throw new InvalidKeyException("Private-value length too big");
} catch (IOException e) {
throw new InvalidKeyException(
"Error parsing key encoding: " + e.toString());
} }
} }
@ -212,8 +208,9 @@ javax.crypto.interfaces.DHPublicKey, Serializable {
DerOutputStream params = new DerOutputStream(); DerOutputStream params = new DerOutputStream();
params.putInteger(this.p); params.putInteger(this.p);
params.putInteger(this.g); params.putInteger(this.g);
if (this.l != 0) if (this.l != 0) {
params.putInteger(this.l); params.putInteger(this.l);
}
// wrap parameters into SEQUENCE // wrap parameters into SEQUENCE
DerValue paramSequence = new DerValue(DerValue.tag_Sequence, DerValue paramSequence = new DerValue(DerValue.tag_Sequence,
params.toByteArray()); params.toByteArray());
@ -253,11 +250,12 @@ javax.crypto.interfaces.DHPublicKey, Serializable {
* @return the key parameters * @return the key parameters
*/ */
public DHParameterSpec getParams() { public DHParameterSpec getParams() {
if (this.l != 0) if (this.l != 0) {
return new DHParameterSpec(this.p, this.g, this.l); return new DHParameterSpec(this.p, this.g, this.l);
else } else {
return new DHParameterSpec(this.p, this.g); return new DHParameterSpec(this.p, this.g);
} }
}
public String toString() { public String toString() {
String LINE_SEP = System.getProperty("line.separator"); String LINE_SEP = System.getProperty("line.separator");
@ -290,26 +288,22 @@ javax.crypto.interfaces.DHPublicKey, Serializable {
* Objects that are equal will also have the same hashcode. * Objects that are equal will also have the same hashcode.
*/ */
public int hashCode() { public int hashCode() {
int retval = 0; return Objects.hash(y, p, g);
byte[] enc = getEncoded();
for (int i = 1; i < enc.length; i++) {
retval += enc[i] * i;
}
return(retval);
} }
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) if (this == obj) return true;
return true;
if (!(obj instanceof PublicKey)) if (!(obj instanceof javax.crypto.interfaces.DHPublicKey)) {
return false; return false;
}
byte[] thisEncoded = this.getEncoded(); javax.crypto.interfaces.DHPublicKey other =
byte[] thatEncoded = ((PublicKey)obj).getEncoded(); (javax.crypto.interfaces.DHPublicKey) obj;
DHParameterSpec otherParams = other.getParams();
return java.util.Arrays.equals(thisEncoded, thatEncoded); return ((this.y.compareTo(other.getY()) == 0) &&
(this.p.compareTo(otherParams.getP()) == 0) &&
(this.g.compareTo(otherParams.getG()) == 0));
} }
/** /**

View File

@ -134,7 +134,7 @@ public class UnpackerImpl extends TLGlobals implements Pack200.Unpacker {
} else { } else {
try { try {
(new NativeUnpack(this)).run(in0, out); (new NativeUnpack(this)).run(in0, out);
} catch (UnsatisfiedLinkError ule) { } catch (UnsatisfiedLinkError | NoClassDefFoundError ex) {
// failover to java implementation // failover to java implementation
(new DoUnpack()).run(in0, out); (new DoUnpack()).run(in0, out);
} }

View File

@ -52,6 +52,7 @@ import javax.management.NotCompliantMBeanException;
import com.sun.jmx.remote.util.EnvHelp; import com.sun.jmx.remote.util.EnvHelp;
import java.lang.reflect.Array; import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.security.AccessController;
import javax.management.AttributeNotFoundException; import javax.management.AttributeNotFoundException;
import javax.management.openmbean.CompositeData; import javax.management.openmbean.CompositeData;
import sun.reflect.misc.MethodUtil; import sun.reflect.misc.MethodUtil;
@ -64,7 +65,11 @@ import sun.reflect.misc.ReflectUtil;
* @since 1.5 * @since 1.5
*/ */
public class Introspector { 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); 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) public static void testComplianceMXBeanInterface(Class<?> interfaceClass)
throws NotCompliantMBeanException { throws NotCompliantMBeanException {
MXBeanIntrospector.getInstance().getAnalyzer(interfaceClass); 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) public static void testComplianceMBeanInterface(Class<?> interfaceClass)
throws NotCompliantMBeanException{ throws NotCompliantMBeanException{
StandardMBeanIntrospector.getInstance().getAnalyzer(interfaceClass); StandardMBeanIntrospector.getInstance().getAnalyzer(interfaceClass);
@ -507,9 +528,12 @@ public class Introspector {
} }
Class<?>[] interfaces = c.getInterfaces(); Class<?>[] interfaces = c.getInterfaces();
for (int i = 0;i < interfaces.length; i++) { 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 Util.cast(interfaces[i]);
} }
}
return null; return null;
} }

View File

@ -28,6 +28,8 @@ package com.sun.jmx.mbeanserver;
import static com.sun.jmx.mbeanserver.Util.*; import static com.sun.jmx.mbeanserver.Util.*;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.util.Arrays; import java.util.Arrays;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
@ -50,7 +52,6 @@ import javax.management.NotCompliantMBeanException;
* @since 1.6 * @since 1.6
*/ */
class MBeanAnalyzer<M> { class MBeanAnalyzer<M> {
static interface MBeanVisitor<M> { static interface MBeanVisitor<M> {
public void visitAttribute(String attributeName, public void visitAttribute(String attributeName,
M getter, M getter,
@ -107,6 +108,10 @@ class MBeanAnalyzer<M> {
if (!mbeanType.isInterface()) { if (!mbeanType.isInterface()) {
throw new NotCompliantMBeanException("Not an interface: " + throw new NotCompliantMBeanException("Not an interface: " +
mbeanType.getName()); mbeanType.getName());
} else if (!Modifier.isPublic(mbeanType.getModifiers()) &&
!Introspector.ALLOW_NONPUBLIC_MBEAN) {
throw new NotCompliantMBeanException("Interface is not public: " +
mbeanType.getName());
} }
try { try {

View File

@ -2,36 +2,34 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.algorithms; 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.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
/** /**
* The Algorithm class which stores the Algorithm URI as a string. * The Algorithm class which stores the Algorithm URI as a string.
*
*/ */
public abstract class Algorithm extends SignatureElementProxy { public abstract class Algorithm extends SignatureElementProxy {
@ -41,7 +39,6 @@ public abstract class Algorithm extends SignatureElementProxy {
* @param algorithmURI is the URI of the algorithm as String * @param algorithmURI is the URI of the algorithm as String
*/ */
public Algorithm(Document doc, String algorithmURI) { public Algorithm(Document doc, String algorithmURI) {
super(doc); super(doc);
this.setAlgorithmURI(algorithmURI); this.setAlgorithmURI(algorithmURI);
@ -54,18 +51,17 @@ public abstract class Algorithm extends SignatureElementProxy {
* @param BaseURI * @param BaseURI
* @throws XMLSecurityException * @throws XMLSecurityException
*/ */
public Algorithm(Element element, String BaseURI) public Algorithm(Element element, String BaseURI) throws XMLSecurityException {
throws XMLSecurityException {
super(element, BaseURI); super(element, BaseURI);
} }
/** /**
* Method getAlgorithmURI * Method getAlgorithmURI
* *
* @return The URI of the alogrithm * @return The URI of the algorithm
*/ */
public String getAlgorithmURI() { public String getAlgorithmURI() {
return this._constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM); return this.constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
} }
/** /**
@ -74,10 +70,10 @@ public abstract class Algorithm extends SignatureElementProxy {
* @param algorithmURI is the URI of the algorithm as String * @param algorithmURI is the URI of the algorithm as String
*/ */
protected void setAlgorithmURI(String algorithmURI) { protected void setAlgorithmURI(String algorithmURI) {
if (algorithmURI != null) {
if ( (algorithmURI != null)) { this.constructionElement.setAttributeNS(
this._constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, null, Constants._ATT_ALGORITHM, algorithmURI
algorithmURI); );
} }
} }
} }

View File

@ -114,6 +114,18 @@ public class JCEMapper {
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1, XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1,
new Algorithm("", "SHA1withECDSA", "Signature") 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( algorithmsMap.put(
XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5, XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5,
new Algorithm("", "HmacMD5", "Mac") new Algorithm("", "HmacMD5", "Mac")
@ -154,6 +166,18 @@ public class JCEMapper {
XMLCipher.AES_256, XMLCipher.AES_256,
new Algorithm("AES", "AES/CBC/ISO10126Padding", "BlockEncryption", 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( algorithmsMap.put(
XMLCipher.RSA_v1dot5, XMLCipher.RSA_v1dot5,
new Algorithm("RSA", "RSA/ECB/PKCS1Padding", "KeyTransport") new Algorithm("RSA", "RSA/ECB/PKCS1Padding", "KeyTransport")
@ -162,6 +186,10 @@ public class JCEMapper {
XMLCipher.RSA_OAEP, XMLCipher.RSA_OAEP,
new Algorithm("RSA", "RSA/ECB/OAEPPadding", "KeyTransport") new Algorithm("RSA", "RSA/ECB/OAEPPadding", "KeyTransport")
); );
algorithmsMap.put(
XMLCipher.RSA_OAEP_11,
new Algorithm("RSA", "RSA/ECB/OAEPPadding", "KeyTransport")
);
algorithmsMap.put( algorithmsMap.put(
XMLCipher.DIFFIE_HELLMAN, XMLCipher.DIFFIE_HELLMAN,
new Algorithm("", "", "KeyAgreement") new Algorithm("", "", "KeyAgreement")

View File

@ -2,82 +2,77 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.algorithms; package com.sun.org.apache.xml.internal.security.algorithms;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchProviderException; 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.signature.XMLSignatureException;
import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants; import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants;
import org.w3c.dom.Document; import org.w3c.dom.Document;
/** /**
* Digest Message wrapper & selector class. * Digest Message wrapper & selector class.
* *
* <pre> * <pre>
* MessageDigestAlgorithm.getInstance() * MessageDigestAlgorithm.getInstance()
* </pre> * </pre>
*
*/ */
public class MessageDigestAlgorithm extends Algorithm { public class MessageDigestAlgorithm extends Algorithm {
/** Message Digest - NOT RECOMMENDED MD5*/ /** Message Digest - NOT RECOMMENDED MD5*/
public static final String ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5 = Constants.MoreAlgorithmsSpecNS + "md5"; public static final String ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5 =
Constants.MoreAlgorithmsSpecNS + "md5";
/** Digest - Required SHA1*/ /** Digest - Required SHA1*/
public static final String ALGO_ID_DIGEST_SHA1 = Constants.SignatureSpecNS + "sha1"; public static final String ALGO_ID_DIGEST_SHA1 = Constants.SignatureSpecNS + "sha1";
/** Message Digest - RECOMMENDED SHA256*/ /** Message Digest - RECOMMENDED SHA256*/
public static final String ALGO_ID_DIGEST_SHA256 = EncryptionConstants.EncryptionSpecNS + "sha256"; public static final String ALGO_ID_DIGEST_SHA256 =
EncryptionConstants.EncryptionSpecNS + "sha256";
/** Message Digest - OPTIONAL SHA384*/ /** Message Digest - OPTIONAL SHA384*/
public static final String ALGO_ID_DIGEST_SHA384 = Constants.MoreAlgorithmsSpecNS + "sha384"; public static final String ALGO_ID_DIGEST_SHA384 =
Constants.MoreAlgorithmsSpecNS + "sha384";
/** Message Digest - OPTIONAL SHA512*/ /** Message Digest - OPTIONAL SHA512*/
public static final String ALGO_ID_DIGEST_SHA512 = EncryptionConstants.EncryptionSpecNS + "sha512"; public static final String ALGO_ID_DIGEST_SHA512 =
EncryptionConstants.EncryptionSpecNS + "sha512";
/** Message Digest - OPTIONAL RIPEMD-160*/ /** Message Digest - OPTIONAL RIPEMD-160*/
public static final String ALGO_ID_DIGEST_RIPEMD160 = EncryptionConstants.EncryptionSpecNS + "ripemd160"; public static final String ALGO_ID_DIGEST_RIPEMD160 =
EncryptionConstants.EncryptionSpecNS + "ripemd160";
/** Field algorithm stores the actual {@link java.security.MessageDigest} */ /** Field algorithm stores the actual {@link java.security.MessageDigest} */
java.security.MessageDigest algorithm = null; private final MessageDigest algorithm;
/** /**
* Constructor for the brave who pass their own message digest algorithms and the corresponding URI. * Constructor for the brave who pass their own message digest algorithms and the
* corresponding URI.
* @param doc * @param doc
* @param messageDigest
* @param algorithmURI * @param algorithmURI
*/ */
private MessageDigestAlgorithm(Document doc, MessageDigest messageDigest, private MessageDigestAlgorithm(Document doc, String algorithmURI)
String algorithmURI) { throws XMLSignatureException {
super(doc, algorithmURI); super(doc, algorithmURI);
this.algorithm = messageDigest; algorithm = getDigestInstance(algorithmURI);
} }
static ThreadLocal<Map<String, MessageDigest>> instances=new
ThreadLocal<Map<String, MessageDigest>>() {
protected Map<String, MessageDigest> initialValue() {
return new HashMap<String, MessageDigest>();
};
};
/** /**
* Factory method for constructing a message digest algorithm by name. * Factory method for constructing a message digest algorithm by name.
* *
@ -87,15 +82,12 @@ public class MessageDigestAlgorithm extends Algorithm {
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
public static MessageDigestAlgorithm getInstance( public static MessageDigestAlgorithm getInstance(
Document doc, String algorithmURI) throws XMLSignatureException { Document doc, String algorithmURI
MessageDigest md = getDigestInstance(algorithmURI); ) throws XMLSignatureException {
return new MessageDigestAlgorithm(doc, md, algorithmURI); return new MessageDigestAlgorithm(doc, algorithmURI);
} }
private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSignatureException { private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSignatureException {
MessageDigest result= instances.get().get(algorithmURI);
if (result!=null)
return result;
String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI); String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI);
if (algorithmID == null) { if (algorithmID == null) {
@ -104,27 +96,25 @@ private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSi
} }
MessageDigest md; MessageDigest md;
String provider=JCEMapper.getProviderId(); String provider = JCEMapper.getProviderId();
try { try {
if (provider==null) { if (provider == null) {
md = MessageDigest.getInstance(algorithmID); md = MessageDigest.getInstance(algorithmID);
} else { } else {
md = MessageDigest.getInstance(algorithmID,provider); md = MessageDigest.getInstance(algorithmID, provider);
} }
} catch (java.security.NoSuchAlgorithmException ex) { } catch (java.security.NoSuchAlgorithmException ex) {
Object[] exArgs = { algorithmID, Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
ex.getLocalizedMessage() };
throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
} catch (NoSuchProviderException ex) { } catch (NoSuchProviderException ex) {
Object[] exArgs = { algorithmID, Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
ex.getLocalizedMessage() };
throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
} }
instances.get().put(algorithmURI, md);
return md; return md;
} }
/** /**
* Returns the actual {@link java.security.MessageDigest} algorithm object * Returns the actual {@link java.security.MessageDigest} algorithm object
@ -132,7 +122,7 @@ private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSi
* @return the actual {@link java.security.MessageDigest} algorithm object * @return the actual {@link java.security.MessageDigest} algorithm object
*/ */
public java.security.MessageDigest getAlgorithm() { public java.security.MessageDigest getAlgorithm() {
return this.algorithm; return algorithm;
} }
/** /**
@ -154,7 +144,7 @@ private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSi
* @return the result of the {@link java.security.MessageDigest#digest()} method * @return the result of the {@link java.security.MessageDigest#digest()} method
*/ */
public byte[] digest() { public byte[] digest() {
return this.algorithm.digest(); return algorithm.digest();
} }
/** /**
@ -165,7 +155,7 @@ private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSi
* @return the result of the {@link java.security.MessageDigest#digest(byte[])} method * @return the result of the {@link java.security.MessageDigest#digest(byte[])} method
*/ */
public byte[] digest(byte input[]) { public byte[] digest(byte input[]) {
return this.algorithm.digest(input); return algorithm.digest(input);
} }
/** /**
@ -178,9 +168,8 @@ private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSi
* @return the result of the {@link java.security.MessageDigest#digest(byte[], int, int)} method * @return the result of the {@link java.security.MessageDigest#digest(byte[], int, int)} method
* @throws java.security.DigestException * @throws java.security.DigestException
*/ */
public int digest(byte buf[], int offset, int len) public int digest(byte buf[], int offset, int len) throws java.security.DigestException {
throws java.security.DigestException { return algorithm.digest(buf, offset, len);
return this.algorithm.digest(buf, offset, len);
} }
/** /**
@ -190,7 +179,7 @@ private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSi
* @return the result of the {@link java.security.MessageDigest#getAlgorithm} method * @return the result of the {@link java.security.MessageDigest#getAlgorithm} method
*/ */
public String getJCEAlgorithmString() { public String getJCEAlgorithmString() {
return this.algorithm.getAlgorithm(); return algorithm.getAlgorithm();
} }
/** /**
@ -200,7 +189,7 @@ private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSi
* @return the result of the {@link java.security.MessageDigest#getProvider} method * @return the result of the {@link java.security.MessageDigest#getProvider} method
*/ */
public java.security.Provider getJCEProvider() { public java.security.Provider getJCEProvider() {
return this.algorithm.getProvider(); return algorithm.getProvider();
} }
/** /**
@ -210,7 +199,7 @@ private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSi
* @return the result of the {@link java.security.MessageDigest#getDigestLength} method * @return the result of the {@link java.security.MessageDigest#getDigestLength} method
*/ */
public int getDigestLength() { public int getDigestLength() {
return this.algorithm.getDigestLength(); return algorithm.getDigestLength();
} }
/** /**
@ -219,7 +208,7 @@ private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSi
* *
*/ */
public void reset() { public void reset() {
this.algorithm.reset(); algorithm.reset();
} }
/** /**
@ -229,7 +218,7 @@ private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSi
* @param input * @param input
*/ */
public void update(byte[] input) { public void update(byte[] input) {
this.algorithm.update(input); algorithm.update(input);
} }
/** /**
@ -239,7 +228,7 @@ private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSi
* @param input * @param input
*/ */
public void update(byte input) { public void update(byte input) {
this.algorithm.update(input); algorithm.update(input);
} }
/** /**
@ -251,7 +240,7 @@ private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSi
* @param len * @param len
*/ */
public void update(byte buf[], int offset, int len) { public void update(byte buf[], int offset, int len) {
this.algorithm.update(buf, offset, len); algorithm.update(buf, offset, len);
} }
/** @inheritDoc */ /** @inheritDoc */

View File

@ -74,7 +74,7 @@ public class SignatureAlgorithm extends Algorithm {
this.algorithmURI = algorithmURI; this.algorithmURI = algorithmURI;
signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI); signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI);
signatureAlgorithm.engineGetContextFromElement(this._constructionElement); signatureAlgorithm.engineGetContextFromElement(this.constructionElement);
} }
/** /**
@ -92,10 +92,10 @@ public class SignatureAlgorithm extends Algorithm {
this.algorithmURI = algorithmURI; this.algorithmURI = algorithmURI;
signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI); signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI);
signatureAlgorithm.engineGetContextFromElement(this._constructionElement); signatureAlgorithm.engineGetContextFromElement(this.constructionElement);
signatureAlgorithm.engineSetHMACOutputLength(hmacOutputLength); signatureAlgorithm.engineSetHMACOutputLength(hmacOutputLength);
((IntegrityHmac)signatureAlgorithm).engineAddContextToElement(_constructionElement); ((IntegrityHmac)signatureAlgorithm).engineAddContextToElement(constructionElement);
} }
/** /**
@ -136,7 +136,7 @@ public class SignatureAlgorithm extends Algorithm {
} }
signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI); 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 * @return the URI representation of Transformation algorithm
*/ */
public final String getURI() { 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. * This method registers the default algorithms.
*/ */
public static void registerDefaultAlgorithms() { public static void registerDefaultAlgorithms() {
algorithmHash.put( algorithmHash.put(SignatureDSA.URI, SignatureDSA.class);
XMLSignature.ALGO_ID_SIGNATURE_DSA, SignatureDSA.class
);
algorithmHash.put( algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, SignatureBaseRSA.SignatureRSASHA1.class XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, SignatureBaseRSA.SignatureRSASHA1.class
); );
@ -409,6 +407,15 @@ public class SignatureAlgorithm extends Algorithm {
algorithmHash.put( algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1, SignatureECDSA.SignatureECDSASHA1.class 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( algorithmHash.put(
XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5, IntegrityHmac.IntegrityHmacMD5.class XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5, IntegrityHmac.IntegrityHmacMD5.class
); );

View File

@ -2,21 +2,23 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.algorithms; package com.sun.org.apache.xml.internal.security.algorithms;
@ -27,11 +29,6 @@ import java.security.spec.AlgorithmParameterSpec;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
import org.w3c.dom.Element; import org.w3c.dom.Element;
/**
*
* @author $Author: mullan $
*/
public abstract class SignatureAlgorithmSpi { public abstract class SignatureAlgorithmSpi {
/** /**
@ -63,8 +60,7 @@ public abstract class SignatureAlgorithmSpi {
* @param input * @param input
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
protected abstract void engineUpdate(byte[] input) protected abstract void engineUpdate(byte[] input) throws XMLSignatureException;
throws XMLSignatureException;
/** /**
* Proxy method for {@link java.security.Signature#update(byte[])} * Proxy method for {@link java.security.Signature#update(byte[])}
@ -73,8 +69,7 @@ public abstract class SignatureAlgorithmSpi {
* @param input * @param input
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
protected abstract void engineUpdate(byte input) protected abstract void engineUpdate(byte input) throws XMLSignatureException;
throws XMLSignatureException;
/** /**
* Proxy method for {@link java.security.Signature#update(byte[], int, int)} * Proxy method for {@link java.security.Signature#update(byte[], int, int)}
@ -95,19 +90,19 @@ public abstract class SignatureAlgorithmSpi {
* @param signingKey * @param signingKey
* @throws XMLSignatureException if this method is called on a MAC * @throws XMLSignatureException if this method is called on a MAC
*/ */
protected abstract void engineInitSign(Key signingKey) protected abstract void engineInitSign(Key signingKey) throws XMLSignatureException;
throws XMLSignatureException;
/** /**
* Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey, java.security.SecureRandom)} * 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. * which is executed on the internal {@link java.security.Signature} object.
* *
* @param signingKey * @param signingKey
* @param secureRandom * @param secureRandom
* @throws XMLSignatureException if this method is called on a MAC * @throws XMLSignatureException if this method is called on a MAC
*/ */
protected abstract void engineInitSign( protected abstract void engineInitSign(Key signingKey, SecureRandom secureRandom)
Key signingKey, SecureRandom secureRandom) throws XMLSignatureException; throws XMLSignatureException;
/** /**
* Proxy method for {@link javax.crypto.Mac} * Proxy method for {@link javax.crypto.Mac}
@ -118,8 +113,8 @@ public abstract class SignatureAlgorithmSpi {
* @throws XMLSignatureException if this method is called on a Signature * @throws XMLSignatureException if this method is called on a Signature
*/ */
protected abstract void engineInitSign( protected abstract void engineInitSign(
Key signingKey, AlgorithmParameterSpec algorithmParameterSpec) Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
throws XMLSignatureException; ) throws XMLSignatureException;
/** /**
* Proxy method for {@link java.security.Signature#sign()} * Proxy method for {@link java.security.Signature#sign()}
@ -136,8 +131,7 @@ public abstract class SignatureAlgorithmSpi {
* @param verificationKey * @param verificationKey
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
protected abstract void engineInitVerify(Key verificationKey) protected abstract void engineInitVerify(Key verificationKey) throws XMLSignatureException;
throws XMLSignatureException;
/** /**
* Proxy method for {@link java.security.Signature#verify(byte[])} * Proxy method for {@link java.security.Signature#verify(byte[])}
@ -147,11 +141,11 @@ public abstract class SignatureAlgorithmSpi {
* @return true if the signature is correct * @return true if the signature is correct
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
protected abstract boolean engineVerify(byte[] signature) protected abstract boolean engineVerify(byte[] signature) throws XMLSignatureException;
throws XMLSignatureException;
/** /**
* Proxy method for {@link java.security.Signature#setParameter(java.security.spec.AlgorithmParameterSpec)} * Proxy method for {@link java.security.Signature#setParameter(
* java.security.spec.AlgorithmParameterSpec)}
* which is executed on the internal {@link java.security.Signature} object. * which is executed on the internal {@link java.security.Signature} object.
* *
* @param params * @param params

View File

@ -2,26 +2,26 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.algorithms.implementations; package com.sun.org.apache.xml.internal.security.algorithms.implementations;
import java.security.InvalidAlgorithmParameterException; import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException; import java.security.InvalidKeyException;
import java.security.Key; import java.security.Key;
@ -42,16 +42,18 @@ import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import org.w3c.dom.Text; import org.w3c.dom.Text;
/**
*
* @author $Author: mullan $
*/
public abstract class IntegrityHmac extends SignatureAlgorithmSpi { public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
/** {@link java.util.logging} logging facility */ /** {@link org.apache.commons.logging} logging facility */
static java.util.logging.Logger log = private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(IntegrityHmacSHA1.class.getName()); java.util.logging.Logger.getLogger(IntegrityHmac.class.getName());
/** Field macAlgorithm */
private Mac macAlgorithm = null;
/** Field HMACOutputLength */
private int HMACOutputLength = 0;
private boolean HMACOutputLengthSet = false;
/** /**
* Method engineGetURI * Method engineGetURI
@ -65,50 +67,42 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
*/ */
abstract int getDigestLength(); abstract int getDigestLength();
/** Field _macAlgorithm */
private Mac _macAlgorithm = null;
private boolean _HMACOutputLengthSet = false;
/** Field _HMACOutputLength */
int _HMACOutputLength = 0;
/** /**
* Method IntegrityHmacSHA1das * Method IntegrityHmac
* *
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
public IntegrityHmac() throws XMLSignatureException { public IntegrityHmac() throws XMLSignatureException {
String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); 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 IntegrityHmacSHA1 using " + algorithmID); log.log(java.util.logging.Level.FINE, "Created IntegrityHmacSHA1 using " + algorithmID);
}
try { try {
this._macAlgorithm = Mac.getInstance(algorithmID); this.macAlgorithm = Mac.getInstance(algorithmID);
} catch (java.security.NoSuchAlgorithmException ex) { } catch (java.security.NoSuchAlgorithmException ex) {
Object[] exArgs = { algorithmID, Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
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)} * Proxy method for {@link java.security.Signature#setParameter(
* java.security.spec.AlgorithmParameterSpec)}
* which is executed on the internal {@link java.security.Signature} object. * which is executed on the internal {@link java.security.Signature} object.
* *
* @param params * @param params
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
protected void engineSetParameter(AlgorithmParameterSpec params) protected void engineSetParameter(AlgorithmParameterSpec params) throws XMLSignatureException {
throws XMLSignatureException {
throw new XMLSignatureException("empty"); throw new XMLSignatureException("empty");
} }
public void reset() { public void reset() {
_HMACOutputLength=0; HMACOutputLength = 0;
_HMACOutputLengthSet = false; HMACOutputLengthSet = false;
_macAlgorithm.reset(); this.macAlgorithm.reset();
} }
/** /**
@ -119,18 +113,16 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
* @return true if the signature is correct * @return true if the signature is correct
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
protected boolean engineVerify(byte[] signature) protected boolean engineVerify(byte[] signature) throws XMLSignatureException {
throws XMLSignatureException {
try { try {
if (this._HMACOutputLengthSet && this._HMACOutputLength < getDigestLength()) { if (this.HMACOutputLengthSet && this.HMACOutputLength < getDigestLength()) {
if (log.isLoggable(java.util.logging.Level.FINE)) { if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, log.log(java.util.logging.Level.FINE, "HMACOutputLength must not be less than " + getDigestLength());
"HMACOutputLength must not be less than " + getDigestLength());
} }
throw new XMLSignatureException("errorMessages.XMLSignatureException"); Object[] exArgs = { String.valueOf(getDigestLength()) };
throw new XMLSignatureException("algorithms.HMACOutputLengthMin", exArgs);
} else { } else {
byte[] completeResult = this._macAlgorithm.doFinal(); byte[] completeResult = this.macAlgorithm.doFinal();
return MessageDigestAlgorithm.isEqual(completeResult, signature); return MessageDigestAlgorithm.isEqual(completeResult, signature);
} }
} catch (IllegalStateException ex) { } catch (IllegalStateException ex) {
@ -146,31 +138,28 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
protected void engineInitVerify(Key secretKey) throws XMLSignatureException { protected void engineInitVerify(Key secretKey) throws XMLSignatureException {
if (!(secretKey instanceof SecretKey)) { if (!(secretKey instanceof SecretKey)) {
String supplied = secretKey.getClass().getName(); String supplied = secretKey.getClass().getName();
String needed = SecretKey.class.getName(); String needed = SecretKey.class.getName();
Object exArgs[] = { supplied, needed }; Object exArgs[] = { supplied, needed };
throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
exArgs);
} }
try { try {
this._macAlgorithm.init(secretKey); this.macAlgorithm.init(secretKey);
} catch (InvalidKeyException ex) { } catch (InvalidKeyException ex) {
// reinstantiate Mac object to work around bug in JDK // reinstantiate Mac object to work around bug in JDK
// see: http://bugs.sun.com/view_bug.do?bug_id=4953555 // see: http://bugs.sun.com/view_bug.do?bug_id=4953555
Mac mac = this._macAlgorithm; Mac mac = this.macAlgorithm;
try { try {
this._macAlgorithm = Mac.getInstance this.macAlgorithm = Mac.getInstance(macAlgorithm.getAlgorithm());
(_macAlgorithm.getAlgorithm());
} catch (Exception e) { } catch (Exception e) {
// this shouldn't occur, but if it does, restore previous Mac // this shouldn't occur, but if it does, restore previous Mac
if (log.isLoggable(java.util.logging.Level.FINE)) { if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Mac:" + e); log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Mac:" + e);
} }
this._macAlgorithm = mac; this.macAlgorithm = mac;
} }
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -184,50 +173,21 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
protected byte[] engineSign() throws XMLSignatureException { protected byte[] engineSign() throws XMLSignatureException {
try { try {
if (this._HMACOutputLengthSet && this._HMACOutputLength < getDigestLength()) { if (this.HMACOutputLengthSet && this.HMACOutputLength < getDigestLength()) {
if (log.isLoggable(java.util.logging.Level.FINE)) { if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, log.log(java.util.logging.Level.FINE, "HMACOutputLength must not be less than " + getDigestLength());
"HMACOutputLength must not be less than " + getDigestLength());
} }
throw new XMLSignatureException("errorMessages.XMLSignatureException"); Object[] exArgs = { String.valueOf(getDigestLength()) };
throw new XMLSignatureException("algorithms.HMACOutputLengthMin", exArgs);
} else { } else {
return this._macAlgorithm.doFinal(); return this.macAlgorithm.doFinal();
} }
} catch (IllegalStateException ex) { } catch (IllegalStateException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
} }
/**
* Method reduceBitLength
*
* @param completeResult
* @return the reduced bits.
* @param length
*
*/
private static byte[] reduceBitLength(byte completeResult[], int length) {
int bytes = length / 8;
int abits = length % 8;
byte[] strippedResult = new byte[bytes + ((abits == 0)
? 0
: 1)];
System.arraycopy(completeResult, 0, strippedResult, 0, bytes);
if (abits > 0) {
byte[] MASK = { (byte) 0x00, (byte) 0x80, (byte) 0xC0, (byte) 0xE0,
(byte) 0xF0, (byte) 0xF8, (byte) 0xFC, (byte) 0xFE };
strippedResult[bytes] = (byte) (completeResult[bytes] & MASK[abits]);
}
return strippedResult;
}
/** /**
* Method engineInitSign * Method engineInitSign
* *
@ -235,18 +195,16 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
protected void engineInitSign(Key secretKey) throws XMLSignatureException { protected void engineInitSign(Key secretKey) throws XMLSignatureException {
if (!(secretKey instanceof SecretKey)) { if (!(secretKey instanceof SecretKey)) {
String supplied = secretKey.getClass().getName(); String supplied = secretKey.getClass().getName();
String needed = SecretKey.class.getName(); String needed = SecretKey.class.getName();
Object exArgs[] = { supplied, needed }; Object exArgs[] = { supplied, needed };
throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
exArgs);
} }
try { try {
this._macAlgorithm.init(secretKey); this.macAlgorithm.init(secretKey);
} catch (InvalidKeyException ex) { } catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -260,20 +218,18 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
protected void engineInitSign( protected void engineInitSign(
Key secretKey, AlgorithmParameterSpec algorithmParameterSpec) Key secretKey, AlgorithmParameterSpec algorithmParameterSpec
throws XMLSignatureException { ) throws XMLSignatureException {
if (!(secretKey instanceof SecretKey)) { if (!(secretKey instanceof SecretKey)) {
String supplied = secretKey.getClass().getName(); String supplied = secretKey.getClass().getName();
String needed = SecretKey.class.getName(); String needed = SecretKey.class.getName();
Object exArgs[] = { supplied, needed }; Object exArgs[] = { supplied, needed };
throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
exArgs);
} }
try { try {
this._macAlgorithm.init(secretKey, algorithmParameterSpec); this.macAlgorithm.init(secretKey, algorithmParameterSpec);
} catch (InvalidKeyException ex) { } catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} catch (InvalidAlgorithmParameterException ex) { } catch (InvalidAlgorithmParameterException ex) {
@ -301,9 +257,8 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
protected void engineUpdate(byte[] input) throws XMLSignatureException { protected void engineUpdate(byte[] input) throws XMLSignatureException {
try { try {
this._macAlgorithm.update(input); this.macAlgorithm.update(input);
} catch (IllegalStateException ex) { } catch (IllegalStateException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -317,9 +272,8 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
protected void engineUpdate(byte input) throws XMLSignatureException { protected void engineUpdate(byte input) throws XMLSignatureException {
try { try {
this._macAlgorithm.update(input); this.macAlgorithm.update(input);
} catch (IllegalStateException ex) { } catch (IllegalStateException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -334,11 +288,9 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
* @param len * @param len
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
protected void engineUpdate(byte buf[], int offset, int len) protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException {
throws XMLSignatureException {
try { try {
this._macAlgorithm.update(buf, offset, len); this.macAlgorithm.update(buf, offset, len);
} catch (IllegalStateException ex) { } catch (IllegalStateException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -350,10 +302,7 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
* *
*/ */
protected String engineGetJCEAlgorithmString() { protected String engineGetJCEAlgorithmString() {
return this.macAlgorithm.getAlgorithm();
log.log(java.util.logging.Level.FINE, "engineGetJCEAlgorithmString()");
return this._macAlgorithm.getAlgorithm();
} }
/** /**
@ -362,7 +311,7 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
* @inheritDoc * @inheritDoc
*/ */
protected String engineGetJCEProviderName() { protected String engineGetJCEProviderName() {
return this._macAlgorithm.getProvider().getName(); return this.macAlgorithm.getProvider().getName();
} }
/** /**
@ -371,8 +320,8 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
* @param HMACOutputLength * @param HMACOutputLength
*/ */
protected void engineSetHMACOutputLength(int HMACOutputLength) { protected void engineSetHMACOutputLength(int HMACOutputLength) {
this._HMACOutputLength = HMACOutputLength; this.HMACOutputLength = HMACOutputLength;
this._HMACOutputLengthSet = true; this.HMACOutputLengthSet = true;
} }
/** /**
@ -381,21 +330,19 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
* @param element * @param element
*/ */
protected void engineGetContextFromElement(Element element) { protected void engineGetContextFromElement(Element element) {
super.engineGetContextFromElement(element); super.engineGetContextFromElement(element);
if (element == null) { if (element == null) {
throw new IllegalArgumentException("element null"); throw new IllegalArgumentException("element null");
} }
Text hmaclength =XMLUtils.selectDsNodeText(element.getFirstChild(), Text hmaclength =
Constants._TAG_HMACOUTPUTLENGTH,0); XMLUtils.selectDsNodeText(element.getFirstChild(), Constants._TAG_HMACOUTPUTLENGTH, 0);
if (hmaclength != null) { if (hmaclength != null) {
this._HMACOutputLength = Integer.parseInt(hmaclength.getData()); this.HMACOutputLength = Integer.parseInt(hmaclength.getData());
this._HMACOutputLengthSet = true; this.HMACOutputLengthSet = true;
} }
} }
/** /**
@ -404,17 +351,16 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
* @param element * @param element
*/ */
public void engineAddContextToElement(Element element) { public void engineAddContextToElement(Element element) {
if (element == null) { if (element == null) {
throw new IllegalArgumentException("null element"); throw new IllegalArgumentException("null element");
} }
if (this._HMACOutputLengthSet) { if (this.HMACOutputLengthSet) {
Document doc = element.getOwnerDocument(); Document doc = element.getOwnerDocument();
Element HMElem = XMLUtils.createElementInSignatureSpace(doc, Element HMElem =
Constants._TAG_HMACOUTPUTLENGTH); XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_HMACOUTPUTLENGTH);
Text HMText = Text HMText =
doc.createTextNode(new Integer(this._HMACOutputLength).toString()); doc.createTextNode(Integer.valueOf(this.HMACOutputLength).toString());
HMElem.appendChild(HMText); HMElem.appendChild(HMText);
XMLUtils.addReturnToElement(element); XMLUtils.addReturnToElement(element);
@ -425,9 +371,6 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
/** /**
* Class IntegrityHmacSHA1 * Class IntegrityHmacSHA1
*
* @author $Author: mullan $
* @version $Revision: 1.5 $
*/ */
public static class IntegrityHmacSHA1 extends IntegrityHmac { public static class IntegrityHmacSHA1 extends IntegrityHmac {
@ -456,9 +399,6 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
/** /**
* Class IntegrityHmacSHA256 * Class IntegrityHmacSHA256
*
* @author $Author: mullan $
* @version $Revision: 1.5 $
*/ */
public static class IntegrityHmacSHA256 extends IntegrityHmac { public static class IntegrityHmacSHA256 extends IntegrityHmac {
@ -487,9 +427,6 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
/** /**
* Class IntegrityHmacSHA384 * Class IntegrityHmacSHA384
*
* @author $Author: mullan $
* @version $Revision: 1.5 $
*/ */
public static class IntegrityHmacSHA384 extends IntegrityHmac { public static class IntegrityHmacSHA384 extends IntegrityHmac {
@ -518,9 +455,6 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
/** /**
* Class IntegrityHmacSHA512 * Class IntegrityHmacSHA512
*
* @author $Author: mullan $
* @version $Revision: 1.5 $
*/ */
public static class IntegrityHmacSHA512 extends IntegrityHmac { public static class IntegrityHmacSHA512 extends IntegrityHmac {
@ -549,9 +483,6 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
/** /**
* Class IntegrityHmacRIPEMD160 * Class IntegrityHmacRIPEMD160
*
* @author $Author: mullan $
* @version $Revision: 1.5 $
*/ */
public static class IntegrityHmacRIPEMD160 extends IntegrityHmac { public static class IntegrityHmacRIPEMD160 extends IntegrityHmac {
@ -580,9 +511,6 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
/** /**
* Class IntegrityHmacMD5 * Class IntegrityHmacMD5
*
* @author $Author: mullan $
* @version $Revision: 1.5 $
*/ */
public static class IntegrityHmacMD5 extends IntegrityHmac { public static class IntegrityHmacMD5 extends IntegrityHmac {

View File

@ -2,21 +2,23 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.algorithms.implementations; 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.XMLSignature;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
/**
*
* @author $Author: mullan $
*/
public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi {
/** {@link java.util.logging} logging facility */ /** {@link org.apache.commons.logging} logging facility */
static java.util.logging.Logger log = private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger java.util.logging.Logger.getLogger(SignatureBaseRSA.class.getName());
(SignatureBaseRSA.class.getName());
/** @inheritDoc */ /** @inheritDoc */
public abstract String engineGetURI(); public abstract String engineGetURI();
/** Field algorithm */ /** Field algorithm */
private java.security.Signature _signatureAlgorithm = null; private java.security.Signature signatureAlgorithm = null;
/** /**
* Constructor SignatureRSA * Constructor SignatureRSA
@ -59,17 +56,17 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi {
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
public SignatureBaseRSA() throws XMLSignatureException { public SignatureBaseRSA() throws XMLSignatureException {
String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); 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); log.log(java.util.logging.Level.FINE, "Created SignatureRSA using " + algorithmID);
String provider=JCEMapper.getProviderId(); }
String provider = JCEMapper.getProviderId();
try { try {
if (provider==null) { if (provider == null) {
this._signatureAlgorithm = Signature.getInstance(algorithmID); this.signatureAlgorithm = Signature.getInstance(algorithmID);
} else { } else {
this._signatureAlgorithm = Signature.getInstance(algorithmID,provider); this.signatureAlgorithm = Signature.getInstance(algorithmID,provider);
} }
} catch (java.security.NoSuchAlgorithmException ex) { } catch (java.security.NoSuchAlgorithmException ex) {
Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
@ -85,20 +82,17 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi {
/** @inheritDoc */ /** @inheritDoc */
protected void engineSetParameter(AlgorithmParameterSpec params) protected void engineSetParameter(AlgorithmParameterSpec params)
throws XMLSignatureException { throws XMLSignatureException {
try { try {
this._signatureAlgorithm.setParameter(params); this.signatureAlgorithm.setParameter(params);
} catch (InvalidAlgorithmParameterException ex) { } catch (InvalidAlgorithmParameterException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
} }
/** @inheritDoc */ /** @inheritDoc */
protected boolean engineVerify(byte[] signature) protected boolean engineVerify(byte[] signature) throws XMLSignatureException {
throws XMLSignatureException {
try { try {
return this._signatureAlgorithm.verify(signature); return this.signatureAlgorithm.verify(signature);
} catch (SignatureException ex) { } catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -106,32 +100,29 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi {
/** @inheritDoc */ /** @inheritDoc */
protected void engineInitVerify(Key publicKey) throws XMLSignatureException { protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
if (!(publicKey instanceof PublicKey)) { if (!(publicKey instanceof PublicKey)) {
String supplied = publicKey.getClass().getName(); String supplied = publicKey.getClass().getName();
String needed = PublicKey.class.getName(); String needed = PublicKey.class.getName();
Object exArgs[] = { supplied, needed }; Object exArgs[] = { supplied, needed };
throw new XMLSignatureException throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
("algorithms.WrongKeyForThisOperation", exArgs);
} }
try { try {
this._signatureAlgorithm.initVerify((PublicKey) publicKey); this.signatureAlgorithm.initVerify((PublicKey) publicKey);
} catch (InvalidKeyException ex) { } catch (InvalidKeyException ex) {
// reinstantiate Signature object to work around bug in JDK // reinstantiate Signature object to work around bug in JDK
// see: http://bugs.sun.com/view_bug.do?bug_id=4953555 // see: http://bugs.sun.com/view_bug.do?bug_id=4953555
Signature sig = this._signatureAlgorithm; Signature sig = this.signatureAlgorithm;
try { try {
this._signatureAlgorithm = Signature.getInstance this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm());
(_signatureAlgorithm.getAlgorithm());
} catch (Exception e) { } catch (Exception e) {
// this shouldn't occur, but if it does, restore previous // this shouldn't occur, but if it does, restore previous
// Signature // Signature
if (log.isLoggable(java.util.logging.Level.FINE)) { if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e); log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e);
} }
this._signatureAlgorithm = sig; this.signatureAlgorithm = sig;
} }
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -140,7 +131,7 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi {
/** @inheritDoc */ /** @inheritDoc */
protected byte[] engineSign() throws XMLSignatureException { protected byte[] engineSign() throws XMLSignatureException {
try { try {
return this._signatureAlgorithm.sign(); return this.signatureAlgorithm.sign();
} catch (SignatureException ex) { } catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -149,19 +140,16 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi {
/** @inheritDoc */ /** @inheritDoc */
protected void engineInitSign(Key privateKey, SecureRandom secureRandom) protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
throws XMLSignatureException { throws XMLSignatureException {
if (!(privateKey instanceof PrivateKey)) { if (!(privateKey instanceof PrivateKey)) {
String supplied = privateKey.getClass().getName(); String supplied = privateKey.getClass().getName();
String needed = PrivateKey.class.getName(); String needed = PrivateKey.class.getName();
Object exArgs[] = { supplied, needed }; Object exArgs[] = { supplied, needed };
throw new XMLSignatureException throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
("algorithms.WrongKeyForThisOperation", exArgs);
} }
try { try {
this._signatureAlgorithm.initSign this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
((PrivateKey) privateKey, secureRandom);
} catch (InvalidKeyException ex) { } catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -169,18 +157,16 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi {
/** @inheritDoc */ /** @inheritDoc */
protected void engineInitSign(Key privateKey) throws XMLSignatureException { protected void engineInitSign(Key privateKey) throws XMLSignatureException {
if (!(privateKey instanceof PrivateKey)) { if (!(privateKey instanceof PrivateKey)) {
String supplied = privateKey.getClass().getName(); String supplied = privateKey.getClass().getName();
String needed = PrivateKey.class.getName(); String needed = PrivateKey.class.getName();
Object exArgs[] = { supplied, needed }; Object exArgs[] = { supplied, needed };
throw new XMLSignatureException throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
("algorithms.WrongKeyForThisOperation", exArgs);
} }
try { try {
this._signatureAlgorithm.initSign((PrivateKey) privateKey); this.signatureAlgorithm.initSign((PrivateKey) privateKey);
} catch (InvalidKeyException ex) { } catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -189,7 +175,7 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi {
/** @inheritDoc */ /** @inheritDoc */
protected void engineUpdate(byte[] input) throws XMLSignatureException { protected void engineUpdate(byte[] input) throws XMLSignatureException {
try { try {
this._signatureAlgorithm.update(input); this.signatureAlgorithm.update(input);
} catch (SignatureException ex) { } catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -198,17 +184,16 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi {
/** @inheritDoc */ /** @inheritDoc */
protected void engineUpdate(byte input) throws XMLSignatureException { protected void engineUpdate(byte input) throws XMLSignatureException {
try { try {
this._signatureAlgorithm.update(input); this.signatureAlgorithm.update(input);
} catch (SignatureException ex) { } catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
} }
/** @inheritDoc */ /** @inheritDoc */
protected void engineUpdate(byte buf[], int offset, int len) protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException {
throws XMLSignatureException {
try { try {
this._signatureAlgorithm.update(buf, offset, len); this.signatureAlgorithm.update(buf, offset, len);
} catch (SignatureException ex) { } catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -216,34 +201,29 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi {
/** @inheritDoc */ /** @inheritDoc */
protected String engineGetJCEAlgorithmString() { protected String engineGetJCEAlgorithmString() {
return this._signatureAlgorithm.getAlgorithm(); return this.signatureAlgorithm.getAlgorithm();
} }
/** @inheritDoc */ /** @inheritDoc */
protected String engineGetJCEProviderName() { protected String engineGetJCEProviderName() {
return this._signatureAlgorithm.getProvider().getName(); return this.signatureAlgorithm.getProvider().getName();
} }
/** @inheritDoc */ /** @inheritDoc */
protected void engineSetHMACOutputLength(int HMACOutputLength) protected void engineSetHMACOutputLength(int HMACOutputLength)
throws XMLSignatureException { throws XMLSignatureException {
throw new XMLSignatureException throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC");
("algorithms.HMACOutputLengthOnlyForHMAC");
} }
/** @inheritDoc */ /** @inheritDoc */
protected void engineInitSign( protected void engineInitSign(
Key signingKey, AlgorithmParameterSpec algorithmParameterSpec) Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
throws XMLSignatureException { ) throws XMLSignatureException {
throw new XMLSignatureException( throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnRSA");
"algorithms.CannotUseAlgorithmParameterSpecOnRSA");
} }
/** /**
* Class SignatureRSASHA1 * Class SignatureRSASHA1
*
* @author $Author: mullan $
* @version $Revision: 1.5 $
*/ */
public static class SignatureRSASHA1 extends SignatureBaseRSA { public static class SignatureRSASHA1 extends SignatureBaseRSA {
@ -264,9 +244,6 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi {
/** /**
* Class SignatureRSASHA256 * Class SignatureRSASHA256
*
* @author $Author: mullan $
* @version $Revision: 1.5 $
*/ */
public static class SignatureRSASHA256 extends SignatureBaseRSA { public static class SignatureRSASHA256 extends SignatureBaseRSA {
@ -287,9 +264,6 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi {
/** /**
* Class SignatureRSASHA384 * Class SignatureRSASHA384
*
* @author $Author: mullan $
* @version $Revision: 1.5 $
*/ */
public static class SignatureRSASHA384 extends SignatureBaseRSA { public static class SignatureRSASHA384 extends SignatureBaseRSA {
@ -310,9 +284,6 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi {
/** /**
* Class SignatureRSASHA512 * Class SignatureRSASHA512
*
* @author $Author: mullan $
* @version $Revision: 1.5 $
*/ */
public static class SignatureRSASHA512 extends SignatureBaseRSA { public static class SignatureRSASHA512 extends SignatureBaseRSA {
@ -333,9 +304,6 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi {
/** /**
* Class SignatureRSARIPEMD160 * Class SignatureRSARIPEMD160
*
* @author $Author: mullan $
* @version $Revision: 1.5 $
*/ */
public static class SignatureRSARIPEMD160 extends SignatureBaseRSA { public static class SignatureRSARIPEMD160 extends SignatureBaseRSA {
@ -356,9 +324,6 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi {
/** /**
* Class SignatureRSAMD5 * Class SignatureRSAMD5
*
* @author $Author: mullan $
* @version $Revision: 1.5 $
*/ */
public static class SignatureRSAMD5 extends SignatureBaseRSA { public static class SignatureRSAMD5 extends SignatureBaseRSA {

View File

@ -2,21 +2,23 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.algorithms.implementations; 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.Base64;
import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.Constants;
/**
*
* @author $Author: mullan $
*/
public class SignatureDSA extends SignatureAlgorithmSpi { public class SignatureDSA extends SignatureAlgorithmSpi {
/** {@link java.util.logging} logging facility */ /** {@link org.apache.commons.logging} logging facility */
static java.util.logging.Logger log = private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(SignatureDSA.class.getName()); java.util.logging.Logger.getLogger(SignatureDSA.class.getName());
/** Field _URI */ /** Field URI */
public static final String _URI = Constants.SignatureSpecNS + "dsa-sha1"; public static final String URI = Constants.SignatureSpecNS + "dsa-sha1";
/** Field algorithm */ /** Field algorithm */
private java.security.Signature _signatureAlgorithm = null; private java.security.Signature signatureAlgorithm = null;
/** /**
* Method engineGetURI * Method engineGetURI
@ -59,7 +57,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
* @inheritDoc * @inheritDoc
*/ */
protected String engineGetURI() { protected String engineGetURI() {
return SignatureDSA._URI; return SignatureDSA.URI;
} }
/** /**
@ -68,17 +66,17 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
public SignatureDSA() throws XMLSignatureException { public SignatureDSA() throws XMLSignatureException {
String algorithmID = JCEMapper.translateURItoJCEID(SignatureDSA.URI);
String algorithmID = JCEMapper.translateURItoJCEID(SignatureDSA._URI); if (log.isLoggable(java.util.logging.Level.FINE)) {
if (log.isLoggable(java.util.logging.Level.FINE))
log.log(java.util.logging.Level.FINE, "Created SignatureDSA using " + algorithmID); log.log(java.util.logging.Level.FINE, "Created SignatureDSA using " + algorithmID);
}
String provider = JCEMapper.getProviderId(); String provider = JCEMapper.getProviderId();
try { try {
if (provider == null) { if (provider == null) {
this._signatureAlgorithm = Signature.getInstance(algorithmID); this.signatureAlgorithm = Signature.getInstance(algorithmID);
} else { } else {
this._signatureAlgorithm = this.signatureAlgorithm =
Signature.getInstance(algorithmID, provider); Signature.getInstance(algorithmID, provider);
} }
} catch (java.security.NoSuchAlgorithmException ex) { } catch (java.security.NoSuchAlgorithmException ex) {
@ -95,9 +93,8 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
*/ */
protected void engineSetParameter(AlgorithmParameterSpec params) protected void engineSetParameter(AlgorithmParameterSpec params)
throws XMLSignatureException { throws XMLSignatureException {
try { try {
this._signatureAlgorithm.setParameter(params); this.signatureAlgorithm.setParameter(params);
} catch (InvalidAlgorithmParameterException ex) { } catch (InvalidAlgorithmParameterException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -108,14 +105,14 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
*/ */
protected boolean engineVerify(byte[] signature) protected boolean engineVerify(byte[] signature)
throws XMLSignatureException { throws XMLSignatureException {
try { 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)); log.log(java.util.logging.Level.FINE, "Called DSA.verify() on " + Base64.encode(signature));
}
byte[] jcebytes = SignatureDSA.convertXMLDSIGtoASN1(signature); byte[] jcebytes = SignatureDSA.convertXMLDSIGtoASN1(signature);
return this._signatureAlgorithm.verify(jcebytes); return this.signatureAlgorithm.verify(jcebytes);
} catch (SignatureException ex) { } catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} catch (IOException ex) { } catch (IOException ex) {
@ -127,32 +124,29 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
* @inheritDoc * @inheritDoc
*/ */
protected void engineInitVerify(Key publicKey) throws XMLSignatureException { protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
if (!(publicKey instanceof PublicKey)) { if (!(publicKey instanceof PublicKey)) {
String supplied = publicKey.getClass().getName(); String supplied = publicKey.getClass().getName();
String needed = PublicKey.class.getName(); String needed = PublicKey.class.getName();
Object exArgs[] = { supplied, needed }; Object exArgs[] = { supplied, needed };
throw new XMLSignatureException throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
("algorithms.WrongKeyForThisOperation", exArgs);
} }
try { try {
this._signatureAlgorithm.initVerify((PublicKey) publicKey); this.signatureAlgorithm.initVerify((PublicKey) publicKey);
} catch (InvalidKeyException ex) { } catch (InvalidKeyException ex) {
// reinstantiate Signature object to work around bug in JDK // reinstantiate Signature object to work around bug in JDK
// see: http://bugs.sun.com/view_bug.do?bug_id=4953555 // see: http://bugs.sun.com/view_bug.do?bug_id=4953555
Signature sig = this._signatureAlgorithm; Signature sig = this.signatureAlgorithm;
try { try {
this._signatureAlgorithm = Signature.getInstance this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm());
(_signatureAlgorithm.getAlgorithm());
} catch (Exception e) { } catch (Exception e) {
// this shouldn't occur, but if it does, restore previous // this shouldn't occur, but if it does, restore previous
// Signature // Signature
if (log.isLoggable(java.util.logging.Level.FINE)) { if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e); log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e);
} }
this._signatureAlgorithm = sig; this.signatureAlgorithm = sig;
} }
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -162,9 +156,8 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
* @inheritDoc * @inheritDoc
*/ */
protected byte[] engineSign() throws XMLSignatureException { protected byte[] engineSign() throws XMLSignatureException {
try { try {
byte jcebytes[] = this._signatureAlgorithm.sign(); byte jcebytes[] = this.signatureAlgorithm.sign();
return SignatureDSA.convertASN1toXMLDSIG(jcebytes); return SignatureDSA.convertASN1toXMLDSIG(jcebytes);
} catch (IOException ex) { } catch (IOException ex) {
@ -179,19 +172,16 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
*/ */
protected void engineInitSign(Key privateKey, SecureRandom secureRandom) protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
throws XMLSignatureException { throws XMLSignatureException {
if (!(privateKey instanceof PrivateKey)) { if (!(privateKey instanceof PrivateKey)) {
String supplied = privateKey.getClass().getName(); String supplied = privateKey.getClass().getName();
String needed = PrivateKey.class.getName(); String needed = PrivateKey.class.getName();
Object exArgs[] = { supplied, needed }; Object exArgs[] = { supplied, needed };
throw new XMLSignatureException throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
("algorithms.WrongKeyForThisOperation", exArgs);
} }
try { try {
this._signatureAlgorithm.initSign((PrivateKey) privateKey, this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
secureRandom);
} catch (InvalidKeyException ex) { } catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -201,18 +191,16 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
* @inheritDoc * @inheritDoc
*/ */
protected void engineInitSign(Key privateKey) throws XMLSignatureException { protected void engineInitSign(Key privateKey) throws XMLSignatureException {
if (!(privateKey instanceof PrivateKey)) { if (!(privateKey instanceof PrivateKey)) {
String supplied = privateKey.getClass().getName(); String supplied = privateKey.getClass().getName();
String needed = PrivateKey.class.getName(); String needed = PrivateKey.class.getName();
Object exArgs[] = { supplied, needed }; Object exArgs[] = { supplied, needed };
throw new XMLSignatureException throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
("algorithms.WrongKeyForThisOperation", exArgs);
} }
try { try {
this._signatureAlgorithm.initSign((PrivateKey) privateKey); this.signatureAlgorithm.initSign((PrivateKey) privateKey);
} catch (InvalidKeyException ex) { } catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -223,7 +211,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
*/ */
protected void engineUpdate(byte[] input) throws XMLSignatureException { protected void engineUpdate(byte[] input) throws XMLSignatureException {
try { try {
this._signatureAlgorithm.update(input); this.signatureAlgorithm.update(input);
} catch (SignatureException ex) { } catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -234,7 +222,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
*/ */
protected void engineUpdate(byte input) throws XMLSignatureException { protected void engineUpdate(byte input) throws XMLSignatureException {
try { try {
this._signatureAlgorithm.update(input); this.signatureAlgorithm.update(input);
} catch (SignatureException ex) { } catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -243,10 +231,9 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
/** /**
* @inheritDoc * @inheritDoc
*/ */
protected void engineUpdate(byte buf[], int offset, int len) protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException {
throws XMLSignatureException {
try { try {
this._signatureAlgorithm.update(buf, offset, len); this.signatureAlgorithm.update(buf, offset, len);
} catch (SignatureException ex) { } catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -258,7 +245,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
* @inheritDoc * @inheritDoc
*/ */
protected String engineGetJCEAlgorithmString() { protected String engineGetJCEAlgorithmString() {
return this._signatureAlgorithm.getAlgorithm(); return this.signatureAlgorithm.getAlgorithm();
} }
/** /**
@ -267,7 +254,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
* @inheritDoc * @inheritDoc
*/ */
protected String engineGetJCEProviderName() { protected String engineGetJCEProviderName() {
return this._signatureAlgorithm.getProvider().getName(); return this.signatureAlgorithm.getProvider().getName();
} }
/** /**
@ -282,8 +269,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
* @throws IOException * @throws IOException
* @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A> * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
*/ */
private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) throws IOException {
throws IOException {
byte rLength = asn1Bytes[3]; byte rLength = asn1Bytes[3];
int i; int i;
@ -303,8 +289,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
} }
byte xmldsigBytes[] = new byte[40]; byte xmldsigBytes[] = new byte[40];
System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 20 - i, System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 20 - i, i);
i);
System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes, System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes,
40 - j, j); 40 - j, j);
@ -323,8 +308,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
* @throws IOException * @throws IOException
* @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A> * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
*/ */
private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException {
throws IOException {
if (xmldsigBytes.length != 40) { if (xmldsigBytes.length != 40) {
throw new IOException("Invalid XMLDSIG format of DSA signature"); throw new IOException("Invalid XMLDSIG format of DSA signature");
@ -373,10 +357,8 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
* @param HMACOutputLength * @param HMACOutputLength
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
protected void engineSetHMACOutputLength(int HMACOutputLength) protected void engineSetHMACOutputLength(int HMACOutputLength) throws XMLSignatureException {
throws XMLSignatureException { throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC");
throw new XMLSignatureException(
"algorithms.HMACOutputLengthOnlyForHMAC");
} }
/** /**
@ -387,9 +369,8 @@ public class SignatureDSA extends SignatureAlgorithmSpi {
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
protected void engineInitSign( protected void engineInitSign(
Key signingKey, AlgorithmParameterSpec algorithmParameterSpec) Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
throws XMLSignatureException { ) throws XMLSignatureException {
throw new XMLSignatureException( throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnDSA");
"algorithms.CannotUseAlgorithmParameterSpecOnDSA");
} }
} }

View File

@ -2,26 +2,26 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.algorithms.implementations; package com.sun.org.apache.xml.internal.security.algorithms.implementations;
import java.io.IOException; import java.io.IOException;
import java.security.InvalidAlgorithmParameterException; import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException; import java.security.InvalidKeyException;
@ -40,22 +40,22 @@ 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.signature.XMLSignatureException;
import com.sun.org.apache.xml.internal.security.utils.Base64; 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 { public abstract class SignatureECDSA extends SignatureAlgorithmSpi {
/** {@link java.util.logging} logging facility */ /** {@link org.apache.commons.logging} logging facility */
static java.util.logging.Logger log = private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(SignatureECDSA.class.getName()); java.util.logging.Logger.getLogger(SignatureECDSA.class.getName());
/** @inheritDoc */ /** @inheritDoc */
public abstract String engineGetURI(); public abstract String engineGetURI();
/** Field algorithm */ /** Field algorithm */
private java.security.Signature _signatureAlgorithm = null; private java.security.Signature signatureAlgorithm = null;
/** /**
* Converts an ASN.1 ECDSA value to a XML Signature ECDSA Value. * Converts an ASN.1 ECDSA value to a XML Signature ECDSA Value.
@ -70,31 +70,44 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi {
* @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A> * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
* @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A> * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
*/ */
private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) public static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) throws IOException {
throws IOException {
byte rLength = asn1Bytes[3]; 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");
}
byte rLength = asn1Bytes[offset + 1];
int i; int i;
for (i = rLength; (i > 0) && (asn1Bytes[(4 + rLength) - i] == 0); i--); for (i = rLength; (i > 0) && (asn1Bytes[(offset + 2 + rLength) - i] == 0); i--);
byte sLength = asn1Bytes[5 + rLength]; byte sLength = asn1Bytes[offset + 2 + rLength + 1];
int j; int j;
for (j = sLength; for (j = sLength;
(j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--); (j > 0) && (asn1Bytes[(offset + 2 + rLength + 2 + sLength) - j] == 0); j--);
if ((asn1Bytes[0] != 48) || (asn1Bytes[1] != asn1Bytes.length - 2) int rawLen = Math.max(i, j);
|| (asn1Bytes[2] != 2) || (i > 24)
|| (asn1Bytes[4 + rLength] != 2) || (j > 24)) { 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"); throw new IOException("Invalid ASN.1 format of ECDSA signature");
} }
byte xmldsigBytes[] = new byte[48]; byte xmldsigBytes[] = new byte[2*rawLen];
System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 24 - i, System.arraycopy(asn1Bytes, (offset + 2 + rLength) - i, xmldsigBytes, rawLen - i, i);
i); System.arraycopy(asn1Bytes, (offset + 2 + rLength + 2 + sLength) - j, xmldsigBytes,
System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes, 2*rawLen - j, j);
48 - j, j);
return xmldsigBytes; return xmldsigBytes;
} }
@ -112,46 +125,57 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi {
* @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A> * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
* @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A> * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
*/ */
private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) public static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException {
throws IOException {
if (xmldsigBytes.length != 48) { int rawLen = xmldsigBytes.length/2;
throw new IOException("Invalid XMLDSIG format of ECDSA signature");
}
int i; int i;
for (i = 24; (i > 0) && (xmldsigBytes[24 - i] == 0); i--); for (i = rawLen; (i > 0) && (xmldsigBytes[rawLen - i] == 0); i--);
int j = i; int j = i;
if (xmldsigBytes[24 - i] < 0) { if (xmldsigBytes[rawLen - i] < 0) {
j += 1; j += 1;
} }
int k; int k;
for (k = 24; (k > 0) && (xmldsigBytes[48 - k] == 0); k--); for (k = rawLen; (k > 0) && (xmldsigBytes[2*rawLen - k] == 0); k--);
int l = k; int l = k;
if (xmldsigBytes[48 - k] < 0) { if (xmldsigBytes[2*rawLen - k] < 0) {
l += 1; l += 1;
} }
byte asn1Bytes[] = new byte[6 + j + l]; 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[0] = 48;
asn1Bytes[1] = (byte) (4 + j + l); asn1Bytes[offset++] = (byte) len;
asn1Bytes[2] = 2; asn1Bytes[offset++] = 2;
asn1Bytes[3] = (byte) j; asn1Bytes[offset++] = (byte) j;
System.arraycopy(xmldsigBytes, 24 - i, asn1Bytes, (4 + j) - i, i); System.arraycopy(xmldsigBytes, rawLen - i, asn1Bytes, (offset + j) - i, i);
asn1Bytes[4 + j] = 2; offset += j;
asn1Bytes[5 + j] = (byte) l;
System.arraycopy(xmldsigBytes, 48 - k, asn1Bytes, (6 + j + l) - k, k); asn1Bytes[offset++] = 2;
asn1Bytes[offset++] = (byte) l;
System.arraycopy(xmldsigBytes, 2*rawLen - k, asn1Bytes, (offset + l) - k, k);
return asn1Bytes; return asn1Bytes;
} }
@ -165,23 +189,22 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi {
String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); 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 SignatureECDSA using " + algorithmID); log.log(java.util.logging.Level.FINE, "Created SignatureECDSA using " + algorithmID);
String provider=JCEMapper.getProviderId(); }
String provider = JCEMapper.getProviderId();
try { try {
if (provider==null) { if (provider == null) {
this._signatureAlgorithm = Signature.getInstance(algorithmID); this.signatureAlgorithm = Signature.getInstance(algorithmID);
} else { } else {
this._signatureAlgorithm = Signature.getInstance(algorithmID,provider); this.signatureAlgorithm = Signature.getInstance(algorithmID,provider);
} }
} catch (java.security.NoSuchAlgorithmException ex) { } catch (java.security.NoSuchAlgorithmException ex) {
Object[] exArgs = { algorithmID, Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
ex.getLocalizedMessage() };
throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
} catch (NoSuchProviderException ex) { } catch (NoSuchProviderException ex) {
Object[] exArgs = { algorithmID, Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
ex.getLocalizedMessage() };
throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
} }
@ -190,25 +213,23 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi {
/** @inheritDoc */ /** @inheritDoc */
protected void engineSetParameter(AlgorithmParameterSpec params) protected void engineSetParameter(AlgorithmParameterSpec params)
throws XMLSignatureException { throws XMLSignatureException {
try { try {
this._signatureAlgorithm.setParameter(params); this.signatureAlgorithm.setParameter(params);
} catch (InvalidAlgorithmParameterException ex) { } catch (InvalidAlgorithmParameterException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
} }
/** @inheritDoc */ /** @inheritDoc */
protected boolean engineVerify(byte[] signature) protected boolean engineVerify(byte[] signature) throws XMLSignatureException {
throws XMLSignatureException {
try { try {
byte[] jcebytes = SignatureECDSA.convertXMLDSIGtoASN1(signature); byte[] jcebytes = SignatureECDSA.convertXMLDSIGtoASN1(signature);
if (log.isLoggable(java.util.logging.Level.FINE)) if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Called ECDSA.verify() on " + Base64.encode(signature)); log.log(java.util.logging.Level.FINE, "Called ECDSA.verify() on " + Base64.encode(signature));
}
return this._signatureAlgorithm.verify(jcebytes); return this.signatureAlgorithm.verify(jcebytes);
} catch (SignatureException ex) { } catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} catch (IOException ex) { } catch (IOException ex) {
@ -224,26 +245,24 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi {
String needed = PublicKey.class.getName(); String needed = PublicKey.class.getName();
Object exArgs[] = { supplied, needed }; Object exArgs[] = { supplied, needed };
throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
exArgs);
} }
try { try {
this._signatureAlgorithm.initVerify((PublicKey) publicKey); this.signatureAlgorithm.initVerify((PublicKey) publicKey);
} catch (InvalidKeyException ex) { } catch (InvalidKeyException ex) {
// reinstantiate Signature object to work around bug in JDK // reinstantiate Signature object to work around bug in JDK
// see: http://bugs.sun.com/view_bug.do?bug_id=4953555 // see: http://bugs.sun.com/view_bug.do?bug_id=4953555
Signature sig = this._signatureAlgorithm; Signature sig = this.signatureAlgorithm;
try { try {
this._signatureAlgorithm = Signature.getInstance this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm());
(_signatureAlgorithm.getAlgorithm());
} catch (Exception e) { } catch (Exception e) {
// this shouldn't occur, but if it does, restore previous // this shouldn't occur, but if it does, restore previous
// Signature // Signature
if (log.isLoggable(java.util.logging.Level.FINE)) { if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e); log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e);
} }
this._signatureAlgorithm = sig; this.signatureAlgorithm = sig;
} }
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -251,9 +270,8 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi {
/** @inheritDoc */ /** @inheritDoc */
protected byte[] engineSign() throws XMLSignatureException { protected byte[] engineSign() throws XMLSignatureException {
try { try {
byte jcebytes[] = this._signatureAlgorithm.sign(); byte jcebytes[] = this.signatureAlgorithm.sign();
return SignatureECDSA.convertASN1toXMLDSIG(jcebytes); return SignatureECDSA.convertASN1toXMLDSIG(jcebytes);
} catch (SignatureException ex) { } catch (SignatureException ex) {
@ -266,19 +284,16 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi {
/** @inheritDoc */ /** @inheritDoc */
protected void engineInitSign(Key privateKey, SecureRandom secureRandom) protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
throws XMLSignatureException { throws XMLSignatureException {
if (!(privateKey instanceof PrivateKey)) { if (!(privateKey instanceof PrivateKey)) {
String supplied = privateKey.getClass().getName(); String supplied = privateKey.getClass().getName();
String needed = PrivateKey.class.getName(); String needed = PrivateKey.class.getName();
Object exArgs[] = { supplied, needed }; Object exArgs[] = { supplied, needed };
throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
exArgs);
} }
try { try {
this._signatureAlgorithm.initSign((PrivateKey) privateKey, this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
secureRandom);
} catch (InvalidKeyException ex) { } catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -286,18 +301,16 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi {
/** @inheritDoc */ /** @inheritDoc */
protected void engineInitSign(Key privateKey) throws XMLSignatureException { protected void engineInitSign(Key privateKey) throws XMLSignatureException {
if (!(privateKey instanceof PrivateKey)) { if (!(privateKey instanceof PrivateKey)) {
String supplied = privateKey.getClass().getName(); String supplied = privateKey.getClass().getName();
String needed = PrivateKey.class.getName(); String needed = PrivateKey.class.getName();
Object exArgs[] = { supplied, needed }; Object exArgs[] = { supplied, needed };
throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
exArgs);
} }
try { try {
this._signatureAlgorithm.initSign((PrivateKey) privateKey); this.signatureAlgorithm.initSign((PrivateKey) privateKey);
} catch (InvalidKeyException ex) { } catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -305,9 +318,8 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi {
/** @inheritDoc */ /** @inheritDoc */
protected void engineUpdate(byte[] input) throws XMLSignatureException { protected void engineUpdate(byte[] input) throws XMLSignatureException {
try { try {
this._signatureAlgorithm.update(input); this.signatureAlgorithm.update(input);
} catch (SignatureException ex) { } catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -315,20 +327,17 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi {
/** @inheritDoc */ /** @inheritDoc */
protected void engineUpdate(byte input) throws XMLSignatureException { protected void engineUpdate(byte input) throws XMLSignatureException {
try { try {
this._signatureAlgorithm.update(input); this.signatureAlgorithm.update(input);
} catch (SignatureException ex) { } catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
} }
/** @inheritDoc */ /** @inheritDoc */
protected void engineUpdate(byte buf[], int offset, int len) protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException {
throws XMLSignatureException {
try { try {
this._signatureAlgorithm.update(buf, offset, len); this.signatureAlgorithm.update(buf, offset, len);
} catch (SignatureException ex) { } catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex); throw new XMLSignatureException("empty", ex);
} }
@ -336,12 +345,12 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi {
/** @inheritDoc */ /** @inheritDoc */
protected String engineGetJCEAlgorithmString() { protected String engineGetJCEAlgorithmString() {
return this._signatureAlgorithm.getAlgorithm(); return this.signatureAlgorithm.getAlgorithm();
} }
/** @inheritDoc */ /** @inheritDoc */
protected String engineGetJCEProviderName() { protected String engineGetJCEProviderName() {
return this._signatureAlgorithm.getProvider().getName(); return this.signatureAlgorithm.getProvider().getName();
} }
/** @inheritDoc */ /** @inheritDoc */
@ -352,20 +361,17 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi {
/** @inheritDoc */ /** @inheritDoc */
protected void engineInitSign( protected void engineInitSign(
Key signingKey, AlgorithmParameterSpec algorithmParameterSpec) Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
throws XMLSignatureException { ) throws XMLSignatureException {
throw new XMLSignatureException( throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnRSA");
"algorithms.CannotUseAlgorithmParameterSpecOnRSA");
} }
/** /**
* Class SignatureRSASHA1 * Class SignatureRSASHA1
* *
* @author $Author: mullan $ * @author $Author: marcx $
* @version $Revision: 1.2 $
*/ */
public static class SignatureECDSASHA1 extends SignatureECDSA { public static class SignatureECDSASHA1 extends SignatureECDSA {
/** /**
* Constructor SignatureRSASHA1 * Constructor SignatureRSASHA1
* *
@ -381,4 +387,70 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi {
} }
} }
/**
* Class SignatureRSASHA256
*
* @author Alex Dupre
*/
public static class SignatureECDSASHA256 extends SignatureECDSA {
/**
* Constructor SignatureRSASHA256
*
* @throws XMLSignatureException
*/
public SignatureECDSASHA256() throws XMLSignatureException {
super();
}
/** @inheritDoc */
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256;
}
}
/**
* Class SignatureRSASHA384
*
* @author Alex Dupre
*/
public static class SignatureECDSASHA384 extends SignatureECDSA {
/**
* Constructor SignatureRSASHA384
*
* @throws XMLSignatureException
*/
public SignatureECDSASHA384() throws XMLSignatureException {
super();
}
/** @inheritDoc */
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384;
}
}
/**
* 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;
}
}
} }

View File

@ -2,29 +2,28 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.c14n; package com.sun.org.apache.xml.internal.security.c14n;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
/** /**
* Class CanonicalizationException * Class CanonicalizationException
* *
@ -48,41 +47,42 @@ public class CanonicalizationException extends XMLSecurityException {
/** /**
* Constructor CanonicalizationException * Constructor CanonicalizationException
* *
* @param _msgID * @param msgID
*/ */
public CanonicalizationException(String _msgID) { public CanonicalizationException(String msgID) {
super(_msgID); super(msgID);
} }
/** /**
* Constructor CanonicalizationException * Constructor CanonicalizationException
* *
* @param _msgID * @param msgID
* @param exArgs * @param exArgs
*/ */
public CanonicalizationException(String _msgID, Object exArgs[]) { public CanonicalizationException(String msgID, Object exArgs[]) {
super(_msgID, exArgs); super(msgID, exArgs);
} }
/** /**
* Constructor CanonicalizationException * Constructor CanonicalizationException
* *
* @param _msgID * @param msgID
* @param _originalException * @param originalException
*/ */
public CanonicalizationException(String _msgID, Exception _originalException) { public CanonicalizationException(String msgID, Exception originalException) {
super(_msgID, _originalException); super(msgID, originalException);
} }
/** /**
* Constructor CanonicalizationException * Constructor CanonicalizationException
* *
* @param _msgID * @param msgID
* @param exArgs * @param exArgs
* @param _originalException * @param originalException
*/ */
public CanonicalizationException(String _msgID, Object exArgs[], public CanonicalizationException(
Exception _originalException) { String msgID, Object exArgs[], Exception originalException
super(_msgID, exArgs, _originalException); ) {
super(msgID, exArgs, originalException);
} }
} }

View File

@ -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.Canonicalizer20010315ExclWithComments;
import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315OmitComments; 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.Canonicalizer20010315WithComments;
import com.sun.org.apache.xml.internal.security.c14n.implementations.CanonicalizerPhysical;
import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException; import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Node; import org.w3c.dom.Node;
@ -91,6 +92,11 @@ public class Canonicalizer {
*/ */
public static final String ALGO_ID_C14N11_WITH_COMMENTS = public static final String ALGO_ID_C14N11_WITH_COMMENTS =
ALGO_ID_C14N11_OMIT_COMMENTS + "#WithComments"; 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<String, Class<? extends CanonicalizerSpi>> canonicalizerHash = private static Map<String, Class<? extends CanonicalizerSpi>> canonicalizerHash =
new ConcurrentHashMap<String, Class<? extends CanonicalizerSpi>>(); new ConcurrentHashMap<String, Class<? extends CanonicalizerSpi>>();
@ -202,6 +208,10 @@ public class Canonicalizer {
Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS, Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS,
Canonicalizer11_WithComments.class Canonicalizer11_WithComments.class
); );
canonicalizerHash.put(
Canonicalizer.ALGO_ID_C14N_PHYSICAL,
CanonicalizerPhysical.class
);
} }
/** /**

View File

@ -2,26 +2,26 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.c14n; package com.sun.org.apache.xml.internal.security.c14n;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.Set; import java.util.Set;
@ -29,7 +29,6 @@ import java.util.Set;
import javax.xml.XMLConstants; import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Document; import org.w3c.dom.Document;
@ -37,72 +36,43 @@ import org.w3c.dom.Node;
import org.w3c.dom.NodeList; import org.w3c.dom.NodeList;
import org.xml.sax.InputSource; 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 * @author Christian Geuer-Pollmann
*/ */
public abstract class CanonicalizerSpi { public abstract class CanonicalizerSpi {
/** Reset the writer after a c14n */
protected boolean reset = false;
/** /**
* Method canonicalize * Method canonicalize
* *
*
* @param inputBytes * @param inputBytes
* @return the c14n bytes. * @return the c14n bytes.
* *
*
* @throws CanonicalizationException * @throws CanonicalizationException
* @throws java.io.IOException * @throws java.io.IOException
* @throws javax.xml.parsers.ParserConfigurationException * @throws javax.xml.parsers.ParserConfigurationException
* @throws org.xml.sax.SAXException * @throws org.xml.sax.SAXException
*
*/ */
public byte[] engineCanonicalize(byte[] inputBytes) public byte[] engineCanonicalize(byte[] inputBytes)
throws javax.xml.parsers.ParserConfigurationException, throws javax.xml.parsers.ParserConfigurationException, java.io.IOException,
java.io.IOException, org.xml.sax.SAXException, org.xml.sax.SAXException, CanonicalizationException {
CanonicalizationException {
java.io.ByteArrayInputStream bais = new ByteArrayInputStream(inputBytes); java.io.InputStream bais = new ByteArrayInputStream(inputBytes);
InputSource in = new InputSource(bais); InputSource in = new InputSource(bais);
DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
// needs to validate for ID attribute nomalization // needs to validate for ID attribute normalization
dfactory.setNamespaceAware(true); dfactory.setNamespaceAware(true);
DocumentBuilder db = dfactory.newDocumentBuilder(); DocumentBuilder db = dfactory.newDocumentBuilder();
/*
* 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.
*
*/
// ErrorHandler eh = new C14NErrorHandler();
// db.setErrorHandler(eh);
Document document = db.parse(in); Document document = db.parse(in);
byte result[] = this.engineCanonicalizeSubTree(document); return this.engineCanonicalizeSubTree(document);
return result;
} }
/** /**
@ -114,10 +84,9 @@ public abstract class CanonicalizerSpi {
*/ */
public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet) public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet)
throws CanonicalizationException { throws CanonicalizationException {
return this.engineCanonicalizeXPathNodeSet(
return this XMLUtils.convertNodelistToSet(xpathNodeSet)
.engineCanonicalizeXPathNodeSet(XMLUtils );
.convertNodelistToSet(xpathNodeSet));
} }
/** /**
@ -130,20 +99,20 @@ public abstract class CanonicalizerSpi {
*/ */
public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet, String inclusiveNamespaces) public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet, String inclusiveNamespaces)
throws CanonicalizationException { throws CanonicalizationException {
return this.engineCanonicalizeXPathNodeSet(
return this XMLUtils.convertNodelistToSet(xpathNodeSet), inclusiveNamespaces
.engineCanonicalizeXPathNodeSet(XMLUtils );
.convertNodelistToSet(xpathNodeSet), inclusiveNamespaces);
} }
//J- /**
/** Returns the URI of this engine. * Returns the URI of this engine.
* @return the URI * @return the URI
*/ */
public abstract String engineGetURI(); public abstract String engineGetURI();
/** Returns the URI if include comments /**
* @return true if include. * Returns true if comments are included
* @return true if comments are included
*/ */
public abstract boolean engineGetIncludeComments(); public abstract boolean engineGetIncludeComments();
@ -165,8 +134,9 @@ public abstract class CanonicalizerSpi {
* @return the c14n bytes * @return the c14n bytes
* @throws CanonicalizationException * @throws CanonicalizationException
*/ */
public abstract byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet, String inclusiveNamespaces) public abstract byte[] engineCanonicalizeXPathNodeSet(
throws CanonicalizationException; Set<Node> xpathNodeSet, String inclusiveNamespaces
) throws CanonicalizationException;
/** /**
* C14n a node tree. * C14n a node tree.
@ -190,13 +160,10 @@ public abstract class CanonicalizerSpi {
throws CanonicalizationException; throws CanonicalizationException;
/** /**
* Sets the writter where the cannocalization ends. ByteArrayOutputStream if * Sets the writer where the canonicalization ends. ByteArrayOutputStream if
* none is setted. * none is set.
* @param os * @param os
*/ */
public abstract void setWriter(OutputStream os); public abstract void setWriter(OutputStream os);
/** Reset the writter after a c14n */
protected boolean reset=false;
//J+
} }

View File

@ -2,33 +2,28 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.c14n; package com.sun.org.apache.xml.internal.security.c14n;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
/**
*
* @author Christian Geuer-Pollmann
*/
public class InvalidCanonicalizerException extends XMLSecurityException { public class InvalidCanonicalizerException extends XMLSecurityException {
/** /**
@ -47,42 +42,42 @@ public class InvalidCanonicalizerException extends XMLSecurityException {
/** /**
* Constructor InvalidCanonicalizerException * Constructor InvalidCanonicalizerException
* *
* @param _msgID * @param msgID
*/ */
public InvalidCanonicalizerException(String _msgID) { public InvalidCanonicalizerException(String msgID) {
super(_msgID); super(msgID);
} }
/** /**
* Constructor InvalidCanonicalizerException * Constructor InvalidCanonicalizerException
* *
* @param _msgID * @param msgID
* @param exArgs * @param exArgs
*/ */
public InvalidCanonicalizerException(String _msgID, Object exArgs[]) { public InvalidCanonicalizerException(String msgID, Object exArgs[]) {
super(_msgID, exArgs); super(msgID, exArgs);
} }
/** /**
* Constructor InvalidCanonicalizerException * Constructor InvalidCanonicalizerException
* *
* @param _msgID * @param msgID
* @param _originalException * @param originalException
*/ */
public InvalidCanonicalizerException(String _msgID, public InvalidCanonicalizerException(String msgID, Exception originalException) {
Exception _originalException) { super(msgID, originalException);
super(_msgID, _originalException);
} }
/** /**
* Constructor InvalidCanonicalizerException * Constructor InvalidCanonicalizerException
* *
* @param _msgID * @param msgID
* @param exArgs * @param exArgs
* @param _originalException * @param originalException
*/ */
public InvalidCanonicalizerException(String _msgID, Object exArgs[], public InvalidCanonicalizerException(
Exception _originalException) { String msgID, Object exArgs[], Exception originalException
super(_msgID, exArgs, _originalException); ) {
super(msgID, exArgs, originalException);
} }
} }

View File

@ -2,21 +2,23 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.c14n.helper; package com.sun.org.apache.xml.internal.security.c14n.helper;
@ -43,10 +45,10 @@ import java.util.Comparator;
*/ */
public class AttrCompare implements Comparator<Attr>, Serializable { public class AttrCompare implements Comparator<Attr>, Serializable {
private final static long serialVersionUID = -7113259629930576230L; private static final long serialVersionUID = -7113259629930576230L;
private final static int ATTR0_BEFORE_ATTR1 = -1; private static final int ATTR0_BEFORE_ATTR1 = -1;
private final static int ATTR1_BEFORE_ATTR0 = 1; private static final int ATTR1_BEFORE_ATTR0 = 1;
private final static String XMLNS=Constants.NamespaceSpecNS; private static final String XMLNS = Constants.NamespaceSpecNS;
/** /**
* Compares two attributes based on the C14n specification. * Compares two attributes based on the C14n specification.
@ -69,12 +71,11 @@ public class AttrCompare implements Comparator<Attr>, Serializable {
* *
*/ */
public int compare(Attr attr0, Attr attr1) { public int compare(Attr attr0, Attr attr1) {
String namespaceURI0 = attr0.getNamespaceURI(); String namespaceURI0 = attr0.getNamespaceURI();
String namespaceURI1 = attr1.getNamespaceURI(); String namespaceURI1 = attr1.getNamespaceURI();
boolean isNamespaceAttr0 = XMLNS==namespaceURI0; boolean isNamespaceAttr0 = XMLNS.equals(namespaceURI0);
boolean isNamespaceAttr1 = XMLNS==namespaceURI1; boolean isNamespaceAttr1 = XMLNS.equals(namespaceURI1);
if (isNamespaceAttr0) { if (isNamespaceAttr0) {
if (isNamespaceAttr1) { if (isNamespaceAttr1) {
@ -82,11 +83,11 @@ public class AttrCompare implements Comparator<Attr>, Serializable {
String localname0 = attr0.getLocalName(); String localname0 = attr0.getLocalName();
String localname1 = attr1.getLocalName(); String localname1 = attr1.getLocalName();
if (localname0.equals("xmlns")) { if ("xmlns".equals(localname0)) {
localname0 = ""; localname0 = "";
} }
if (localname1.equals("xmlns")) { if ("xmlns".equals(localname1)) {
localname1 = ""; localname1 = "";
} }
@ -94,9 +95,7 @@ public class AttrCompare implements Comparator<Attr>, Serializable {
} }
// attr0 is a namespace, attr1 is not // attr0 is a namespace, attr1 is not
return ATTR0_BEFORE_ATTR1; return ATTR0_BEFORE_ATTR1;
} } else if (isNamespaceAttr1) {
if (isNamespaceAttr1) {
// attr1 is a namespace, attr0 is not // attr1 is a namespace, attr0 is not
return ATTR1_BEFORE_ATTR0; return ATTR1_BEFORE_ATTR0;
} }
@ -109,9 +108,7 @@ public class AttrCompare implements Comparator<Attr>, Serializable {
return name0.compareTo(name1); return name0.compareTo(name1);
} }
return ATTR0_BEFORE_ATTR1; return ATTR0_BEFORE_ATTR1;
} } else if (namespaceURI1 == null) {
if (namespaceURI1 == null) {
return ATTR1_BEFORE_ATTR0; return ATTR1_BEFORE_ATTR0;
} }

View File

@ -2,33 +2,32 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.c14n.helper; package com.sun.org.apache.xml.internal.security.c14n.helper;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
import org.w3c.dom.Attr; import org.w3c.dom.Attr;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NamedNodeMap;
/** /**
* Temporary swapped static functions from the normalizer Section * Temporary swapped static functions from the normalizer Section
* *
@ -41,7 +40,6 @@ public class C14nHelper {
* *
*/ */
private C14nHelper() { private C14nHelper() {
// don't allow instantiation // don't allow instantiation
} }
@ -82,12 +80,11 @@ public class C14nHelper {
* @return true if the given namespace is absolute. * @return true if the given namespace is absolute.
*/ */
public static boolean namespaceIsAbsolute(String namespaceValue) { public static boolean namespaceIsAbsolute(String namespaceValue) {
// assume empty namespaces are absolute // assume empty namespaces are absolute
if (namespaceValue.length() == 0) { if (namespaceValue.length() == 0) {
return true; return true;
} }
return namespaceValue.indexOf(':')>0; return namespaceValue.indexOf(':') > 0;
} }
/** /**
@ -97,9 +94,7 @@ public class C14nHelper {
* @param attr * @param attr
* @throws CanonicalizationException * @throws CanonicalizationException
*/ */
public static void assertNotRelativeNS(Attr attr) public static void assertNotRelativeNS(Attr attr) throws CanonicalizationException {
throws CanonicalizationException {
if (attr == null) { if (attr == null) {
return; return;
} }
@ -108,15 +103,14 @@ public class C14nHelper {
boolean definesDefaultNS = nodeAttrName.equals("xmlns"); boolean definesDefaultNS = nodeAttrName.equals("xmlns");
boolean definesNonDefaultNS = nodeAttrName.startsWith("xmlns:"); boolean definesNonDefaultNS = nodeAttrName.startsWith("xmlns:");
if (definesDefaultNS || definesNonDefaultNS) { if ((definesDefaultNS || definesNonDefaultNS) && namespaceIsRelative(attr)) {
if (namespaceIsRelative(attr)) {
String parentName = attr.getOwnerElement().getTagName(); String parentName = attr.getOwnerElement().getTagName();
String attrValue = attr.getValue(); String attrValue = attr.getValue();
Object exArgs[] = { parentName, nodeAttrName, attrValue }; Object exArgs[] = { parentName, nodeAttrName, attrValue };
throw new CanonicalizationException( throw new CanonicalizationException(
"c14n.Canonicalizer.RelativeNamespace", exArgs); "c14n.Canonicalizer.RelativeNamespace", exArgs
} );
} }
} }
@ -129,13 +123,12 @@ public class C14nHelper {
*/ */
public static void checkTraversability(Document document) public static void checkTraversability(Document document)
throws CanonicalizationException { throws CanonicalizationException {
if (!document.isSupported("Traversal", "2.0")) { if (!document.isSupported("Traversal", "2.0")) {
Object exArgs[] = { Object exArgs[] = {document.getImplementation().getClass().getName() };
document.getImplementation().getClass().getName() };
throw new CanonicalizationException( throw new CanonicalizationException(
"c14n.Canonicalizer.TraversalNotSupported", exArgs); "c14n.Canonicalizer.TraversalNotSupported", exArgs
);
} }
} }
@ -149,7 +142,6 @@ public class C14nHelper {
*/ */
public static void checkForRelativeNamespace(Element ctxNode) public static void checkForRelativeNamespace(Element ctxNode)
throws CanonicalizationException { throws CanonicalizationException {
if (ctxNode != null) { if (ctxNode != null) {
NamedNodeMap attributes = ctxNode.getAttributes(); NamedNodeMap attributes = ctxNode.getAttributes();
@ -157,8 +149,7 @@ public class C14nHelper {
C14nHelper.assertNotRelativeNS((Attr) attributes.item(i)); C14nHelper.assertNotRelativeNS((Attr) attributes.item(i));
} }
} else { } else {
throw new CanonicalizationException( throw new CanonicalizationException("Called checkForRelativeNamespace() on null");
"Called checkForRelativeNamespace() on null");
} }
} }
} }

View File

@ -2,21 +2,23 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.c14n.implementations; package com.sun.org.apache.xml.internal.security.c14n.implementations;
@ -25,7 +27,6 @@ import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@ -34,7 +35,6 @@ import java.util.Set;
import java.util.SortedSet; import java.util.SortedSet;
import java.util.TreeSet; import java.util.TreeSet;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import org.w3c.dom.Attr; import org.w3c.dom.Attr;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
@ -42,8 +42,6 @@ import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import org.xml.sax.SAXException; 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.CanonicalizationException;
import com.sun.org.apache.xml.internal.security.c14n.helper.C14nHelper; import com.sun.org.apache.xml.internal.security.c14n.helper.C14nHelper;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; 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 Sean Mullan
* @author Raul Benito * @author Raul Benito
* @version $Revision: 1.2 $
*/ */
public abstract class Canonicalizer11 extends CanonicalizerBase { public abstract class Canonicalizer11 extends CanonicalizerBase {
boolean firstCall = true;
final SortedSet<Attr> result = new TreeSet<Attr>(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<Attr> result = new TreeSet<Attr>(COMPARE);
static class XmlAttrStack { private boolean firstCall = true;
int currentLevel = 0;
int lastlevel = 0; private static class XmlAttrStack {
XmlsStackElement cur;
static class XmlsStackElement { static class XmlsStackElement {
int level; int level;
boolean rendered = false; boolean rendered = false;
List<Attr> nodes = new ArrayList<Attr>(); List<Attr> nodes = new ArrayList<Attr>();
}; };
int currentLevel = 0;
int lastlevel = 0;
XmlsStackElement cur;
List<XmlsStackElement> levels = new ArrayList<XmlsStackElement>(); List<XmlsStackElement> levels = new ArrayList<XmlsStackElement>();
void push(int level) { void push(int level) {
currentLevel = level; currentLevel = level;
if (currentLevel == -1) if (currentLevel == -1) {
return; return;
}
cur = null; cur = null;
while (lastlevel >= currentLevel) { while (lastlevel >= currentLevel) {
levels.remove(levels.size() - 1); levels.remove(levels.size() - 1);
if (levels.size() == 0) { int newSize = levels.size();
if (newSize == 0) {
lastlevel = 0; lastlevel = 0;
return; return;
} }
lastlevel=(levels.get(levels.size()-1)).level; lastlevel = (levels.get(newSize - 1)).level;
} }
} }
void addXmlnsAttr(Attr n) { void addXmlnsAttr(Attr n) {
if (cur == null) { if (cur == null) {
cur = new XmlsStackElement(); cur = new XmlsStackElement();
@ -100,23 +104,25 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
} }
cur.nodes.add(n); cur.nodes.add(n);
} }
void getXmlnsAttr(Collection<Attr> col) { void getXmlnsAttr(Collection<Attr> col) {
int size = levels.size() - 1;
if (cur == null) { if (cur == null) {
cur = new XmlsStackElement(); cur = new XmlsStackElement();
cur.level = currentLevel; cur.level = currentLevel;
lastlevel = currentLevel; lastlevel = currentLevel;
levels.add(cur); levels.add(cur);
} }
int size = levels.size() - 2;
boolean parentRendered = false; boolean parentRendered = false;
XmlsStackElement e = null; XmlsStackElement e = null;
if (size == -1) { if (size == -1) {
parentRendered = true; parentRendered = true;
} else { } else {
e = levels.get(size); e = levels.get(size);
if (e.rendered && e.level+1 == currentLevel) if (e.rendered && e.level + 1 == currentLevel) {
parentRendered = true; parentRendered = true;
} }
}
if (parentRendered) { if (parentRendered) {
col.addAll(cur.nodes); col.addAll(cur.nodes);
cur.rendered = true; cur.rendered = true;
@ -126,7 +132,7 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
Map<String, Attr> loa = new HashMap<String, Attr>(); Map<String, Attr> loa = new HashMap<String, Attr>();
List<Attr> baseAttrs = new ArrayList<Attr>(); List<Attr> baseAttrs = new ArrayList<Attr>();
boolean successiveOmitted = true; boolean successiveOmitted = true;
for (;size>=0;size--) { for (; size >= 0; size--) {
e = levels.get(size); e = levels.get(size);
if (e.rendered) { if (e.rendered) {
successiveOmitted = false; successiveOmitted = false;
@ -134,16 +140,15 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
Iterator<Attr> it = e.nodes.iterator(); Iterator<Attr> it = e.nodes.iterator();
while (it.hasNext() && successiveOmitted) { while (it.hasNext() && successiveOmitted) {
Attr n = it.next(); Attr n = it.next();
if (n.getLocalName().equals("base")) { if (n.getLocalName().equals("base") && !e.rendered) {
if (!e.rendered) {
baseAttrs.add(n); baseAttrs.add(n);
} } else if (!loa.containsKey(n.getName())) {
} else if (!loa.containsKey(n.getName()))
loa.put(n.getName(), n); loa.put(n.getName(), n);
} }
} }
}
if (!baseAttrs.isEmpty()) { if (!baseAttrs.isEmpty()) {
Iterator<Attr> it = cur.nodes.iterator(); Iterator<Attr> it = col.iterator();
String base = null; String base = null;
Attr baseAttr = null; Attr baseAttr = null;
while (it.hasNext()) { while (it.hasNext()) {
@ -164,7 +169,9 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
try { try {
base = joinURI(n.getValue(), base); base = joinURI(n.getValue(), base);
} catch (URISyntaxException ue) { } 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()); col.addAll(loa.values());
} }
}; };
XmlAttrStack xmlattrStack = new XmlAttrStack();
private XmlAttrStack xmlattrStack = new XmlAttrStack();
/** /**
* Constructor Canonicalizer11 * Constructor Canonicalizer11
@ -189,194 +197,6 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
super(includeComments); super(includeComments);
} }
/**
* Returns the Attr[]s to be outputted for the given element.
* <br>
* 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<Attr> 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<Attr> 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.
* <br>
* 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<Attr> 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<Attr> 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. * Always throws a CanonicalizationException because this is inclusive c14n.
* *
@ -385,10 +205,10 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
* @return none it always fails * @return none it always fails
* @throws CanonicalizationException always * @throws CanonicalizationException always
*/ */
public byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet, public byte[] engineCanonicalizeXPathNodeSet(
String inclusiveNamespaces) throws CanonicalizationException { Set<Node> xpathNodeSet, String inclusiveNamespaces
throw new CanonicalizationException( ) throws CanonicalizationException {
"c14n.Canonicalizer.UnsupportedOperation"); throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
} }
/** /**
@ -399,17 +219,189 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
* @return none it always fails * @return none it always fails
* @throws CanonicalizationException * @throws CanonicalizationException
*/ */
public byte[] engineCanonicalizeSubTree(Node rootNode, public byte[] engineCanonicalizeSubTree(
String inclusiveNamespaces) throws CanonicalizationException { Node rootNode, String inclusiveNamespaces
throw new CanonicalizationException( ) throws CanonicalizationException {
"c14n.Canonicalizer.UnsupportedOperation"); throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
} }
void circumventBugIfNeeded(XMLSignatureInput input) /**
* Returns the Attr[]s to be output for the given element.
* <br>
* 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<Attr> 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<Attr> 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.
* <br>
* 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<Attr> 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<Attr> 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, throws CanonicalizationException, ParserConfigurationException,
IOException, SAXException { IOException, SAXException {
if (!input.isNeedsToBeExpanded()) if (!input.isNeedsToBeExpanded()) {
return; return;
}
Document doc = null; Document doc = null;
if (input.getSubNode() != null) { if (input.getSubNode() != null) {
doc = XMLUtils.getOwnerDocument(input.getSubNode()); doc = XMLUtils.getOwnerDocument(input.getSubNode());
@ -419,40 +411,47 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
XMLUtils.circumventBug2650(doc); XMLUtils.circumventBug2650(doc);
} }
void handleParent(Element e, NameSpaceSymbTable ns) { protected void handleParent(Element e, NameSpaceSymbTable ns) {
if (!e.hasAttributes()) { if (!e.hasAttributes() && e.getNamespaceURI() == null) {
return; return;
} }
xmlattrStack.push(-1); xmlattrStack.push(-1);
NamedNodeMap attrs = e.getAttributes(); NamedNodeMap attrs = e.getAttributes();
int attrsLength = attrs.getLength(); int attrsLength = attrs.getLength();
for (int i = 0; i < attrsLength; i++) { for (int i = 0; i < attrsLength; i++) {
Attr N = (Attr) attrs.item(i); Attr attribute = (Attr) attrs.item(i);
if (Constants.NamespaceSpecNS != N.getNamespaceURI()) { String NName = attribute.getLocalName();
// Not a namespace definition, ignore. String NValue = attribute.getNodeValue();
if (XML_LANG_URI == N.getNamespaceURI()) {
xmlattrStack.addXmlnsAttr(N);
}
continue;
}
String NName = N.getLocalName(); if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI())) {
String NValue = N.getNodeValue(); if (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
if (XML.equals(NName) ns.addMapping(NName, NValue, attribute);
&& Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
continue;
} }
ns.addMapping(NName,NValue,N); } else if (!"id".equals(NName) && 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);
} }
} }
private static String joinURI(String baseURI, String relativeURI) private static String joinURI(String baseURI, String relativeURI) throws URISyntaxException {
throws URISyntaxException {
String bscheme = null; String bscheme = null;
String bauthority = null; String bauthority = null;
String bpath = ""; String bpath = "";
String bquery = null; String bquery = null;
String bfragment = null; // Is this correct?
// pre-parse the baseURI // pre-parse the baseURI
if (baseURI != null) { if (baseURI != null) {
@ -464,7 +463,6 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
bauthority = base.getAuthority(); bauthority = base.getAuthority();
bpath = base.getPath(); bpath = base.getPath();
bquery = base.getQuery(); bquery = base.getQuery();
bfragment = base.getFragment();
} }
URI r = new URI(relativeURI); URI r = new URI(relativeURI);
@ -472,9 +470,8 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
String rauthority = r.getAuthority(); String rauthority = r.getAuthority();
String rpath = r.getPath(); String rpath = r.getPath();
String rquery = r.getQuery(); String rquery = r.getQuery();
String rfragment = null;
String tscheme, tauthority, tpath, tquery, tfragment; String tscheme, tauthority, tpath, tquery;
if (rscheme != null && rscheme.equals(bscheme)) { if (rscheme != null && rscheme.equals(bscheme)) {
rscheme = null; rscheme = null;
} }
@ -518,13 +515,13 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
} }
tscheme = bscheme; tscheme = bscheme;
} }
tfragment = rfragment; return new URI(tscheme, tauthority, tpath, tquery, null).toString();
return new URI(tscheme, tauthority, tpath, tquery, tfragment).toString();
} }
private static String removeDotSegments(String path) { private static String removeDotSegments(String path) {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "STEP OUTPUT BUFFER\t\tINPUT BUFFER"); log.log(java.util.logging.Level.FINE, "STEP OUTPUT BUFFER\t\tINPUT BUFFER");
}
// 1. The input buffer is initialized with the now-appended path // 1. The input buffer is initialized with the now-appended path
// components then replace occurrences of "//" in the input buffer // 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. // 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 // If the input buffer starts with a root slash "/" then move this
// character to the output buffer. // character to the output buffer.
@ -594,7 +591,7 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
} else { } else {
int index = output.lastIndexOf("/"); int index = output.lastIndexOf("/");
if (index == -1) { if (index == -1) {
output = new StringBuffer(); output = new StringBuilder();
if (input.charAt(0) == '/') { if (input.charAt(0) == '/') {
input = input.substring(1); input = input.substring(1);
} }
@ -615,7 +612,7 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
} else { } else {
int index = output.lastIndexOf("/"); int index = output.lastIndexOf("/");
if (index == -1) { if (index == -1) {
output = new StringBuffer(); output = new StringBuilder();
if (input.charAt(0) == '/') { if (input.charAt(0) == '/') {
input = input.substring(1); input = input.substring(1);
} }
@ -633,8 +630,9 @@ public abstract class Canonicalizer11 extends CanonicalizerBase {
input = ""; input = "";
printStep("2D", output.toString(), input); printStep("2D", output.toString(), input);
} else if (input.equals("..")) { } else if (input.equals("..")) {
if (!output.toString().equals("/")) if (!output.toString().equals("/")) {
output.append(".."); output.append("..");
}
input = ""; input = "";
printStep("2D", output.toString(), input); printStep("2D", output.toString(), input);
// 2E. move the first path segment (if any) in the input buffer // 2E. move the first path segment (if any) in the input buffer

View File

@ -2,21 +2,23 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.c14n.implementations; package com.sun.org.apache.xml.internal.security.c14n.implementations;

View File

@ -2,21 +2,23 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.c14n.implementations; package com.sun.org.apache.xml.internal.security.c14n.implementations;

View File

@ -2,26 +2,26 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.c14n.implementations; package com.sun.org.apache.xml.internal.security.c14n.implementations;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
@ -47,97 +47,102 @@ import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
/** /**
* Implements <A HREF="http://www.w3.org/TR/2001/REC-xml-c14n-20010315">Canonical * Implements <A HREF="http://www.w3.org/TR/2001/REC-xml-c14n-20010315">Canonical
* XML Version 1.0</A>, a W3C Recommendation from 15 March 2001. * XML Version 1.0</A>, a W3C Recommendation from 15 March 2001.
* *
* @author Christian Geuer-Pollmann <geuerp@apache.org> * @author Christian Geuer-Pollmann <geuerp@apache.org>
* @version $Revision: 1.5 $
*/ */
public abstract class Canonicalizer20010315 extends CanonicalizerBase { public abstract class Canonicalizer20010315 extends CanonicalizerBase {
boolean firstCall=true; private static final String XMLNS_URI = Constants.NamespaceSpecNS;
final SortedSet<Attr> result= new TreeSet<Attr>(COMPARE); private static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS;
static final String XMLNS_URI=Constants.NamespaceSpecNS;
static final String XML_LANG_URI=Constants.XML_LANG_SPACE_SpecNS; private boolean firstCall = true;
static class XmlAttrStack { private final SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
int currentLevel=0;
int lastlevel=0; private static class XmlAttrStack {
XmlsStackElement cur;
static class XmlsStackElement { static class XmlsStackElement {
int level; int level;
boolean rendered=false; boolean rendered = false;
List<Attr> nodes=new ArrayList<Attr>(); List<Attr> nodes = new ArrayList<Attr>();
}; };
List<XmlsStackElement> levels=new ArrayList<XmlsStackElement>();
int currentLevel = 0;
int lastlevel = 0;
XmlsStackElement cur;
List<XmlsStackElement> levels = new ArrayList<XmlsStackElement>();
void push(int level) { void push(int level) {
currentLevel=level; currentLevel = level;
if (currentLevel==-1) if (currentLevel == -1) {
return;
cur=null;
while (lastlevel>=currentLevel) {
levels.remove(levels.size()-1);
if (levels.size()==0) {
lastlevel=0;
return; return;
} }
lastlevel=(levels.get(levels.size()-1)).level; 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) { void addXmlnsAttr(Attr n) {
if (cur==null) { if (cur == null) {
cur=new XmlsStackElement(); cur = new XmlsStackElement();
cur.level=currentLevel; cur.level = currentLevel;
levels.add(cur); levels.add(cur);
lastlevel=currentLevel; lastlevel = currentLevel;
} }
cur.nodes.add(n); cur.nodes.add(n);
} }
void getXmlnsAttr(Collection<Attr> col) { void getXmlnsAttr(Collection<Attr> col) {
int size=levels.size()-1; int size = levels.size() - 1;
if (cur==null) { if (cur == null) {
cur=new XmlsStackElement(); cur = new XmlsStackElement();
cur.level=currentLevel; cur.level = currentLevel;
lastlevel=currentLevel; lastlevel = currentLevel;
levels.add(cur); levels.add(cur);
} }
boolean parentRendered=false; boolean parentRendered = false;
XmlsStackElement e=null; XmlsStackElement e = null;
if (size==-1) { if (size == -1) {
parentRendered=true; parentRendered = true;
} else { } else {
e=levels.get(size); e = levels.get(size);
if (e.rendered && e.level+1==currentLevel) if (e.rendered && e.level + 1 == currentLevel) {
parentRendered=true; parentRendered = true;
}
} }
if (parentRendered) { if (parentRendered) {
col.addAll(cur.nodes); col.addAll(cur.nodes);
cur.rendered=true; cur.rendered = true;
return; return;
} }
Map<String,Attr> loa = new HashMap<String,Attr>(); Map<String, Attr> loa = new HashMap<String, Attr>();
for (;size>=0;size--) { for (; size >= 0; size--) {
e=levels.get(size); e = levels.get(size);
Iterator<Attr> it=e.nodes.iterator(); Iterator<Attr> it = e.nodes.iterator();
while (it.hasNext()) { while (it.hasNext()) {
Attr n=it.next(); Attr n = it.next();
if (!loa.containsKey(n.getName())) if (!loa.containsKey(n.getName())) {
loa.put(n.getName(),n); loa.put(n.getName(), n);
}
}
} }
//if (e.rendered)
//break;
}; cur.rendered = true;
//cur.nodes.clear();
//cur.nodes.addAll(loa.values());
cur.rendered=true;
col.addAll(loa.values()); col.addAll(loa.values());
} }
} }
XmlAttrStack xmlattrStack=new XmlAttrStack();
private XmlAttrStack xmlattrStack = new XmlAttrStack();
/** /**
* Constructor Canonicalizer20010315 * Constructor Canonicalizer20010315
* *
@ -147,176 +152,6 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase {
super(includeComments); super(includeComments);
} }
/**
* Returns the Attr[]s to be outputted for the given element.
* <br>
* 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<Attr> 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<Attr> 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.
* <br>
* 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<Attr> 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();
}
SortedSet<Attr> 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) {
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 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.
//addXmlAttributes(E,result);
xmlattrStack.getXmlnsAttr(result);
ns.getUnrenderedNodes(getSortedSetAsCollection(result));
}
return result.iterator();
}
/** /**
* Always throws a CanonicalizationException because this is inclusive c14n. * Always throws a CanonicalizationException because this is inclusive c14n.
* *
@ -329,8 +164,7 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase {
throws CanonicalizationException { throws CanonicalizationException {
/** $todo$ well, should we throw UnsupportedOperationException ? */ /** $todo$ well, should we throw UnsupportedOperationException ? */
throw new CanonicalizationException( throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
"c14n.Canonicalizer.UnsupportedOperation");
} }
/** /**
@ -345,46 +179,216 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase {
throws CanonicalizationException { throws CanonicalizationException {
/** $todo$ well, should we throw UnsupportedOperationException ? */ /** $todo$ well, should we throw UnsupportedOperationException ? */
throw new CanonicalizationException( throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
"c14n.Canonicalizer.UnsupportedOperation");
} }
void circumventBugIfNeeded(XMLSignatureInput input) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException {
if (!input.isNeedsToBeExpanded()) /**
* Returns the Attr[]s to be output for the given element.
* <br>
* 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<Attr> 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<Attr> 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.
* <br>
* 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<Attr> 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<Attr> 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)) {
//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()) {
return; return;
}
Document doc = null; Document doc = null;
if (input.getSubNode() != null) { if (input.getSubNode() != null) {
doc=XMLUtils.getOwnerDocument(input.getSubNode()); doc = XMLUtils.getOwnerDocument(input.getSubNode());
} else { } else {
doc=XMLUtils.getOwnerDocument(input.getNodeSet()); doc = XMLUtils.getOwnerDocument(input.getNodeSet());
} }
XMLUtils.circumventBug2650(doc); XMLUtils.circumventBug2650(doc);
} }
void handleParent(Element e, NameSpaceSymbTable ns) { @Override
if (!e.hasAttributes()) { protected void handleParent(Element e, NameSpaceSymbTable ns) {
if (!e.hasAttributes() && e.getNamespaceURI() == null) {
return; return;
} }
xmlattrStack.push(-1); xmlattrStack.push(-1);
NamedNodeMap attrs = e.getAttributes(); NamedNodeMap attrs = e.getAttributes();
int attrsLength = attrs.getLength(); int attrsLength = attrs.getLength();
for (int i = 0; i < attrsLength; i++) { for (int i = 0; i < attrsLength; i++) {
Attr N = (Attr) attrs.item(i); Attr attribute = (Attr) attrs.item(i);
if (Constants.NamespaceSpecNS!=N.getNamespaceURI()) { String NName = attribute.getLocalName();
//Not a namespace definition, ignore. String NValue = attribute.getNodeValue();
if (XML_LANG_URI==N.getNamespaceURI()) {
xmlattrStack.addXmlnsAttr(N);
}
continue;
}
String NName=N.getLocalName(); if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI())) {
String NValue=N.getNodeValue(); if (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
if (XML.equals(NName) ns.addMapping(NName, NValue, attribute);
&& Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
continue;
} }
ns.addMapping(NName,NValue,N); } 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);
} }
} }
} }

View File

@ -2,21 +2,23 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); you may not * distributed with this work for additional information
* use this file except in compliance with the License. You may obtain a copy of * regarding copyright ownership. The ASF licenses this file
* the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * software distributed under the License is distributed on an
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* License for the specific language governing permissions and limitations under * KIND, either express or implied. See the License for the
* the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.c14n.implementations; 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.Set;
import java.util.SortedSet; import java.util.SortedSet;
import java.util.TreeSet; import java.util.TreeSet;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; 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.NamedNodeMap;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
/** /**
* Implements &quot; <A * Implements &quot; <A
* HREF="http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/">Exclusive XML * HREF="http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/">Exclusive XML
@ -52,18 +54,23 @@ import org.xml.sax.SAXException;
* <i>THIS </i> implementation is a complete rewrite of the algorithm. * <i>THIS </i> implementation is a complete rewrite of the algorithm.
* *
* @author Christian Geuer-Pollmann <geuerp@apache.org> * @author Christian Geuer-Pollmann <geuerp@apache.org>
* @version $Revision: 1.5 $ * @version $Revision: 1147448 $
* @see <a href="http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/ Exclusive#"> * @see <a href="http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/ Exclusive#">
* XML Canonicalization, Version 1.0</a> * XML Canonicalization, Version 1.0</a>
*/ */
public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { 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 * This Set contains the names (Strings like "xmlns" or "xmlns:foo") of
* the inclusive namespaces. * the inclusive namespaces.
*/ */
TreeSet<String> _inclusiveNSSet = new TreeSet<String>(); private SortedSet<String> inclusiveNSSet;
static final String XMLNS_URI=Constants.NamespaceSpecNS;
final SortedSet<Attr> result = new TreeSet<Attr>(COMPARE); private final SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
/** /**
* Constructor Canonicalizer20010315Excl * Constructor Canonicalizer20010315Excl
* *
@ -82,8 +89,9 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase {
*/ */
public byte[] engineCanonicalizeSubTree(Node rootNode) public byte[] engineCanonicalizeSubTree(Node rootNode)
throws CanonicalizationException { throws CanonicalizationException {
return this.engineCanonicalizeSubTree(rootNode, "",null); return engineCanonicalizeSubTree(rootNode, "", null);
} }
/** /**
* Method engineCanonicalizeSubTree * Method engineCanonicalizeSubTree
* @inheritDoc * @inheritDoc
@ -92,10 +100,12 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase {
* *
* @throws CanonicalizationException * @throws CanonicalizationException
*/ */
public byte[] engineCanonicalizeSubTree(Node rootNode, public byte[] engineCanonicalizeSubTree(
String inclusiveNamespaces) throws CanonicalizationException { Node rootNode, String inclusiveNamespaces
return this.engineCanonicalizeSubTree(rootNode, inclusiveNamespaces,null); ) throws CanonicalizationException {
return engineCanonicalizeSubTree(rootNode, inclusiveNamespaces, null);
} }
/** /**
* Method engineCanonicalizeSubTree * Method engineCanonicalizeSubTree
* @param rootNode * @param rootNode
@ -104,11 +114,13 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase {
* @return the rootNode c14n. * @return the rootNode c14n.
* @throws CanonicalizationException * @throws CanonicalizationException
*/ */
public byte[] engineCanonicalizeSubTree(Node rootNode, public byte[] engineCanonicalizeSubTree(
String inclusiveNamespaces,Node excl) throws CanonicalizationException { Node rootNode, String inclusiveNamespaces, Node excl
this._inclusiveNSSet = getInclusiveNameSpace(inclusiveNamespaces); ) throws CanonicalizationException{
return super.engineCanonicalizeSubTree(rootNode,excl); inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces);
return super.engineCanonicalizeSubTree(rootNode, excl);
} }
/** /**
* *
* @param rootNode * @param rootNode
@ -116,89 +128,13 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase {
* @return the rootNode c14n. * @return the rootNode c14n.
* @throws CanonicalizationException * @throws CanonicalizationException
*/ */
@SuppressWarnings("unchecked") public byte[] engineCanonicalize(
public byte[] engineCanonicalize(XMLSignatureInput rootNode, XMLSignatureInput rootNode, String inclusiveNamespaces
String inclusiveNamespaces) throws CanonicalizationException { ) throws CanonicalizationException {
this._inclusiveNSSet = getInclusiveNameSpace(inclusiveNamespaces); inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces);
return super.engineCanonicalize(rootNode); return super.engineCanonicalize(rootNode);
} }
/**
* Method handleAttributesSubtree
* @inheritDoc
* @param E
* @throws CanonicalizationException
*/
Iterator<Attr> 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<Attr> 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<String> 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<String> 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 * Method engineCanonicalizeXPathNodeSet
* @inheritDoc * @inheritDoc
@ -206,147 +142,191 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase {
* @param inclusiveNamespaces * @param inclusiveNamespaces
* @throws CanonicalizationException * @throws CanonicalizationException
*/ */
public byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet, public byte[] engineCanonicalizeXPathNodeSet(
String inclusiveNamespaces) throws CanonicalizationException { Set<Node> xpathNodeSet, String inclusiveNamespaces
) throws CanonicalizationException {
this._inclusiveNSSet = getInclusiveNameSpace(inclusiveNamespaces); inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces);
return super.engineCanonicalizeXPathNodeSet(xpathNodeSet); return super.engineCanonicalizeXPathNodeSet(xpathNodeSet);
} }
@SuppressWarnings("unchecked") @Override
private TreeSet<String> getInclusiveNameSpace(String inclusiveNameSpaces) { protected Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
return (TreeSet<String>)InclusiveNamespaces.prefixStr2Set(inclusiveNameSpaces);
}
@SuppressWarnings("unchecked")
private SortedSet<String> getNSSetClone() {
return (SortedSet<String>) this._inclusiveNSSet.clone();
}
/**
* @inheritDoc
* @param E
* @throws CanonicalizationException
*/
final Iterator<Attr> handleAttributes(Element E, NameSpaceSymbTable ns)
throws CanonicalizationException { throws CanonicalizationException {
// result will contain the attrs which have to be outputted // result will contain the attrs which have to be output
SortedSet<Attr> result = this.result; final SortedSet<Attr> result = this.result;
result.clear(); result.clear();
NamedNodeMap attrs = null;
int attrsLength = 0; // The prefix visibly utilized (in the attribute or in the name) in
if (E.hasAttributes()) { // the element
attrs = E.getAttributes(); SortedSet<String> visiblyUtilized = new TreeSet<String>();
attrsLength = attrs.getLength(); if (inclusiveNSSet != null && !inclusiveNSSet.isEmpty()) {
} visiblyUtilized.addAll(inclusiveNSSet);
//The prefix visibly utilized(in the attribute or in the name) in the element
Set<String> visiblyUtilized =null;
//It's the output selected.
boolean isOutputElement=isVisibleDO(E,ns.getLevel())==1;
if (isOutputElement) {
visiblyUtilized = getNSSetClone();
} }
if (element.hasAttributes()) {
NamedNodeMap attrs = element.getAttributes();
int attrsLength = attrs.getLength();
for (int i = 0; i < attrsLength; i++) { for (int i = 0; i < attrsLength; i++) {
Attr N = (Attr) attrs.item(i); Attr attribute = (Attr) attrs.item(i);
String NName = attribute.getLocalName();
String NNodeValue = attribute.getNodeValue();
if (!XMLNS_URI.equals(attribute.getNamespaceURI())) {
if (XMLNS_URI!=N.getNamespaceURI()) { // Not a namespace definition.
if ( !isVisible(N) ) { // The Element is output element, add the prefix (if used) to
//The node is not in the nodeset(if there is a nodeset) // visiblyUtilized
continue; String prefix = attribute.getPrefix();
} if (prefix != null && !(prefix.equals(XML) || prefix.equals(XMLNS))) {
//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); visiblyUtilized.add(prefix);
} }
//Add to the result. // Add to the result.
result.add(N); result.add(attribute);
} } else if (!(XML.equals(NName) && XML_LANG_URI.equals(NNodeValue))
continue; && ns.addMapping(NName, NNodeValue, attribute)
} && C14nHelper.namespaceIsRelative(NNodeValue)) {
String NName=N.getLocalName(); // The default mapping for xml must not be output.
if (isOutputElement && !isVisible(N) && NName!=XMLNS) { // New definition check if it is relative.
ns.removeMappingIfNotRender(NName); Object exArgs[] = {element.getTagName(), NName, attribute.getNodeValue()};
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( throw new CanonicalizationException(
"c14n.Canonicalizer.RelativeNamespace", exArgs); "c14n.Canonicalizer.RelativeNamespace", exArgs
);
} }
} }
} }
String prefix = null;
if (element.getNamespaceURI() != null
&& !(element.getPrefix() == null || element.getPrefix().length() == 0)) {
if (ns.addMapping(NName, NNodeValue,N)) { prefix = element.getPrefix();
//New definiton check if it is relative
if (C14nHelper.namespaceIsRelative(NNodeValue)) {
Object exArgs[] = {E.getTagName(), NName,
N.getNodeValue()};
throw new CanonicalizationException(
"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 { } else {
visiblyUtilized.add( prefix); prefix = XMLNS;
}
} else {
visiblyUtilized.add(XMLNS);
}
//This can be optimezed by I don't have time
//visiblyUtilized.addAll(this._inclusiveNSSet);
Iterator<String> it=visiblyUtilized.iterator();
while (it.hasNext()) {
String s=it.next();
Attr key=ns.getMapping(s);
if (key==null) {
continue;
} }
visiblyUtilized.add(prefix);
for (String s : visiblyUtilized) {
Attr key = ns.getMapping(s);
if (key != null) {
result.add(key); result.add(key);
} }
} }
return result.iterator(); return result.iterator();
} }
void circumventBugIfNeeded(XMLSignatureInput input) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException {
if (!input.isNeedsToBeExpanded() || _inclusiveNSSet.isEmpty()) /**
return; * @inheritDoc
Document doc = null; * @param element
if (input.getSubNode() != null) { * @throws CanonicalizationException
doc=XMLUtils.getOwnerDocument(input.getSubNode()); */
} else { @Override
doc=XMLUtils.getOwnerDocument(input.getNodeSet()); protected final Iterator<Attr> handleAttributes(Element element, NameSpaceSymbTable ns)
throws CanonicalizationException {
// result will contain the attrs which have to be output
final SortedSet<Attr> result = this.result;
result.clear();
// The prefix visibly utilized (in the attribute or in the name) in
// the element
Set<String> visiblyUtilized = null;
// It's the output selected.
boolean isOutputElement = isVisibleDO(element, ns.getLevel()) == 1;
if (isOutputElement) {
visiblyUtilized = new TreeSet<String>();
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); XMLUtils.circumventBug2650(doc);
} }
} }

View File

@ -2,33 +2,29 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.c14n.implementations; package com.sun.org.apache.xml.internal.security.c14n.implementations;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
/** public class Canonicalizer20010315ExclOmitComments extends Canonicalizer20010315Excl {
*
*
*/
public class Canonicalizer20010315ExclOmitComments
extends Canonicalizer20010315Excl {
/** /**
* *

View File

@ -2,36 +2,32 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.c14n.implementations; package com.sun.org.apache.xml.internal.security.c14n.implementations;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
/** /**
* Class Canonicalizer20010315ExclWithComments * Class Canonicalizer20010315ExclWithComments
*
* @version $Revision: 1.5 $
*/ */
public class Canonicalizer20010315ExclWithComments public class Canonicalizer20010315ExclWithComments extends Canonicalizer20010315Excl {
extends Canonicalizer20010315Excl {
/** /**
* Constructor Canonicalizer20010315ExclWithComments * Constructor Canonicalizer20010315ExclWithComments

View File

@ -2,31 +2,29 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.c14n.implementations; package com.sun.org.apache.xml.internal.security.c14n.implementations;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
/** /**
*
* @author Christian Geuer-Pollmann * @author Christian Geuer-Pollmann
*/ */
public class Canonicalizer20010315OmitComments extends Canonicalizer20010315 { public class Canonicalizer20010315OmitComments extends Canonicalizer20010315 {

View File

@ -2,35 +2,35 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.c14n.implementations; package com.sun.org.apache.xml.internal.security.c14n.implementations;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
/** /**
*
* @author Christian Geuer-Pollmann * @author Christian Geuer-Pollmann
*/ */
public class Canonicalizer20010315WithComments extends Canonicalizer20010315 { public class Canonicalizer20010315WithComments extends Canonicalizer20010315 {
/** /**
* Constructor Canonicalizer20010315WithXPathWithComments * Constructor Canonicalizer20010315WithXPathWithComments
*
*/ */
public Canonicalizer20010315WithComments() { public Canonicalizer20010315WithComments() {
super(true); super(true);

View File

@ -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<Attr> result = new TreeSet<Attr>(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<Node> 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.
* <br>
* 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<Attr> 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<Attr> 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<Attr> 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);
}
}

View File

@ -2,21 +2,23 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.c14n.implementations; package com.sun.org.apache.xml.internal.security.c14n.implementations;
@ -29,37 +31,37 @@ import java.util.List;
import org.w3c.dom.Attr; import org.w3c.dom.Attr;
import org.w3c.dom.Node; import org.w3c.dom.Node;
/** /**
* A stack based Symble Table. * A stack based Symbol Table.
*<br>For speed reasons all the symbols are introduced in the same map, *<br>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. * and at the same time in a list so it can be removed when the frame is pop back.
* @author Raul Benito * @author Raul Benito
**/ */
public class NameSpaceSymbTable { public class NameSpaceSymbTable {
/**The map betwen prefix-> entry table. */ private static final String XMLNS = "xmlns";
SymbMap symb; private static final SymbMap initialMap = new SymbMap();
/**The level of nameSpaces (for Inclusive visibility).*/
int nameSpaces=0;
/**The stacks for removing the definitions when doing pop.*/
List<SymbMap> level;
boolean cloned=true;
static final String XMLNS="xmlns";
final static SymbMap initialMap=new SymbMap();
static { static {
NameSpaceSymbEntry ne=new NameSpaceSymbEntry("",null,true,XMLNS); NameSpaceSymbEntry ne = new NameSpaceSymbEntry("", null, true, XMLNS);
ne.lastrendered=""; ne.lastrendered = "";
initialMap.put(XMLNS,ne); initialMap.put(XMLNS, ne);
} }
/**The map betwen prefix-> entry table. */
private SymbMap symb;
/**The stacks for removing the definitions when doing pop.*/
private List<SymbMap> level;
private boolean cloned = true;
/** /**
* Default constractor * Default constractor
**/ **/
public NameSpaceSymbTable() { public NameSpaceSymbTable() {
level = new ArrayList<SymbMap>(10); level = new ArrayList<SymbMap>();
//Insert the default binding for xmlns. //Insert the default binding for xmlns.
symb=(SymbMap) initialMap.clone(); symb = (SymbMap) initialMap.clone();
} }
/** /**
@ -68,20 +70,18 @@ public class NameSpaceSymbTable {
* @param result the list where to fill the unrendered xmlns definitions. * @param result the list where to fill the unrendered xmlns definitions.
**/ **/
public void getUnrenderedNodes(Collection<Attr> result) { public void getUnrenderedNodes(Collection<Attr> result) {
//List result=new ArrayList(); Iterator<NameSpaceSymbEntry> it = symb.entrySet().iterator();
Iterator<NameSpaceSymbEntry> it=symb.entrySet().iterator();
while (it.hasNext()) { while (it.hasNext()) {
NameSpaceSymbEntry n= it.next(); NameSpaceSymbEntry n = it.next();
//put them rendered? //put them rendered?
if ((!n.rendered) && (n.n!=null)) { if ((!n.rendered) && (n.n != null)) {
n=(NameSpaceSymbEntry) n.clone(); n = (NameSpaceSymbEntry) n.clone();
needsClone(); needsClone();
symb.put(n.prefix,n); symb.put(n.prefix, n);
n.lastrendered=n.uri; n.lastrendered = n.uri;
n.rendered=true; n.rendered = true;
result.add(n.n); result.add(n.n);
} }
} }
} }
@ -91,7 +91,6 @@ public class NameSpaceSymbTable {
* For Inclusive rendering. * For Inclusive rendering.
**/ **/
public void outputNodePush() { public void outputNodePush() {
nameSpaces++;
push(); push();
} }
@ -99,7 +98,6 @@ public class NameSpaceSymbTable {
* Pop a frame for visible namespace. * Pop a frame for visible namespace.
**/ **/
public void outputNodePop() { public void outputNodePop() {
nameSpaces--;
pop(); pop();
} }
@ -110,7 +108,7 @@ public class NameSpaceSymbTable {
public void push() { public void push() {
//Put the number of namespace definitions in the stack. //Put the number of namespace definitions in the stack.
level.add(null); level.add(null);
cloned=false; cloned = false;
} }
/** /**
@ -118,26 +116,25 @@ public class NameSpaceSymbTable {
* Inclusive or Exclusive. * Inclusive or Exclusive.
**/ **/
public void pop() { public void pop() {
int size=level.size()-1; int size = level.size() - 1;
Object ob= level.remove(size); Object ob = level.remove(size);
if (ob!=null) { if (ob != null) {
symb=(SymbMap)ob; symb = (SymbMap)ob;
if (size==0) { if (size == 0) {
cloned=false; cloned = false;
} else
cloned=(level.get(size-1)!=symb);
} else { } else {
cloned=false; cloned = (level.get(size - 1) != symb);
}
} else {
cloned = false;
} }
} }
final void needsClone() { final void needsClone() {
if (!cloned) { if (!cloned) {
level.set(level.size()-1,symb); level.set(level.size() - 1, symb);
symb=(SymbMap) symb.clone(); symb = (SymbMap) symb.clone();
cloned=true; cloned = true;
} }
} }
@ -149,8 +146,8 @@ public class NameSpaceSymbTable {
* definition. * definition.
**/ **/
public Attr getMapping(String prefix) { public Attr getMapping(String prefix) {
NameSpaceSymbEntry entry=symb.get(prefix); NameSpaceSymbEntry entry = symb.get(prefix);
if (entry==null) { if (entry == null) {
//There is no definition for the prefix(a bug?). //There is no definition for the prefix(a bug?).
return null; return null;
} }
@ -159,12 +156,11 @@ public class NameSpaceSymbTable {
return null; return null;
} }
// Mark this entry as render. // Mark this entry as render.
entry=(NameSpaceSymbEntry) entry.clone(); entry = (NameSpaceSymbEntry) entry.clone();
needsClone(); needsClone();
symb.put(prefix,entry); symb.put(prefix, entry);
entry.rendered=true; entry.rendered = true;
entry.level=nameSpaces; entry.lastrendered = entry.uri;
entry.lastrendered=entry.uri;
// Return the node for outputing. // Return the node for outputing.
return entry.n; return entry.n;
} }
@ -176,8 +172,8 @@ public class NameSpaceSymbTable {
* @return the attr to render, null if there is no need to render * @return the attr to render, null if there is no need to render
**/ **/
public Attr getMappingWithoutRendered(String prefix) { public Attr getMappingWithoutRendered(String prefix) {
NameSpaceSymbEntry entry= symb.get(prefix); NameSpaceSymbEntry entry = symb.get(prefix);
if (entry==null) { if (entry == null) {
return null; return null;
} }
if (entry.rendered) { if (entry.rendered) {
@ -193,23 +189,23 @@ public class NameSpaceSymbTable {
* @param n the attribute that have the definition * @param n the attribute that have the definition
* @return true if there is already defined. * @return true if there is already defined.
**/ **/
public boolean addMapping(String prefix, String uri,Attr n) { public boolean addMapping(String prefix, String uri, Attr n) {
NameSpaceSymbEntry ob = symb.get(prefix); NameSpaceSymbEntry ob = symb.get(prefix);
if ((ob!=null) && uri.equals(ob.uri)) { if ((ob != null) && uri.equals(ob.uri)) {
//If we have it previously defined. Don't keep working. //If we have it previously defined. Don't keep working.
return false; return false;
} }
//Creates and entry in the table for this new definition. //Creates and entry in the table for this new definition.
NameSpaceSymbEntry ne=new NameSpaceSymbEntry(uri,n,false,prefix); NameSpaceSymbEntry ne = new NameSpaceSymbEntry(uri, n, false, prefix);
needsClone(); needsClone();
symb.put(prefix, ne); symb.put(prefix, ne);
if (ob != null) { if (ob != null) {
//We have a previous definition store it for the pop. //We have a previous definition store it for the pop.
//Check if a previous definition(not the inmidiatly one) has been rendered. //Check if a previous definition(not the inmidiatly one) has been rendered.
ne.lastrendered=ob.lastrendered; ne.lastrendered = ob.lastrendered;
if ((ob.lastrendered!=null)&& (ob.lastrendered.equals(uri))) { if ((ob.lastrendered != null) && (ob.lastrendered.equals(uri))) {
//Yes it is. Mark as rendered. //Yes it is. Mark as rendered.
ne.rendered=true; ne.rendered = true;
} }
} }
return true; return true;
@ -223,64 +219,60 @@ public class NameSpaceSymbTable {
* @param n the attribute that have the definition * @param n the attribute that have the definition
* @return the attr to render, null if there is no need to render * @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); NameSpaceSymbEntry ob = symb.get(prefix);
if ((ob!=null) && uri.equals(ob.uri)) { if ((ob != null) && uri.equals(ob.uri)) {
if (!ob.rendered) { if (!ob.rendered) {
ob=(NameSpaceSymbEntry) ob.clone(); ob = (NameSpaceSymbEntry) ob.clone();
needsClone(); needsClone();
symb.put(prefix,ob); symb.put(prefix, ob);
ob.lastrendered=uri; ob.lastrendered = uri;
ob.rendered=true; ob.rendered = true;
return ob.n; return ob.n;
} }
return null; return null;
} }
NameSpaceSymbEntry ne=new NameSpaceSymbEntry(uri,n,true,prefix); NameSpaceSymbEntry ne = new NameSpaceSymbEntry(uri,n,true,prefix);
ne.lastrendered=uri; ne.lastrendered = uri;
needsClone(); needsClone();
symb.put(prefix, ne); symb.put(prefix, ne);
if (ob != null) { if ((ob != null) && (ob.lastrendered != null) && (ob.lastrendered.equals(uri))) {
ne.rendered = true;
if ((ob.lastrendered!=null)&& (ob.lastrendered.equals(uri))) {
ne.rendered=true;
return null; return null;
} }
}
return ne.n; return ne.n;
} }
public int getLevel() { public int getLevel() {
// TODO Auto-generated method stub
return level.size(); return level.size();
} }
public void removeMapping(String prefix) { public void removeMapping(String prefix) {
NameSpaceSymbEntry ob = symb.get(prefix); NameSpaceSymbEntry ob = symb.get(prefix);
if (ob!=null) { if (ob != null) {
needsClone(); needsClone();
symb.put(prefix,null); symb.put(prefix, null);
} }
} }
public void removeMappingIfNotRender(String prefix) { public void removeMappingIfNotRender(String prefix) {
NameSpaceSymbEntry ob = symb.get(prefix); NameSpaceSymbEntry ob = symb.get(prefix);
if (ob!=null && !ob.rendered) { if (ob != null && !ob.rendered) {
needsClone(); needsClone();
symb.put(prefix,null); symb.put(prefix, null);
} }
} }
public boolean removeMappingIfRender(String prefix) { public boolean removeMappingIfRender(String prefix) {
NameSpaceSymbEntry ob = symb.get(prefix); NameSpaceSymbEntry ob = symb.get(prefix);
if (ob!=null && ob.rendered) { if (ob != null && ob.rendered) {
needsClone(); needsClone();
symb.put(prefix,null); symb.put(prefix, null);
} }
return false; return false;
} }
@ -290,12 +282,28 @@ public class NameSpaceSymbTable {
* The internal structure of NameSpaceSymbTable. * The internal structure of NameSpaceSymbTable.
**/ **/
class NameSpaceSymbEntry implements Cloneable { class NameSpaceSymbEntry implements Cloneable {
NameSpaceSymbEntry(String name,Attr n,boolean rendered,String prefix) {
this.uri=name; String prefix;
this.rendered=rendered;
this.n=n; /**The URI that the prefix defines */
this.prefix=prefix; 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 */ /** @inheritDoc */
public Object clone() { public Object clone() {
try { try {
@ -304,45 +312,34 @@ class NameSpaceSymbEntry implements Cloneable {
return null; 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 { class SymbMap implements Cloneable {
int free=23; int free = 23;
NameSpaceSymbEntry[] entries; NameSpaceSymbEntry[] entries;
String[] keys; String[] keys;
SymbMap() { SymbMap() {
entries=new NameSpaceSymbEntry[free]; entries = new NameSpaceSymbEntry[free];
keys=new String[free]; keys = new String[free];
} }
void put(String key, NameSpaceSymbEntry value) { void put(String key, NameSpaceSymbEntry value) {
int index = index(key); int index = index(key);
Object oldKey = keys[index]; Object oldKey = keys[index];
keys[index] = key; keys[index] = key;
entries[index] = value; entries[index] = value;
if (oldKey==null || !oldKey.equals(key)) { if ((oldKey == null || !oldKey.equals(key)) && (--free == 0)) {
if (--free == 0) { free = entries.length;
free=entries.length; int newCapacity = free << 2;
int newCapacity = free<<2;
rehash(newCapacity); rehash(newCapacity);
} }
} }
}
List<NameSpaceSymbEntry> entrySet() { List<NameSpaceSymbEntry> entrySet() {
List<NameSpaceSymbEntry> a=new ArrayList<NameSpaceSymbEntry>(); List<NameSpaceSymbEntry> a = new ArrayList<NameSpaceSymbEntry>();
for (int i=0;i<entries.length;i++) { for (int i = 0;i < entries.length;i++) {
if ((entries[i]!=null) && !("".equals(entries[i].uri))) { if ((entries[i] != null) && !("".equals(entries[i].uri))) {
a.add(entries[i]); a.add(entries[i]);
} }
} }
@ -356,12 +353,12 @@ class SymbMap implements Cloneable {
int index = (obj.hashCode() & 0x7fffffff) % length; int index = (obj.hashCode() & 0x7fffffff) % length;
Object cur = set[index]; Object cur = set[index];
if (cur == null || (cur.equals( obj))) { if (cur == null || (cur.equals(obj))) {
return index; return index;
} }
length=length-1; length--;
do { do {
index=index==length? 0:++index; index = index == length ? 0 : ++index;
cur = set[index]; cur = set[index];
} while (cur != null && (!cur.equals(obj))); } while (cur != null && (!cur.equals(obj)));
return index; return index;
@ -381,7 +378,7 @@ class SymbMap implements Cloneable {
entries = new NameSpaceSymbEntry[newCapacity]; entries = new NameSpaceSymbEntry[newCapacity];
for (int i = oldCapacity; i-- > 0;) { for (int i = oldCapacity; i-- > 0;) {
if(oldKeys[i] != null) { if (oldKeys[i] != null) {
String o = oldKeys[i]; String o = oldKeys[i];
int index = index(o); int index = index(o);
keys[index] = o; keys[index] = o;
@ -396,15 +393,14 @@ class SymbMap implements Cloneable {
protected Object clone() { protected Object clone() {
try { try {
SymbMap copy=(SymbMap) super.clone(); SymbMap copy = (SymbMap) super.clone();
copy.entries=new NameSpaceSymbEntry[entries.length]; copy.entries = new NameSpaceSymbEntry[entries.length];
System.arraycopy(entries,0,copy.entries,0,entries.length); System.arraycopy(entries, 0, copy.entries, 0, entries.length);
copy.keys=new String[keys.length]; copy.keys = new String[keys.length];
System.arraycopy(keys,0,copy.keys,0,keys.length); System.arraycopy(keys, 0, copy.keys, 0, keys.length);
return copy; return copy;
} catch (CloneNotSupportedException e) { } catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;

View File

@ -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; package com.sun.org.apache.xml.internal.security.c14n.implementations;
import java.io.IOException; import java.io.IOException;
@ -6,23 +28,26 @@ import java.util.Map;
public class UtfHelpper { public class UtfHelpper {
final static void writeByte(final String str,final OutputStream out,Map<String,byte[]> cache) throws IOException { static final void writeByte(
byte []result= cache.get(str); final String str,
if (result==null) { final OutputStream out,
result=getStringInUtf8(str); Map<String, byte[]> cache
cache.put(str,result); ) 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{ static final void writeCharToUtf8(final char c, final OutputStream out) throws IOException {
if (c < 0x80) { if (c < 0x80) {
out.write(c); out.write(c);
return; return;
} }
if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){ if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF)) {
//No Surrogates in sun java //No Surrogates in sun java
out.write(0x3f); out.write(0x3f);
return; return;
@ -31,38 +56,41 @@ public class UtfHelpper {
int write; int write;
char ch; char ch;
if (c > 0x07FF) { if (c > 0x07FF) {
ch=(char)(c>>>12); ch = (char)(c>>>12);
write=0xE0; write = 0xE0;
if (ch>0) { if (ch > 0) {
write |= ( ch & 0x0F); write |= (ch & 0x0F);
} }
out.write(write); out.write(write);
write=0x80; write = 0x80;
bias=0x3F; bias = 0x3F;
} else { } else {
write=0xC0; write = 0xC0;
bias=0x1F; bias = 0x1F;
} }
ch=(char)(c>>>6); ch = (char)(c>>>6);
if (ch>0) { if (ch > 0) {
write|= (ch & bias); write |= (ch & bias);
} }
out.write(write); out.write(write);
out.write(0x80 | ((c) & 0x3F)); out.write(0x80 | ((c) & 0x3F));
} }
final static void writeStringToUtf8(final String str,final OutputStream out) throws IOException{ static final void writeStringToUtf8(
final int length=str.length(); final String str,
int i=0; final OutputStream out
) throws IOException{
final int length = str.length();
int i = 0;
char c; char c;
while (i<length) { while (i < length) {
c=str.charAt(i++); c = str.charAt(i++);
if (c < 0x80) { if (c < 0x80) {
out.write(c); out.write(c);
continue; continue;
} }
if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){ if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF)) {
//No Surrogates in sun java //No Surrogates in sun java
out.write(0x3f); out.write(0x3f);
continue; continue;
@ -71,21 +99,21 @@ public class UtfHelpper {
int bias; int bias;
int write; int write;
if (c > 0x07FF) { if (c > 0x07FF) {
ch=(char)(c>>>12); ch = (char)(c>>>12);
write=0xE0; write = 0xE0;
if (ch>0) { if (ch > 0) {
write |= ( ch & 0x0F); write |= (ch & 0x0F);
} }
out.write(write); out.write(write);
write=0x80; write = 0x80;
bias=0x3F; bias = 0x3F;
} else { } else {
write=0xC0; write = 0xC0;
bias=0x1F; bias = 0x1F;
} }
ch=(char)(c>>>6); ch = (char)(c>>>6);
if (ch>0) { if (ch > 0) {
write|= (ch & bias); write |= (ch & bias);
} }
out.write(write); out.write(write);
out.write(0x80 | ((c) & 0x3F)); out.write(0x80 | ((c) & 0x3F));
@ -93,63 +121,60 @@ public class UtfHelpper {
} }
} }
public final static byte[] getStringInUtf8(final String str) {
final int length=str.length(); public static final byte[] getStringInUtf8(final String str) {
boolean expanded=false; final int length = str.length();
byte []result=new byte[length]; boolean expanded = false;
int i=0; byte[] result = new byte[length];
int out=0; int i = 0;
int out = 0;
char c; char c;
while (i<length) { while (i < length) {
c=str.charAt(i++); c = str.charAt(i++);
if ( c < 0x80 ) { if (c < 0x80) {
result[out++]=(byte)c; result[out++] = (byte)c;
continue; continue;
} }
if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){ if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF)) {
//No Surrogates in sun java //No Surrogates in sun java
result[out++]=0x3f; result[out++] = 0x3f;
continue; continue;
} }
if (!expanded) { if (!expanded) {
byte newResult[]=new byte[3*length]; byte newResult[] = new byte[3*length];
System.arraycopy(result, 0, newResult, 0, out); System.arraycopy(result, 0, newResult, 0, out);
result=newResult; result = newResult;
expanded=true; expanded = true;
} }
char ch; char ch;
int bias; int bias;
byte write; byte write;
if (c > 0x07FF) { if (c > 0x07FF) {
ch=(char)(c>>>12); ch = (char)(c>>>12);
write=(byte)0xE0; write = (byte)0xE0;
if (ch>0) { if (ch > 0) {
write |= ( ch & 0x0F); write |= (ch & 0x0F);
} }
result[out++]=write; result[out++] = write;
write=(byte)0x80; write = (byte)0x80;
bias=0x3F; bias = 0x3F;
} else { } else {
write=(byte)0xC0; write = (byte)0xC0;
bias=0x1F; bias = 0x1F;
} }
ch=(char)(c>>>6); ch = (char)(c>>>6);
if (ch>0) { if (ch > 0) {
write|= (ch & bias); write |= (ch & bias);
} }
result[out++]=write; result[out++] = write;
result[out++]=(byte)(0x80 | ((c) & 0x3F));/**/ result[out++] = (byte)(0x80 | ((c) & 0x3F));
} }
if (expanded) { if (expanded) {
byte newResult[]=new byte[out]; byte newResult[] = new byte[out];
System.arraycopy(result, 0, newResult, 0, out); System.arraycopy(result, 0, newResult, 0, out);
result=newResult; result = newResult;
} }
return result; return result;
} }
} }

View File

@ -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 <code>String</code>s into <code>Node</code>s 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 <code>String</code> representation of the specified
* <code>Element</code>.
* <p/>
* Refer also to comments about setup of format.
*
* @param element the <code>Element</code> to serialize.
* @return the <code>String</code> representation of the serilaized
* <code>Element</code>.
* @throws Exception
*/
public String serialize(Element element) throws Exception {
return canonSerialize(element);
}
/**
* Returns a <code>byte[]</code> representation of the specified
* <code>Element</code>.
*
* @param element the <code>Element</code> to serialize.
* @return the <code>byte[]</code> representation of the serilaized
* <code>Element</code>.
* @throws Exception
*/
public byte[] serializeToByteArray(Element element) throws Exception {
return canonSerializeToByteArray(element);
}
/**
* Returns a <code>String</code> representation of the specified
* <code>NodeList</code>.
* <p/>
* This is a special case because the NodeList may represent a
* <code>DocumentFragment</code>. 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.
* <p/>
* 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.
* <p/>
* Refer also to comments about setup of format.
*
* @param content the <code>NodeList</code> to serialize.
* @return the <code>String</code> representation of the serialized
* <code>NodeList</code>.
* @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 <code>byte[]</code> representation of the specified
* <code>NodeList</code>.
*
* @param content the <code>NodeList</code> to serialize.
* @return the <code>byte[]</code> representation of the serialized
* <code>NodeList</code>.
* @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("<?xml version=\"1.0\" encoding=\"UTF-8\"?><dummy");
// Run through each node up to the document node and find any xmlns: nodes
Map<String, String> storedNamespaces = new HashMap<String, String>();
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("</dummy>");
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("<?xml version=\"1.0\" encoding=\"UTF-8\"?><dummy");
// Run through each node up to the document node and find any xmlns: nodes
Map<String, String> storedNamespaces = new HashMap<String, String>();
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 + "</dummy>");
return sb.toString();
}
}

View File

@ -2,30 +2,30 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.encryption; package com.sun.org.apache.xml.internal.security.encryption;
import java.util.Iterator; import java.util.Iterator;
import com.sun.org.apache.xml.internal.security.keys.KeyInfo; import com.sun.org.apache.xml.internal.security.keys.KeyInfo;
import org.w3c.dom.Element; import org.w3c.dom.Element;
/** /**
* A Key Agreement algorithm provides for the derivation of a shared secret key * 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 * based on a shared secret computed from certain types of compatible public
@ -79,9 +79,10 @@ import org.w3c.dom.Element;
* @author Axl Mattheus * @author Axl Mattheus
*/ */
public interface AgreementMethod { public interface AgreementMethod {
/** /**
* Returns an <code>byte</code> array. * Returns a <code>byte</code> array.
* @return * @return a <code>byte</code> array.
*/ */
byte[] getKANonce(); byte[] getKANonce();
@ -92,8 +93,8 @@ public interface AgreementMethod {
void setKANonce(byte[] kanonce); void setKANonce(byte[] kanonce);
/** /**
* Returns aditional information regarding the <code>AgreementMethod</code>. * Returns additional information regarding the <code>AgreementMethod</code>.
* @return * @return additional information regarding the <code>AgreementMethod</code>.
*/ */
Iterator<Element> getAgreementMethodInformation(); Iterator<Element> getAgreementMethodInformation();
@ -134,7 +135,7 @@ public interface AgreementMethod {
void setOriginatorKeyInfo(KeyInfo keyInfo); 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. * @return information relating to the recipient's shared secret.
*/ */

View File

@ -2,25 +2,26 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.encryption; package com.sun.org.apache.xml.internal.security.encryption;
/** /**
* <code>CipherData</code> provides encrypted data. It must either contain the * <code>CipherData</code> provides encrypted data. It must either contain the
* encrypted octet sequence as base64 encoded text of 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 * @author Axl Mattheus
*/ */
public interface CipherData { public interface CipherData {
/** VALUE_TYPE ASN */ /** VALUE_TYPE ASN */
public static final int VALUE_TYPE = 0x00000001; int VALUE_TYPE = 0x00000001;
/** REFERENCE_TYPE ASN */ /** REFERENCE_TYPE ASN */
public static final int REFERENCE_TYPE = 0x00000002; int REFERENCE_TYPE = 0x00000002;
/** /**
* Returns the type of encrypted data contained in the * Returns the type of encrypted data contained in the
@ -76,7 +79,7 @@ public interface CipherData {
* Returns a reference to an external location containing the encrypted * Returns a reference to an external location containing the encrypted
* octet sequence (<code>byte</code> array). * octet sequence (<code>byte</code> array).
* *
* @return the reference to an external location containing the enctrypted * @return the reference to an external location containing the encrypted
* octet sequence. * octet sequence.
*/ */
CipherReference getCipherReference(); CipherReference getCipherReference();
@ -84,10 +87,9 @@ public interface CipherData {
/** /**
* Sets the <code>CipherData</code>'s reference. * Sets the <code>CipherData</code>'s reference.
* *
* @param reference an external location containing the enctrypted octet * @param reference an external location containing the encrypted octet sequence.
* sequence.
* @throws XMLEncryptionException * @throws XMLEncryptionException
*/ */
void setCipherReference(CipherReference reference) throws void setCipherReference(CipherReference reference) throws XMLEncryptionException;
XMLEncryptionException;
} }

View File

@ -2,34 +2,34 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.encryption; package com.sun.org.apache.xml.internal.security.encryption;
import org.w3c.dom.Attr; import org.w3c.dom.Attr;
/** /**
* <code>CipherReference</code> identifies a source which, when processed, * <code>CipherReference</code> identifies a source which, when processed,
* yields the encrypted octet sequence. * yields the encrypted octet sequence.
* <p> * <p>
* The actual value is obtained as follows. The <code>CipherReference URI</code> * The actual value is obtained as follows. The <code>CipherReference URI</code>
* contains an identifier that is dereferenced. Should the * contains an identifier that is dereferenced. Should the
* <code>CipherReference</code> element contain an OPTIONAL sequence of
* Transforms, the data resulting from dereferencing the <code>URI</code> is * Transforms, the data resulting from dereferencing the <code>URI</code> is
* transformed as specified so as to yield the intended cipher value. For * transformed as specified so as to yield the intended cipher value. For
* example, if the value is base64 encoded within an XML document; the * example, if the value is base64 encoded within an XML document; the
@ -62,20 +62,21 @@ public interface CipherReference {
/** /**
* Returns an <code>URI</code> that contains an identifier that should be * Returns an <code>URI</code> that contains an identifier that should be
* dereferenced. * dereferenced.
* @return * @return an <code>URI</code> that contains an identifier that should be
* dereferenced.
*/ */
String getURI(); String getURI();
/** /**
* Gets the URI as an Attribute node. Used to meld the CipherREference * Gets the URI as an Attribute node. Used to meld the CipherReference
* with the XMLSignature ResourceResolvers * with the XMLSignature ResourceResolvers
* @return * @return the URI as an Attribute node
*/ */
public Attr getURIAsAttr(); Attr getURIAsAttr();
/** /**
* Returns the <code>Transforms</code> that specifies how to transform the * Returns the <code>Transforms</code> that specifies how to transform the
* <code>URI</code> to yield the appropiate cipher value. * <code>URI</code> to yield the appropriate cipher value.
* *
* @return the transform that specifies how to transform the reference to * @return the transform that specifies how to transform the reference to
* yield the intended cipher value. * yield the intended cipher value.
@ -84,10 +85,11 @@ public interface CipherReference {
/** /**
* Sets the <code>Transforms</code> that specifies how to transform the * Sets the <code>Transforms</code> that specifies how to transform the
* <code>URI</code> to yield the appropiate cipher value. * <code>URI</code> to yield the appropriate cipher value.
* *
* @param transforms the set of <code>Transforms</code> that specifies how * @param transforms the set of <code>Transforms</code> that specifies how
* to transform the reference to yield the intended cipher value. * to transform the reference to yield the intended cipher value.
*/ */
void setTransforms(Transforms transforms); void setTransforms(Transforms transforms);
} }

View File

@ -2,25 +2,26 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.encryption; package com.sun.org.apache.xml.internal.security.encryption;
/** /**
* <code>CipherValue</code> is the wrapper for cipher text. * <code>CipherValue</code> is the wrapper for cipher text.
* *
@ -28,20 +29,18 @@ package com.sun.org.apache.xml.internal.security.encryption;
*/ */
public interface CipherValue { public interface CipherValue {
/** /**
* Resturns the Base 64 encoded, encrypted octets that is the * Returns the Base 64 encoded, encrypted octets that is the
* <code>CihperValue</code>. * <code>CipherValue</code>.
* *
* @return cipher value. * @return cipher value.
*/ */
String getValue(); String getValue();
// byte[] getValue();
/** /**
* Sets the Base 64 encoded, encrypted octets that is the * Sets the Base 64 encoded, encrypted octets that is the
* <code>CihperValue</code>. * <code>CipherValue</code>.
* *
* @param value the cipher value. * @param value the cipher value.
*/ */
void setValue(String value); void setValue(String value);
// void setValue(byte[] value);
} }

View File

@ -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 <code>String</code>s into <code>Node</code>s 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);
}
}
}

View File

@ -2,25 +2,26 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.encryption; package com.sun.org.apache.xml.internal.security.encryption;
/** /**
* The <code>EncryptedData</code> element is the core element in the syntax. Not * The <code>EncryptedData</code> element is the core element in the syntax. Not
* only does its <code>CipherData</code> child contain the encrypted data, but * only does its <code>CipherData</code> child contain the encrypted data, but
@ -42,3 +43,4 @@ package com.sun.org.apache.xml.internal.security.encryption;
*/ */
public interface EncryptedData extends EncryptedType { public interface EncryptedData extends EncryptedType {
} }

View File

@ -2,26 +2,26 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * 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
* Licensed under the Apache License, Version 2.0 (the "License"); * distributed with this work for additional information
* you may not use this file except in compliance with the License. * regarding copyright ownership. The ASF licenses this file
* You may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing,
* distributed under the License is distributed on an "AS IS" BASIS, * software distributed under the License is distributed on an
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* See the License for the specific language governing permissions and * KIND, either express or implied. See the License for the
* limitations under the License. * specific language governing permissions and limitations
* * under the License.
*/ */
package com.sun.org.apache.xml.internal.security.encryption; package com.sun.org.apache.xml.internal.security.encryption;
/** /**
* The <code>EncryptedKey</code> element is used to transport encryption keys * The <code>EncryptedKey</code> element is used to transport encryption keys
* from the originator to a known recipient(s). It may be used as a stand-alone * 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 * @author Axl Mattheus
*/ */
public interface EncryptedKey extends EncryptedType { public interface EncryptedKey extends EncryptedType {
/** /**
* Returns a hint as to which recipient this encrypted key value is intended * Returns a hint as to which recipient this encrypted key value is intended for.
* for.
* *
* @return the recipient of the <code>EncryptedKey</code>. * @return the recipient of the <code>EncryptedKey</code>.
*/ */
@ -110,3 +110,4 @@ public interface EncryptedKey extends EncryptedType {
*/ */
void setCarriedName(String name); void setCarriedName(String name);
} }

Some files were not shown because too many files have changed in this diff Show More