├── java-csp-native ├── java-csp-platform-amd64-linux │ └── pom.xml ├── java-csp-platform-amd64-windows │ └── pom.xml ├── java-csp-platform-x86-linux │ └── pom.xml ├── java-csp-platform-x86-windows │ └── pom.xml ├── pom.xml └── src │ └── main │ └── native │ └── c │ └── csp │ ├── cspCipher.c │ ├── cspDigest.c │ ├── cspKey.c │ ├── cspKeyStore.c │ ├── cspProvider.h │ ├── cspSignature.c │ └── cspUtil.c ├── java-csp-provider-impl ├── pom.xml └── src │ ├── main │ └── java │ │ └── org │ │ └── company │ │ └── security │ │ └── csp │ │ ├── BundleNativeCode.java │ │ ├── CSPCertificateFactory.java │ │ ├── CSPCipher.java │ │ ├── CSPDigest.java │ │ ├── CSPKey.java │ │ ├── CSPKeyFactory.java │ │ ├── CSPKeyPair.java │ │ ├── CSPKeyStore.java │ │ ├── CSPNative.java │ │ ├── CSPPrivateKey.java │ │ ├── CSPProvider.java │ │ ├── CSPPublicKey.java │ │ ├── CSPSignature.java │ │ ├── KeyManagerFactoryImpl.java │ │ ├── KeyManagerImpl.java │ │ ├── NativeCrypto.java │ │ ├── NativeLibraryLoader.java │ │ ├── TrustManagerFactoryImpl.java │ │ ├── TrustManagerImpl.java │ │ └── parameter │ │ └── DigestParameterSpec.java │ └── test │ └── java │ └── org │ └── company │ └── security │ └── csp │ └── TestBundleNativeCode.java ├── java-csp-provider ├── pom.xml └── src │ └── test │ ├── java │ └── org │ │ └── company │ │ └── security │ │ └── csp │ │ ├── LoadNative.java │ │ ├── TestCertFactory.java │ │ ├── TestCipher.java │ │ ├── TestDigest.java │ │ ├── TestLoadKeyStore.java │ │ ├── TestLoadKeyStoreFromFile.java │ │ └── TestSignature.java │ └── resources │ ├── META-INF │ ├── cspprovider.properties │ └── hyjsse.properties │ ├── cert.sst │ └── log4j.properties ├── java-csp-wss4j ├── pom.xml └── src │ ├── main │ └── java │ │ └── org │ │ └── company │ │ └── security │ │ └── csp │ │ └── ws │ │ └── security │ │ ├── action │ │ └── LocalSignatureAction.java │ │ ├── components │ │ └── crypto │ │ │ ├── LocalAlgorithmSuiteValidator.java │ │ │ └── LocalMerlin.java │ │ ├── message │ │ └── LocalWSSecSignature.java │ │ └── processor │ │ └── LocalSignatureProcessor.java │ └── test │ ├── java │ └── org │ │ └── company │ │ └── security │ │ └── csp │ │ └── wss4j │ │ └── test │ │ ├── CXFGostTest.java │ │ ├── KeyStoreFileTest.java │ │ ├── LocalClient.java │ │ ├── LocalMerlinTest.java │ │ ├── LocalServer.java │ │ ├── WSS4JCallbackHandlerImpl.java │ │ └── hello_world_soap_http │ │ ├── FaultDetail.java │ │ ├── Greeter.java │ │ ├── GreeterServiceImpl.java │ │ ├── PingMeFault.java │ │ └── SOAPService.java │ └── resources │ ├── integration │ ├── helloWorld.wsdl │ └── test-application-context.xml │ ├── log4j.properties │ ├── receiver-crypto.properties │ ├── transmitter-crypto.properties │ └── trusted │ └── cert.sst ├── java-csp-xmlsec-jsr105 ├── pom.xml └── src │ ├── main │ └── java │ │ └── org │ │ └── company │ │ └── security │ │ └── csp │ │ └── xml │ │ ├── dsig │ │ └── internal │ │ │ └── dom │ │ │ ├── AbstractDOMSignatureMethod.java │ │ │ ├── ApacheCanonicalizer.java │ │ │ ├── ApacheData.java │ │ │ ├── ApacheNodeSetData.java │ │ │ ├── ApacheOctetStreamData.java │ │ │ ├── ApacheTransform.java │ │ │ ├── BaseStructure.java │ │ │ ├── DOMBase64Transform.java │ │ │ ├── DOMCanonicalXMLC14N11Method.java │ │ │ ├── DOMCanonicalXMLC14NMethod.java │ │ │ ├── DOMCanonicalizationMethod.java │ │ │ ├── DOMDigestMethod.java │ │ │ ├── DOMDigestMethodFactory.java │ │ │ ├── DOMDigestMethodProxy.java │ │ │ ├── DOMEnvelopedTransform.java │ │ │ ├── DOMExcC14NMethod.java │ │ │ ├── DOMHMACSignatureMethod.java │ │ │ ├── DOMKeyInfo.java │ │ │ ├── DOMKeyInfoFactory.java │ │ │ ├── DOMKeyName.java │ │ │ ├── DOMKeyValue.java │ │ │ ├── DOMManifest.java │ │ │ ├── DOMPGPData.java │ │ │ ├── DOMReference.java │ │ │ ├── DOMRetrievalMethod.java │ │ │ ├── DOMSignatureMethod.java │ │ │ ├── DOMSignatureProperties.java │ │ │ ├── DOMSignatureProperty.java │ │ │ ├── DOMSignedInfo.java │ │ │ ├── DOMStructure.java │ │ │ ├── DOMSubTreeData.java │ │ │ ├── DOMTransform.java │ │ │ ├── DOMURIDereferencer.java │ │ │ ├── DOMUtils.java │ │ │ ├── DOMX509Data.java │ │ │ ├── DOMX509IssuerSerial.java │ │ │ ├── DOMXMLObject.java │ │ │ ├── DOMXMLSignature.java │ │ │ ├── DOMXMLSignatureFactory.java │ │ │ ├── DOMXPathFilter2Transform.java │ │ │ ├── DOMXPathTransform.java │ │ │ ├── DOMXSLTTransform.java │ │ │ ├── Marshaller.java │ │ │ ├── Utils.java │ │ │ ├── XMLDSigRI.java │ │ │ ├── XmlWriter.java │ │ │ └── XmlWriterToTree.java │ │ └── security │ │ ├── exceptions │ │ └── Base64DecodingException.java │ │ └── utils │ │ └── Base64.java │ └── test │ ├── java │ └── org │ │ └── company │ │ └── security │ │ └── csp │ │ └── xml │ │ └── dsig │ │ └── test │ │ ├── PhaosXMLDSig3Test.java-t │ │ ├── SignTest.java │ │ └── SignatureValidator.java-t │ └── resources │ ├── log4j.properties │ └── signature-enveloping-gost-template.xml ├── java-csp-xmlsec-santuario ├── pom.xml └── src │ └── main │ └── java │ └── org │ └── company │ └── security │ └── csp │ └── xml │ └── security │ ├── XmlDSignTools.java │ └── algorithms │ ├── SignatureGostR34102001.java │ ├── SignatureGostR34102001Gostr3411.java │ └── SignatureGostR34102001URN.java ├── parent └── pom.xml └── pom.xml /java-csp-native/java-csp-platform-amd64-linux/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | 4 | 5 | org.company.security.csp 6 | java-csp-native 7 | 1.0.0-SNAPSHOT 8 | 9 | 10 | java-csp-platform 11 | Java CSP Security Provider Native amd64 Linux 12 | so 13 | 14 | 15 | /opt/cprocsp 16 | -I${csp.path}/include -I${csp.path}/include/cpcsp -I${build.path}/native 17 | -L${csp.path}/lib/amd64 -lcapi20 -lcapi10 -lssp -lasn1data -m64 18 | ${include.params} -DUNIX -O3 -Wall -c -fmessage-length=0 -fPIC -m64 19 | 20 | 21 | 22 | 23 | 24 | org.codehaus.mojo 25 | native-maven-plugin 26 | true 27 | 28 | linux 29 | 30 | 31 | ${commonCompilerOptions} 32 | 33 | 34 | 35 | -L${csp.path}/lib/amd64 -shared -m64 36 | 37 | 38 | -lcapi20 -lcapi10 -lssp -lasn1data 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | ${project.groupId} 48 | java-csp-provider-impl 49 | ${project.version} 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /java-csp-native/java-csp-platform-amd64-windows/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | 4 | 5 | org.company.security.csp 6 | java-csp-native 7 | 1.0.0-SNAPSHOT 8 | 9 | 10 | java-csp-platform 11 | Java CSP Security Provider Native amd64 Windows 12 | dll 13 | 14 | 15 | C:/Program Files/Crypto Pro/SDK 16 | -I"${csp.path}/include" -I${build.path}/native 17 | ${include.params} /O1 /Gr /LD /TC 18 | 19 | 20 | 21 | 22 | 23 | org.codehaus.mojo 24 | native-maven-plugin 25 | true 26 | 27 | msvc 28 | org.codehaus.mojo.natives.msvc.MSVC2008x86EnvFactory 29 | win32 30 | 31 | 32 | ${commonCompilerOptions} 33 | 34 | 35 | 36 | /OPT:NOWIN98 /DLL /MACHINE:X86 37 | -L"${csp.path}/lib" 38 | 39 | 40 | user32.lib advapi32.lib oldnames.lib kernel32.lib crypt32.lib 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | ${project.groupId} 50 | java-csp-provider-impl 51 | ${project.version} 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /java-csp-native/java-csp-platform-x86-linux/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | 4 | 5 | org.company.security.csp 6 | java-csp-native 7 | 1.0.0-SNAPSHOT 8 | 9 | 10 | java-csp-platform 11 | Java CSP Security Provider Native x86 Linux 12 | so 13 | 14 | 15 | /opt/cprocsp 16 | -I${csp.path}/include -I${csp.path}/include/cpcsp -I${build.path}/native 17 | -L${csp.path}/lib/amd64 -lcapi20 -lcapi10 -lssp -lasn1data -m32 18 | ${include.params} -DUNIX -O3 -Wall -c -fmessage-length=0 -fPIC -m32 19 | 20 | 21 | 22 | 23 | 24 | org.codehaus.mojo 25 | native-maven-plugin 26 | true 27 | 28 | linux 29 | 30 | 31 | ${commonCompilerOptions} 32 | 33 | 34 | 35 | -L${csp.path}/lib/amd64 -shared -m64 36 | 37 | 38 | -lcapi20 -lcapi10 -lssp -lasn1data 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | ${project.groupId} 48 | java-csp-provider-impl 49 | ${project.version} 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /java-csp-native/java-csp-platform-x86-windows/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | 4 | 5 | org.company.security.csp 6 | java-csp-native 7 | 1.0.0-SNAPSHOT 8 | 9 | 10 | java-csp-platform 11 | Java CSP Security Provider Native x86 Windows 12 | dll 13 | 14 | 15 | C:/Program Files/Crypto Pro/SDK 16 | -I"${csp.path}/include" -I${build.path}/native 17 | ${include.params} /O1 /Gr /LD /TC /DDEBUG 18 | 19 | 20 | 21 | 22 | 23 | org.codehaus.mojo 24 | native-maven-plugin 25 | true 26 | 27 | msvc 28 | org.codehaus.mojo.natives.msvc.MSVC2008x86EnvFactory 29 | win32 30 | 31 | 32 | ${commonCompilerOptions} 33 | 34 | 35 | 36 | /OPT:NOWIN98 /DLL /MACHINE:X86 37 | -L"${csp.path}/lib" 38 | 39 | 40 | user32.lib advapi32.lib oldnames.lib kernel32.lib crypt32.lib 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | ${project.groupId} 50 | java-csp-provider-impl 51 | ${project.version} 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /java-csp-native/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | 4 | 5 | org.company.security.csp 6 | parent 7 | 1.0.0-SNAPSHOT 8 | ../parent 9 | 10 | 11 | java-csp-native 12 | Java CSP Native platform 13 | pom 14 | 15 | 16 | ${java.home} 17 | ${java.os.path}/../include 18 | 19 | 20 | 21 | 22 | 23 | java-csp-platform-${javaOS.arch}-${javaOS} 24 | 25 | 26 | 27 | 28 | 29 | 30 | org.codehaus.mojo 31 | native-maven-plugin 32 | 1.0-alpha-7 33 | true 34 | 35 | 36 | org.company.security.csp.NativeCrypto 37 | 38 | 39 | 40 | 41 | ../src/main/native/c/csp 42 | 43 | **/*.c 44 | 45 | 46 | 47 | 48 | ${javaOS.arch}-${javaOS} 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | amd64-Linux 58 | 59 | 60 | Linux 61 | amd64 62 | 63 | 64 | 65 | linux 66 | amd64 67 | 68 | 69 | 70 | 71 | x86-Linux 72 | 73 | 74 | Linux 75 | i386 76 | 77 | 78 | 79 | linux 80 | x86 81 | 82 | 83 | 84 | 85 | amd64-Windows 86 | 87 | 88 | Windows 89 | amd64 90 | 91 | 92 | 93 | windows 94 | amd64 95 | 96 | 97 | 98 | 99 | x86-Windows 100 | 101 | 102 | Windows 103 | x86 104 | 105 | 106 | 107 | windows 108 | x86 109 | 110 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /java-csp-native/src/main/native/c/csp/cspCipher.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | /* 18 | * cspCipher.c 19 | * 20 | * Author: alexey 21 | */ 22 | #include "cspProvider.h" 23 | #include "org_company_security_csp_NativeCrypto.h" 24 | 25 | /* 26 | * Class: org_company_security_csp_NativeCrypto 27 | * Method: encryptDecrypt 28 | * Signature: ([BIJJZ)[B 29 | */ 30 | JNIEXPORT jbyteArray JNICALL Java_org_company_security_csp_NativeCrypto_encryptDecrypt( 31 | JNIEnv *env, jclass clazz, 32 | jbyteArray jData, jint jDataOffset, jint jDataSize, 33 | jlong hKey, jboolean doEncrypt, jboolean doFinal, 34 | jint jPaddingLength) { 35 | jbyteArray result = NULL; 36 | jbyte* pData = NULL; 37 | DWORD dwDataLen = (DWORD) jDataSize; 38 | DWORD dwBufLen = dwDataLen; 39 | DWORD i; 40 | BYTE tmp; 41 | HCRYPTKEY hDuplicateKey = (HCRYPTKEY) NULL; 42 | DWORD dwOffset; 43 | 44 | { 45 | if (! CryptDuplicateKey(hKey, NULL, 0, &hDuplicateKey)) { 46 | #ifdef DEBUG 47 | fprintf(stderr, "error CryptDuplicateKey\n"); 48 | #endif 49 | ThrowException(env, INVALID_KEY_EXCEPTION, GetLastError()); 50 | goto _m_leave; 51 | } 52 | 53 | if(jPaddingLength <= 0) 54 | jPaddingLength = 512; 55 | 56 | dwOffset = dwDataLen % jPaddingLength; 57 | if(dwOffset) 58 | dwBufLen = dwDataLen - dwOffset + jPaddingLength; 59 | 60 | // Copy data from Java buffer to native buffer 61 | pData = (jbyte*) malloc(dwBufLen); 62 | (*env)->GetByteArrayRegion(env, jData, jDataOffset, jDataSize, pData); 63 | 64 | if (doEncrypt == JNI_TRUE) { 65 | // encrypt 66 | if (! CryptEncrypt((HCRYPTKEY) hDuplicateKey, 0, doFinal, 0, (BYTE *)pData, 67 | &dwDataLen, dwBufLen)) { 68 | 69 | #ifdef DEBUG 70 | fprintf(stderr, "error CryptEncrypt %x\n", GetLastError()); 71 | #endif 72 | ThrowException(env, INVALID_KEY_EXCEPTION, GetLastError()); 73 | goto _m_leave; 74 | } 75 | dwBufLen = dwDataLen; 76 | 77 | // convert from little-endian 78 | for (i = 0; i < dwBufLen / 2; i++) { 79 | tmp = pData[i]; 80 | pData[i] = pData[dwBufLen - i -1]; 81 | pData[dwBufLen - i - 1] = tmp; 82 | } 83 | } else { 84 | // convert to little-endian 85 | for (i = 0; i < dwBufLen / 2; i++) { 86 | tmp = pData[i]; 87 | pData[i] = pData[dwBufLen - i -1]; 88 | pData[dwBufLen - i - 1] = tmp; 89 | } 90 | 91 | // decrypt 92 | if (! CryptDecrypt((HCRYPTKEY) hKey, 0, TRUE, 0, (BYTE *)pData, &dwBufLen)) { 93 | 94 | #ifdef DEBUG 95 | fprintf(stderr, "error CryptDecrypt %x\n", GetLastError()); 96 | #endif 97 | ThrowException(env, INVALID_KEY_EXCEPTION, GetLastError()); 98 | goto _m_leave; 99 | } 100 | } 101 | 102 | // Create new byte array 103 | result = (*env)->NewByteArray(env, dwBufLen); 104 | 105 | // Copy data from native buffer to Java buffer 106 | (*env)->SetByteArrayRegion(env, result, 0, dwBufLen, (jbyte*) pData); 107 | } 108 | _m_leave: 109 | { 110 | if (pData) 111 | free(pData); 112 | 113 | if (hDuplicateKey) 114 | CryptDestroyKey(hDuplicateKey); 115 | } 116 | 117 | return result; 118 | } 119 | 120 | 121 | -------------------------------------------------------------------------------- /java-csp-native/src/main/native/c/csp/cspDigest.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | /* 18 | * cspDigest.c 19 | * 20 | * Author: Alexey 21 | */ 22 | #include "cspProvider.h" 23 | #include "org_company_security_csp_NativeCrypto.h" 24 | 25 | /* 26 | * Class: org_company_security_csp_NativeCrypto 27 | * Method: digestInit 28 | * Signature: (Lorg/company/security/csp/CSPDigest;Ljava/lang/String;)V 29 | */ 30 | JNIEXPORT void JNICALL Java_org_company_security_csp_NativeCrypto_digestInit( 31 | JNIEnv *env, jclass clazz, jobject jMessageDigest, jstring jHashAlgorithm) { 32 | 33 | HCRYPTPROV hCryptProv = (HCRYPTPROV) NULL; 34 | HCRYPTHASH hCryptHash = (HCRYPTHASH) NULL; 35 | DWORD dwBlockSize; 36 | BOOL result = FALSE; 37 | 38 | { 39 | ALG_ID algId = MapHashAlgorithm(env, jHashAlgorithm); 40 | DWORD dwProvId; 41 | jclass clazzCSPDigest; 42 | jmethodID mCSPPublicKeyInit; 43 | 44 | if(! FindProviderByAlg(env, NULL, algId, &dwProvId, &dwBlockSize)) { 45 | goto _m_leave; 46 | } 47 | 48 | if(! CryptAcquireContext(&hCryptProv, NULL, NULL, dwProvId, CRYPT_VERIFYCONTEXT)) { 49 | ThrowException(env, PROVIDER_EXCEPTION, GetLastError()); 50 | goto _m_leave; 51 | } 52 | 53 | // выделяем контекст хеш функции 54 | if(! CryptCreateHash(hCryptProv, algId, 0, 0, &hCryptHash)) { 55 | ThrowException(env, DIGEST_EXCEPTION, GetLastError()); 56 | goto _m_leave; 57 | } 58 | 59 | // Get the method ID for the CSPPublicKey constructor 60 | clazzCSPDigest = 61 | (*env)->FindClass(env, "org/company/security/csp/CSPDigest"); 62 | 63 | mCSPPublicKeyInit = 64 | (*env)->GetMethodID(env, clazzCSPDigest, "initDigest", "(JJI)V"); 65 | 66 | // Create a new CSP public key 67 | (*env)->CallVoidMethod(env, jMessageDigest, mCSPPublicKeyInit, 68 | (jlong) hCryptProv, (jlong) hCryptHash, (jint) dwBlockSize); 69 | 70 | result = TRUE; 71 | } 72 | _m_leave: 73 | { 74 | if(! result) { 75 | if (hCryptHash) 76 | CryptDestroyHash((HCRYPTHASH) hCryptHash); 77 | 78 | if(hCryptProv) 79 | CryptReleaseContext((HCRYPTPROV) hCryptProv, 0); 80 | } 81 | } 82 | } 83 | /* 84 | * Class: org_company_security_csp_NativeCrypto 85 | * Method: digestDestroy 86 | * Signature: (JJ)V 87 | */ 88 | JNIEXPORT void JNICALL Java_org_company_security_csp_NativeCrypto_digestDestroy( 89 | JNIEnv *env, jclass clazz, jlong hCryptProv, jlong hCryptHash) { 90 | 91 | if (hCryptHash) 92 | CryptDestroyHash((HCRYPTHASH) hCryptHash); 93 | 94 | if(hCryptProv) 95 | CryptReleaseContext((HCRYPTPROV) hCryptProv, 0); 96 | } 97 | 98 | /* 99 | * Class: org_company_security_csp_NativeCrypto 100 | * Method: digestEngineUpdateByte 101 | * Signature: (JB)V 102 | */ 103 | JNIEXPORT void JNICALL Java_org_company_security_csp_NativeCrypto_digestEngineUpdateByte( 104 | JNIEnv *env, jclass clazz, jlong hCryptHash, jbyte jByte) { 105 | 106 | if(hCryptHash) { 107 | BYTE buffer[1]; 108 | buffer[0] = (BYTE) jByte; 109 | 110 | if(! CryptHashData((HCRYPTHASH) hCryptHash, buffer, 1, 0)) { 111 | ThrowException(env, DIGEST_EXCEPTION, GetLastError()); 112 | } 113 | } 114 | } 115 | 116 | /* 117 | * Class: org_company_security_csp_NativeCrypto 118 | * Method: digestEngineUpdateBytes 119 | * Signature: (J[BII)V 120 | */ 121 | JNIEXPORT void JNICALL Java_org_company_security_csp_NativeCrypto_digestEngineUpdateBytes( 122 | JNIEnv *env, jclass clazz, jlong hCryptHash, jbyteArray jBytes, jint offset, jint len) { 123 | 124 | if(hCryptHash) { 125 | jbyte *buffer = (jbyte*) malloc(len * sizeof(jbyte)); 126 | (*env)->GetByteArrayRegion(env, jBytes, offset, len, buffer); 127 | 128 | if(!CryptHashData((HCRYPTHASH) hCryptHash, (BYTE*) buffer, len, 0)) { 129 | ThrowException(env, DIGEST_EXCEPTION, GetLastError()); 130 | } 131 | 132 | free(buffer); 133 | } 134 | } 135 | 136 | /* 137 | * Class: org_company_security_csp_NativeCrypto 138 | * Method: digestEngineDigest 139 | * Signature: (J)[B 140 | */ 141 | JNIEXPORT jbyteArray JNICALL Java_org_company_security_csp_NativeCrypto_digestEngineDigest( 142 | JNIEnv *env, jclass clazz, jlong hCryptHash) { 143 | 144 | jbyteArray buffer = NULL; 145 | BYTE *rgbHash = NULL; 146 | 147 | { 148 | DWORD cbSize; 149 | DWORD cbSizeLen = sizeof(DWORD); 150 | 151 | if(!CryptGetHashParam((HCRYPTHASH) hCryptHash, HP_HASHSIZE, (BYTE *) &cbSize, &cbSizeLen, 0)) { 152 | ThrowException(env, DIGEST_EXCEPTION, GetLastError()); 153 | goto _m_leave; 154 | } 155 | 156 | rgbHash = (BYTE*) malloc(cbSize); 157 | 158 | if(! CryptGetHashParam((HCRYPTHASH) hCryptHash, HP_HASHVAL, rgbHash, &cbSize, 0)) { 159 | ThrowException(env, DIGEST_EXCEPTION, GetLastError()); 160 | goto _m_leave; 161 | } 162 | 163 | buffer = (*env)->NewByteArray(env, cbSize); 164 | 165 | if(buffer) 166 | (*env)->SetByteArrayRegion(env, buffer, 0, cbSize, (jbyte *) rgbHash); 167 | } 168 | _m_leave: 169 | { 170 | if(rgbHash) 171 | free(rgbHash); 172 | } 173 | return buffer; 174 | } 175 | 176 | JNIEXPORT void JNICALL Java_org_company_security_csp_NativeCrypto_digestSetParameter( 177 | JNIEnv *env, jclass clazz, jlong hCryptHash, jint param, jbyteArray jBytes, jint offset, jint len) { 178 | 179 | if(hCryptHash) { 180 | jbyte *buffer = (jbyte*) malloc(len * sizeof(jbyte)); 181 | (*env)->GetByteArrayRegion(env, jBytes, offset, len, buffer); 182 | 183 | if(!CryptSetHashParam((HCRYPTHASH) hCryptHash, (DWORD) param, (BYTE*) buffer, 0)) { 184 | ThrowException(env, DIGEST_EXCEPTION, GetLastError()); 185 | } 186 | 187 | free(buffer); 188 | } 189 | } 190 | 191 | -------------------------------------------------------------------------------- /java-csp-native/src/main/native/c/csp/cspProvider.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | /* 18 | * cspProvider.h 19 | * 20 | * Author: alexey 21 | */ 22 | 23 | #ifndef CSPPROVIDER_H_ 24 | #define CSPPROVIDER_H_ 25 | 26 | #include 27 | #include 28 | #if ( __WORDSIZE == 64 ) 29 | # define SIZEOF_VOID_P 8 30 | #else 31 | # define SIZEOF_VOID_P 4 32 | #endif 33 | 34 | #ifdef _WIN32 35 | # include 36 | # include 37 | #else 38 | # include 39 | # include 40 | # include 41 | # include 42 | #endif 43 | #include 44 | #include 45 | 46 | #define OID_EKU_ANY "2.5.29.37.0" 47 | 48 | #define CERTIFICATE_PARSING_EXCEPTION \ 49 | "java/security/cert/CertificateParsingException" 50 | #define DIGEST_EXCEPTION "java/security/DigestException" 51 | #define INVALID_KEY_EXCEPTION \ 52 | "java/security/InvalidKeyException" 53 | #define INVALID_KEYSPEC_EXCEPTION \ 54 | "InvalidKeySpecException" 55 | //#define KEY_EXCEPTION "java/security/KeyException" 56 | #define KEYSTORE_EXCEPTION "java/security/KeyStoreException" 57 | #define PROVIDER_EXCEPTION "java/security/ProviderException" 58 | #define SIGNATURE_EXCEPTION "java/security/SignatureException" 59 | #define NOSUCHALGORITHM_EXCEPTION \ 60 | "java/security/NoSuchAlgorithmException" 61 | 62 | /* 63 | * Throws an arbitrary Java exception. 64 | * The exception message is a Windows system error message. 65 | */ 66 | void ThrowException(JNIEnv *env, char *exceptionName, DWORD dwError); 67 | 68 | /* 69 | * Maps the name of a hash algorithm to an algorithm identifier. 70 | */ 71 | ALG_ID MapHashAlgorithm(JNIEnv *env, jstring jAlgorithm); 72 | 73 | ALG_ID MapSignAlgorithm(JNIEnv *env, jstring jAlgorithm); 74 | 75 | ALG_ID MapEncryptAlgorithm(JNIEnv *env, jstring jAlgorithm); 76 | 77 | ALG_ID MapExchangeAlgorithm(JNIEnv *env, jstring jAlgorithm); 78 | 79 | BOOL FindProviderByAlg(JNIEnv *env, const char* pszAlgOID, ALG_ID algId, DWORD *pdwProvId, DWORD *pdwBitLen); 80 | 81 | #endif /* CSPPROVIDER_H_ */ 82 | -------------------------------------------------------------------------------- /java-csp-provider-impl/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | 4 | 5 | org.company.security.csp 6 | parent 7 | 1.0.0-SNAPSHOT 8 | ../parent 9 | 10 | 11 | java-csp-provider-impl 12 | Java CSP Security Provider implementatin 13 | jar 14 | 15 | 16 | 17 | org.slf4j 18 | slf4j-api 19 | 20 | 21 | org.bouncycastle 22 | bcprov-jdk15on 23 | 24 | 25 | org.slf4j 26 | slf4j-log4j12 27 | test 28 | 29 | 30 | junit 31 | junit 32 | test 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /java-csp-provider-impl/src/main/java/org/company/security/csp/CSPCertificateFactory.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp; 18 | 19 | import java.io.InputStream; 20 | import java.security.cert.CRL; 21 | import java.security.cert.CRLException; 22 | import java.security.cert.Certificate; 23 | import java.security.cert.CertificateException; 24 | import java.security.cert.CertificateFactorySpi; 25 | import java.util.Collection; 26 | 27 | /** 28 | * На самом деле, всё управление передается в BouncyCastle 29 | * 30 | * @author Aleksey 31 | */ 32 | public class CSPCertificateFactory extends CertificateFactorySpi { 33 | private org.bouncycastle.jcajce.provider.asymmetric.x509.CertificateFactory delegate = 34 | new org.bouncycastle.jcajce.provider.asymmetric.x509.CertificateFactory(); 35 | 36 | @Override 37 | public Certificate engineGenerateCertificate(InputStream inStream) throws CertificateException { 38 | return delegate.engineGenerateCertificate(inStream); 39 | } 40 | 41 | @SuppressWarnings("unchecked") 42 | @Override 43 | public Collection engineGenerateCertificates(InputStream inStream) throws CertificateException { 44 | return delegate.engineGenerateCertificates(inStream); 45 | } 46 | 47 | @Override 48 | public CRL engineGenerateCRL(InputStream inStream) throws CRLException { 49 | return delegate.engineGenerateCRL(inStream); 50 | } 51 | 52 | @SuppressWarnings("unchecked") 53 | @Override 54 | public Collection engineGenerateCRLs(InputStream inStream) throws CRLException { 55 | return delegate.engineGenerateCRLs(inStream); 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /java-csp-provider-impl/src/main/java/org/company/security/csp/CSPDigest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp; 18 | 19 | import java.security.DigestException; 20 | import java.security.GeneralSecurityException; 21 | import java.security.MessageDigestSpi; 22 | 23 | 24 | public abstract class CSPDigest extends MessageDigestSpi { 25 | 26 | public static class GOST3411 extends CSPDigest { 27 | 28 | public GOST3411() { 29 | super("GOST3411"); 30 | } 31 | } 32 | 33 | public static class GOST3411_SafeTouch extends CSPDigest { 34 | 35 | public GOST3411_SafeTouch() { 36 | super("GOST3411"); 37 | } 38 | 39 | @Override 40 | public void initDigest(long hCryptoProvider, long hCryptoHash, int length) { 41 | super.initDigest(hCryptoProvider, hCryptoHash, length); 42 | 43 | // включаем отображение данных на экране 44 | } 45 | 46 | } 47 | 48 | protected final String algorithm; 49 | protected long hCryptoProvider = 0; 50 | protected long hCryptoHash = 0; 51 | protected int length; 52 | private boolean init = false; 53 | 54 | public CSPDigest(String algorithm) { 55 | this.algorithm = algorithm; 56 | } 57 | 58 | private void engineInit() { 59 | if(!init) { 60 | synchronized (this) { 61 | if(!init) { 62 | try { 63 | NativeCrypto.digestInit(this, algorithm); 64 | } catch (GeneralSecurityException e) { 65 | throw new IllegalArgumentException(e.getMessage(), e); 66 | } 67 | } 68 | } 69 | } 70 | } 71 | 72 | /** 73 | * Вызывается из {@link NativeCrypto#digestInit(CSPDigest, String)} 74 | * 75 | * @param hCryptoProvider нативный крипто провайдер 76 | * @param hCryptoHash нативный крипто хеш 77 | * @param length размер хеша в битах 78 | */ 79 | public void initDigest(long hCryptoProvider, long hCryptoHash, int length) { 80 | this.hCryptoProvider = hCryptoProvider; 81 | this.hCryptoHash = hCryptoHash; 82 | this.length = length; 83 | this.init = hCryptoHash != 0; 84 | } 85 | 86 | @Override 87 | protected void finalize() throws Throwable { 88 | try { 89 | synchronized(this) { 90 | destroy(); 91 | } 92 | } 93 | finally { 94 | super.finalize(); 95 | } 96 | } 97 | 98 | public void destroy() { 99 | NativeCrypto.digestDestroy(hCryptoProvider, hCryptoHash); 100 | hCryptoHash = 0; 101 | hCryptoProvider = 0; 102 | init = false; 103 | } 104 | 105 | @Override 106 | protected void engineUpdate(byte input) { 107 | engineInit(); 108 | try { 109 | NativeCrypto.digestEngineUpdateByte(hCryptoHash, input); 110 | } catch (DigestException e) { 111 | throw new IllegalStateException(e.getMessage(), e); 112 | } 113 | } 114 | 115 | @Override 116 | protected void engineUpdate(byte[] input, int offset, int len) { 117 | engineInit(); 118 | try { 119 | NativeCrypto.digestEngineUpdateBytes(hCryptoHash, input, offset, len); 120 | } catch (DigestException e) { 121 | throw new IllegalStateException(e.getMessage(), e); 122 | } 123 | } 124 | 125 | @Override 126 | protected byte[] engineDigest() { 127 | engineInit(); 128 | try { 129 | return NativeCrypto.digestEngineDigest(hCryptoHash); 130 | } catch (DigestException e) { 131 | throw new IllegalStateException(e.getMessage(), e); 132 | } 133 | } 134 | 135 | @Override 136 | protected void engineReset() { 137 | destroy(); 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /java-csp-provider-impl/src/main/java/org/company/security/csp/CSPKey.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp; 18 | 19 | import java.security.KeyStoreException; 20 | 21 | abstract class CSPKey implements java.security.Key { 22 | private static final long serialVersionUID = 4852829008747501367L; 23 | 24 | protected long hCryptProvider = 0; 25 | protected long hCryptKey = 0; 26 | protected int keyLength = 0; 27 | /** 28 | * Название контейнера, в котором находится ключ 29 | */ 30 | protected String container; 31 | /** 32 | * Идентификатор провайдера 33 | */ 34 | protected int providerId; 35 | 36 | public CSPKey(long hCryptoProvider, long hCryptoKey, int keyLength) { 37 | this.hCryptProvider = hCryptoProvider; 38 | this.hCryptKey = hCryptoKey; 39 | this.keyLength = keyLength; 40 | } 41 | 42 | @Override 43 | protected void finalize() throws Throwable { 44 | try { 45 | synchronized(this) { 46 | destroy(); 47 | } 48 | } 49 | finally { 50 | super.finalize(); 51 | } 52 | } 53 | 54 | public void destroy() { 55 | NativeCrypto.keyDestroy(hCryptProvider, hCryptKey); 56 | hCryptKey = 0; 57 | hCryptProvider = 0; 58 | } 59 | 60 | public int length() { 61 | return keyLength; 62 | } 63 | 64 | /** 65 | * native HCRYPTPROV 66 | */ 67 | public long getHCryptProvider() { 68 | return hCryptProvider; 69 | } 70 | 71 | /** 72 | * native HCRYPTKEY 73 | */ 74 | public long getHCryptKey() { 75 | return hCryptKey; 76 | } 77 | 78 | @Override 79 | public abstract String getAlgorithm(); 80 | 81 | @Override 82 | public String getFormat() { 83 | return null; 84 | } 85 | 86 | @Override 87 | public byte[] getEncoded() { 88 | return null; 89 | } 90 | 91 | public String getContainer() { 92 | return container; 93 | } 94 | 95 | public void setContainer(String container) { 96 | this.container = container; 97 | } 98 | 99 | public int getProviderId() { 100 | return providerId; 101 | } 102 | 103 | public void setProviderId(int providerId) { 104 | this.providerId = providerId; 105 | } 106 | 107 | protected static String getContainerName(long hCryptoProv) throws KeyStoreException { 108 | return NativeCrypto.getContainerName(hCryptoProv); 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /java-csp-provider-impl/src/main/java/org/company/security/csp/CSPKeyFactory.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp; 18 | 19 | import java.security.InvalidKeyException; 20 | import java.security.Key; 21 | import java.security.KeyException; 22 | import java.security.KeyFactorySpi; 23 | import java.security.NoSuchAlgorithmException; 24 | import java.security.PrivateKey; 25 | import java.security.PublicKey; 26 | import java.security.spec.InvalidKeySpecException; 27 | import java.security.spec.KeySpec; 28 | import java.security.spec.X509EncodedKeySpec; 29 | 30 | abstract class CSPKeyFactory extends KeyFactorySpi { 31 | private final String algorithm; 32 | 33 | // public static class GOST3410 extends CSPKeyFactory { 34 | // 35 | // public GOST3410() { 36 | // super("GOST3410"); 37 | // } 38 | // } 39 | 40 | public static class GOST3410EL extends CSPKeyFactory { 41 | 42 | public GOST3410EL() { 43 | super("GOST3410EL"); 44 | } 45 | } 46 | 47 | // public static class GOST3410DH extends CSPKeyFactory { 48 | // 49 | // public GOST3410DH() { 50 | // super("GOST3410DH"); 51 | // } 52 | // } 53 | 54 | public static class GOST3410DHEL extends CSPKeyFactory { 55 | 56 | public GOST3410DHEL() { 57 | super("GOST3410DHEL"); 58 | } 59 | } 60 | 61 | public CSPKeyFactory(String algorithm) { 62 | this.algorithm = algorithm; 63 | } 64 | 65 | @Override 66 | protected PublicKey engineGeneratePublic(KeySpec keySpec) 67 | throws InvalidKeySpecException { 68 | 69 | if(keySpec instanceof X509EncodedKeySpec) { 70 | byte[] encoded = ((X509EncodedKeySpec) keySpec).getEncoded(); 71 | try { 72 | return NativeCrypto.initPublicKey(encoded, encoded.length); 73 | } catch (InvalidKeyException e) { 74 | throw new InvalidKeySpecException(e.getMessage(), e); 75 | } catch (NoSuchAlgorithmException e) { 76 | throw new InvalidKeySpecException(e.getMessage(), e); 77 | } 78 | } 79 | else 80 | throw new InvalidKeySpecException("Use only X509EncodedKeySpec"); 81 | } 82 | 83 | @Override 84 | protected PrivateKey engineGeneratePrivate(KeySpec keySpec) 85 | throws InvalidKeySpecException { 86 | 87 | return null; 88 | } 89 | 90 | @Override 91 | protected T engineGetKeySpec(Key key, Class keySpec) 92 | throws InvalidKeySpecException { 93 | 94 | return null; 95 | } 96 | 97 | @Override 98 | protected Key engineTranslateKey(Key key) throws InvalidKeyException { 99 | 100 | return null; 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /java-csp-provider-impl/src/main/java/org/company/security/csp/CSPKeyPair.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp; 18 | 19 | public class CSPKeyPair { 20 | private final CSPPrivateKey privateKey; 21 | private final CSPPublicKey publicKey; 22 | 23 | public CSPKeyPair(long hCryptoProvider, long hCryptoKey, int keyLength) { 24 | privateKey = new CSPPrivateKey(hCryptoProvider, hCryptoKey, keyLength); 25 | publicKey = new CSPPublicKey(hCryptoProvider, hCryptoKey, keyLength); 26 | } 27 | 28 | public CSPPrivateKey getPrivateKey() { 29 | return privateKey; 30 | } 31 | 32 | public CSPPublicKey getPublicKey() { 33 | return publicKey; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /java-csp-provider-impl/src/main/java/org/company/security/csp/CSPPrivateKey.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp; 18 | 19 | import java.io.IOException; 20 | import java.security.InvalidKeyException; 21 | 22 | import org.slf4j.Logger; 23 | import org.slf4j.LoggerFactory; 24 | 25 | import sun.security.util.ObjectIdentifier; 26 | import sun.security.x509.AlgorithmId; 27 | 28 | public class CSPPrivateKey extends CSPKey implements java.security.PrivateKey { 29 | private static final long serialVersionUID = 8986466200520529548L; 30 | private static final Logger LOGGER = LoggerFactory.getLogger(CSPPrivateKey.class); 31 | 32 | public CSPPrivateKey(long hCryptoProvider, long hCryptoKey, int keyLength) { 33 | super(hCryptoProvider, hCryptoKey, keyLength); 34 | } 35 | 36 | @Override 37 | public String getAlgorithm() { 38 | try { 39 | if(getHCryptKey() != 0) { 40 | String oid = getAlgOID(); 41 | 42 | if(oid != null) { 43 | return new AlgorithmId(new ObjectIdentifier(oid)).getName(); 44 | } 45 | } 46 | } catch (IOException e) { 47 | LOGGER.error("Error parse algorithm", e); 48 | } catch (InvalidKeyException e) { 49 | LOGGER.error("Error algorithm id", e); 50 | } 51 | return "CSP CryptoAPI"; 52 | } 53 | 54 | /** 55 | * Данный класс не сериализуется 56 | */ 57 | private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { 58 | throw new java.io.NotSerializableException(); 59 | } 60 | 61 | private String getAlgOID() throws InvalidKeyException { 62 | return NativeCrypto.getKeyAlgOID(getHCryptKey()); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /java-csp-provider-impl/src/main/java/org/company/security/csp/CSPPublicKey.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp; 18 | 19 | import java.io.IOException; 20 | import java.security.InvalidKeyException; 21 | import java.security.KeyRep; 22 | 23 | import org.slf4j.Logger; 24 | import org.slf4j.LoggerFactory; 25 | 26 | import sun.security.util.DerValue; 27 | import sun.security.util.ObjectIdentifier; 28 | import sun.security.x509.AlgorithmId; 29 | 30 | public class CSPPublicKey extends CSPKey implements java.security.PublicKey { 31 | private static final long serialVersionUID = -1096435996831392504L; 32 | private static final Logger LOGGER = LoggerFactory.getLogger(CSPPublicKey.class); 33 | 34 | private byte[] encoding = null; 35 | 36 | public CSPPublicKey(long hCryptoProvider, long hCryptoKey, int keyLength) { 37 | super(hCryptoProvider, hCryptoKey, keyLength); 38 | } 39 | 40 | public CSPPublicKey(long hCryptoProvider, long hCryptoKey, int keyLength, byte[] encoding) { 41 | super(hCryptoProvider, hCryptoKey, keyLength); 42 | this.encoding = encoding; 43 | } 44 | 45 | @Override 46 | public String getAlgorithm() { 47 | try { 48 | if(getHCryptKey() != 0) { 49 | String oid = getAlgOID(); 50 | 51 | if(oid != null) { 52 | return new AlgorithmId(new ObjectIdentifier(oid)).getName(); 53 | } 54 | } 55 | 56 | if(getEncoded() != null) { 57 | return AlgorithmId.parse(new DerValue(getEncoded())).getName(); 58 | } 59 | } catch (IOException e) { 60 | LOGGER.error("Error parse algorithm", e); 61 | } catch (InvalidKeyException e) { 62 | LOGGER.error("Error algorithm id", e); 63 | } 64 | return "CSP CryptoAPI"; 65 | } 66 | 67 | @Override 68 | public String getFormat() { 69 | return "X.509"; 70 | } 71 | 72 | @Override 73 | public byte[] getEncoded() { 74 | if(encoding == null) { 75 | encoding = NativeCrypto.getPublicKeyEncode(hCryptProvider, hCryptKey); 76 | } 77 | return encoding; 78 | } 79 | 80 | protected Object writeObject() throws java.io.ObjectStreamException { 81 | return new KeyRep(KeyRep.Type.PUBLIC, getAlgorithm(), getFormat(), getEncoded()); 82 | } 83 | 84 | private String getAlgOID() throws InvalidKeyException { 85 | return NativeCrypto.getKeyAlgOID(getHCryptKey()); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /java-csp-provider-impl/src/main/java/org/company/security/csp/KeyManagerFactoryImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp; 18 | 19 | import java.io.File; 20 | import java.io.FileInputStream; 21 | import java.io.FileNotFoundException; 22 | import java.io.IOException; 23 | import java.security.AccessController; 24 | import java.security.InvalidAlgorithmParameterException; 25 | import java.security.KeyStore; 26 | import java.security.KeyStoreException; 27 | import java.security.NoSuchAlgorithmException; 28 | import java.security.UnrecoverableKeyException; 29 | import java.security.cert.CertificateException; 30 | 31 | import javax.net.ssl.KeyManager; 32 | import javax.net.ssl.KeyManagerFactorySpi; 33 | import javax.net.ssl.ManagerFactoryParameters; 34 | 35 | /** 36 | * KeyManagerFactory implementation. 37 | * 38 | * @see javax.net.ssl.KeyManagerFactorySpi 39 | */ 40 | public class KeyManagerFactoryImpl extends KeyManagerFactorySpi { 41 | 42 | // source of key material 43 | private KeyStore keyStore; 44 | 45 | // password 46 | private char[] pwd; 47 | 48 | /** 49 | * @see javax.net.ssl.KeyManagerFactorySpi.engineInit(KeyStore ks, char[] 50 | * password) 51 | */ 52 | @Override 53 | public void engineInit(KeyStore ks, char[] password) 54 | throws KeyStoreException, NoSuchAlgorithmException, 55 | UnrecoverableKeyException { 56 | if (ks != null) { 57 | keyStore = ks; 58 | if (password != null) { 59 | pwd = password.clone(); 60 | } else { 61 | pwd = new char[0]; 62 | } 63 | } else { 64 | keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); 65 | String keyStoreName = AccessController 66 | .doPrivileged(new java.security.PrivilegedAction() { 67 | public String run() { 68 | return System.getProperty("javax.net.ssl.keyStore"); 69 | } 70 | }); 71 | String keyStorePwd = null; 72 | if (keyStoreName == null || keyStoreName.equalsIgnoreCase("NONE") 73 | || keyStoreName.length() == 0) { 74 | try { 75 | keyStore.load(null, null); 76 | } catch (IOException e) { 77 | throw new KeyStoreException(e); 78 | } catch (CertificateException e) { 79 | throw new KeyStoreException(e); 80 | } 81 | } else { 82 | keyStorePwd = AccessController 83 | .doPrivileged(new java.security.PrivilegedAction() { 84 | public String run() { 85 | return System 86 | .getProperty("javax.net.ssl.keyStorePassword"); 87 | } 88 | }); 89 | if (keyStorePwd == null) { 90 | pwd = new char[0]; 91 | } else { 92 | pwd = keyStorePwd.toCharArray(); 93 | } 94 | try { 95 | keyStore.load(new FileInputStream(new File(keyStoreName)), 96 | pwd); 97 | 98 | } catch (FileNotFoundException e) { 99 | throw new KeyStoreException(e); 100 | } catch (IOException e) { 101 | throw new KeyStoreException(e); 102 | } catch (CertificateException e) { 103 | throw new KeyStoreException(e); 104 | } 105 | } 106 | } 107 | } 108 | 109 | /** 110 | * @see 111 | * javax.net.ssl.KeyManagerFactorySpi.engineInit(ManagerFactoryParameters 112 | * spec) 113 | */ 114 | @Override 115 | public void engineInit(ManagerFactoryParameters spec) 116 | throws InvalidAlgorithmParameterException { 117 | throw new InvalidAlgorithmParameterException( 118 | "ManagerFactoryParameters not supported"); 119 | } 120 | 121 | /** 122 | * @see javax.net.ssl.KeyManagerFactorySpi.engineGetKeyManagers() 123 | */ 124 | @Override 125 | public KeyManager[] engineGetKeyManagers() { 126 | if (keyStore == null) { 127 | throw new IllegalStateException( 128 | "KeyManagerFactory is not initialized"); 129 | } 130 | return new KeyManager[] { new KeyManagerImpl(keyStore, pwd) }; 131 | } 132 | 133 | } 134 | -------------------------------------------------------------------------------- /java-csp-provider-impl/src/main/java/org/company/security/csp/NativeLibraryLoader.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp; 18 | 19 | import java.io.File; 20 | import java.io.FileInputStream; 21 | import java.io.IOException; 22 | import java.io.InputStream; 23 | import java.util.Properties; 24 | import java.util.StringTokenizer; 25 | 26 | public class NativeLibraryLoader { 27 | public static final String OPENSSL_CONF = "openssl.config"; 28 | // public static final String DEFAULT_CONFIG = "/META-INF/hyjsse.properties"; 29 | public static final String DEFAULT_CONFIG = "etc/cspprovider.properties"; 30 | public static final String INTERNAL_CONFIG = "META-INF/cspprovider.properties"; 31 | public static final String DEFAULT_LIBRARIES = "csp-provider-native"; 32 | static Properties defaultConfig; 33 | 34 | public static Properties getDefaultConfig() { 35 | if(defaultConfig == null) 36 | defaultConfig = loadConfig(DEFAULT_CONFIG); 37 | return defaultConfig; 38 | } 39 | 40 | private static Properties loadConfig(String fileName) { 41 | Properties properties = new Properties(); 42 | // ClassLoader cl = NativeLibraryLoader.class.getClassLoader(); 43 | // Thread.currentThread().getContextClassLoader(); 44 | InputStream is = null; 45 | 46 | try { 47 | is = new FileInputStream(fileName); 48 | properties.load(is); 49 | } catch (IOException e) { 50 | try { 51 | ClassLoader cl = Thread.currentThread().getContextClassLoader(); 52 | is = cl.getResourceAsStream(INTERNAL_CONFIG); 53 | properties.load(is); 54 | } 55 | catch(Exception exc) { 56 | // FIXME 57 | System.err.println(e.getMessage()); 58 | } 59 | } finally { 60 | try { 61 | if(is != null) 62 | is.close(); 63 | } catch (IOException ignore) { 64 | } 65 | } 66 | return properties; 67 | } 68 | 69 | public static void setDefaultConfig(Properties defaultConfig) { 70 | NativeLibraryLoader.defaultConfig = defaultConfig; 71 | } 72 | 73 | public static void setDefaultConfig(String fileName) { 74 | NativeLibraryLoader.defaultConfig = loadConfig(fileName); 75 | } 76 | 77 | public NativeLibraryLoader() { 78 | } 79 | 80 | public String getSSLCongig() { 81 | String config = getDefaultConfig().getProperty(OPENSSL_CONF, "openssl.cnf"); 82 | return config; 83 | } 84 | 85 | public void loadLibraries() { 86 | loadLibraries(getDefaultConfig()); 87 | } 88 | 89 | public void loadLibraries(String fileName) { 90 | Properties config = loadConfig(fileName); 91 | loadLibraries(config); 92 | } 93 | 94 | public void loadLibraries(Properties config) { 95 | String libraries = config.getProperty("library", DEFAULT_LIBRARIES); 96 | StringTokenizer st = new StringTokenizer(libraries, ","); 97 | 98 | while(st.hasMoreTokens()) { 99 | String librayName = st.nextToken().trim(); 100 | 101 | loadLibrary(librayName, config); 102 | } 103 | } 104 | 105 | public void loadLibrary(String librayName, Properties config) { 106 | if(!dinamicLoadLibrary(librayName, config)) 107 | System.loadLibrary(librayName); 108 | } 109 | 110 | private boolean dinamicLoadLibrary(String librayName, Properties config) { 111 | String osName = System.getProperty("os.name"); 112 | StringBuilder name = new StringBuilder(); 113 | String key = "path." + librayName; 114 | File dir = null; 115 | 116 | if("Windows".equals(osName)) { 117 | name.append(librayName).append(".dll"); 118 | } 119 | else { 120 | name.append("lib").append(librayName).append(".so"); 121 | } 122 | String osNameLibrary = name.toString(); 123 | 124 | 125 | if(config.containsKey(key)) { 126 | String path = config.getProperty(key); 127 | dir = new File(path); 128 | 129 | if(dir.exists() && dir.isDirectory()) { 130 | File f = new File(dir.getAbsoluteFile(), osNameLibrary); 131 | 132 | if(f.exists()) { 133 | System.load(f.getAbsolutePath()); 134 | return true; 135 | } 136 | } 137 | } 138 | else { 139 | dir = new File(System.getProperty("user.dir")); 140 | 141 | File f = new File(dir.getAbsoluteFile(), osNameLibrary); 142 | 143 | if(f.exists()) { 144 | System.load(f.getAbsolutePath()); 145 | return true; 146 | } 147 | } 148 | return false; 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /java-csp-provider-impl/src/main/java/org/company/security/csp/TrustManagerFactoryImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | package org.company.security.csp; 19 | 20 | import java.io.File; 21 | import java.io.FileInputStream; 22 | import java.io.FileNotFoundException; 23 | import java.io.IOException; 24 | import java.security.AccessController; 25 | import java.security.InvalidAlgorithmParameterException; 26 | import java.security.KeyStore; 27 | import java.security.KeyStoreException; 28 | import java.security.NoSuchAlgorithmException; 29 | import java.security.cert.CertificateException; 30 | 31 | import javax.net.ssl.ManagerFactoryParameters; 32 | import javax.net.ssl.TrustManager; 33 | import javax.net.ssl.TrustManagerFactorySpi; 34 | 35 | /** 36 | * 37 | * TrustManagerFactory service provider interface implementation. 38 | * 39 | * @see javax.net.ssl.TrustManagerFactorySpi 40 | */ 41 | public class TrustManagerFactoryImpl extends TrustManagerFactorySpi { 42 | 43 | private KeyStore keyStore; 44 | 45 | /** 46 | * @see javax.net.ssl.TrustManagerFactorySpi#engineInit(KeyStore) 47 | */ 48 | @Override 49 | public void engineInit(KeyStore ks) throws KeyStoreException { 50 | if (ks != null) { 51 | keyStore = ks; 52 | } else { 53 | keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); 54 | String keyStoreName = AccessController 55 | .doPrivileged(new java.security.PrivilegedAction() { 56 | public String run() { 57 | return System 58 | .getProperty("javax.net.ssl.trustStore"); 59 | } 60 | }); 61 | String keyStorePwd = null; 62 | if (keyStoreName == null || keyStoreName.equalsIgnoreCase("NONE") 63 | || keyStoreName.length() == 0) { 64 | try { 65 | keyStore.load(null, null); 66 | } catch (IOException e) { 67 | throw new KeyStoreException(e); 68 | } catch (CertificateException e) { 69 | throw new KeyStoreException(e); 70 | } catch (NoSuchAlgorithmException e) { 71 | throw new KeyStoreException(e); 72 | } 73 | } else { 74 | keyStorePwd = AccessController 75 | .doPrivileged(new java.security.PrivilegedAction() { 76 | public String run() { 77 | return System 78 | .getProperty("javax.net.ssl.trustStorePassword"); 79 | } 80 | }); 81 | char[] pwd; 82 | if (keyStorePwd == null) { 83 | pwd = new char[0]; 84 | } else { 85 | pwd = keyStorePwd.toCharArray(); 86 | } 87 | try { 88 | keyStore.load(new FileInputStream(new File(keyStoreName)), 89 | pwd); 90 | } catch (FileNotFoundException e) { 91 | throw new KeyStoreException(e); 92 | } catch (IOException e) { 93 | throw new KeyStoreException(e); 94 | } catch (CertificateException e) { 95 | throw new KeyStoreException(e); 96 | } catch (NoSuchAlgorithmException e) { 97 | throw new KeyStoreException(e); 98 | } 99 | } 100 | } 101 | 102 | } 103 | 104 | /** 105 | * @see javax.net.ssl.engineInit(ManagerFactoryParameters) 106 | */ 107 | @Override 108 | public void engineInit(ManagerFactoryParameters spec) 109 | throws InvalidAlgorithmParameterException { 110 | throw new InvalidAlgorithmParameterException( 111 | "ManagerFactoryParameters not supported"); 112 | } 113 | 114 | /** 115 | * @see javax.net.ssl.engineGetTrustManagers() 116 | */ 117 | @Override 118 | public TrustManager[] engineGetTrustManagers() { 119 | if (keyStore == null) { 120 | throw new IllegalStateException( 121 | "TrustManagerFactory is not initialized"); 122 | } 123 | return new TrustManager[] { new TrustManagerImpl(keyStore) }; 124 | } 125 | } -------------------------------------------------------------------------------- /java-csp-provider-impl/src/main/java/org/company/security/csp/TrustManagerImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | package org.company.security.csp; 19 | 20 | import java.security.InvalidAlgorithmParameterException; 21 | import java.security.KeyStore; 22 | import java.security.cert.CertPathValidator; 23 | import java.security.cert.CertPathValidatorException; 24 | import java.security.cert.CertificateException; 25 | import java.security.cert.CertificateFactory; 26 | import java.security.cert.PKIXParameters; 27 | import java.security.cert.TrustAnchor; 28 | import java.security.cert.X509Certificate; 29 | import java.util.Arrays; 30 | import java.util.Enumeration; 31 | import java.util.HashSet; 32 | import java.util.Iterator; 33 | import java.util.Set; 34 | 35 | import javax.net.ssl.X509TrustManager; 36 | 37 | /** 38 | * 39 | * TrustManager implementation. The implementation is based on CertPathValidator 40 | * PKIX and CertificateFactory X509 implementations. This implementations should 41 | * be provided by some certification provider. 42 | * 43 | * @see javax.net.ssl.X509TrustManager 44 | */ 45 | public class TrustManagerImpl implements X509TrustManager { 46 | 47 | private CertPathValidator validator; 48 | 49 | private PKIXParameters params; 50 | 51 | private Exception err = null; 52 | 53 | private CertificateFactory factory; 54 | 55 | /** 56 | * Creates trust manager implementation 57 | * 58 | * @param ks 59 | */ 60 | public TrustManagerImpl(KeyStore ks) { 61 | try { 62 | validator = CertPathValidator.getInstance("PKIX"); 63 | factory = CertificateFactory.getInstance("X509"); 64 | byte[] nameConstrains = null; 65 | Set trusted = new HashSet(); 66 | for (Enumeration en = ks.aliases(); en.hasMoreElements();) { 67 | final String alias = en.nextElement(); 68 | final X509Certificate cert = (X509Certificate) ks 69 | .getCertificate(alias); 70 | if (cert != null) { 71 | trusted.add(new TrustAnchor(cert, nameConstrains)); 72 | } 73 | } 74 | params = new PKIXParameters(trusted); 75 | params.setRevocationEnabled(false); 76 | } catch (Exception e) { 77 | err = e; 78 | } 79 | } 80 | 81 | /** 82 | * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[], 83 | * String) 84 | */ 85 | public void checkClientTrusted(X509Certificate[] chain, String authType) 86 | throws CertificateException { 87 | if (chain == null || chain.length == 0 || authType == null 88 | || authType.length() == 0) { 89 | throw new IllegalArgumentException("null or zero-length parameter"); 90 | } 91 | if (err != null) { 92 | throw new CertificateException(err); 93 | } 94 | try { 95 | validator.validate(factory.generateCertPath(Arrays.asList(chain)), 96 | params); 97 | } catch (InvalidAlgorithmParameterException e) { 98 | throw new CertificateException(e); 99 | } catch (CertPathValidatorException e) { 100 | throw new CertificateException(e); 101 | } 102 | } 103 | 104 | /** 105 | * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[], 106 | * String) 107 | */ 108 | public void checkServerTrusted(X509Certificate[] chain, String authType) 109 | throws CertificateException { 110 | if (chain == null || chain.length == 0 || authType == null 111 | || authType.length() == 0) { 112 | throw new IllegalArgumentException("null or zero-length parameter"); 113 | } 114 | if (err != null) { 115 | throw new CertificateException(err); 116 | } 117 | try { 118 | validator.validate(factory.generateCertPath(Arrays.asList(chain)), 119 | params); 120 | } catch (InvalidAlgorithmParameterException e) { 121 | throw new CertificateException(e); 122 | } catch (CertPathValidatorException e) { 123 | throw new CertificateException(e); 124 | } 125 | } 126 | 127 | /** 128 | * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers() 129 | */ 130 | public X509Certificate[] getAcceptedIssuers() { 131 | if (params == null) { 132 | return new X509Certificate[0]; 133 | } 134 | Set anchors = params.getTrustAnchors(); 135 | X509Certificate[] certs = new X509Certificate[anchors.size()]; 136 | int i = 0; 137 | for (Iterator it = anchors.iterator(); it.hasNext();) { 138 | certs[i++] = it.next().getTrustedCert(); 139 | } 140 | return certs; 141 | } 142 | 143 | } 144 | -------------------------------------------------------------------------------- /java-csp-provider-impl/src/main/java/org/company/security/csp/parameter/DigestParameterSpec.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp.parameter; 18 | 19 | import java.security.spec.AlgorithmParameterSpec; 20 | 21 | public interface DigestParameterSpec extends AlgorithmParameterSpec { 22 | void initDigestParameter(long hCryptoProvider, long hCryptoHash); 23 | } 24 | -------------------------------------------------------------------------------- /java-csp-provider-impl/src/test/java/org/company/security/csp/TestBundleNativeCode.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp; 18 | 19 | import static org.junit.Assert.*; 20 | 21 | import java.util.List; 22 | 23 | import org.company.security.csp.BundleNativeCode; 24 | import org.junit.Test; 25 | 26 | public class TestBundleNativeCode { 27 | private static String BUNDLE_NATIVE = 28 | "lib/java-csp-platform-amd64-linux.so; osname=Linux; processor=x86-64," + 29 | "lib/java-csp-platform-x86-linux.so; osname=Linux; processor=x86," + 30 | "lib/java-csp-platform-amd64-windows.dll; osname=Win32; processor=x86-64," + 31 | "lib/java-csp-platform-x86-windows.dll; osname=Win32; processor=x86"; 32 | 33 | @Test 34 | public void test_01_x86_windows() { 35 | BundleNativeCode matcher = new BundleNativeCode(BUNDLE_NATIVE, null); 36 | List list; 37 | 38 | matcher.setOsArch("x86"); 39 | matcher.setOsName("Windows 7"); 40 | matcher.setOsVersion(null); 41 | list = matcher.match(); 42 | 43 | assertEquals("Надо найти одну библиотеку", 1, list.size()); 44 | assertEquals("Нашли другую библиотеку", "lib/java-csp-platform-x86-windows.dll", list.get(0)); 45 | } 46 | 47 | @Test 48 | public void test_02_amd64_windows() { 49 | BundleNativeCode matcher = new BundleNativeCode(BUNDLE_NATIVE, null); 50 | List list; 51 | 52 | matcher.setOsArch("amd64"); 53 | matcher.setOsName("Windows 7"); 54 | matcher.setOsVersion(null); 55 | list = matcher.match(); 56 | 57 | assertEquals("Надо найти одну библиотеку", 1, list.size()); 58 | assertEquals("Нашли другую библиотеку", "lib/java-csp-platform-amd64-windows.dll", list.get(0)); 59 | } 60 | 61 | @Test 62 | public void test_03_x86_linux() { 63 | BundleNativeCode matcher = new BundleNativeCode(BUNDLE_NATIVE, null); 64 | List list; 65 | 66 | matcher.setOsArch("x86"); 67 | matcher.setOsName("Linux"); 68 | matcher.setOsVersion(null); 69 | list = matcher.match(); 70 | 71 | assertEquals("Надо найти одну библиотеку", 1, list.size()); 72 | assertEquals("Нашли другую библиотеку", "lib/java-csp-platform-x86-linux.so", list.get(0)); 73 | } 74 | @Test 75 | public void test_04_amd64_linux() { 76 | BundleNativeCode matcher = new BundleNativeCode(BUNDLE_NATIVE, null); 77 | List list; 78 | 79 | matcher.setOsArch("amd64"); 80 | matcher.setOsName("Linux"); 81 | matcher.setOsVersion(null); 82 | list = matcher.match(); 83 | 84 | assertEquals("Надо найти одну библиотеку", 1, list.size()); 85 | assertEquals("Нашли другую библиотеку", "lib/java-csp-platform-amd64-linux.so", list.get(0)); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /java-csp-provider/src/test/java/org/company/security/csp/LoadNative.java: -------------------------------------------------------------------------------- 1 | package org.company.security.csp; 2 | 3 | import java.security.Security; 4 | 5 | public class LoadNative { 6 | private static final String CSP_PROVIDER = "CSPProvider"; 7 | 8 | public static void loadProvider() { 9 | CSPNative.init("target/classes/native", 10 | "lib/java-csp-platform-amd64-linux.so; osname=Linux; processor=x86-64," + 11 | "lib/java-csp-platform-x86-linux.so; osname=Linux; processor=x86," + 12 | "lib/java-csp-platform-amd64-windows.dll; osname=Win32; processor=x86-64," + 13 | "lib/java-csp-platform-x86-windows.dll; osname=Win32; processor=x86"); 14 | 15 | if(Security.getProvider(CSP_PROVIDER) == null) 16 | Security.addProvider(new CSPProvider()); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java-csp-provider/src/test/java/org/company/security/csp/TestCertFactory.java: -------------------------------------------------------------------------------- 1 | package org.company.security.csp; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import java.io.ByteArrayInputStream; 6 | import java.security.KeyStore; 7 | import java.security.Security; 8 | import java.security.cert.Certificate; 9 | import java.security.cert.CertificateFactory; 10 | import java.security.cert.X509Certificate; 11 | import java.util.Enumeration; 12 | 13 | import org.bouncycastle.jce.provider.BouncyCastleProvider; 14 | import org.junit.BeforeClass; 15 | import org.junit.Test; 16 | import org.slf4j.Logger; 17 | import org.slf4j.LoggerFactory; 18 | 19 | public class TestCertFactory { 20 | private static final String CSP_PROVIDER = "CSPProvider"; 21 | private static final String BC_PROVIDER = "BC"; 22 | private static final String STORE_NAME = "Windows-MY"; 23 | 24 | private static final Logger LOGGER = LoggerFactory.getLogger(TestLoadKeyStoreFromFile.class); 25 | 26 | @BeforeClass 27 | public static void setUpBeforeClass() throws Exception { 28 | LoadNative.loadProvider(); 29 | 30 | if(Security.getProvider(CSP_PROVIDER) == null) 31 | Security.addProvider(new CSPProvider()); 32 | 33 | if(Security.getProvider(BC_PROVIDER) == null) 34 | Security.addProvider(new BouncyCastleProvider()); 35 | } 36 | 37 | @Test 38 | public void test() throws Exception { 39 | CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", CSP_PROVIDER); 40 | CertificateFactory bcCertificateFactory = CertificateFactory.getInstance("X509", BC_PROVIDER); 41 | KeyStore keyStore = java.security.KeyStore.getInstance(STORE_NAME, CSP_PROVIDER); 42 | keyStore.load(null, null); 43 | 44 | for(Enumeration aliases = keyStore.aliases(); aliases.hasMoreElements(); ) { 45 | String alias = aliases.nextElement(); 46 | 47 | X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias); 48 | byte[] encoded = certificate.getEncoded(); 49 | ByteArrayInputStream bis = new ByteArrayInputStream(encoded); 50 | 51 | X509Certificate certificate2 = (X509Certificate) certificateFactory.generateCertificate(bis); 52 | 53 | assertNotEquals("Не совпадают сертификаты", encoded, certificate2.getEncoded()); 54 | 55 | bis.close(); 56 | 57 | bis = new ByteArrayInputStream(encoded); 58 | X509Certificate certificate3 = (X509Certificate) bcCertificateFactory.generateCertificate(bis); 59 | 60 | String cspIssuer = certificate.getIssuerX500Principal().getName(); 61 | String bcIssuer = certificate3.getIssuerX500Principal().getName(); 62 | String cspIssuerDN = certificate.getIssuerDN().getName(); 63 | String bcIssuerDN = certificate3.getIssuerDN().getName(); 64 | 65 | String cspSubject = certificate.getSubjectX500Principal().getName(); 66 | String bcSubject = certificate3.getSubjectX500Principal().getName(); 67 | String cspSubjectDN = certificate.getSubjectDN().getName(); 68 | String bcSubjectDN = certificate3.getSubjectDN().getName(); 69 | 70 | LOGGER.debug("IssuerX500Principal" + 71 | "\n\tCSP: {}" + 72 | "\n\tBC: {}" + 73 | "\n\tequals {}", new Object[]{ 74 | cspIssuer, 75 | bcIssuer, 76 | cspIssuer.equals(bcIssuer)}); 77 | 78 | LOGGER.debug("IssuerDN" + 79 | "\n\tCSP: {}" + 80 | "\n\tBC: {}" + 81 | "\n\tequals {}", new Object[]{ 82 | cspIssuerDN, 83 | bcIssuerDN, 84 | cspIssuerDN.equals(bcIssuerDN)}); 85 | 86 | LOGGER.debug("SubjectX500Principal" + 87 | "\n\tCSP: {}" + 88 | "\n\tBC : {}" + 89 | "\n\tequals {}", new Object[]{ 90 | cspSubject, 91 | bcSubject, 92 | cspSubject.equals(bcSubject)}); 93 | 94 | LOGGER.debug("SubjectDN" + 95 | "\n\tCSP: {}" + 96 | "\n\tBC: {}" + 97 | "\n\tequals {}", new Object[]{ 98 | cspSubjectDN, 99 | bcSubjectDN, 100 | cspSubjectDN.equals(bcSubjectDN)}); 101 | 102 | // assertNotEquals("Не совпадают названия IssuerX500Principal", 103 | // certificate.getIssuerX500Principal().getName(), 104 | // bcIssuerBC); 105 | // 106 | // assertEquals("Не совпадают названия IssuerX500Principal", 107 | // certificate.getSubjectX500Principal().getName(), 108 | // certificate3.getSubjectX500Principal().getName()); 109 | } 110 | } 111 | 112 | } 113 | -------------------------------------------------------------------------------- /java-csp-provider/src/test/java/org/company/security/csp/TestCipher.java: -------------------------------------------------------------------------------- 1 | package org.company.security.csp; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import java.security.Key; 6 | import java.security.KeyStore; 7 | import java.security.Provider; 8 | import java.security.Security; 9 | import java.security.cert.Certificate; 10 | import java.util.Enumeration; 11 | 12 | import javax.crypto.Cipher; 13 | 14 | import org.junit.BeforeClass; 15 | import org.junit.Test; 16 | 17 | 18 | public class TestCipher { 19 | private static final String CSP_PROVIDER = "CSPProvider"; 20 | private static final String STORE_NAME = "Windows-MY"; 21 | private static final String CIPHER_NAME = "GOST28147"; 22 | 23 | @BeforeClass 24 | public static void setUpBeforeClass() throws Exception { 25 | LoadNative.loadProvider(); 26 | 27 | if(Security.getProvider(CSP_PROVIDER) == null) 28 | Security.addProvider(new CSPProvider()); 29 | 30 | // if(Security.getProperty(BC_PROVIDER) == null) 31 | // Security.addProvider(new BouncyCastleProvider()); 32 | } 33 | 34 | @Test 35 | public void test() throws Exception { 36 | 37 | Cipher cipher; 38 | try { 39 | cipher = Cipher.getInstance(CIPHER_NAME, CSP_PROVIDER); 40 | } 41 | catch(SecurityException e) { 42 | String message = e.getMessage(); 43 | String actual = "JCE cannot authenticate the provider"; 44 | 45 | if(message.startsWith(actual)) { 46 | System.err.println("Надо использовать OpenJDK. " + message); 47 | return; 48 | } 49 | else 50 | throw e; 51 | } 52 | 53 | KeyStore keyStore = java.security.KeyStore.getInstance(STORE_NAME, CSP_PROVIDER); 54 | keyStore.load(null, null); 55 | for(Enumeration aliases = keyStore.aliases(); aliases.hasMoreElements(); ) { 56 | String alias = aliases.nextElement(); 57 | 58 | Key key = keyStore.getKey(alias, null); 59 | 60 | if(key != null) { 61 | Certificate certificate = keyStore.getCertificate(alias); 62 | byte[] input = alias.getBytes(); 63 | 64 | // cipher.init(Cipher.ENCRYPT_MODE, certificate); 65 | // byte[] encode = cipher.doFinal(input); 66 | // 67 | // cipher.init(Cipher.DECRYPT_MODE, key); 68 | // byte[] decode = cipher.doFinal(encode); 69 | // 70 | // 71 | // assertNotEquals(decode, input); 72 | } 73 | } 74 | 75 | // fail("Not yet implemented"); 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /java-csp-provider/src/test/java/org/company/security/csp/TestDigest.java: -------------------------------------------------------------------------------- 1 | package org.company.security.csp; 2 | 3 | import static org.junit.Assert.assertNotEquals; 4 | 5 | import java.security.MessageDigest; 6 | import java.security.Security; 7 | 8 | import org.bouncycastle.jce.provider.BouncyCastleProvider; 9 | import org.junit.BeforeClass; 10 | import org.junit.Test; 11 | 12 | public class TestDigest { 13 | private static final String CSP_PROVIDER = "CSPProvider"; 14 | private static final String CSP_DIGEST = "GOST3411"; 15 | 16 | private static final String BC_PROVIDER = "BC"; 17 | private static final String BC_DIGEST = "GOST3411"; 18 | 19 | @BeforeClass 20 | public static void setUpBeforeClass() throws Exception { 21 | LoadNative.loadProvider(); 22 | 23 | if(Security.getProvider(CSP_PROVIDER) == null) 24 | Security.addProvider(new CSPProvider()); 25 | 26 | if(Security.getProperty(BC_PROVIDER) == null) 27 | Security.addProvider(new BouncyCastleProvider()); 28 | } 29 | 30 | @Test 31 | public void test() throws Exception { 32 | byte[] input = new byte[]{ 1, 2, 3 }; 33 | 34 | MessageDigest messageDigestBC = MessageDigest.getInstance(BC_DIGEST, BC_PROVIDER); 35 | messageDigestBC.digest(input); 36 | byte[] digestBC = messageDigestBC.digest(); 37 | 38 | MessageDigest messageDigestCSP = MessageDigest.getInstance(CSP_DIGEST, CSP_PROVIDER); 39 | messageDigestCSP.digest(input); 40 | byte[] digestCSP = messageDigestCSP.digest(); 41 | 42 | assertNotEquals("MessageDigest error", digestCSP, digestBC); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /java-csp-provider/src/test/java/org/company/security/csp/TestLoadKeyStore.java: -------------------------------------------------------------------------------- 1 | package org.company.security.csp; 2 | 3 | import java.security.KeyStore; 4 | import java.security.Security; 5 | import java.security.cert.X509Certificate; 6 | import java.util.Enumeration; 7 | 8 | import org.junit.BeforeClass; 9 | import org.junit.Test; 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | 13 | public class TestLoadKeyStore { 14 | private static final Logger LOGGER = LoggerFactory.getLogger(TestLoadKeyStore.class); 15 | 16 | private static final String PROVIDER_NAME = "CSPProvider"; 17 | private static final String STORE_NAME = "Windows-MY"; 18 | 19 | @BeforeClass 20 | public static void setUpBeforeClass() throws Exception { 21 | LoadNative.loadProvider(); 22 | 23 | if(Security.getProvider(PROVIDER_NAME) == null) 24 | Security.addProvider(new CSPProvider()); 25 | } 26 | 27 | @Test 28 | public void testLoalCertificates() throws Exception { 29 | KeyStore keyStore = java.security.KeyStore.getInstance(STORE_NAME, PROVIDER_NAME); 30 | keyStore.load(null, null); 31 | 32 | Enumeration aliases = keyStore.aliases(); 33 | 34 | while(aliases.hasMoreElements()) { 35 | String alias = aliases.nextElement(); 36 | X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias); 37 | 38 | LOGGER.debug("Ключ {}" + 39 | "\n\tSubject {}" + 40 | "\n\tS/N {}" + 41 | "\n\tIssuer {}", 42 | new Object[]{ 43 | alias, 44 | cert.getSubjectDN().getName(), 45 | cert.getSerialNumber().toString(16), 46 | cert.getIssuerDN().getName() 47 | }); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /java-csp-provider/src/test/java/org/company/security/csp/TestLoadKeyStoreFromFile.java: -------------------------------------------------------------------------------- 1 | package org.company.security.csp; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.security.KeyStore; 6 | import java.security.Provider; 7 | import java.security.Security; 8 | import java.security.cert.X509Certificate; 9 | import java.util.Enumeration; 10 | 11 | import org.bouncycastle.jce.provider.BouncyCastleProvider; 12 | import org.bouncycastle.x509.X509CollectionStoreParameters; 13 | import org.bouncycastle.x509.X509Store; 14 | import org.junit.After; 15 | import org.junit.Before; 16 | import org.junit.BeforeClass; 17 | import org.junit.Rule; 18 | import org.junit.Test; 19 | import org.junit.rules.TestName; 20 | import org.slf4j.Logger; 21 | import org.slf4j.LoggerFactory; 22 | 23 | public class TestLoadKeyStoreFromFile { 24 | private static final String KEYSTORE_FILE = "target/test-classes/cert.sst"; 25 | 26 | private static final Logger LOGGER = LoggerFactory.getLogger(TestLoadKeyStoreFromFile.class); 27 | 28 | private static final String PROVIDER_NAME = "CSPProvider"; 29 | private static final String STORE_NAME = "FILE"; 30 | private static Provider cspProvider; 31 | 32 | 33 | @BeforeClass 34 | public static void setUpBeforeClass() throws Exception { 35 | LoadNative.loadProvider(); 36 | 37 | if(Security.getProvider(PROVIDER_NAME) == null) 38 | Security.addProvider(new CSPProvider()); 39 | 40 | cspProvider = Security.getProvider(PROVIDER_NAME); 41 | } 42 | 43 | @Rule 44 | public TestName testName = new TestName(); 45 | 46 | @Before 47 | public void setUp() throws Exception { 48 | LOGGER.info("********************************************************************************"); 49 | LOGGER.info("Testing: " + getTestMethodName() + "(" + getClass().getName() + ")"); 50 | LOGGER.info("********************************************************************************"); 51 | } 52 | @After 53 | public void tearDown() throws Exception { 54 | LOGGER.info("********************************************************************************"); 55 | LOGGER.info("Testing done: " + getTestMethodName() + "(" + getClass().getName() + ")"); 56 | LOGGER.info("********************************************************************************"); 57 | } 58 | 59 | public String getTestMethodName() { 60 | return testName.getMethodName(); 61 | } 62 | 63 | @Test 64 | public void testLoalCertificatesByBuilder() throws Exception { 65 | new TestName().getMethodName(); 66 | LOGGER.debug("--- testLoalCertificatesByBuilder ---"); 67 | 68 | KeyStore keyStore = CSPKeyStore.Builder.newInstance("FILE", 69 | cspProvider, 70 | KEYSTORE_FILE, 71 | null).getKeyStore(); 72 | 73 | Enumeration aliases = keyStore.aliases(); 74 | 75 | while(aliases.hasMoreElements()) { 76 | String alias = aliases.nextElement(); 77 | X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias); 78 | boolean keyEntry = keyStore.isKeyEntry(alias); 79 | 80 | LOGGER.debug("Ключ {}" + 81 | "\n\tSubject {}" + 82 | "\n\tS/N {}" + 83 | "\n\tIssuer {}" + 84 | "\n\tKeyEntry {}", 85 | new Object[]{ 86 | alias, 87 | cert.getSubjectDN().getName(), 88 | cert.getSerialNumber().toString(16), 89 | cert.getIssuerDN().getName(), 90 | keyEntry 91 | }); 92 | } 93 | } 94 | 95 | @Test 96 | public void testLoalCertificatesByParams() throws Exception { 97 | LOGGER.debug("--- testLoalCertificatesByParams ---"); 98 | 99 | CSPKeyStore.KeyStoreProtection protection = new CSPKeyStore.KeyStoreProtection( 100 | STORE_NAME, 101 | cspProvider, 102 | KEYSTORE_FILE, 103 | null); 104 | CSPKeyStore.SimpleLoadStoreParameter parameter = new CSPKeyStore.SimpleLoadStoreParameter(protection); 105 | 106 | KeyStore keyStore = java.security.KeyStore.getInstance(STORE_NAME, PROVIDER_NAME); 107 | keyStore.load(parameter); 108 | 109 | Enumeration aliases = keyStore.aliases(); 110 | 111 | while(aliases.hasMoreElements()) { 112 | String alias = aliases.nextElement(); 113 | X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias); 114 | boolean keyEntry = keyStore.isKeyEntry(alias); 115 | 116 | LOGGER.debug("Ключ {}" + 117 | "\n\tSubject {}" + 118 | "\n\tS/N {}" + 119 | "\n\tIssuer {}" + 120 | "\n\tKeyEntry {}", 121 | new Object[]{ 122 | alias, 123 | cert.getSubjectDN().getName(), 124 | cert.getSerialNumber().toString(16), 125 | cert.getIssuerDN().getName(), 126 | keyEntry 127 | }); 128 | } 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /java-csp-provider/src/test/java/org/company/security/csp/TestSignature.java: -------------------------------------------------------------------------------- 1 | package org.company.security.csp; 2 | 3 | import java.security.Key; 4 | import java.security.KeyStore; 5 | import java.security.PrivateKey; 6 | import java.security.Security; 7 | import java.security.Signature; 8 | import java.security.cert.Certificate; 9 | import java.security.cert.X509Certificate; 10 | import java.util.Enumeration; 11 | 12 | import org.bouncycastle.jce.provider.BouncyCastleProvider; 13 | import org.junit.BeforeClass; 14 | import org.junit.Test; 15 | import org.slf4j.Logger; 16 | import org.slf4j.LoggerFactory; 17 | 18 | public class TestSignature { 19 | 20 | private static final Logger LOGGER = LoggerFactory.getLogger(TestSignature.class); 21 | 22 | private static final String CSP_PROVIDER = "CSPProvider"; 23 | private static final String CSP_DIGEST = "GOST3411"; 24 | private static final String CSP_SIGNATURE = "GOST3411withGOST3410EL"; 25 | 26 | private static final String BC_PROVIDER = "BC"; 27 | private static final String BC_SIGNATURE = "GOST3411withECGOST3410"; 28 | 29 | private static final String STORE_NAME = "Windows-MY"; 30 | private static final String ALG_OID_GOST = "1.2.643.2.2.98"; 31 | 32 | @BeforeClass 33 | public static void setUpBeforeClass() throws Exception { 34 | // new NativeLibraryLoader().loadLibraries(); 35 | LoadNative.loadProvider(); 36 | 37 | if(Security.getProvider(CSP_PROVIDER) == null) 38 | Security.addProvider(new CSPProvider()); 39 | 40 | if(Security.getProperty(BC_PROVIDER) == null) 41 | Security.addProvider(new BouncyCastleProvider()); 42 | } 43 | 44 | @Test 45 | public void test() throws Exception { 46 | LOGGER.debug("start TestSignature test"); 47 | 48 | Signature cspSignatureSign = Signature.getInstance(CSP_SIGNATURE, CSP_PROVIDER); 49 | Signature cspSignatureVerify = Signature.getInstance(CSP_SIGNATURE, CSP_PROVIDER); 50 | Signature bcSignatureVerify = Signature.getInstance(BC_SIGNATURE, BC_PROVIDER); 51 | 52 | KeyStore keyStore = java.security.KeyStore.getInstance(STORE_NAME, CSP_PROVIDER); 53 | keyStore.load(null, null); 54 | 55 | for(Enumeration aliases = keyStore.aliases(); aliases.hasMoreElements(); ) { 56 | String alias = aliases.nextElement(); 57 | 58 | Key key = keyStore.getKey(alias, null); 59 | 60 | if(key != null) { 61 | X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias); 62 | byte[] input = alias.getBytes(); 63 | 64 | LOGGER.debug("Certificate" + 65 | "\n\tSubject {}" + 66 | "\n\tIssuer {}" + 67 | "\n\tSerial Number {}" + 68 | "\n\talgorithm {}", new Object[]{ 69 | certificate.getSubjectDN().getName(), 70 | certificate.getIssuerDN().getName(), 71 | certificate.getSerialNumber().toString(16), 72 | certificate.getPublicKey().getAlgorithm() 73 | }); 74 | String algorithm = key.getAlgorithm(); 75 | LOGGER.debug("PrivateKey algorithm {}", algorithm); 76 | 77 | if(ALG_OID_GOST.equals(algorithm)) { 78 | LOGGER.debug("TestSignature test -> cspSignatureSign.initSign"); 79 | cspSignatureSign.initSign((PrivateKey) key); 80 | LOGGER.debug("TestSignature test -> cspSignatureSign.update"); 81 | cspSignatureSign.update(input); 82 | LOGGER.debug("TestSignature test -> cspSignatureSign.sign"); 83 | byte[] sign = cspSignatureSign.sign(); 84 | 85 | bcSignatureVerify.initVerify(certificate); 86 | bcSignatureVerify.update(input); 87 | bcSignatureVerify.verify(sign); 88 | 89 | LOGGER.debug("TestSignature test -> cspSignatureVerify.initVerify"); 90 | cspSignatureVerify.initVerify(certificate); 91 | LOGGER.debug("TestSignature test -> cspSignatureVerify.update"); 92 | cspSignatureVerify.update(input); 93 | LOGGER.debug("TestSignature test -> cspSignatureVerify.verify"); 94 | cspSignatureVerify.verify(sign); 95 | } 96 | } 97 | } 98 | //fail("Not yet implemented"); 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /java-csp-provider/src/test/resources/META-INF/cspprovider.properties: -------------------------------------------------------------------------------- 1 | #library = cpext,asn1data,rdrsup,ssp,capi10,capi20,csp-provider-native 2 | #library =capi20,csp-provider-native 3 | library =capi20 4 | #path.csp-provider-native= /home/alexey/EclipseProjects/smev/csp-provider-native/Debug 5 | path.csp-provider-native= /home/sushko/EclipseProjects/smev/csp-provider-native/Debug 6 | path.asn1data = /opt/cprocsp/lib/amd64 7 | path.ssp = /opt/cprocsp/lib/amd64 8 | path.capi10 = /opt/cprocsp/lib/amd64 9 | path.capi20 = /opt/cprocsp/lib/amd64 10 | path.cpext = /opt/cprocsp/lib/amd64 11 | path.rdrsup = /opt/cprocsp/lib/amd64 12 | -------------------------------------------------------------------------------- /java-csp-provider/src/test/resources/META-INF/hyjsse.properties: -------------------------------------------------------------------------------- 1 | #library = openssl,crypto,hyjsse 2 | library = csp-provider-native 3 | #path.openssl = /usr/local/lib 4 | #path.crypto = /usr/local/lib 5 | #path.hyjsse = /usr/local/lib 6 | #path.xnet = /home/sushko/EclipseProjects-cpp/xnet/Release 7 | csp-provider-native= /home/alexey/EclipseProjects/smev/csp-provider-native/Debug 8 | #openssl.config = /usr/local/lib/ssl/openssl.cnf 9 | -------------------------------------------------------------------------------- /java-csp-provider/src/test/resources/cert.sst: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexey-su/java-csp/e8453480b6a3a9036b03e37d8e108e0b7a1861b2/java-csp-provider/src/test/resources/cert.sst -------------------------------------------------------------------------------- /java-csp-provider/src/test/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=TRACE, out, outfile 2 | 3 | ## CONSOLE appender not used by default 4 | log4j.appender.out=org.apache.log4j.ConsoleAppender 5 | ##log4j.appender.out.threshold=WARN 6 | log4j.appender.out.layout=org.apache.log4j.PatternLayout 7 | log4j.appender.out.layout.ConversionPattern=%d{dd.MM.yy HH:mm:ss} [%30.30t] %-30.30c{1} %-5p %m%n 8 | 9 | log4j.appender.outfile=org.apache.log4j.FileAppender 10 | log4j.appender.outfile.File=target/logging.log 11 | log4j.appender.outfile.layout=org.apache.log4j.PatternLayout 12 | log4j.appender.outfile.layout.ConversionPattern=%d{dd.MM.yy HH:mm:ss} [%30.30t] %-30.30c{1} %-5p %m%n 13 | 14 | log4j.throwableRenderer=org.apache.log4j.EnhancedThrowableRenderer 15 | -------------------------------------------------------------------------------- /java-csp-wss4j/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | 4 | 5 | org.company.security.csp 6 | parent 7 | 1.0.0-SNAPSHOT 8 | ../parent 9 | 10 | 11 | Java CSP WSS4J with JSR-105 and Apache Santuario 12 | java-csp-wss4j 13 | 14 | 15 | org.company.security.csp.ws.security 16 | 6.5.2 17 | 18 | 19 | 20 | 21 | 22 | org.apache.felix 23 | maven-bundle-plugin 24 | true 25 | 26 | 27 | 28 | org.slf4j; version="[1.6,2)"; provider=paxlogging,* 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | ${project.groupId} 38 | java-csp-provider 39 | ${project.version} 40 | 41 | 42 | 43 | ${project.groupId} 44 | java-csp-provider-impl 45 | ${project.version} 46 | provided 47 | 48 | 49 | ${project.groupId} 50 | java-csp-xmlsec-jsr105 51 | ${project.version} 52 | 53 | 54 | org.slf4j 55 | slf4j-api 56 | 57 | 58 | org.apache.ws.security 59 | wss4j 60 | compile 61 | 62 | 63 | 64 | junit 65 | junit 66 | test 67 | 68 | 69 | org.slf4j 70 | slf4j-log4j12 71 | test 72 | 73 | 74 | log4j 75 | log4j 76 | test 77 | 78 | 79 | 80 | org.apache.cxf 81 | cxf-api 82 | ${cxf.version} 83 | test 84 | 85 | 86 | org.apache.cxf 87 | cxf-bundle 88 | ${cxf.version} 89 | test 90 | 91 | 92 | org.apache.cxf 93 | cxf-testutils 94 | ${cxf.version} 95 | test 96 | 97 | 98 | -------------------------------------------------------------------------------- /java-csp-wss4j/src/main/java/org/company/security/csp/ws/security/action/LocalSignatureAction.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp.ws.security.action; 18 | 19 | 20 | import java.util.List; 21 | 22 | import javax.security.auth.callback.CallbackHandler; 23 | 24 | import org.apache.ws.security.WSConstants; 25 | import org.apache.ws.security.WSEncryptionPart; 26 | import org.apache.ws.security.WSPasswordCallback; 27 | import org.apache.ws.security.WSSecurityException; 28 | import org.apache.ws.security.action.Action; 29 | import org.apache.ws.security.handler.RequestData; 30 | import org.apache.ws.security.handler.WSHandler; 31 | import org.apache.ws.security.util.WSSecurityUtil; 32 | import org.w3c.dom.Document; 33 | import org.w3c.dom.Element; 34 | import org.w3c.dom.Node; 35 | 36 | import org.company.security.csp.ws.security.message.LocalWSSecSignature; 37 | 38 | /** 39 | * Замена базового механизма подписания SOAP запроса. 40 | *
Вместо создания WSSecSignature создается LocalWSSecSignature. 41 | * 42 | * @see org.apache.ws.security.action.SignatureAction 43 | * @see org.apache.ws.security.message.WSSecSignature 44 | * @author Aleksey Sushko 45 | * 46 | */ 47 | public class LocalSignatureAction implements Action { 48 | public void execute(WSHandler handler, int actionToDo, Document doc, RequestData reqData) 49 | throws WSSecurityException { 50 | CallbackHandler callbackHandler = 51 | handler.getPasswordCallbackHandler(reqData); 52 | WSPasswordCallback passwordCallback = 53 | handler.getPasswordCB(reqData.getSignatureUser(), actionToDo, callbackHandler, reqData); 54 | LocalWSSecSignature wsSign = loadWSSecSignature(reqData); 55 | 56 | if (reqData.getSigKeyId() != 0) { 57 | wsSign.setKeyIdentifierType(reqData.getSigKeyId()); 58 | } 59 | if (reqData.getSigAlgorithm() != null) { 60 | wsSign.setSignatureAlgorithm(reqData.getSigAlgorithm()); 61 | } 62 | if (reqData.getSigDigestAlgorithm() != null) { 63 | wsSign.setDigestAlgo(reqData.getSigDigestAlgorithm()); 64 | } 65 | 66 | wsSign.setUserInfo(reqData.getSignatureUser(), passwordCallback.getPassword()); 67 | wsSign.setUseSingleCertificate(reqData.isUseSingleCert()); 68 | if (reqData.getSignatureParts().size() > 0) { 69 | wsSign.setParts(reqData.getSignatureParts()); 70 | } 71 | 72 | if (passwordCallback.getKey() != null) { 73 | wsSign.setSecretKey(passwordCallback.getKey()); 74 | } 75 | 76 | try { 77 | wsSign.prepare(doc, reqData.getSigCrypto(), reqData.getSecHeader()); 78 | 79 | Element siblingElementToPrepend = null; 80 | for (WSEncryptionPart part : reqData.getSignatureParts()) { 81 | if ("STRTransform".equals(part.getName()) && part.getId() == null) { 82 | part.setId(wsSign.getSecurityTokenReferenceURI()); 83 | } else if (reqData.isAppendSignatureAfterTimestamp() 84 | && WSConstants.WSU_NS.equals(part.getNamespace()) 85 | && "Timestamp".equals(part.getName())) { 86 | List elements = 87 | WSSecurityUtil.findElements( 88 | doc.getDocumentElement(), part.getName(), part.getNamespace() 89 | ); 90 | if (elements != null && !elements.isEmpty()) { 91 | Element timestampElement = elements.get(0); 92 | Node child = timestampElement.getNextSibling(); 93 | while (child != null && child.getNodeType() != Node.ELEMENT_NODE) { 94 | child = child.getNextSibling(); 95 | } 96 | siblingElementToPrepend = (Element)child; 97 | } 98 | } 99 | } 100 | 101 | List referenceList = 102 | wsSign.addReferencesToSign(reqData.getSignatureParts(), reqData.getSecHeader()); 103 | 104 | if (reqData.isAppendSignatureAfterTimestamp() && siblingElementToPrepend == null) { 105 | wsSign.computeSignature(referenceList, false, null); 106 | } else { 107 | wsSign.computeSignature(referenceList, true, siblingElementToPrepend); 108 | } 109 | 110 | wsSign.prependBSTElementToHeader(reqData.getSecHeader()); 111 | reqData.getSignatureValues().add(wsSign.getSignatureValue()); 112 | } catch (WSSecurityException e) { 113 | throw new WSSecurityException("Error during Signature: ", e); 114 | } 115 | } 116 | 117 | protected LocalWSSecSignature loadWSSecSignature(RequestData reqData) { 118 | LocalWSSecSignature wsSign = new LocalWSSecSignature(reqData.getWssConfig()); 119 | return wsSign; 120 | } 121 | 122 | } 123 | -------------------------------------------------------------------------------- /java-csp-wss4j/src/main/java/org/company/security/csp/ws/security/components/crypto/LocalAlgorithmSuiteValidator.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp.ws.security.components.crypto; 18 | 19 | import java.security.PublicKey; 20 | import java.security.interfaces.DSAPublicKey; 21 | import java.security.interfaces.RSAPublicKey; 22 | 23 | import org.apache.ws.security.WSSecurityException; 24 | import org.apache.ws.security.components.crypto.AlgorithmSuite; 25 | import org.apache.ws.security.components.crypto.AlgorithmSuiteValidator; 26 | import org.slf4j.Logger; 27 | import org.slf4j.LoggerFactory; 28 | 29 | public class LocalAlgorithmSuiteValidator extends AlgorithmSuiteValidator { 30 | private static final Logger LOG = LoggerFactory.getLogger(LocalAlgorithmSuiteValidator.class); 31 | 32 | private final AlgorithmSuite algorithmSuite; 33 | 34 | public LocalAlgorithmSuiteValidator(AlgorithmSuite algorithmSuite) { 35 | super(algorithmSuite); 36 | this.algorithmSuite = algorithmSuite; 37 | } 38 | 39 | @Override 40 | /** 41 | * Check the asymmetric key length 42 | */ 43 | public void checkAsymmetricKeyLength( 44 | PublicKey publicKey 45 | ) throws WSSecurityException { 46 | if (publicKey == null) { 47 | return; 48 | } 49 | int length = -1; 50 | 51 | LOG.debug("Algorithm {}", publicKey.getAlgorithm()); 52 | 53 | if (publicKey instanceof RSAPublicKey) { 54 | length = ((RSAPublicKey)publicKey).getModulus().bitLength(); 55 | } else if (publicKey instanceof DSAPublicKey) { 56 | length = ((DSAPublicKey)publicKey).getParams().getP().bitLength(); 57 | } else { 58 | try { 59 | // FIXME verify Algorithm OID in provider's KeyFactory 60 | 61 | byte[] encoded = publicKey.getEncoded(); 62 | if(encoded != null && encoded.length > 0) 63 | length = algorithmSuite.getMinimumAsymmetricKeyLength() + 1; 64 | } 65 | catch(Exception e) { 66 | LOG.error(e.getMessage(), e); 67 | } 68 | } 69 | 70 | if (length < 0) { 71 | LOG.debug("An unknown public key was provided"); 72 | throw new WSSecurityException(WSSecurityException.INVALID_SECURITY); 73 | } 74 | else if (length < algorithmSuite.getMinimumAsymmetricKeyLength() 75 | || length > algorithmSuite.getMaximumAsymmetricKeyLength()) { 76 | LOG.debug("The asymmetric key length does not match the requirement"); 77 | throw new WSSecurityException(WSSecurityException.INVALID_SECURITY); 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /java-csp-wss4j/src/test/java/org/company/security/csp/wss4j/test/CXFGostTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp.wss4j.test; 18 | 19 | import java.lang.reflect.Field; 20 | import java.security.Security; 21 | 22 | import javax.xml.stream.XMLInputFactory; 23 | 24 | import org.apache.cxf.staxutils.StaxUtils; 25 | import org.apache.cxf.testutil.common.AbstractBusClientServerTestBase; 26 | import org.junit.BeforeClass; 27 | import org.junit.Test; 28 | 29 | import org.company.security.csp.CSPNative; 30 | import org.company.security.csp.CSPProvider; 31 | import org.company.security.csp.wss4j.test.hello_world_soap_http.Greeter; 32 | 33 | public class CXFGostTest extends AbstractBusClientServerTestBase { 34 | private static final String CSP_PROVIDER = "CSPProvider"; 35 | private static final String CSPXML_PROVIDER = "CSPXMLDSig"; 36 | private static final String STORE_NAME = "Windows-MY"; 37 | private static final String ALG_OID_GOST_PRIVATEKEY_EXCHANGE = "1.2.643.2.2.98"; // закрытый ключ обмена 38 | private static final String ALG_OID_GOST_PRIVATEKEY_SIGN = "1.2.643.2.2.99"; // закрытый ключ подписи 39 | 40 | private static Greeter clientGreeterStream; 41 | private static String userKeyAlias; 42 | private static LocalClient localClient; 43 | 44 | static { 45 | try { 46 | Field xmlInputFactoryField = StaxUtils.class.getDeclaredField("SAFE_INPUT_FACTORY"); 47 | xmlInputFactoryField.setAccessible(true); 48 | XMLInputFactory xmlInputFactory = (XMLInputFactory)xmlInputFactoryField.get(null); 49 | xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE); 50 | 51 | // подгружаем в Apache Santuario xmlsign ГОСТ ЭЦП 52 | // XmlDSignTools.init(); 53 | } catch (Exception e) { 54 | throw new RuntimeException(e); 55 | } 56 | } 57 | 58 | /** 59 | * Регистрация криптографических поставщиков 60 | */ 61 | private static void createProviders() throws Exception { 62 | CSPNative.init("target/native", null); 63 | 64 | // Поставщик хеш функций и подписей 65 | if(Security.getProvider(CSP_PROVIDER) == null) 66 | Security.addProvider(new CSPProvider()); 67 | 68 | // Поставщик XML dsign JSR-105 69 | if(Security.getProvider(CSPXML_PROVIDER) == null) 70 | Security.addProvider(new org.company.security.csp.xml.dsig.internal.dom.XMLDSigRI()); 71 | } 72 | 73 | @BeforeClass 74 | public static void beforeClass() throws Exception { 75 | // Регистрация криптографических поставщиков 76 | createProviders(); 77 | 78 | if(LocalServer.findKeyAlias() != null) { 79 | assertTrue("Server failed to launch", launchServer(LocalServer.class, true)); 80 | 81 | // стартуем локальную шину веб сервисов 82 | createStaticBus(); 83 | 84 | // создаем локального клиента 85 | localClient = new LocalClient(); 86 | } 87 | } 88 | 89 | @Test 90 | public void f() { 91 | if(localClient != null) 92 | localClient.getGreeter().greetMe("Cold start"); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /java-csp-wss4j/src/test/java/org/company/security/csp/wss4j/test/KeyStoreFileTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp.wss4j.test; 18 | 19 | import static org.junit.Assert.*; 20 | 21 | import java.math.BigInteger; 22 | import java.security.KeyStore; 23 | import java.security.Security; 24 | import java.security.cert.X509Certificate; 25 | import java.util.Enumeration; 26 | import java.util.Properties; 27 | 28 | import org.apache.ws.security.components.crypto.CryptoType; 29 | import org.junit.BeforeClass; 30 | import org.junit.Test; 31 | import org.slf4j.Logger; 32 | import org.slf4j.LoggerFactory; 33 | 34 | import org.company.security.csp.CSPNative; 35 | import org.company.security.csp.CSPProvider; 36 | import org.company.security.csp.ws.security.components.crypto.LocalMerlin; 37 | 38 | public class KeyStoreFileTest { 39 | private static final String CSP_PROVIDER = "CSPProvider"; 40 | 41 | private static final Logger LOGGER = LoggerFactory.getLogger(KeyStoreFileTest.class); 42 | 43 | @BeforeClass 44 | public static void setUpBeforeClass() throws Exception { 45 | CSPNative.init("target/native", null); 46 | 47 | // Поставщик хеш функций и подписей 48 | if(Security.getProvider(CSP_PROVIDER) == null) 49 | Security.addProvider(new CSPProvider()); 50 | } 51 | 52 | @Test 53 | public void test() throws Exception { 54 | Properties prop = new Properties(); 55 | 56 | // настройка системы криптографии 57 | prop.put("org.apache.ws.security.crypto.provider", "org.company.security.csp.ws.security.components.crypto.LocalMerlin"); 58 | prop.put("org.apache.ws.security.crypto.merlin.cert.provider", "CSPProvider"); 59 | prop.put("org.apache.ws.security.crypto.merlin.keystore.provider", "CSPProvider"); 60 | prop.put("org.apache.ws.security.crypto.merlin.keystore.type", "Windows-MY"); 61 | // prop.put("org.apache.ws.security.crypto.merlin.truststore.type", "Linux-AddressBook"); 62 | prop.put("org.apache.ws.security.crypto.merlin.truststore.type", "FILE"); 63 | prop.put("org.apache.ws.security.crypto.merlin.truststore.password", ""); 64 | prop.put("org.apache.ws.security.crypto.merlin.truststore.file", "target/test-classes/trusted/cert.sst"); 65 | 66 | 67 | 68 | LocalMerlin crypto = new LocalMerlin(prop); 69 | 70 | KeyStore keyStore = crypto.getTrustStore(); 71 | assertNotNull("Не загрузилось хранилище доверенных сертификатов", keyStore); 72 | 73 | Enumeration aliases = keyStore.aliases(); 74 | String issuerName = null; 75 | BigInteger serial = null; 76 | 77 | assertTrue("В хранилище нет сертификатов", aliases.hasMoreElements()); 78 | 79 | while(aliases.hasMoreElements()) { 80 | String alias = aliases.nextElement(); 81 | X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias); 82 | boolean keyEntry = keyStore.isKeyEntry(alias); 83 | 84 | LOGGER.debug("Ключ {}" + 85 | "\n\tSubject {}" + 86 | "\n\tS/N {}" + 87 | "\n\tIssuer {}" + 88 | "\n\tKeyEntry {}", 89 | new Object[]{ 90 | alias, 91 | cert.getSubjectDN().getName(), 92 | cert.getSerialNumber().toString(16), 93 | cert.getIssuerDN().getName(), 94 | keyEntry 95 | }); 96 | 97 | issuerName = cert.getIssuerX500Principal().getName(); 98 | serial = cert.getSerialNumber(); 99 | } 100 | 101 | assertNotNull("Не удалось получить IssuerName", issuerName); 102 | assertNotNull("Не удалось получить SerialNumber", serial); 103 | 104 | CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ISSUER_SERIAL); 105 | cryptoType.setIssuerSerial(issuerName, serial); 106 | 107 | X509Certificate[] certificates = crypto.getX509Certificates(cryptoType); 108 | int count = certificates != null ? certificates.length : 0; 109 | 110 | assertEquals("Не найден сертификат", 1, count); 111 | } 112 | 113 | } 114 | -------------------------------------------------------------------------------- /java-csp-wss4j/src/test/java/org/company/security/csp/wss4j/test/LocalMerlinTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp.wss4j.test; 18 | 19 | import java.security.KeyStore; 20 | import java.security.Security; 21 | import java.util.Enumeration; 22 | import java.util.Properties; 23 | 24 | import org.junit.Test; 25 | import org.slf4j.Logger; 26 | import org.slf4j.LoggerFactory; 27 | 28 | import org.company.security.csp.CSPNative; 29 | import org.company.security.csp.CSPProvider; 30 | import org.company.security.csp.ws.security.components.crypto.LocalMerlin; 31 | 32 | public class LocalMerlinTest { 33 | private static final Logger LOGGER = LoggerFactory.getLogger(LocalMerlinTest.class); 34 | 35 | public static final String CSP_PROVIDER = "CSPProvider"; 36 | public static final String CSPXML_PROVIDER = "CSPXMLDSig"; 37 | public static final String STORE_NAME = "Windows-MY"; 38 | 39 | @Test 40 | public void test() throws Exception { 41 | createProviders(); 42 | Properties config = getConfig(); 43 | LocalMerlin crypto = new LocalMerlin(config); 44 | 45 | LOGGER.debug("LocalMerlin получение ключей"); 46 | Enumeration aliases = crypto.getKeyStore().aliases(); 47 | int size = 0; 48 | while(aliases.hasMoreElements()) { 49 | String alias = aliases.nextElement(); 50 | LOGGER.debug("LocalMerlin load alias {}", alias); 51 | size++; 52 | } 53 | LOGGER.debug("Количество ключей в хранилище {}", size); 54 | } 55 | 56 | /** 57 | * Регистрация криптографических поставщиков 58 | */ 59 | private void createProviders() throws Exception { 60 | CSPNative.init("target/native", null); 61 | 62 | // Поставщик хеш функций и подписей 63 | if(Security.getProvider(CSP_PROVIDER) == null) 64 | Security.addProvider(new CSPProvider()); 65 | } 66 | 67 | private Properties getConfig() { 68 | Properties prop = new Properties(); 69 | prop.put("org.apache.ws.security.crypto.provider", "org.company.security.csp.ws.security.components.crypto.LocalMerlin"); 70 | prop.put("org.apache.ws.security.crypto.merlin.cert.provider", "CSPProvider"); 71 | prop.put("org.apache.ws.security.crypto.merlin.keystore.provider", "CSPProvider"); 72 | prop.put("org.apache.ws.security.crypto.merlin.keystore.type", "Windows-MY"); 73 | prop.put("org.apache.ws.security.crypto.merlin.truststore.type", "Windows-MY"); 74 | return prop; 75 | } 76 | 77 | /** 78 | * Находим первый доступный закрытый ключ для подписывания SOAP сообщения 79 | * @return 80 | * @throws Exception 81 | */ 82 | @Test 83 | public void findKeyAlias() throws Exception { 84 | KeyStore keyStore = java.security.KeyStore.getInstance(STORE_NAME, CSP_PROVIDER); 85 | keyStore.load(null, null); 86 | 87 | LOGGER.debug("KeyStore получение ключей"); 88 | int size = 0; 89 | for(Enumeration aliases = keyStore.aliases(); aliases.hasMoreElements(); ) { 90 | String alias = aliases.nextElement(); 91 | LOGGER.debug("KeyStore load alias {}", alias); 92 | size++; 93 | } 94 | LOGGER.debug("Количество ключей в хранилище {}", size); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /java-csp-wss4j/src/test/java/org/company/security/csp/wss4j/test/WSS4JCallbackHandlerImpl.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp.wss4j.test; 18 | 19 | import java.io.IOException; 20 | 21 | import javax.security.auth.callback.CallbackHandler; 22 | import javax.security.auth.callback.UnsupportedCallbackException; 23 | 24 | import org.apache.ws.security.WSPasswordCallback; 25 | 26 | public class WSS4JCallbackHandlerImpl implements CallbackHandler { 27 | 28 | private byte[] secret; 29 | 30 | public WSS4JCallbackHandlerImpl() { 31 | } 32 | 33 | public WSS4JCallbackHandlerImpl(byte[] secret) { 34 | this.secret = secret; 35 | } 36 | 37 | @Override 38 | public void handle(javax.security.auth.callback.Callback[] callbacks) throws IOException, UnsupportedCallbackException { 39 | WSPasswordCallback pc = (WSPasswordCallback) callbacks[0]; 40 | 41 | // if (pc.getUsage() == org.apache.wss4j.WSPasswordCallback.DECRYPT || pc.getUsage() == org.apache.ws.security.WSPasswordCallback.SIGNATURE) { 42 | pc.setPassword("default"); 43 | /* } else { 44 | throw new UnsupportedCallbackException(pc, "Unrecognized CallbackHandlerImpl"); 45 | } 46 | */ 47 | if (pc.getUsage() == WSPasswordCallback.SECURITY_CONTEXT_TOKEN) { 48 | pc.setKey(secret); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /java-csp-wss4j/src/test/java/org/company/security/csp/wss4j/test/hello_world_soap_http/FaultDetail.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp.wss4j.test.hello_world_soap_http; 18 | 19 | import javax.annotation.Generated; 20 | import javax.xml.bind.annotation.XmlAccessType; 21 | import javax.xml.bind.annotation.XmlAccessorType; 22 | import javax.xml.bind.annotation.XmlRootElement; 23 | import javax.xml.bind.annotation.XmlType; 24 | 25 | 26 | /** 27 | *

Java class for anonymous complex type. 28 | * 29 | *

The following schema fragment specifies the expected content contained within this class. 30 | * 31 | *

32 |  * <complexType>
33 |  *   <complexContent>
34 |  *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
35 |  *       <sequence>
36 |  *         <element name="minor" type="{http://www.w3.org/2001/XMLSchema}short"/>
37 |  *         <element name="major" type="{http://www.w3.org/2001/XMLSchema}short"/>
38 |  *       </sequence>
39 |  *     </restriction>
40 |  *   </complexContent>
41 |  * </complexType>
42 |  * 
43 | * 44 | * 45 | */ 46 | @XmlAccessorType(XmlAccessType.FIELD) 47 | @XmlType(name = "", propOrder = { 48 | "minor", 49 | "major" 50 | }) 51 | @XmlRootElement(name = "faultDetail") 52 | @Generated(value = "com.sun.tools.xjc.Driver", date = "2013-01-28T07:05:22-05:00", comments = "JAXB RI vhudson-jaxb-ri-2.1-2") 53 | public class FaultDetail { 54 | 55 | @Generated(value = "com.sun.tools.xjc.Driver", date = "2013-01-28T07:05:22-05:00", comments = "JAXB RI vhudson-jaxb-ri-2.1-2") 56 | protected short minor; 57 | @Generated(value = "com.sun.tools.xjc.Driver", date = "2013-01-28T07:05:22-05:00", comments = "JAXB RI vhudson-jaxb-ri-2.1-2") 58 | protected short major; 59 | 60 | /** 61 | * Gets the value of the minor property. 62 | * 63 | */ 64 | @Generated(value = "com.sun.tools.xjc.Driver", date = "2013-01-28T07:05:22-05:00", comments = "JAXB RI vhudson-jaxb-ri-2.1-2") 65 | public short getMinor() { 66 | return minor; 67 | } 68 | 69 | /** 70 | * Sets the value of the minor property. 71 | * 72 | */ 73 | @Generated(value = "com.sun.tools.xjc.Driver", date = "2013-01-28T07:05:22-05:00", comments = "JAXB RI vhudson-jaxb-ri-2.1-2") 74 | public void setMinor(short value) { 75 | this.minor = value; 76 | } 77 | 78 | /** 79 | * Gets the value of the major property. 80 | * 81 | */ 82 | @Generated(value = "com.sun.tools.xjc.Driver", date = "2013-01-28T07:05:22-05:00", comments = "JAXB RI vhudson-jaxb-ri-2.1-2") 83 | public short getMajor() { 84 | return major; 85 | } 86 | 87 | /** 88 | * Sets the value of the major property. 89 | * 90 | */ 91 | @Generated(value = "com.sun.tools.xjc.Driver", date = "2013-01-28T07:05:22-05:00", comments = "JAXB RI vhudson-jaxb-ri-2.1-2") 92 | public void setMajor(short value) { 93 | this.major = value; 94 | } 95 | 96 | } 97 | -------------------------------------------------------------------------------- /java-csp-wss4j/src/test/java/org/company/security/csp/wss4j/test/hello_world_soap_http/Greeter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp.wss4j.test.hello_world_soap_http; 18 | 19 | import javax.jws.Oneway; 20 | import javax.jws.WebMethod; 21 | import javax.jws.WebParam; 22 | import javax.jws.WebResult; 23 | import javax.jws.WebService; 24 | //import javax.xml.bind.annotation.XmlSeeAlso; 25 | import javax.xml.ws.RequestWrapper; 26 | import javax.xml.ws.ResponseWrapper; 27 | 28 | /** 29 | * This class was generated by Apache CXF 2.7.3 30 | * 2013-02-28T10:12:10.684Z 31 | * Generated source version: 2.7.3 32 | * 33 | */ 34 | @WebService(targetNamespace = "http://apache.org/hello_world_soap_http", name = "Greeter") 35 | //@XmlSeeAlso({org.apache.hello_world_soap_http.types.ObjectFactory.class}) 36 | public interface Greeter { 37 | 38 | @RequestWrapper(localName = "pingMe", targetNamespace = "http://apache.org/hello_world_soap_http/types", className = "org.apache.hello_world_soap_http.types.PingMe") 39 | @WebMethod 40 | @ResponseWrapper(localName = "pingMeResponse", targetNamespace = "http://apache.org/hello_world_soap_http/types", className = "org.apache.hello_world_soap_http.types.PingMeResponse") 41 | public void pingMe() throws PingMeFault; 42 | 43 | @WebResult(name = "responseType", targetNamespace = "http://apache.org/hello_world_soap_http/types") 44 | @RequestWrapper(localName = "sayHi", targetNamespace = "http://apache.org/hello_world_soap_http/types", className = "org.apache.hello_world_soap_http.types.SayHi") 45 | @WebMethod 46 | @ResponseWrapper(localName = "sayHiResponse", targetNamespace = "http://apache.org/hello_world_soap_http/types", className = "org.apache.hello_world_soap_http.types.SayHiResponse") 47 | public java.lang.String sayHi(); 48 | 49 | @Oneway 50 | @RequestWrapper(localName = "greetMeOneWay", targetNamespace = "http://apache.org/hello_world_soap_http/types", className = "org.apache.hello_world_soap_http.types.GreetMeOneWay") 51 | @WebMethod 52 | public void greetMeOneWay( 53 | @WebParam(name = "requestType", targetNamespace = "http://apache.org/hello_world_soap_http/types") 54 | java.lang.String requestType 55 | ); 56 | 57 | @WebResult(name = "responseType", targetNamespace = "http://apache.org/hello_world_soap_http/types") 58 | @RequestWrapper(localName = "greetMe", targetNamespace = "http://apache.org/hello_world_soap_http/types", className = "org.apache.hello_world_soap_http.types.GreetMe") 59 | @WebMethod 60 | @ResponseWrapper(localName = "greetMeResponse", targetNamespace = "http://apache.org/hello_world_soap_http/types", className = "org.apache.hello_world_soap_http.types.GreetMeResponse") 61 | public java.lang.String greetMe( 62 | @WebParam(name = "requestType", targetNamespace = "http://apache.org/hello_world_soap_http/types") 63 | java.lang.String requestType 64 | ); 65 | } 66 | -------------------------------------------------------------------------------- /java-csp-wss4j/src/test/java/org/company/security/csp/wss4j/test/hello_world_soap_http/GreeterServiceImpl.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp.wss4j.test.hello_world_soap_http; 18 | 19 | import javax.annotation.Resource; 20 | import javax.jws.WebParam; 21 | import javax.jws.WebService; 22 | import javax.xml.ws.WebServiceContext; 23 | 24 | //import org.apache.hello_world_soap_http.Greeter; 25 | //import org.apache.hello_world_soap_http.PingMeFault; 26 | 27 | @WebService(targetNamespace = "http://apache.org/hello_world_soap_http", 28 | serviceName = "SOAPService", 29 | endpointInterface = "org.company.security.csp.wss4j.test.hello_world_soap_http.Greeter") 30 | //endpointInterface = "org.apache.hello_world_soap_http.Greeter") 31 | public class GreeterServiceImpl implements Greeter { 32 | 33 | @Resource 34 | WebServiceContext context; 35 | 36 | @Override 37 | public void pingMe() throws PingMeFault { 38 | } 39 | 40 | @Override 41 | public String sayHi() { 42 | return "Hi"; 43 | } 44 | 45 | @Override 46 | public void greetMeOneWay(@WebParam(name = "requestType", targetNamespace = "http://apache.org/hello_world_soap_http/types") String requestType) { 47 | } 48 | 49 | @Override 50 | public String greetMe(@WebParam(name = "requestType", targetNamespace = "http://apache.org/hello_world_soap_http/types") String requestType) { 51 | return requestType; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /java-csp-wss4j/src/test/java/org/company/security/csp/wss4j/test/hello_world_soap_http/PingMeFault.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp.wss4j.test.hello_world_soap_http; 18 | 19 | import javax.xml.ws.WebFault; 20 | 21 | 22 | /** 23 | * This class was generated by Apache CXF 2.7.3 24 | * 2013-02-28T10:12:10.652Z 25 | * Generated source version: 2.7.3 26 | */ 27 | 28 | @WebFault(name = "faultDetail", targetNamespace = "http://apache.org/hello_world_soap_http/types") 29 | public class PingMeFault extends Exception { 30 | private static final long serialVersionUID = -8313446712127506030L; 31 | 32 | private FaultDetail faultDetail; 33 | 34 | public PingMeFault() { 35 | super(); 36 | } 37 | 38 | public PingMeFault(String message) { 39 | super(message); 40 | } 41 | 42 | public PingMeFault(String message, Throwable cause) { 43 | super(message, cause); 44 | } 45 | 46 | public PingMeFault(String message, FaultDetail faultDetail) { 47 | super(message); 48 | this.faultDetail = faultDetail; 49 | } 50 | 51 | public PingMeFault(String message, FaultDetail faultDetail, Throwable cause) { 52 | super(message, cause); 53 | this.faultDetail = faultDetail; 54 | } 55 | 56 | public FaultDetail getFaultInfo() { 57 | return this.faultDetail; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /java-csp-wss4j/src/test/java/org/company/security/csp/wss4j/test/hello_world_soap_http/SOAPService.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp.wss4j.test.hello_world_soap_http; 18 | 19 | import java.net.MalformedURLException; 20 | import java.net.URL; 21 | import javax.xml.namespace.QName; 22 | import javax.xml.ws.WebEndpoint; 23 | import javax.xml.ws.WebServiceClient; 24 | import javax.xml.ws.WebServiceFeature; 25 | import javax.xml.ws.Service; 26 | 27 | /** 28 | * This class was generated by Apache CXF 2.7.3 29 | * 2013-02-28T10:12:10.702Z 30 | * Generated source version: 2.7.3 31 | * 32 | */ 33 | @WebServiceClient(name = "SOAPService", 34 | wsdlLocation = "file:/home/hudson/hudson-slave/workspace/wss4j-trunk/wss4j/cxf-integration/src/test/resources/integration/helloWorld.wsdl", 35 | targetNamespace = "http://apache.org/hello_world_soap_http") 36 | public class SOAPService extends Service { 37 | 38 | public final static URL WSDL_LOCATION; 39 | 40 | public final static QName SERVICE = new QName("http://apache.org/hello_world_soap_http", "SOAPService"); 41 | public final static QName SoapPort = new QName("http://apache.org/hello_world_soap_http", "SoapPort"); 42 | static { 43 | URL url = null; 44 | try { 45 | url = new URL("file:/home/hudson/hudson-slave/workspace/wss4j-trunk/wss4j/cxf-integration/src/test/resources/integration/helloWorld.wsdl"); 46 | } catch (MalformedURLException e) { 47 | java.util.logging.Logger.getLogger(SOAPService.class.getName()) 48 | .log(java.util.logging.Level.INFO, 49 | "Can not initialize the default wsdl from {0}", "file:/home/hudson/hudson-slave/workspace/wss4j-trunk/wss4j/cxf-integration/src/test/resources/integration/helloWorld.wsdl"); 50 | } 51 | WSDL_LOCATION = url; 52 | } 53 | 54 | public SOAPService(URL wsdlLocation) { 55 | super(wsdlLocation, SERVICE); 56 | } 57 | 58 | public SOAPService(URL wsdlLocation, QName serviceName) { 59 | super(wsdlLocation, serviceName); 60 | } 61 | 62 | public SOAPService() { 63 | super(WSDL_LOCATION, SERVICE); 64 | } 65 | 66 | 67 | /** 68 | * 69 | * @return 70 | * returns Greeter 71 | */ 72 | @WebEndpoint(name = "SoapPort") 73 | public Greeter getSoapPort() { 74 | return super.getPort(SoapPort, Greeter.class); 75 | } 76 | 77 | /** 78 | * 79 | * @param features 80 | * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the features parameter will have their default values. 81 | * @return 82 | * returns Greeter 83 | */ 84 | @WebEndpoint(name = "SoapPort") 85 | public Greeter getSoapPort(WebServiceFeature... features) { 86 | return super.getPort(SoapPort, Greeter.class, features); 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /java-csp-wss4j/src/test/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=TRACE, out, outfile 2 | 3 | ## CONSOLE appender not used by default 4 | log4j.appender.out=org.apache.log4j.ConsoleAppender 5 | ##log4j.appender.out.threshold=WARN 6 | log4j.appender.out.layout=org.apache.log4j.PatternLayout 7 | log4j.appender.out.layout.ConversionPattern=%d{dd.MM.yy HH:mm:ss} [%30.30t] %-30.30c{1} %-5p %m%n 8 | 9 | log4j.appender.outfile=org.apache.log4j.FileAppender 10 | log4j.appender.outfile.File=target/logging.log 11 | log4j.appender.outfile.layout=org.apache.log4j.PatternLayout 12 | log4j.appender.outfile.layout.ConversionPattern=%d{dd.MM.yy HH:mm:ss} [%30.30t] %-30.30c{1} %-5p %m%n 13 | 14 | log4j.throwableRenderer=org.apache.log4j.EnhancedThrowableRenderer 15 | -------------------------------------------------------------------------------- /java-csp-wss4j/src/test/resources/receiver-crypto.properties: -------------------------------------------------------------------------------- 1 | org.apache.ws.security.crypto.provider=org.company.security.csp.ws.security.components.crypto.LocalMerlin 2 | org.apache.ws.security.crypto.merlin.cert.provider=CSPProvider 3 | org.apache.ws.security.crypto.merlin.keystore.provider=CSPProvider 4 | org.apache.ws.security.crypto.merlin.keystore.type=Windows-MY 5 | org.apache.ws.security.crypto.merlin.truststore.type=Windows-MY 6 | -------------------------------------------------------------------------------- /java-csp-wss4j/src/test/resources/transmitter-crypto.properties: -------------------------------------------------------------------------------- 1 | org.apache.ws.security.crypto.provider=org.company.security.csp.ws.security.components.crypto.LocalMerlin 2 | org.apache.ws.security.crypto.merlin.cert.provider=CSPProvider 3 | org.apache.ws.security.crypto.merlin.keystore.provider=CSPProvider 4 | org.apache.ws.security.crypto.merlin.keystore.type=Windows-MY 5 | org.apache.ws.security.crypto.merlin.truststore.type=Windows-MY 6 | -------------------------------------------------------------------------------- /java-csp-wss4j/src/test/resources/trusted/cert.sst: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexey-su/java-csp/e8453480b6a3a9036b03e37d8e108e0b7a1861b2/java-csp-wss4j/src/test/resources/trusted/cert.sst -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | 4 | 5 | org.company.security.csp 6 | parent 7 | 1.0.0-SNAPSHOT 8 | ../parent 9 | 10 | 11 | Java CSP XMLSIGN JSR-105 12 | java-csp-xmlsec-jsr105 13 | 14 | 15 | org.company.security.csp.xml.dsig.internal.dom 16 | 17 | 18 | 19 | 20 | ${project.groupId} 21 | java-csp-provider 22 | ${project.version} 23 | 24 | 25 | 26 | ${project.groupId} 27 | java-csp-provider-impl 28 | ${project.version} 29 | provided 30 | 31 | 32 | 33 | org.apache.santuario 34 | xmlsec 35 | 36 | 37 | org.slf4j 38 | slf4j-api 39 | 40 | 41 | 42 | 43 | org.slf4j 44 | slf4j-log4j12 45 | test 46 | 47 | 48 | junit 49 | junit 50 | test 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/main/java/org/company/security/csp/xml/dsig/internal/dom/ApacheData.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | /* 20 | * Copyright 2005 Sun Microsystems, Inc. All rights reserved. 21 | */ 22 | /* 23 | * $Id$ 24 | */ 25 | package org.company.security.csp.xml.dsig.internal.dom; 26 | 27 | import javax.xml.crypto.Data; 28 | import org.apache.xml.security.signature.XMLSignatureInput; 29 | 30 | /** 31 | * XMLSignatureInput Data wrapper. 32 | * 33 | * @author Sean Mullan 34 | */ 35 | public interface ApacheData extends Data { 36 | 37 | /** 38 | * Returns the XMLSignatureInput. 39 | */ 40 | XMLSignatureInput getXMLSignatureInput(); 41 | } 42 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/main/java/org/company/security/csp/xml/dsig/internal/dom/ApacheNodeSetData.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | /* 20 | * Copyright 2005 Sun Microsystems, Inc. All rights reserved. 21 | */ 22 | /* 23 | * $Id$ 24 | */ 25 | package org.company.security.csp.xml.dsig.internal.dom; 26 | 27 | import java.util.Collections; 28 | import java.util.Iterator; 29 | import java.util.LinkedHashSet; 30 | import java.util.List; 31 | import java.util.Set; 32 | import javax.xml.crypto.NodeSetData; 33 | import org.w3c.dom.Node; 34 | import org.apache.xml.security.signature.NodeFilter; 35 | import org.apache.xml.security.signature.XMLSignatureInput; 36 | import org.apache.xml.security.utils.XMLUtils; 37 | 38 | public class ApacheNodeSetData implements ApacheData, NodeSetData { 39 | 40 | private XMLSignatureInput xi; 41 | 42 | public ApacheNodeSetData(XMLSignatureInput xi) { 43 | this.xi = xi; 44 | } 45 | 46 | public Iterator iterator() { 47 | // If nodefilters are set, must execute them first to create node-set 48 | if (xi.getNodeFilters() != null) { 49 | return Collections.unmodifiableSet 50 | (getNodeSet(xi.getNodeFilters())).iterator(); 51 | } 52 | try { 53 | return Collections.unmodifiableSet(xi.getNodeSet()).iterator(); 54 | } catch (Exception e) { 55 | // should not occur 56 | throw new RuntimeException 57 | ("unrecoverable error retrieving nodeset", e); 58 | } 59 | } 60 | 61 | public XMLSignatureInput getXMLSignatureInput() { 62 | return xi; 63 | } 64 | 65 | private Set getNodeSet(List nodeFilters) { 66 | if (xi.isNeedsToBeExpanded()) { 67 | XMLUtils.circumventBug2650 68 | (XMLUtils.getOwnerDocument(xi.getSubNode())); 69 | } 70 | 71 | Set inputSet = new LinkedHashSet(); 72 | XMLUtils.getSet(xi.getSubNode(), inputSet, 73 | null, !xi.isExcludeComments()); 74 | Set nodeSet = new LinkedHashSet(); 75 | for (Node currentNode : inputSet) { 76 | Iterator it = nodeFilters.iterator(); 77 | boolean skipNode = false; 78 | while (it.hasNext() && !skipNode) { 79 | NodeFilter nf = it.next(); 80 | if (nf.isNodeInclude(currentNode) != 1) { 81 | skipNode = true; 82 | } 83 | } 84 | if (!skipNode) { 85 | nodeSet.add(currentNode); 86 | } 87 | } 88 | return nodeSet; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/main/java/org/company/security/csp/xml/dsig/internal/dom/ApacheOctetStreamData.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | /* 20 | * Copyright 2005 Sun Microsystems, Inc. All rights reserved. 21 | */ 22 | /* 23 | * $Id$ 24 | */ 25 | package org.company.security.csp.xml.dsig.internal.dom; 26 | 27 | import java.io.IOException; 28 | import javax.xml.crypto.OctetStreamData; 29 | import org.apache.xml.security.c14n.CanonicalizationException; 30 | import org.apache.xml.security.signature.XMLSignatureInput; 31 | 32 | public class ApacheOctetStreamData extends OctetStreamData 33 | implements ApacheData { 34 | 35 | private XMLSignatureInput xi; 36 | 37 | public ApacheOctetStreamData(XMLSignatureInput xi) 38 | throws CanonicalizationException, IOException 39 | { 40 | super(xi.getOctetStream(), xi.getSourceURI(), xi.getMIMEType()); 41 | this.xi = xi; 42 | } 43 | 44 | @Override 45 | public XMLSignatureInput getXMLSignatureInput() { 46 | return xi; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/main/java/org/company/security/csp/xml/dsig/internal/dom/BaseStructure.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | package org.company.security.csp.xml.dsig.internal.dom; 20 | 21 | import javax.xml.crypto.XMLStructure; 22 | 23 | import org.w3c.dom.Node; 24 | 25 | public abstract class BaseStructure implements XMLStructure { 26 | 27 | /** 28 | * Since the behavior of {@link Model#getStringValue(Object)} returns the value 29 | * of all descendant text nodes of an element, whereas we just want the immediate children. 30 | * 31 | * @param 32 | * @param model 33 | * @param node 34 | * @return 35 | */ 36 | public static String textOfNode(Node node) { 37 | return node.getFirstChild().getNodeValue(); 38 | } 39 | 40 | public final boolean isFeatureSupported(String feature) { 41 | if (feature == null) { 42 | throw new NullPointerException(); 43 | } else { 44 | return false; 45 | } 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/main/java/org/company/security/csp/xml/dsig/internal/dom/DOMBase64Transform.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | /* 20 | * Copyright 2005 Sun Microsystems, Inc. All rights reserved. 21 | */ 22 | /* 23 | * $Id$ 24 | */ 25 | package org.company.security.csp.xml.dsig.internal.dom; 26 | 27 | import java.security.InvalidAlgorithmParameterException; 28 | 29 | import javax.xml.crypto.dsig.spec.TransformParameterSpec; 30 | 31 | /** 32 | * DOM-based implementation of Base64 Encoding Transform. 33 | * (Uses Apache XML-Sec Transform implementation) 34 | * 35 | * @author Sean Mullan 36 | */ 37 | public final class DOMBase64Transform extends ApacheTransform { 38 | 39 | @Override 40 | public void init(TransformParameterSpec params) 41 | throws InvalidAlgorithmParameterException { 42 | if (params != null) { 43 | throw new InvalidAlgorithmParameterException("params must be null"); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/main/java/org/company/security/csp/xml/dsig/internal/dom/DOMCanonicalXMLC14N11Method.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | /* 20 | * Copyright 2008 Sun Microsystems, Inc. All rights reserved. 21 | */ 22 | /* 23 | * $Id$ 24 | */ 25 | package org.company.security.csp.xml.dsig.internal.dom; 26 | 27 | import javax.xml.crypto.*; 28 | import javax.xml.crypto.dsig.*; 29 | import javax.xml.crypto.dsig.spec.TransformParameterSpec; 30 | 31 | import java.security.InvalidAlgorithmParameterException; 32 | 33 | import org.apache.xml.security.c14n.Canonicalizer; 34 | import org.apache.xml.security.c14n.InvalidCanonicalizerException; 35 | 36 | /** 37 | * DOM-based implementation of CanonicalizationMethod for Canonical XML 1.1 38 | * (with or without comments). Uses Apache XML-Sec Canonicalizer. 39 | * 40 | * @author Sean Mullan 41 | */ 42 | public final class DOMCanonicalXMLC14N11Method extends ApacheCanonicalizer { 43 | 44 | public static final String C14N_11 = "http://www.w3.org/2006/12/xml-c14n11"; 45 | public static final String C14N_11_WITH_COMMENTS 46 | = "http://www.w3.org/2006/12/xml-c14n11#WithComments"; 47 | 48 | @Override 49 | public void init(TransformParameterSpec params) 50 | throws InvalidAlgorithmParameterException { 51 | if (params != null) { 52 | throw new InvalidAlgorithmParameterException("no parameters " + 53 | "should be specified for Canonical XML 1.1 algorithm"); 54 | } 55 | } 56 | 57 | @Override 58 | public Data transform(Data data, XMLCryptoContext xc) 59 | throws TransformException { 60 | 61 | // ignore comments if dereferencing same-document URI that requires 62 | // you to omit comments, even if the Transform says otherwise - 63 | // this is to be compliant with section 4.3.3.3 of W3C Rec. 64 | if (data instanceof DOMSubTreeData) { 65 | DOMSubTreeData subTree = (DOMSubTreeData) data; 66 | if (subTree.excludeComments()) { 67 | try { 68 | apacheCanonicalizer = Canonicalizer.getInstance(C14N_11); 69 | } catch (InvalidCanonicalizerException ice) { 70 | throw new TransformException 71 | ("Couldn't find Canonicalizer for: " + 72 | C14N_11 + ": " + ice.getMessage(), ice); 73 | } 74 | } 75 | } 76 | 77 | return canonicalize(data, xc); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/main/java/org/company/security/csp/xml/dsig/internal/dom/DOMCanonicalXMLC14NMethod.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | /* 20 | * Copyright 2005 Sun Microsystems, Inc. All rights reserved. 21 | */ 22 | /* 23 | * $Id$ 24 | */ 25 | package org.company.security.csp.xml.dsig.internal.dom; 26 | 27 | import javax.xml.crypto.*; 28 | import javax.xml.crypto.dsig.*; 29 | import javax.xml.crypto.dsig.spec.TransformParameterSpec; 30 | 31 | import java.security.InvalidAlgorithmParameterException; 32 | 33 | import org.apache.xml.security.c14n.Canonicalizer; 34 | import org.apache.xml.security.c14n.InvalidCanonicalizerException; 35 | 36 | /** 37 | * DOM-based implementation of CanonicalizationMethod for Canonical XML 38 | * (with or without comments). Uses Apache XML-Sec Canonicalizer. 39 | * 40 | * @author Sean Mullan 41 | */ 42 | public final class DOMCanonicalXMLC14NMethod extends ApacheCanonicalizer { 43 | 44 | @Override 45 | public void init(TransformParameterSpec params) 46 | throws InvalidAlgorithmParameterException { 47 | if (params != null) { 48 | throw new InvalidAlgorithmParameterException("no parameters " + 49 | "should be specified for Canonical XML C14N algorithm"); 50 | } 51 | } 52 | 53 | @Override 54 | public Data transform(Data data, XMLCryptoContext xc) 55 | throws TransformException { 56 | 57 | // ignore comments if dereferencing same-document URI that requires 58 | // you to omit comments, even if the Transform says otherwise - 59 | // this is to be compliant with section 4.3.3.3 of W3C Rec. 60 | if (data instanceof DOMSubTreeData) { 61 | DOMSubTreeData subTree = (DOMSubTreeData) data; 62 | if (subTree.excludeComments()) { 63 | try { 64 | apacheCanonicalizer = Canonicalizer.getInstance 65 | (CanonicalizationMethod.INCLUSIVE); 66 | } catch (InvalidCanonicalizerException ice) { 67 | throw new TransformException 68 | ("Couldn't find Canonicalizer for: " + 69 | CanonicalizationMethod.INCLUSIVE + ": " + 70 | ice.getMessage(), ice); 71 | } 72 | } 73 | } 74 | 75 | return canonicalize(data, xc); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/main/java/org/company/security/csp/xml/dsig/internal/dom/DOMCanonicalizationMethod.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | /* 20 | * Copyright 2005 Sun Microsystems, Inc. All rights reserved. 21 | */ 22 | /* 23 | * $Id$ 24 | */ 25 | package org.company.security.csp.xml.dsig.internal.dom; 26 | 27 | import java.io.OutputStream; 28 | import java.security.InvalidAlgorithmParameterException; 29 | import java.security.Provider; 30 | 31 | import org.w3c.dom.Element; 32 | 33 | import javax.xml.crypto.*; 34 | import javax.xml.crypto.dsig.*; 35 | 36 | /** 37 | * DOM-based abstract implementation of CanonicalizationMethod. 38 | * 39 | * @author Sean Mullan 40 | */ 41 | public class DOMCanonicalizationMethod extends DOMTransform 42 | implements CanonicalizationMethod { 43 | 44 | /** 45 | * Creates a DOMCanonicalizationMethod. 46 | * 47 | * @param spi TransformService 48 | */ 49 | public DOMCanonicalizationMethod(TransformService spi) 50 | throws InvalidAlgorithmParameterException 51 | { 52 | super(spi); 53 | } 54 | 55 | /** 56 | * Creates a DOMCanonicalizationMethod from an element. This 57 | * ctor invokes the abstract {@link #unmarshalParams unmarshalParams} 58 | * method to unmarshal any algorithm-specific input parameters. 59 | * 60 | * @param cmElem a CanonicalizationMethod element 61 | */ 62 | public DOMCanonicalizationMethod(Element cmElem, XMLCryptoContext context, 63 | Provider provider) 64 | throws MarshalException 65 | { 66 | super(cmElem, context, provider); 67 | } 68 | 69 | /** 70 | * Canonicalizes the specified data using the underlying canonicalization 71 | * algorithm. This is a convenience method that is equivalent to invoking 72 | * the {@link #transform transform} method. 73 | * 74 | * @param data the data to be canonicalized 75 | * @param xc the XMLCryptoContext containing 76 | * additional context (may be null if not applicable) 77 | * @return the canonicalized data 78 | * @throws NullPointerException if data is null 79 | * @throws TransformException if an unexpected error occurs while 80 | * canonicalizing the data 81 | */ 82 | public Data canonicalize(Data data, XMLCryptoContext xc) 83 | throws TransformException 84 | { 85 | return transform(data, xc); 86 | } 87 | 88 | public Data canonicalize(Data data, XMLCryptoContext xc, OutputStream os) 89 | throws TransformException 90 | { 91 | return transform(data, xc, os); 92 | } 93 | 94 | @Override 95 | public boolean equals(Object o) { 96 | if (this == o) { 97 | return true; 98 | } 99 | 100 | if (!(o instanceof CanonicalizationMethod)) { 101 | return false; 102 | } 103 | CanonicalizationMethod ocm = (CanonicalizationMethod)o; 104 | 105 | return (getAlgorithm().equals(ocm.getAlgorithm()) && 106 | DOMUtils.paramsEqual(getParameterSpec(), ocm.getParameterSpec())); 107 | } 108 | 109 | @Override 110 | public int hashCode() { 111 | assert false : "hashCode not designed"; 112 | return 42; // any arbitrary constant will do 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/main/java/org/company/security/csp/xml/dsig/internal/dom/DOMDigestMethodFactory.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp.xml.dsig.internal.dom; 18 | 19 | import java.security.InvalidAlgorithmParameterException; 20 | import java.security.MessageDigest; 21 | import java.security.NoSuchAlgorithmException; 22 | 23 | import javax.xml.crypto.MarshalException; 24 | import javax.xml.crypto.dsig.DigestMethod; 25 | import javax.xml.crypto.dsig.spec.DigestMethodParameterSpec; 26 | 27 | import org.apache.xml.security.algorithms.JCEMapper; 28 | import org.w3c.dom.Element; 29 | 30 | public class DOMDigestMethodFactory { 31 | 32 | public DigestMethod unmarshal(Element dmElem) throws MarshalException { 33 | String xmlAlgorithm = DOMUtils.getAttributeValue(dmElem, "Algorithm"); 34 | String jceAlgorithm = JCEMapper.translateURItoJCEID(xmlAlgorithm); 35 | DigestMethodParameterSpec params = null; 36 | 37 | if(jceAlgorithm != null) { 38 | try { 39 | MessageDigest.getInstance(jceAlgorithm); 40 | } 41 | catch(NoSuchAlgorithmException e) { 42 | throw new MarshalException("unsupported DigestMethod algorithm: " + xmlAlgorithm, e); 43 | } 44 | } 45 | else { 46 | throw new MarshalException("unsupported DigestMethod algorithm: " + xmlAlgorithm); 47 | } 48 | 49 | DOMDigestMethodProxy proxy = null; 50 | try { 51 | proxy = new DOMDigestMethodProxy(xmlAlgorithm, jceAlgorithm, params); 52 | 53 | Element paramsElem = DOMUtils.getFirstChildElement(dmElem); 54 | if (paramsElem != null) { 55 | params = proxy.unmarshalParams(paramsElem); 56 | 57 | if (params != null) { 58 | proxy.checkParams(params); 59 | proxy = new DOMDigestMethodProxy(xmlAlgorithm, jceAlgorithm, params); 60 | } 61 | } 62 | } 63 | catch (InvalidAlgorithmParameterException iape) { 64 | throw new MarshalException(iape); 65 | } 66 | return proxy; 67 | } 68 | 69 | public DigestMethod newDigestMethod(String algorithm, 70 | DigestMethodParameterSpec params) throws NoSuchAlgorithmException, 71 | InvalidAlgorithmParameterException { 72 | 73 | String jceAlgorithm = JCEMapper.translateURItoJCEID(algorithm); 74 | 75 | if(jceAlgorithm != null) { 76 | MessageDigest.getInstance(jceAlgorithm); 77 | } 78 | else { 79 | throw new NoSuchAlgorithmException("unsupported algorithm " + algorithm); 80 | } 81 | 82 | return new DOMDigestMethodProxy(algorithm, jceAlgorithm, params); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/main/java/org/company/security/csp/xml/dsig/internal/dom/DOMDigestMethodProxy.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp.xml.dsig.internal.dom; 18 | 19 | import java.security.InvalidAlgorithmParameterException; 20 | import java.security.spec.AlgorithmParameterSpec; 21 | 22 | import javax.xml.crypto.MarshalException; 23 | import javax.xml.crypto.dsig.DigestMethod; 24 | import javax.xml.crypto.dsig.spec.DigestMethodParameterSpec; 25 | 26 | import org.w3c.dom.Element; 27 | 28 | public class DOMDigestMethodProxy extends BaseStructure implements DigestMethod { 29 | private String xmlAlgorithm; 30 | private String jceAlgorithm; 31 | private DigestMethodParameterSpec params; 32 | 33 | public DOMDigestMethodProxy(String xmlAlgorithm, String jceAlgorithm, 34 | DigestMethodParameterSpec params) 35 | throws InvalidAlgorithmParameterException { 36 | this.xmlAlgorithm = xmlAlgorithm; 37 | this.jceAlgorithm = jceAlgorithm; 38 | 39 | if (params != null && !(params instanceof DigestMethodParameterSpec)) { 40 | throw new InvalidAlgorithmParameterException( 41 | "params must be of type DigestMethodParameterSpec"); 42 | } 43 | checkParams((DigestMethodParameterSpec) params); 44 | this.params = (DigestMethodParameterSpec) params; 45 | } 46 | 47 | public String getMessageDigestAlgorithm() { 48 | return jceAlgorithm; 49 | } 50 | 51 | @Override 52 | public String getAlgorithm() { 53 | return xmlAlgorithm; 54 | } 55 | 56 | @Override 57 | public AlgorithmParameterSpec getParameterSpec() { 58 | return params; 59 | } 60 | 61 | /** 62 | * Checks if the specified parameters are valid for this algorithm. By 63 | * default, this method throws an exception if parameters are specified 64 | * since most DigestMethod algorithms do not have parameters. Subclasses 65 | * should override it if they have parameters. 66 | * 67 | * @param params 68 | * the algorithm-specific params (may be null) 69 | * @throws InvalidAlgorithmParameterException 70 | * if the parameters are not appropriate for this digest method 71 | */ 72 | void checkParams(DigestMethodParameterSpec params) 73 | throws InvalidAlgorithmParameterException { 74 | if (params != null) { 75 | throw new InvalidAlgorithmParameterException("no parameters " 76 | + "should be specified for the " 77 | + getMessageDigestAlgorithm() + " DigestMethod algorithm"); 78 | } 79 | } 80 | 81 | /** 82 | * Unmarshals DigestMethodParameterSpec from the specified 83 | * Element. By default, this method throws an exception since 84 | * most DigestMethod algorithms do not have parameters. Subclasses should 85 | * override it if they have parameters. 86 | * 87 | * @param paramsElem 88 | * the Element holding the input params 89 | * @return the algorithm-specific DigestMethodParameterSpec 90 | * @throws MarshalException 91 | * if the parameters cannot be unmarshalled 92 | */ 93 | public DigestMethodParameterSpec unmarshalParams(Element paramsElem) 94 | throws MarshalException { 95 | throw new MarshalException("no parameters should " 96 | + "be specified for the " + getMessageDigestAlgorithm() 97 | + " DigestMethod algorithm"); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/main/java/org/company/security/csp/xml/dsig/internal/dom/DOMEnvelopedTransform.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | /* 20 | * Copyright 2005 Sun Microsystems, Inc. All rights reserved. 21 | */ 22 | /* 23 | * $Id$ 24 | */ 25 | package org.company.security.csp.xml.dsig.internal.dom; 26 | 27 | import java.security.InvalidAlgorithmParameterException; 28 | import javax.xml.crypto.dsig.spec.TransformParameterSpec; 29 | 30 | /** 31 | * DOM-based implementation of Enveloped Signature Transform. 32 | * (Uses Apache XML-Sec Transform implementation) 33 | * 34 | * @author Sean Mullan 35 | */ 36 | public final class DOMEnvelopedTransform extends ApacheTransform { 37 | 38 | @Override 39 | public void init(TransformParameterSpec params) 40 | throws InvalidAlgorithmParameterException { 41 | if (params != null) { 42 | throw new InvalidAlgorithmParameterException("params must be null"); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/main/java/org/company/security/csp/xml/dsig/internal/dom/DOMKeyInfoFactory.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | /* 20 | * Copyright 2005 Sun Microsystems, Inc. All rights reserved. 21 | */ 22 | /* 23 | * $Id$ 24 | */ 25 | package org.company.security.csp.xml.dsig.internal.dom; 26 | 27 | import java.math.BigInteger; 28 | import java.security.KeyException; 29 | import java.security.PublicKey; 30 | import java.security.interfaces.DSAPublicKey; 31 | import java.security.interfaces.ECPublicKey; 32 | import java.security.interfaces.RSAPublicKey; 33 | import java.util.List; 34 | import javax.xml.crypto.*; 35 | import javax.xml.crypto.dom.DOMCryptoContext; 36 | import javax.xml.crypto.dsig.keyinfo.*; 37 | import org.w3c.dom.Document; 38 | import org.w3c.dom.Element; 39 | import org.w3c.dom.Node; 40 | 41 | /** 42 | * DOM-based implementation of KeyInfoFactory. 43 | * 44 | * @author Sean Mullan 45 | */ 46 | public final class DOMKeyInfoFactory extends KeyInfoFactory { 47 | 48 | public DOMKeyInfoFactory() { } 49 | 50 | @Override 51 | @SuppressWarnings("rawtypes") 52 | public KeyInfo newKeyInfo(List content) { 53 | return newKeyInfo(content, null); 54 | } 55 | 56 | @Override 57 | @SuppressWarnings({ "unchecked", "rawtypes" }) 58 | public KeyInfo newKeyInfo(List content, String id) { 59 | return new DOMKeyInfo(content, id); 60 | } 61 | 62 | @Override 63 | public KeyName newKeyName(String name) { 64 | return new DOMKeyName(name); 65 | } 66 | 67 | @Override 68 | public KeyValue newKeyValue(PublicKey key) throws KeyException { 69 | return DOMKeyValue.newKeyValue(key); 70 | } 71 | 72 | @Override 73 | public PGPData newPGPData(byte[] keyId) { 74 | return newPGPData(keyId, null, null); 75 | } 76 | 77 | @Override 78 | @SuppressWarnings({ "rawtypes", "unchecked" }) 79 | public PGPData newPGPData(byte[] keyId, byte[] keyPacket, List other) { 80 | return new DOMPGPData(keyId, keyPacket, other); 81 | } 82 | 83 | @Override 84 | @SuppressWarnings({ "unchecked", "rawtypes" }) 85 | public PGPData newPGPData(byte[] keyPacket, List other) { 86 | return new DOMPGPData(keyPacket, other); 87 | } 88 | 89 | @Override 90 | public RetrievalMethod newRetrievalMethod(String uri) { 91 | return newRetrievalMethod(uri, null, null); 92 | } 93 | 94 | @Override 95 | @SuppressWarnings({ "unchecked", "rawtypes" }) 96 | public RetrievalMethod newRetrievalMethod(String uri, String type, 97 | List transforms) { 98 | if (uri == null) { 99 | throw new NullPointerException("uri must not be null"); 100 | } 101 | return new DOMRetrievalMethod(uri, type, transforms); 102 | } 103 | 104 | @Override 105 | @SuppressWarnings("rawtypes") 106 | public X509Data newX509Data(List content) { 107 | return new DOMX509Data(content); 108 | } 109 | 110 | @Override 111 | public X509IssuerSerial newX509IssuerSerial(String issuerName, 112 | BigInteger serialNumber) { 113 | return new DOMX509IssuerSerial(issuerName, serialNumber); 114 | } 115 | 116 | @Override 117 | public boolean isFeatureSupported(String feature) { 118 | if (feature == null) { 119 | throw new NullPointerException(); 120 | } else { 121 | return false; 122 | } 123 | } 124 | 125 | @Override 126 | public URIDereferencer getURIDereferencer() { 127 | return DOMURIDereferencer.INSTANCE; 128 | } 129 | 130 | @Override 131 | public KeyInfo unmarshalKeyInfo(XMLStructure xmlStructure) 132 | throws MarshalException { 133 | if (xmlStructure == null || !(xmlStructure instanceof javax.xml.crypto.dom.DOMStructure)) { 134 | throw new ClassCastException("xmlStructure must be of type DOMStructure"); 135 | } 136 | Node node = 137 | ((javax.xml.crypto.dom.DOMStructure) xmlStructure).getNode(); 138 | node.normalize(); 139 | 140 | Element element = null; 141 | if (node.getNodeType() == Node.DOCUMENT_NODE) { 142 | element = ((Document) node).getDocumentElement(); 143 | } else if (node.getNodeType() == Node.ELEMENT_NODE) { 144 | element = (Element) node; 145 | } else { 146 | throw new MarshalException 147 | ("xmlStructure does not contain a proper Node"); 148 | } 149 | 150 | // check tag 151 | String tag = element.getLocalName(); 152 | if (tag == null) { 153 | throw new MarshalException("Document implementation must " + 154 | "support DOM Level 2 and be namespace aware"); 155 | } 156 | if (tag.equals("KeyInfo")) { 157 | return new DOMKeyInfo(element, new UnmarshalContext(), getProvider()); 158 | } else { 159 | throw new MarshalException("invalid KeyInfo tag: " + tag); 160 | } 161 | } 162 | 163 | private static class UnmarshalContext extends DOMCryptoContext { 164 | UnmarshalContext() {} 165 | } 166 | 167 | } 168 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/main/java/org/company/security/csp/xml/dsig/internal/dom/DOMKeyName.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | /* 20 | * Copyright 2005 Sun Microsystems, Inc. All rights reserved. 21 | */ 22 | /* 23 | * $Id$ 24 | */ 25 | package org.company.security.csp.xml.dsig.internal.dom; 26 | 27 | import javax.xml.crypto.dsig.keyinfo.KeyName; 28 | 29 | import org.w3c.dom.Element; 30 | 31 | /** 32 | * DOM-based implementation of KeyName. 33 | * 34 | * @author Sean Mullan 35 | */ 36 | public final class DOMKeyName extends BaseStructure implements KeyName { 37 | 38 | private final String name; 39 | 40 | /** 41 | * Creates a DOMKeyName. 42 | * 43 | * @param name the name of the key identifier 44 | * @throws NullPointerException if name is null 45 | */ 46 | public DOMKeyName(String name) { 47 | if (name == null) { 48 | throw new NullPointerException("name cannot be null"); 49 | } 50 | this.name = name; 51 | } 52 | 53 | /** 54 | * Creates a DOMKeyName from a KeyName element. 55 | * 56 | * @param knElem a KeyName element 57 | */ 58 | public DOMKeyName(Element knElem) { 59 | name = textOfNode(knElem); 60 | } 61 | 62 | @Override 63 | public String getName() { 64 | return name; 65 | } 66 | 67 | @Override 68 | public boolean equals(Object obj) { 69 | if (this == obj) { 70 | return true; 71 | } 72 | if (!(obj instanceof KeyName)) { 73 | return false; 74 | } 75 | KeyName okn = (KeyName)obj; 76 | return name.equals(okn.getName()); 77 | } 78 | 79 | @Override 80 | public int hashCode() { 81 | int result = 17; 82 | if (name != null) { 83 | result = 31 * result + name.hashCode(); 84 | } 85 | 86 | return result; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/main/java/org/company/security/csp/xml/dsig/internal/dom/DOMStructure.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | /* 20 | * Copyright 2005 Sun Microsystems, Inc. All rights reserved. 21 | */ 22 | /* 23 | * $Id$ 24 | */ 25 | package org.company.security.csp.xml.dsig.internal.dom; 26 | 27 | import javax.xml.crypto.MarshalException; 28 | import javax.xml.crypto.XMLCryptoContext; 29 | 30 | /** 31 | * DOM-based abstract implementation of XMLStructure. 32 | * 33 | * @author Sean Mullan 34 | */ 35 | public abstract class DOMStructure extends BaseStructure { 36 | 37 | public abstract void marshal(XmlWriter xwriter, String dsPrefix, XMLCryptoContext context) throws MarshalException; 38 | } 39 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/main/java/org/company/security/csp/xml/dsig/internal/dom/DOMURIDereferencer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | /* 20 | * Copyright 2005 Sun Microsystems, Inc. All rights reserved. 21 | */ 22 | /* 23 | * $Id$ 24 | */ 25 | package org.company.security.csp.xml.dsig.internal.dom; 26 | 27 | import org.w3c.dom.Attr; 28 | import org.w3c.dom.Element; 29 | import org.w3c.dom.Node; 30 | 31 | import org.apache.xml.security.Init; 32 | import org.apache.xml.security.utils.XMLUtils; 33 | import org.apache.xml.security.utils.resolver.ResourceResolver; 34 | import org.apache.xml.security.signature.XMLSignatureInput; 35 | 36 | import javax.xml.crypto.*; 37 | import javax.xml.crypto.dom.*; 38 | 39 | /** 40 | * DOM-based implementation of URIDereferencer. 41 | * 42 | * @author Sean Mullan 43 | */ 44 | public class DOMURIDereferencer implements URIDereferencer { 45 | 46 | static final URIDereferencer INSTANCE = new DOMURIDereferencer(); 47 | 48 | private DOMURIDereferencer() { 49 | // need to call org.apache.xml.security.Init.init() 50 | // before calling any apache security code 51 | Init.init(); 52 | } 53 | 54 | @Override 55 | public Data dereference(URIReference uriRef, XMLCryptoContext context) 56 | throws URIReferenceException { 57 | 58 | if (uriRef == null) { 59 | throw new NullPointerException("uriRef cannot be null"); 60 | } 61 | if (context == null) { 62 | throw new NullPointerException("context cannot be null"); 63 | } 64 | 65 | DOMURIReference domRef = (DOMURIReference) uriRef; 66 | Attr uriAttr = (Attr) domRef.getHere(); 67 | String uri = uriRef.getURI(); 68 | DOMCryptoContext dcc = (DOMCryptoContext) context; 69 | String baseURI = context.getBaseURI(); 70 | 71 | Boolean secureValidation = (Boolean) 72 | context.getProperty("org.apache.jcp.xml.dsig.secureValidation"); 73 | boolean secVal = false; 74 | if (secureValidation != null && secureValidation) { 75 | secVal = true; 76 | } 77 | 78 | // Check if same-document URI and already registered on the context 79 | if (uri != null && uri.length() != 0 && uri.charAt(0) == '#') { 80 | String id = uri.substring(1); 81 | 82 | if (id.startsWith("xpointer(id(")) { 83 | int i1 = id.indexOf('\''); 84 | int i2 = id.indexOf('\'', i1+1); 85 | id = id.substring(i1+1, i2); 86 | } 87 | 88 | Node referencedElem = dcc.getElementById(id); 89 | if (referencedElem != null) { 90 | if (secVal) { 91 | Element start = referencedElem.getOwnerDocument().getDocumentElement(); 92 | if (!XMLUtils.protectAgainstWrappingAttack(start, (Element)referencedElem, id)) { 93 | String error = "Multiple Elements with the same ID " + id + " were detected"; 94 | throw new URIReferenceException(error); 95 | } 96 | } 97 | 98 | XMLSignatureInput result = new XMLSignatureInput(referencedElem); 99 | if (!uri.substring(1).startsWith("xpointer(id(")) { 100 | result.setExcludeComments(true); 101 | } 102 | 103 | result.setMIMEType("text/xml"); 104 | if (baseURI != null && baseURI.length() > 0) { 105 | result.setSourceURI(baseURI.concat(uriAttr.getNodeValue())); 106 | } else { 107 | result.setSourceURI(uriAttr.getNodeValue()); 108 | } 109 | return new ApacheNodeSetData(result); 110 | } 111 | } 112 | 113 | try { 114 | ResourceResolver apacheResolver = 115 | ResourceResolver.getInstance(uriAttr, baseURI, secVal); 116 | XMLSignatureInput in = apacheResolver.resolve(uriAttr, baseURI); 117 | // TODO xmlsec 2.0 change method signature 118 | // XMLSignatureInput in = apacheResolver.resolve(uriAttr, baseURI, secVal); 119 | if (in.isOctetStream()) { 120 | return new ApacheOctetStreamData(in); 121 | } else { 122 | return new ApacheNodeSetData(in); 123 | } 124 | } catch (Exception e) { 125 | throw new URIReferenceException(e); 126 | } 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/main/java/org/company/security/csp/xml/dsig/internal/dom/DOMX509IssuerSerial.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | /* 20 | * Copyright 2005 Sun Microsystems, Inc. All rights reserved. 21 | */ 22 | /* 23 | * $Id$ 24 | */ 25 | package org.company.security.csp.xml.dsig.internal.dom; 26 | 27 | import javax.xml.crypto.dsig.keyinfo.X509IssuerSerial; 28 | 29 | import java.math.BigInteger; 30 | import javax.security.auth.x500.X500Principal; 31 | import org.w3c.dom.Element; 32 | 33 | /** 34 | * DOM-based implementation of X509IssuerSerial. 35 | * 36 | * @author Sean Mullan 37 | */ 38 | public final class DOMX509IssuerSerial extends BaseStructure 39 | implements X509IssuerSerial { 40 | 41 | private final String issuerName; 42 | private final BigInteger serialNumber; 43 | 44 | /** 45 | * Creates a DOMX509IssuerSerial containing the specified 46 | * issuer distinguished name/serial number pair. 47 | * 48 | * @param issuerName the X.509 issuer distinguished name in RFC 2253 49 | * String format 50 | * @param serialNumber the serial number 51 | * @throws IllegalArgumentException if the format of issuerName 52 | * is not RFC 2253 compliant 53 | * @throws NullPointerException if issuerName or 54 | * serialNumber is null 55 | */ 56 | public DOMX509IssuerSerial(String issuerName, BigInteger serialNumber) { 57 | if (issuerName == null) { 58 | throw new NullPointerException("issuerName cannot be null"); 59 | } 60 | if (serialNumber == null) { 61 | throw new NullPointerException("serialNumber cannot be null"); 62 | } 63 | // check that issuer distinguished name conforms to RFC 2253 64 | new X500Principal(issuerName); 65 | this.issuerName = issuerName; 66 | this.serialNumber = serialNumber; 67 | } 68 | 69 | /** 70 | * Creates a DOMX509IssuerSerial from an element. 71 | * 72 | * @param isElem an X509IssuerSerial element 73 | */ 74 | public DOMX509IssuerSerial(Element isElem) { 75 | Element iNElem = DOMUtils.getFirstChildElement(isElem); 76 | Element sNElem = DOMUtils.getNextSiblingElement(iNElem); 77 | issuerName = iNElem.getFirstChild().getNodeValue(); 78 | serialNumber = new BigInteger(sNElem.getFirstChild().getNodeValue()); 79 | } 80 | 81 | @Override 82 | public String getIssuerName() { 83 | return issuerName; 84 | } 85 | 86 | @Override 87 | public BigInteger getSerialNumber() { 88 | return serialNumber; 89 | } 90 | 91 | @Override 92 | public boolean equals(Object obj) { 93 | if (this == obj) { 94 | return true; 95 | } 96 | if (!(obj instanceof X509IssuerSerial)) { 97 | return false; 98 | } 99 | X509IssuerSerial ois = (X509IssuerSerial)obj; 100 | return (issuerName.equals(ois.getIssuerName()) && 101 | serialNumber.equals(ois.getSerialNumber())); 102 | } 103 | 104 | @Override 105 | public int hashCode() { 106 | int result = 17; 107 | if (issuerName != null) { 108 | result = 31 * result + issuerName.hashCode(); 109 | } 110 | if (serialNumber != null) { 111 | result = 31 * result + serialNumber.hashCode(); 112 | } 113 | 114 | return result; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/main/java/org/company/security/csp/xml/dsig/internal/dom/DOMXPathTransform.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | /* 20 | * Copyright 2005 Sun Microsystems, Inc. All rights reserved. 21 | */ 22 | /* 23 | * $Id$ 24 | */ 25 | package org.company.security.csp.xml.dsig.internal.dom; 26 | 27 | import javax.xml.crypto.*; 28 | import javax.xml.crypto.dsig.*; 29 | import javax.xml.crypto.dsig.spec.TransformParameterSpec; 30 | import javax.xml.crypto.dsig.spec.XPathFilterParameterSpec; 31 | import java.security.InvalidAlgorithmParameterException; 32 | import java.util.HashMap; 33 | import java.util.Map; 34 | import java.util.Set; 35 | import org.w3c.dom.Attr; 36 | import org.w3c.dom.Element; 37 | import org.w3c.dom.NamedNodeMap; 38 | 39 | /** 40 | * DOM-based implementation of XPath Filtering Transform. 41 | * (Uses Apache XML-Sec Transform implementation) 42 | * 43 | * @author Sean Mullan 44 | */ 45 | public final class DOMXPathTransform extends ApacheTransform { 46 | 47 | @Override 48 | public void init(TransformParameterSpec params) 49 | throws InvalidAlgorithmParameterException 50 | { 51 | if (params == null) { 52 | throw new InvalidAlgorithmParameterException("params are required"); 53 | } else if (!(params instanceof XPathFilterParameterSpec)) { 54 | throw new InvalidAlgorithmParameterException 55 | ("params must be of type XPathFilterParameterSpec"); 56 | } 57 | this.params = params; 58 | } 59 | 60 | @Override 61 | public void init(XMLStructure parent, XMLCryptoContext context) 62 | throws InvalidAlgorithmParameterException 63 | { 64 | super.init(parent, context); 65 | unmarshalParams(DOMUtils.getFirstChildElement(transformElem)); 66 | } 67 | 68 | private void unmarshalParams(Element paramsElem) { 69 | String xPath = paramsElem.getFirstChild().getNodeValue(); 70 | // create a Map of namespace prefixes 71 | NamedNodeMap attributes = paramsElem.getAttributes(); 72 | if (attributes != null) { 73 | int length = attributes.getLength(); 74 | Map namespaceMap = 75 | new HashMap(length); 76 | for (int i = 0; i < length; i++) { 77 | Attr attr = (Attr)attributes.item(i); 78 | String prefix = attr.getPrefix(); 79 | if (prefix != null && prefix.equals("xmlns")) { 80 | namespaceMap.put(attr.getLocalName(), attr.getValue()); 81 | } 82 | } 83 | this.params = new XPathFilterParameterSpec(xPath, namespaceMap); 84 | } else { 85 | this.params = new XPathFilterParameterSpec(xPath); 86 | } 87 | } 88 | 89 | @Override 90 | public void marshalParams(XMLStructure parent, XMLCryptoContext context) 91 | throws MarshalException 92 | { 93 | super.marshalParams(parent, context); 94 | XPathFilterParameterSpec xp = 95 | (XPathFilterParameterSpec)getParameterSpec(); 96 | Element xpathElem = DOMUtils.createElement(ownerDoc, "XPath", 97 | XMLSignature.XMLNS, DOMUtils.getSignaturePrefix(context)); 98 | xpathElem.appendChild(ownerDoc.createTextNode(xp.getXPath())); 99 | 100 | // add namespace attributes, if necessary 101 | @SuppressWarnings("unchecked") 102 | Set> entries = 103 | xp.getNamespaceMap().entrySet(); 104 | for (Map.Entry entry : entries) { 105 | xpathElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + 106 | entry.getKey(), 107 | entry.getValue()); 108 | } 109 | 110 | transformElem.appendChild(xpathElem); 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/main/java/org/company/security/csp/xml/dsig/internal/dom/DOMXSLTTransform.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | /* 20 | * Copyright 2005 Sun Microsystems, Inc. All rights reserved. 21 | */ 22 | /* 23 | * $Id$ 24 | */ 25 | package org.company.security.csp.xml.dsig.internal.dom; 26 | 27 | import java.security.InvalidAlgorithmParameterException; 28 | import org.w3c.dom.Element; 29 | import org.w3c.dom.Node; 30 | 31 | import javax.xml.crypto.*; 32 | import javax.xml.crypto.dsig.spec.TransformParameterSpec; 33 | import javax.xml.crypto.dsig.spec.XSLTTransformParameterSpec; 34 | 35 | /** 36 | * DOM-based implementation of XSLT Transform. 37 | * (Uses Apache XML-Sec Transform implementation) 38 | * 39 | * @author Sean Mullan 40 | */ 41 | public final class DOMXSLTTransform extends ApacheTransform { 42 | 43 | @Override 44 | public void init(TransformParameterSpec params) 45 | throws InvalidAlgorithmParameterException { 46 | if (params == null) { 47 | throw new InvalidAlgorithmParameterException("params are required"); 48 | } 49 | if (!(params instanceof XSLTTransformParameterSpec)) { 50 | throw new InvalidAlgorithmParameterException("unrecognized params"); 51 | } 52 | this.params = params; 53 | } 54 | 55 | @Override 56 | public void init(XMLStructure parent, XMLCryptoContext context) 57 | throws InvalidAlgorithmParameterException { 58 | 59 | super.init(parent, context); 60 | unmarshalParams(DOMUtils.getFirstChildElement(transformElem)); 61 | } 62 | 63 | private void unmarshalParams(Element sheet) { 64 | this.params = new XSLTTransformParameterSpec 65 | (new javax.xml.crypto.dom.DOMStructure(sheet)); 66 | } 67 | 68 | @Override 69 | public void marshalParams(XMLStructure parent, XMLCryptoContext context) 70 | throws MarshalException { 71 | super.marshalParams(parent, context); 72 | XSLTTransformParameterSpec xp = 73 | (XSLTTransformParameterSpec) getParameterSpec(); 74 | Node xsltElem = 75 | ((javax.xml.crypto.dom.DOMStructure) xp.getStylesheet()).getNode(); 76 | DOMUtils.appendChild(transformElem, xsltElem); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/main/java/org/company/security/csp/xml/dsig/internal/dom/Utils.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | /* 20 | * Copyright 2005 Sun Microsystems, Inc. All rights reserved. 21 | */ 22 | /* 23 | * $Id$ 24 | */ 25 | package org.company.security.csp.xml.dsig.internal.dom; 26 | 27 | import java.io.ByteArrayOutputStream; 28 | import java.io.InputStream; 29 | import java.io.IOException; 30 | import java.util.*; 31 | import org.w3c.dom.NamedNodeMap; 32 | import org.w3c.dom.Node; 33 | 34 | /** 35 | * Miscellaneous static utility methods for use in JSR 105 RI. 36 | * 37 | * @author Sean Mullan 38 | */ 39 | public final class Utils { 40 | 41 | private Utils() {} 42 | 43 | public static byte[] readBytesFromStream(InputStream is) 44 | throws IOException 45 | { 46 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 47 | byte[] buf = new byte[1024]; 48 | while (true) { 49 | int read = is.read(buf); 50 | if (read == -1) { // EOF 51 | break; 52 | } 53 | baos.write(buf, 0, read); 54 | if (read < 1024) { 55 | break; 56 | } 57 | } 58 | return baos.toByteArray(); 59 | } 60 | 61 | /** 62 | * Converts an Iterator to a Set of Nodes, according to the XPath 63 | * Data Model. 64 | * 65 | * @param i the Iterator 66 | * @return the Set of Nodes 67 | */ 68 | static Set toNodeSet(Iterator i) { 69 | Set nodeSet = new HashSet(); 70 | while (i.hasNext()) { 71 | Node n = i.next(); 72 | nodeSet.add(n); 73 | // insert attributes nodes to comply with XPath 74 | if (n.getNodeType() == Node.ELEMENT_NODE) { 75 | NamedNodeMap nnm = n.getAttributes(); 76 | for (int j = 0, length = nnm.getLength(); j < length; j++) { 77 | nodeSet.add(nnm.item(j)); 78 | } 79 | } 80 | } 81 | return nodeSet; 82 | } 83 | 84 | /** 85 | * Returns the ID from a same-document URI (ex: "#id") 86 | */ 87 | public static String parseIdFromSameDocumentURI(String uri) { 88 | if (uri.length() == 0) { 89 | return null; 90 | } 91 | String id = uri.substring(1); 92 | if (id != null && id.startsWith("xpointer(id(")) { 93 | int i1 = id.indexOf('\''); 94 | int i2 = id.indexOf('\'', i1+1); 95 | id = id.substring(i1+1, i2); 96 | } 97 | return id; 98 | } 99 | 100 | /** 101 | * Returns true if uri is a same-document URI, false otherwise. 102 | */ 103 | public static boolean sameDocumentURI(String uri) { 104 | return (uri != null && (uri.length() == 0 || uri.charAt(0) == '#')); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/main/java/org/company/security/csp/xml/dsig/internal/dom/XmlWriter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | package org.company.security.csp.xml.dsig.internal.dom; 20 | 21 | import javax.xml.crypto.MarshalException; 22 | import javax.xml.crypto.XMLCryptoContext; 23 | import javax.xml.crypto.XMLStructure; 24 | import javax.xml.stream.XMLStreamWriter; 25 | 26 | import org.w3c.dom.Attr; 27 | 28 | /** 29 | * This interface is used to construct XML via a sequence of API calls. 30 | * 31 | *

This is written to be similar to javax.xml.stream.XMLStreamWriter, but 32 | * has slightly different requirements. Specifically, we need to be able to create 33 | * an "ID" type attribute, and get the current node. 34 | *

35 | */ 36 | public interface XmlWriter { 37 | 38 | /** 39 | * Utility class that brings together the class, and the method for marshaling an 40 | * instance of said class. 41 | * 42 | * @param 43 | */ 44 | public static abstract class ToMarshal { 45 | public final Class clazzToMatch; 46 | 47 | public ToMarshal(Class clazzToMatch) { 48 | this.clazzToMatch = clazzToMatch; 49 | } 50 | 51 | public abstract void marshalObject(XmlWriter xwriter, CLZ toMarshal, String dsPrefix, 52 | XMLCryptoContext context) throws MarshalException; 53 | } 54 | 55 | /** 56 | * 57 | * @param prefix What prefix to use? 58 | * @param localName What local name to use? 59 | * @param namespaceURI What namespace URI? 60 | * 61 | * @see {@link XMLStreamWriter#writeStartElement(String, String, String)} 62 | */ 63 | void writeStartElement(String prefix, String localName, String namespaceURI); 64 | 65 | /** 66 | * @see {@link XMLStreamWriter#writeEndElement()} 67 | */ 68 | void writeEndElement(); 69 | 70 | /** 71 | * Convenience method that writes both a start and end tag, with text contents as 72 | * provided. 73 | * 74 | * @param prefix 75 | * @param localName 76 | * @param namespaceURI 77 | * @param value 78 | */ 79 | void writeTextElement(String prefix, String localName, String namespaceURI, String value); 80 | 81 | void writeNamespace(String prefix, String namespaceURI); 82 | 83 | void writeCharacters(String text); 84 | 85 | void writeComment(String text); 86 | 87 | Attr writeAttribute(String prefix, String namespaceURI, String localName, String value); 88 | 89 | void writeIdAttribute(String prefix, String namespaceURI, String localName, String value); 90 | 91 | /** 92 | * Get the local name of the current element. 93 | * @return 94 | */ 95 | String getCurrentLocalName(); 96 | 97 | XMLStructure getCurrentNodeAsStructure(); 98 | 99 | /** 100 | * This method marshals a structure, and relies on implementation specific details for how 101 | * an instance of a particular class maps to the method that actually does the marshaling. 102 | * 103 | * @param toMarshal The object to be marshaled. 104 | * @param dsPrefix The digital signature prefix. 105 | * @param context The context for marshaling. 106 | * @throws MarshalException Thrown if something goes wrong during the marshaling. 107 | */ 108 | void marshalStructure(XMLStructure toMarshal, String dsPrefix, XMLCryptoContext context) throws MarshalException; 109 | } 110 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/main/java/org/company/security/csp/xml/security/exceptions/Base64DecodingException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | package org.company.security.csp.xml.security.exceptions; 20 | 21 | import org.apache.xml.security.exceptions.XMLSecurityException; 22 | 23 | /** 24 | * This Exception is thrown if decoding of Base64 data fails. 25 | * 26 | * @author Christian Geuer-Pollmann 27 | */ 28 | public class Base64DecodingException extends XMLSecurityException { 29 | 30 | private static final long serialVersionUID = 1L; 31 | 32 | /** 33 | * Constructor Base64DecodingException 34 | * 35 | */ 36 | public Base64DecodingException() { 37 | super(); 38 | } 39 | 40 | /** 41 | * Constructor Base64DecodingException 42 | * 43 | * @param msgID 44 | */ 45 | public Base64DecodingException(String msgID) { 46 | super(msgID); 47 | } 48 | 49 | /** 50 | * Constructor Base64DecodingException 51 | * 52 | * @param msgID 53 | * @param exArgs 54 | */ 55 | public Base64DecodingException(String msgID, Object exArgs[]) { 56 | super(msgID, exArgs); 57 | } 58 | 59 | /** 60 | * Constructor Base64DecodingException 61 | * 62 | * @param msgID 63 | * @param originalException 64 | */ 65 | public Base64DecodingException(String msgID, Exception originalException) { 66 | super(msgID, originalException); 67 | } 68 | 69 | /** 70 | * Constructor Base64DecodingException 71 | * 72 | * @param msgID 73 | * @param exArgs 74 | * @param originalException 75 | */ 76 | public Base64DecodingException(String msgID, Object exArgs[], Exception originalException) { 77 | super(msgID, exArgs, originalException); 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/test/java/org/company/security/csp/xml/dsig/test/SignatureValidator.java-t: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | /* 20 | * Copyright 2005 Sun Microsystems, Inc. All rights reserved. 21 | */ 22 | package javax.xml.crypto.test.dsig; 23 | 24 | import java.io.*; 25 | import java.util.*; 26 | import javax.xml.crypto.*; 27 | import javax.xml.crypto.dsig.*; 28 | import javax.xml.crypto.dsig.dom.DOMValidateContext; 29 | import javax.xml.parsers.DocumentBuilderFactory; 30 | import org.w3c.dom.Document; 31 | import org.w3c.dom.Node; 32 | import org.w3c.dom.Element; 33 | import org.w3c.dom.traversal.*; 34 | 35 | /** 36 | * This is a class which performs xml signature validation upon request 37 | * 38 | * @author Sean Mullan 39 | * @author Valerie Peng 40 | */ 41 | public class SignatureValidator { 42 | 43 | private File dir; 44 | 45 | public SignatureValidator(File base) { 46 | dir = base; 47 | } 48 | 49 | public boolean validate(String fn, KeySelector ks) throws Exception { 50 | return validate(fn, ks, null); 51 | } 52 | 53 | public DOMValidateContext getValidateContext(String fn, KeySelector ks) 54 | throws Exception { 55 | DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 56 | dbf.setNamespaceAware(true); 57 | dbf.setValidating(false); 58 | Document doc = dbf.newDocumentBuilder().parse(new File(dir, fn)); 59 | Element sigElement = getSignatureElement(doc); 60 | if (sigElement == null) { 61 | throw new Exception("Couldn't find signature Element"); 62 | } 63 | DOMValidateContext vc = new DOMValidateContext(ks, sigElement); 64 | vc.setBaseURI(dir.toURI().toString()); 65 | return vc; 66 | } 67 | 68 | public boolean validate(String fn, KeySelector ks, URIDereferencer ud) 69 | throws Exception { 70 | 71 | DOMValidateContext vc = getValidateContext(fn, ks); 72 | if (ud != null) { 73 | vc.setURIDereferencer(ud); 74 | } 75 | 76 | return validate(vc); 77 | } 78 | 79 | public boolean validate(DOMValidateContext vc) throws Exception { 80 | 81 | XMLSignatureFactory factory = XMLSignatureFactory.getInstance 82 | ("DOM", new org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI()); 83 | XMLSignature signature = factory.unmarshalXMLSignature(vc); 84 | boolean coreValidity = signature.validate(vc); 85 | 86 | // Check core validation status 87 | if (coreValidity == false) { 88 | // check the validation status of each Reference 89 | Iterator i = signature.getSignedInfo().getReferences().iterator(); 90 | while (i.hasNext()) { 91 | Reference reference = (Reference) i.next(); 92 | reference.validate(vc); 93 | } 94 | } 95 | return coreValidity; 96 | } 97 | 98 | public static Element getSignatureElement(Document doc) { 99 | NodeIterator ni = ((DocumentTraversal)doc).createNodeIterator( 100 | doc.getDocumentElement(), NodeFilter.SHOW_ELEMENT, null, false); 101 | 102 | for (Node n = ni.nextNode(); n != null; n = ni.nextNode() ) { 103 | if ("Signature".equals(n.getLocalName())) { 104 | return (Element) n; 105 | } 106 | } 107 | return null; 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/test/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=TRACE, out, outfile 2 | 3 | ## CONSOLE appender not used by default 4 | log4j.appender.out=org.apache.log4j.ConsoleAppender 5 | ##log4j.appender.out.threshold=WARN 6 | log4j.appender.out.layout=org.apache.log4j.PatternLayout 7 | log4j.appender.out.layout.ConversionPattern=%d{dd.MM.yy HH:mm:ss} [%30.30t] %-30.30c{1} %-5p %m%n 8 | 9 | log4j.appender.outfile=org.apache.log4j.FileAppender 10 | log4j.appender.outfile.File=target/logging.log 11 | log4j.appender.outfile.layout=org.apache.log4j.PatternLayout 12 | log4j.appender.outfile.layout.ConversionPattern=%d{dd.MM.yy HH:mm:ss} [%30.30t] %-30.30c{1} %-5p %m%n 13 | 14 | log4j.throwableRenderer=org.apache.log4j.EnhancedThrowableRenderer 15 | -------------------------------------------------------------------------------- /java-csp-xmlsec-jsr105/src/test/resources/signature-enveloping-gost-template.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /java-csp-xmlsec-santuario/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | 4 | 5 | org.company.security.csp 6 | parent 7 | 1.0.0-SNAPSHOT 8 | ../parent 9 | 10 | 11 | Java CSP XMLSIGN with Apache Santuario 12 | java-csp-xmlsec-santuario 13 | 14 | 15 | org.company.security.csp.xml.security.*;-split-package:=first, 16 | 17 | 18 | 19 | 20 | ${project.groupId} 21 | java-csp-provider 22 | ${project.version} 23 | 24 | 25 | 26 | org.apache.santuario 27 | xmlsec 28 | 29 | 30 | org.slf4j 31 | slf4j-api 32 | 33 | 34 | -------------------------------------------------------------------------------- /java-csp-xmlsec-santuario/src/main/java/org/company/security/csp/xml/security/XmlDSignTools.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp.xml.security; 18 | 19 | import java.security.Provider; 20 | import java.security.Security; 21 | 22 | 23 | //import org.apache.ws.security.WSSConfig; 24 | import org.apache.xml.security.algorithms.JCEMapper; 25 | import org.apache.xml.security.algorithms.SignatureAlgorithm; 26 | import org.apache.xml.security.exceptions.AlgorithmAlreadyRegisteredException; 27 | import org.apache.xml.security.signature.XMLSignatureException; 28 | import org.apache.xml.security.utils.Constants; 29 | import org.company.security.csp.xml.security.algorithms.SignatureGostR34102001Gostr3411; 30 | import org.company.security.csp.xml.security.algorithms.SignatureGostR34102001URN; 31 | 32 | 33 | /** 34 | * Инициализация XMLDSIGN. 35 | * Базовый JCPxml не инициализируется в следствии разных ClassLoader. 36 | */ 37 | public class XmlDSignTools { 38 | public static final String URL_V1_ALGORITHM_DIGEST = Constants.MoreAlgorithmsSpecNS + "gostr3411"; 39 | public static final String URL_V2_ALGORITHM_DIGEST = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr3411"; 40 | public static final String URL_V1_ALGORITHM_SIGNATURE = Constants.MoreAlgorithmsSpecNS + "gostr34102001-gostr3411"; 41 | public static final String URL_V2_ALGORITHM_SIGNATURE = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34102001-gostr3411"; 42 | public static final String URL_V1_ALGORITHM_ENCRIPTION = Constants.MoreAlgorithmsSpecNS + "gost28147"; 43 | public static final String URL_V2_ALGORITHM_ENCRIPTION = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gost28147"; 44 | 45 | public static final String JCENAME_ALGORITHM_DIGEST = "GOST3411"; 46 | public static final String JCENAME_ALGORITHM_SIGNATURE = "GOST3411withGOST3410EL"; 47 | public static final String JCENAME_ALGORITHM_ENCRIPTION = "GostJCE/CBC/ISO10126Padding"; 48 | 49 | public static void init(String providerId) throws AlgorithmAlreadyRegisteredException, XMLSignatureException, ClassNotFoundException { 50 | org.apache.xml.security.Init.init(); 51 | 52 | // CryptoPro MessageDigest 53 | JCEMapper.Algorithm digest = new JCEMapper.Algorithm("", JCENAME_ALGORITHM_DIGEST, "MessageDigest"); 54 | JCEMapper.register(URL_V1_ALGORITHM_DIGEST, digest); 55 | JCEMapper.register(URL_V2_ALGORITHM_DIGEST, digest); 56 | 57 | // CryptoPro Signature 58 | JCEMapper.Algorithm signature = new JCEMapper.Algorithm("", JCENAME_ALGORITHM_SIGNATURE, "Signature"); 59 | JCEMapper.register(URL_V1_ALGORITHM_SIGNATURE, signature); 60 | JCEMapper.register(URL_V2_ALGORITHM_SIGNATURE, signature); 61 | 62 | // CryptoPro BlockEncryption 63 | JCEMapper.Algorithm encryption = new JCEMapper.Algorithm("GOST28147", JCENAME_ALGORITHM_ENCRIPTION, "BlockEncryption", 256); 64 | JCEMapper.register(URL_V1_ALGORITHM_ENCRIPTION, encryption); 65 | JCEMapper.register(URL_V2_ALGORITHM_ENCRIPTION, encryption); 66 | 67 | SignatureAlgorithm.register(URL_V1_ALGORITHM_SIGNATURE, SignatureGostR34102001Gostr3411.class); 68 | SignatureAlgorithm.register(URL_V2_ALGORITHM_SIGNATURE, SignatureGostR34102001URN.class); 69 | 70 | // устанавливаем криптопровайдера 71 | JCEMapper.setProviderId(providerId); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /java-csp-xmlsec-santuario/src/main/java/org/company/security/csp/xml/security/algorithms/SignatureGostR34102001Gostr3411.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp.xml.security.algorithms; 18 | 19 | import org.apache.xml.security.signature.XMLSignatureException; 20 | import org.apache.xml.security.utils.Constants; 21 | 22 | public class SignatureGostR34102001Gostr3411 extends SignatureGostR34102001 { 23 | 24 | /** Field _URI */ 25 | public static final String _URI = Constants.MoreAlgorithmsSpecNS + "gostr34102001-gostr3411"; 26 | 27 | @Override 28 | protected String engineGetURI() { 29 | return SignatureGostR34102001Gostr3411._URI; 30 | } 31 | 32 | /** 33 | * Constructor SignatureGostr34102001Gostr3411 34 | * 35 | * @throws XMLSignatureException 36 | */ 37 | public SignatureGostR34102001Gostr3411() throws XMLSignatureException { 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /java-csp-xmlsec-santuario/src/main/java/org/company/security/csp/xml/security/algorithms/SignatureGostR34102001URN.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.company.security.csp.xml.security.algorithms; 18 | 19 | import org.apache.xml.security.signature.XMLSignatureException; 20 | 21 | public class SignatureGostR34102001URN extends SignatureGostR34102001 { 22 | /** Field _URI */ 23 | public static final String _URI = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34102001-gostr3411"; 24 | 25 | @Override 26 | protected String engineGetURI() { 27 | return SignatureGostR34102001Gostr3411._URI; 28 | } 29 | 30 | /** 31 | * Constructor SignatureGost34102001URN 32 | * 33 | * @throws XMLSignatureException 34 | */ 35 | public SignatureGostR34102001URN() throws XMLSignatureException { 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | org.company.security.csp 4 | java-csp 5 | 1.0.0-SNAPSHOT 6 | pom 7 | 8 | 9 | parent 10 | java-csp-provider-impl 11 | java-csp-native 12 | java-csp-provider 13 | java-csp-xmlsec-jsr105 14 | java-csp-xmlsec-santuario 15 | java-csp-wss4j 16 | 17 | --------------------------------------------------------------------------------