I am trying to validate an assertion signature received from an IDP. It results in a failure with following error :
Verification failed for URI "#_7e59add4-11a0-415f-85a3-6f493110d198"
Expected Digest: PgSvwq0Jn6GLMHID20j1fT40VlhvdavKxEM3PtNUfLM=
Actual Digest: mDcfPO26UwGV/tt/JM20ADDDkGGODjd2CZn7dqqR5LM=
org.opensaml.xml.signature.SignatureValidator(SignatureValidator.java:77) -
Signature did not validate against the credential's key
following is the code I am using to validate :
public class SamlTest {
public static void main(String[] args) throws Exception {
// read the file
File file = new File("d://a.xml");
BufferedReader bf = new BufferedReader(new FileReader(file));
String str = null;
String samlStr = "";
while ((str = bf.readLine()) != null) {
samlStr += str;
}
Assertion assertion = SamlTest.unmarshall(samlStr);
//Always do Profile Validation before cryptographically verify the Signature
SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator();
try {
profileValidator.validate(assertion.getSignature());
} catch (ValidationException e) {
System.out.println("ErrorString [Error in SAMLSignatureProfilValidation]");
}
Certificate certificate = SamlTest.getCertificate(assertion.getSignature());
BasicCredential verificationCredential = new BasicCredential();
verificationCredential.setPublicKey(certificate.getPublicKey());
SignatureValidator sigValidator = new SignatureValidator(verificationCredential);
try {
sigValidator.validate(assertion.getSignature());
} catch (ValidationException e) {
System.out.println("unable to validate");
}
}
private static Assertion unmarshall(String samlStr) throws Exception {
DefaultBootstrap.bootstrap();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = null;
docBuilder = documentBuilderFactory.newDocumentBuilder();
ByteArrayInputStream is = new ByteArrayInputStream(samlStr.getBytes());
Document document = null;
document = docBuilder.parse(is);
Element element = document.getDocumentElement();
UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
return (Assertion) unmarshaller.unmarshall(element);
}
private static Certificate getCertificate(Signature signature) {
try {
X509Certificate certificate = signature.getKeyInfo().getX509Datas().get(0).getX509Certificates().get(0);
if (certificate != null) {
//Converts org.opensaml.xml.signature.X509Certificate to java.security.cert.Certificate
String lexicalXSDBase64Binary = certificate.getValue();
byte[] decoded = DatatypeConverter.parseBase64Binary(lexicalXSDBase64Binary);
try {
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(decoded));
return cert;
} catch (CertificateException e) {
//this should never happen
System.out.println("SAML Signature issue");
return null;
}
}
return null; // TODO Auto-generated method stub
} catch (NullPointerException e) {
//Null certificates
return null;
}
}}
below is the assertion xml received : `
<?xml version="1.0" encoding="UTF-8" standalone="no"?><saml2:Assertion xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" xmlns="http://docs.oasis-open.org/ws-sx/ws-trust/200512" xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns10="urn:oasis:names:tc:SAML:2.0:conditions:delegation" xmlns:ns2="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:ns3="http://www.rsa.com/names/2009/12/std-ext/WS-Trust1.4/advice" xmlns:ns4="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:ns5="http://www.w3.org/2000/09/xmldsig#" xmlns:ns6="http://www.rsa.com/names/2009/12/std-ext/SAML2.0" xmlns:ns7="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:ns8="http://docs.oasis-open.org/ws-sx/ws-trust/200802" xmlns:ns9="http://www.w3.org/2005/08/addressing" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ID="_7e59add4-11a0-415f-85a3-6f493110d198" IssueInstant="2015-06-16T19:38:03.664Z" Version="2.0"><saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://localhost/websso/SAML2/Metadata/vsphere.local</saml2:Issuer><ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/><ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/><ds:Reference URI="#_7e59add4-11a0-415f-85a3-6f493110d198"><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"><ec:InclusiveNamespaces xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="xs xsi"/></ds:Transform></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/><ds:DigestValue>PgSvwq0Jn6GLMHID20j1fT40VlhvdavKxEM3PtNUfLM=</ds:DigestValue></ds:Reference></ds:SignedInfo><ds:SignatureValue>ovoMj6mUzEnhayptgu3MwQOiBEs47GO8Xs/H02SgO8/881X5m7anAmS8yIjHiOTu3Q0kNJH1K2cQ
uBNxKQG75jPHbM3wF6XVKLbcyjAWHjtg3Ndz6F2spIP13LZ7LM2KUBcwGh9YWBnybJWxwr70+qj0
7xHO5wEnV3RpkQPCjMgAfnesEAEHoCGpnQNQu0twSffWzKLKZcg6PHS2g49WY1r65Sw5Jcy9/VdN
4/mtEuNa4fb0wNbaKcpPxsjUo7dbeMdbZxl5T0E2pOTzGJkRKVfw1P6Vd2qIFrORVpfni5LAYkET
GJA40iY7wfVLJflIX7+9QcIEtMKsL5rbtxvQpQ==</ds:SignatureValue><ds:KeyInfo><ds:X509Data><ds:X509Certificate>MIIDcDCCAligAwIBAgIJAMGuXxNnFfBZMA0GCSqGSIb3DQEBCwUAMFwxCzAJBgNVBAMMAkNBMRcw
FQYKCZImiZPyLGQBGRYHdnNwaGVyZTEVMBMGCgmSJomT8ixkARkWBWxvY2FsMQswCQYDVQQGEwJV
UzEQMA4GA1UECgwHcnVjaGF2YzAeFw0xNTAyMTcxNjMzNTFaFw0yNTAyMTExNjQzNDJaMBgxF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gj1WIIB6o8w9R
HsZwm4eVFYhJWWvi9N2wci8X5PMdDi/abUxhOT7EYEQGk39dfc/VTEQoMKrE</ds:X509Certificate></ds:X509Data></ds:KeyInfo></ds:Signature><saml2:Subject><saml2:NameID Format="http://schemas.xmlsoap.org/claims/UPN">Administrator</saml2:NameID><saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:holder-of-key"><saml2:NameID Format="http://schemas.xmlsoap.org/claims/UPN">vsphere-webclient-21665f80-b6c4-11e4-b9fe-005056a638d3#vsphere.local</saml2:NameID><saml2:SubjectConfirmationData xsi:type="saml2:KeyInfoConfirmationDataType"><ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><ds:X509Data><ds:X509Certificate>MIID5TCCAs2gAwIBAgIJAMk0TrGWNX/vMA0GCSqGSIb3DQEBCwUAMFwxCzAJBgNVBAMMAkNBMRcw
FQYKCZImiZPyLGQBGRYHdnNwaGVyZTEVMBMGCgmSJomT8ixkARkWBWxvY2FsMQswCQYDVQQGEwJV
UzEQMA4GA1UECgwHcnVjaGF2YzAeFw0xNTAyMTcxNjM1MDhaFw0yNTAyMTExNjQzNDJaMIGMMRow
GAYDVQQDDBF2c3BoZXJlLXdlYmNsaWVudDEXMBUGCgmSJomT8ixkARkWB3ZzcGhlcmUxFTATBgoJ
kiaJk/IsZAEZFgVsb2NhbDELMAkGA1UEBhMCVVMxMTAvBgNVBAsMKG1JRC0yMTY2NWY4MC1iNmM0
LTExZTQtYjlmZS0wMDUwNTZhNjM4ZDMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDA
zkp7RK+aOZqq4+yyp/gfsLr4jQnOiLCNGdvEeLXVhUPWogYl0MkHEt3DY6i2HqL0xmmPeRjmOJ1T
62eR3Nc8ugrapKUy7bYgCTT6rzvjU7KtzHg/SncuwncrB53//lSndJ41UtTWNxZSqqja3tmfg3pT
4EQkv0YiyEeayKJhfNz6XiuL12wdBvai0SIEFIsZTq92hNlTs4W58tT8ov6408BEMtRcTVHrOSAS
BS2waelqHAt141PWos3ynz4MUsxRs2p0T77K+wh2Mj/eWQgJJnVVuc4oVA1uLOQHjP777QV/gEkd
p6v42q8b+24LtTWJssMIVvmsmvoEtItDbpApAgMBAAGjeTB3MAsGA1UdDwQEAwIF4DAoBgNVHREE
ITAfgh1ydWNoYXZjLnRlc3RsYWIuY29tbXZhdWx0LmNvbTAdBgNVHQ4EFgQUHR0Ta1eFnWxSD37T
ZFPQncCZYlswHwYDVR0jBBgwFoAU++fsPhJCQ4XETaWO1bQCjDDAgM8wDQYJKoZIhvcNAQELBQAD
ggEBAETECKs16qfadNvLwNysQq5F9Y9pAhnss6PniRLdQ2D7dbKgLNjgi4CIEV3SuaDXaqONV9IV
+IjAg6N+yMqGghc64MyAzDS0Rkp2R7hfNjyYUcG9lNTSpsKSZE0iNb9RWaqrPKu4RsnPvjIStx43
EytkF63Q7ktYxFCXlnB9AVeMa6nfOzFZS+SXHrd+zWs62Hp/9mBHLoHKEYYQawpJlbBnAkg8WZxq
uVE/Ky5Gv8ni3eAovM2g0Ot7gqqbfPH09Yk4L9pBUPw/lT2icBvZ6yHgWxmEnZuHBKUF5B8F0smI
TSCwNY2lUghkxxCdTEaqsthPGb9uYEB6JFJDgblgEBg=</ds:X509Certificate></ds:X509Data></ds:KeyInfo></saml2:SubjectConfirmationData></saml2:SubjectConfirmation></saml2:Subject><saml2:Conditions NotBefore="2015-06-16T19:38:51.295Z" NotOnOrAfter="2015-07-16T19:38:51.295Z"><saml2:ProxyRestriction Count="9"/><saml2:Condition xmlns:del="urn:oasis:names:tc:SAML:2.0:conditions:delegation" xsi:type="del:DelegationRestrictionType"><del:Delegate DelegationInstant="2015-06-16T19:36:37.101Z"><saml2:NameID Format="http://schemas.xmlsoap.org/claims/UPN">vsphere-webclient-21665f80-b6c4-11e4-b9fe-005056a638d3#vsphere.local</saml2:NameID></del:Delegate></saml2:Condition><saml2:Condition xmlns:rsa="http://www.rsa.com/names/2009/12/std-ext/SAML2.0" Count="9" xsi:type="rsa:RenewRestrictionType"/></saml2:Conditions><saml2:AuthnStatement AuthnInstant="2015-06-16T19:38:03.662Z"><saml2:AuthnContext><saml2:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PreviousSession</saml2:AuthnContextClassRef></saml2:AuthnContext></saml2:AuthnStatement><saml2:AttributeStatement><saml2:Attribute FriendlyName="givenName" Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"><saml2:AttributeValue xsi:type="xs:string">Administrator</saml2:AttributeValue></saml2:Attribute><saml2:Attribute FriendlyName="Groups" Name="http://rsa.com/schemas/attr-names/2009/01/GroupIdentity" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"><saml2:AttributeValue xsi:type="xs:string">SophosAdministrator</saml2:AttributeValue><saml2:AttributeValue xsi:type="xs:string">Administrators</saml2:AttributeValue><saml2:AttributeValue xsi:type="xs:string">vsphere.localAdministrators</saml2:AttributeValue><saml2:AttributeValue xsi:type="xs:string">vsphere.localEveryone</saml2:AttributeValue></saml2:Attribute><saml2:Attribute FriendlyName="Subject Type" Name="http://vmware.com/schemas/attr-names/2011/07/isSolution" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"><saml2:AttributeValue xsi:type="xs:string">false</saml2:AttributeValue></saml2:Attribute><saml2:Attribute FriendlyName="surname" Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"><saml2:AttributeValue xsi:type="xs:string"/></saml2:Attribute></saml2:AttributeStatement></saml2:Assertion>
`could someone please help me find the issue here.
Related
In a REST service adding a circuit breaker with hystrix, I could do the following:
#HystrixCommand(fallbackMethod = "getBackupResult")
#GetMapping(value = "/result")
public ResponseEntity<ResultDto> getResult(#RequestParam("request") String someRequest) {
ResultDto resultDto = service.parserRequest(someRequest);
return new ResponseEntity<>(resultDto, HttpStatus.OK);
}
public ResponseEntity<ResultDto> getBackupResult(#RequestParam("request") String someRequest) {
ResultDto resultDto = new ResultDto();
return new ResponseEntity<>(resultDto, HttpStatus.OK);
}
Is there something similar I can do for the gRPC call?
public void parseRequest(ParseRequest request, StreamObserver<ParseResponse> responseObserver) {
try {
ParseResponse parseResponse = service.parseRequest(request.getSomeRequest());
responseObserver.onNext(parseResponse);
responseObserver.onCompleted();
} catch (Exception e) {
logger.error("Failed to execute parse request.", e);
responseObserver.onError(new StatusException(Status.INTERNAL));
}
}
I solved my problem by implementing the circuit-breaker on my client. I used the sentinel library
To react on exceptions ratio for example I added this rule:
private static final String KEY = "callGRPC";
private void callGRPC(List<String> userAgents) {
initDegradeRule();
ManagedChannel channel = ManagedChannelBuilder.forAddress(grpcHost, grpcPort).usePlaintext()
.build();
for (String userAgent : userAgents) {
Entry entry = null;
try {
entry = SphU.entry(KEY);
UserAgentServiceGrpc.UserAgentServiceBlockingStub stub
= UserAgentServiceGrpc.newBlockingStub(channel);
UserAgentParseRequest request = UserAgentRequest.newBuilder().setUserAgent(userAgent).build();
UserAgentResponse userAgentResponse = stub.getUserAgentDetails(request);
} catch (BlockException e) {
logger.error("Circuit-breaker is on and the call has been blocked");
} catch (Throwable t) {
logger.error("Exception was thrown", t);
} finally {
if (entry != null) {
entry.exit();
}
}
}
channel.shutdown();
}
private void initDegradeRule() {
List<DegradeRule> rules = new ArrayList<DegradeRule>();
DegradeRule rule = new DegradeRule();
rule.setResource(KEY);
rule.setCount(0.5);
rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);
rule.setTimeWindow(60);
rules.add(rule);
DegradeRuleManager.loadRules(rules);
}
I've signed XML which I validate by code below
<ThreeDSecure>
<Message id="pareq_1514467844949">
<PARes id="WkTyB5IWvmwx1d846aVCTg">
<version>1.0.2</version>
<Merchant>
<acqBIN>454589</acqBIN>
<merID>P2P_WEB</merID>
</Merchant>
<Purchase>
<xid>MTUxNDQ2Nzg0NDk0OTAwMDAwMDA=</xid>
<date>20171228 16:30:44</date>
<purchAmount>1000</purchAmount>
<currency>810</currency>
<exponent>2</exponent>
</Purchase>
<pan>0000000000002635</pan>
<TX>
<time>20171228 13:31:04</time>
<status>Y</status>
<cavv>AAABB3YieEkDliVhUyJ4AAAAAAA=</cavv>
<eci>05</eci>
<cavvAlgorithm>2</cavvAlgorithm>
</TX>
</PARes>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"></CanonicalizationMethod>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></SignatureMethod>
<Reference URI="#WkTyB5IWvmwx1d846aVCTg">
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></DigestMethod>
<DigestValue>vjiyJgkYUPKeX79NBcvZNcZuH7g=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>LcITisdhnjQSLaQnL/VPg8EWCFbmfDhDpOLo8xGntbcCiubVCi6o+luhu38JA2Vo8G8fcSTH/2GvkFm1NTeOyzHDlqV5LCKXY+gNX8U+Toot+TYux9QQ0Ro1D5T2152Sn86SARNyOsnOxSzf7I0+/sAfaCD2kjbNyZb5YWPNvezM9iMaJVgLhZmAZCUmnb9vBP9HXAgEm5E2pSUhdiaXSLcp3hnccbNsqQUlRejOCOixXPbIExiwguaqYg4XbGx9mnHTin6shHPVqfZ2MvTMjTEkf+S5+yMiXVa1Sjzt7q2iJcDoDAKu5RYrC/zxjZqlNxWzeMqHbeFARUA3eRaQwQ==</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>MIIFOjCCBCKgAwIBAgIQd/2aPtSfIJO8W8DTHLSRPTANBgkqhkiG9w0BAQsFADBxMQswCQYDVQQGEwJVUzENMAsGA1UEChMEVklTQTEvMC0GA1UECxMmVmlzYSBJbnRlcm5hdGlvbmFs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gEGMB0GA1UdDgQWBBQVOIMPPyw/cDMezUb+B4wg4NfDtzANBgkqhkiG9w0BAQUFAAOCAQEAX/FBfXxcCLkr4NWSR/pnXKUTwwMhmytMiUbPWU3J/qVAtmPN3XEolWcRzCSs00Rsca4BIGsDoo8Ytyk6feUWYFN4PMCvFYP3j1IzJL1kk5fui/fbGKhtcbP3LBfQdCVp9/5rPJS+TUtBjE7ic9DjkCJzQ83z7+pzzkWKsKZJ/0x9nXGIxHYdkFsd7v3M9+79YKWxehZx0RbQfBI8 bGmX265fOZpwLwU8GUYEmSA20GBuYQa7FkKMcPcw++DbZqMAAb3mLNqRX6BGi01qnD093QVG/na/oAo85ADmJ7f/hC3euiInlhBx6yLt398znM/jra6O1I7mT1GvFpLgXPYHDw==</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>
</Message>
</ThreeDSecure>
Validation xml signature
private void getSignature (String xmlDoc){
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder builder = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlDoc));
Document doc = builder.parse(is);
NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
if (nl.getLength() == 0) {
throw new Exception("Cannot find Signature element");
}
// Overwrite ID
NodeList elList = doc.getElementsByTagName("PARes");
if (elList != null && elList.getLength() > 0 && ((Element)elList.item(0)).hasAttribute("id")) {
Attr id = ((Element)elList.item(0)).getAttributeNode("id");
((Element)elList.item(0)).setIdAttributeNode(id, true);
}
DOMValidateContext valContext = new DOMValidateContext(new X509KeySelector(), nl.item(0));
XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM");
// Unmarshal the XMLSignature.
XMLSignature signature = factory.unmarshalXMLSignature(valContext);
// Validate the XMLSignature.
boolean coreValidity = signature.validate(valContext);
log.error("Validated :" + (coreValidity?"True":"False"));
} catch (Exception e){
log.error("Exception : "+e.getMessage());
}
}
public class X509KeySelector extends KeySelector {
public KeySelectorResult select(KeyInfo keyInfo,
KeySelector.Purpose purpose,
AlgorithmMethod method,
XMLCryptoContext context)
throws KeySelectorException {
Iterator ki = keyInfo.getContent().iterator();
while (ki.hasNext()) {
XMLStructure info = (XMLStructure) ki.next();
if (!(info instanceof X509Data))
continue;
X509Data x509Data = (X509Data) info;
Iterator xi = x509Data.getContent().iterator();
while (xi.hasNext()) {
Object o = xi.next();
if (!(o instanceof X509Certificate))
continue;
final PublicKey key = ((X509Certificate)o).getPublicKey();
// Make sure the algorithm is compatible
// with the method.
if (algEquals(method.getAlgorithm(), key.getAlgorithm())) {
return new KeySelectorResult() {
public Key getKey() {
return key;
}
};
}
}
}
throw new KeySelectorException("No key found!");
}
private static boolean algEquals(String algURI, String algName) {
if ((algName.equalsIgnoreCase("DSA") &&
algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) ||
(algName.equalsIgnoreCase("RSA") &&
algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1))) {
return true;
} else {
return false;
}
}
Everything is ok, but I should check that public key is trusted.XML's signed by different issuers. I have jssecacerts which contain 14 root CA. How to verify that this public key was signed one of this CA. Thank you for your advices
I've found decision
private boolean checkServerTrusted(X509Certificate cert) throws KeySelectorException {
try {
final File file = new File("C:\\TMP\\jssecacerts");
InputStream inStream = new FileInputStream(file);
KeyStore keystore = KeyStore.getInstance("JKS");
//String password = "";
//keystore.load(inStream, password.toCharArray());
keystore.load(inStream, null);
X509Certificate[] certs = new X509Certificate[keystore.size()];
int i = 0;
Enumeration<String> alias = keystore.aliases();
while (alias.hasMoreElements()) {
certs[i++] = (X509Certificate) keystore.getCertificate(alias
.nextElement());
}
return validateKeyChain(cert, certs);
} catch (Exception e){
throw new KeySelectorException ("Key verify exception reason :"+ e.getMessage());
}
}
/**
* Validate keychain
* #param client is the client X509Certificate
* #param trustedCerts is Array containing all trusted X509Certificate
* #return true if validation until root certificate success, false otherwise
* #throws CertificateException
* #throws InvalidAlgorithmParameterException
* #throws NoSuchAlgorithmException
* #throws NoSuchProviderException
*/
private boolean validateKeyChain(X509Certificate client,
X509Certificate... trustedCerts) throws CertificateException,
InvalidAlgorithmParameterException, NoSuchAlgorithmException,
NoSuchProviderException {
boolean found = false;
int i = trustedCerts.length;
CertificateFactory cf = CertificateFactory.getInstance("X.509");
TrustAnchor anchor;
Set anchors;
CertPath path;
List list;
PKIXParameters params;
CertPathValidator validator = CertPathValidator.getInstance("PKIX");
while (!found && i > 0) {
anchor = new TrustAnchor(trustedCerts[--i], null);
anchors = Collections.singleton(anchor);
list = Arrays.asList(new Certificate[] { client });
path = cf.generateCertPath(list);
params = new PKIXParameters(anchors);
params.setRevocationEnabled(false);
if (client.getIssuerDN().equals(trustedCerts[i].getSubjectDN())) {
try {
validator.validate(path, params);
if (isSelfSigned(trustedCerts[i])) {
// found root ca
found = true;
System.out.println("validating root" + trustedCerts[i].getSubjectX500Principal().getName());
} else if (!client.equals(trustedCerts[i])) {
// find parent ca
System.out.println("validating via:" + trustedCerts[i].getSubjectX500Principal().getName());
found = validateKeyChain(trustedCerts[i], trustedCerts);
}
} catch (CertPathValidatorException e) {
// validation fail, check next certificate in the trustedCerts array
}
}
}
return found;
}
/**
*
* #param cert is X509Certificate that will be tested
* #return true if cert is self signed, false otherwise
* #throws CertificateException
* #throws NoSuchAlgorithmException
* #throws NoSuchProviderException
*/
private boolean isSelfSigned(X509Certificate cert)
throws CertificateException, NoSuchAlgorithmException,
NoSuchProviderException {
try {
PublicKey key = cert.getPublicKey();
cert.verify(key);
return true;
} catch (SignatureException sigEx) {
return false;
} catch (InvalidKeyException keyEx) {
return false;
}
}
I have java SE sample client which run on desktop (code below). But I have access to WebSphere were called EJB is deployed. How to rewrite below code to work on WebSphere? (When I leave this code just like it is program works but I think this can be done more simple and clear)
Main method:
WSConn connection = new WSConn();
final Plan plan = connection.getPlanBean();
com.ibm.websphere.security.auth.WSSubject.doAs(connection.getSubject(), new java.security.PrivilegedAction<Object>() {
public Object run() {
try {
// App logic
} catch (Throwable t) {
System.err.println("PrivilegedAction - Error calling EJB: " + t);
t.printStackTrace();
}
return null;
}
}); // end doAs
WSConn class:
public class WSConn {
private static final String INITIAL_CONTEXT_FACTORY = "com.ibm.websphere.naming.WsnInitialContextFactory";
private static final String JAAS_MODULE = "WSLogin";
private static final String MODEL_EJB_NAME_LONG = "ejb/com/ibm/ModelHome";
private static final String PLAN_EJB_NAME_LONG = "ejb/com/ibm/PlanHome";
private Subject subject;
private InitialContext initialContext;
private String serverName;
private String serverPort;
private String uid;
private String pwd;
private String remoteServerName;
private Model modelBean;
private Plan planBean;
public WSConn() {
Properties props = new Properties();
try {
props.load(WSConn.class.getClassLoader().getResourceAsStream("WSConn.properties"));
} catch (IOException e) {
e.printStackTrace();
}
serverName = props.getProperty("WSConn.serverName");
serverPort = props.getProperty("WSConn.serverPort");
uid = props.getProperty("WSConn.userID");
pwd = props.getProperty("WSConn.password");
remoteServerName = props.getProperty("WSConn.remoteServerName");
}
private void init() {
if (subject == null || initialContext == null) {
subject = login();
}
}
private Subject login() {
Subject subject = null;
try {
LoginContext lc = null;
// CRATE LOGIN CONTEXT
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, "corbaloc:iiop:" + serverName + ":" + serverPort);
initialContext = new InitialContext(env);
// Just to test the connection
initialContext.lookup("");
lc = new LoginContext(JAAS_MODULE, new WSCallbackHandlerImpl(uid, pwd));
lc.login();
subject = lc.getSubject();
} catch (javax.naming.NoPermissionException exc) {
System.err.println("[WSConn] - Login Error: " + exc);
} catch (Exception exc) {
System.err.println("[WSConn] - Error: " + exc);
}
return subject;
}
public wModel getModelBean() {
if (modelBean == null) {
init();
modelBean = (wModel) com.ibm.websphere.security.auth.WSSubject.doAs(subject,
new java.security.PrivilegedAction<wModel>() {
public wModel run() {
wModel session = null;
try {
Object o = initialContext.lookup(MODEL_EJB_NAME_LONG);
wModelHome home = (wModelHome) PortableRemoteObject.narrow(o, wModelHome.class);
if (home != null) {
session = home.create(remoteServerName);
}
} catch (Exception exc) {
System.err.println("Error getting model bean: " + exc);
}
return session;
}
}); // end doAs
}
return modelBean;
}
public wPlan getPlanBean() {
if (planBean == null) {
init();
planBean = (wPlan) com.ibm.websphere.security.auth.WSSubject.doAs(subject,
new java.security.PrivilegedAction<wPlan>() {
public wPlan run() {
wPlan session = null;
try {
Object o = initialContext.lookup(PLAN_EJB_NAME_LONG);
wPlanHome home = (wPlanHome) PortableRemoteObject.narrow(o, wPlanHome.class);
if (home != null) {
session = home.create(remoteServerName);
}
} catch (Exception exc) {
System.err.println("Error getting plan bean: " + exc);
}
return session;
}
}); // end doAs
}
return planBean;
}
public Subject getSubject() {
if (subject == null) {
init();
}
return subject;
}
}
As indicated in another answer, the classic mechanism is to lookup and narrow the home interface.
Get the initial context
final InitialContext initialContext = new InitialContext();
Lookup for the home by jndi name, specifying either the full jndi name
Object obj = initialContext.lookup("ejb/com/ibm/tws/conn/plan/ConnPlanHome");
or you can create e reference in your WAR and use java:comp/env/yourname
Then narrow the home to the home interface class
ConnPlanHome planHome = (ConnPlanHome)PortableRemoteObject.narrow(obj, ConnPlanHome.class);
and then create the EJB remote interface
ConnPlan plan = planHome.create();
The about calls should work for IBM Workload Scheduler distributed.
For IBM Workload Scheduler z/OS the JNDI name and the class names are different:
final InitialContext initialContext = new InitialContext();
String engineName = "XXXX";
Object obj = initialContext.lookup("ejb/com/ibm/tws/zconn/plan/ZConnPlanHome");
ZConnPlanHome planHome = (ZConnPlanHome)PortableRemoteObject.narrow(obj, ZConnPlanHome.class);
ZConnPlan plan = planHome.create(engineName);
User credentials are propagated from the client to the engine, the client need to be authenticated otherwise the engine will reject the request.
If you're trying to access an EJB from a POJO class, then there is nothing more simple than lookup+narrow. However, if the POJO is included in an application (EAR or WAR), then you could declare and lookup an EJB reference (java:comp/ejb/myEJB), and then the container would perform the narrow rather than your code. If you change your code to be a managed class like a servlet, another EJB, or a CDI bean, then you could use #EJB injection, and then you would not even need a lookup.
Before making HttpConnection from blackberry application i want to check if it is open or not?. Because without checking that when i tried to make a connection i got class net.rim.device.api.io.ConnectionClosedException.
EDIT: Posted the code from the OP's answer.
Below is my code for the http connection.
public String makePostRequest(String[] paramName, String[] paramValue) {
StringBuffer postData = new StringBuffer();
HttpConnection connection = null;
InputStream inputStream = null;
OutputStream out = null;
try {
connection = (HttpConnection) Connector.open(this.url);
connection.setRequestMethod(HttpConnection.POST);
for (int i = 0; i < paramName.length; i++) {
postData.append(paramName[i]);
postData.append("=");
postData.append(paramValue[i]);
postData.append("&");
}
String encodedData = postData.toString();
connection.setRequestProperty("Content-Language", "en-US");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", (new Integer(
encodedData.length())).toString());
connection.setRequestProperty("Cookie", Constants.COOKIE_TOKEN);
byte[] postDataByte = postData.toString().getBytes("UTF-8");
out = connection.openOutputStream();
out.write(postDataByte);
DebugScreen.Log("Output stream..."+out);
DebugScreen.Log("Output stream..."+connection.getResponseCode());
// get the response from the input stream..
inputStream = connection.openInputStream();
DebugScreen.Log("Input stream..."+inputStream);
byte[] data = IOUtilities.streamToBytes(inputStream);
response = new String(data);
} catch ( Exception e) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
WaitingScreen.removePopUP();
Status.show(Constants.CONNETION_ERROR);
}
});
DebugScreen.Log("Exception inside the make connection..makePostRequest."
+ e.getMessage());
DebugScreen.Log("Exception inside the make connection..makePostRequest."
+ e.getClass());
}finally {
try {
if(inputStream != null){
inputStream.close();
inputStream = null;
}
if(out != null){
out.close();
out = null;
}
if(connection != null){
connection.close();
connection = null;
}
} catch ( Exception ex) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
WaitingScreen.removePopUP();
}
});
DebugScreen.Log("Exception from the connection2 class.."
+ ex.getMessage());
DebugScreen.Log("Exception from the connection2 class.."
+ ex.getClass());
}
}
return response;
}
Before making httpconnection from blackberry application i want to check if it is open or not.
That doesn't make sense. You want to make sure it is open before you open it. You can't. You have to try to open it, and handle the exception if it fails. That's what the exception is for.
The best way to test whether any resource is available is to try to use it. You can't predict that. You have to try it.
Because without checking that when i tried to make a connection i got class net.rim.device.api.io.ConnectionClosedException.
So it wasn't available. So now you know. That's the correct behaviour. You're already doing the right thing. There is no question here to answer.
I am having some troubles running an Xquery with Saxon9HE, which has a reference to an external module.
I would like Saxon to resolve the module with a relative path rather absolute.
the module declaration
module namespace common = "http://my-xquery-utils";
from the main xquery
import module namespace common = "http://my-xquery-utils" at "/home/myself/common.xquery";
from my java code
public class SaxonInvocator {
private static Processor proc = null;
private static XQueryEvaluator xqe = null;
private static DocumentBuilder db = null;
private static StaticQueryContext ctx = null;
/**
* Utility for debug, should not be called outside your IDE
*
* #param args xml, xqFile, xqParameter
*/
public static void main(String[] args) {
XmlObject instance = null;
try {
instance = XmlObject.Factory.parse(new File(args[0]));
} catch (XmlException ex) {
Logger.getLogger(SaxonInvocator.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex){
Logger.getLogger(SaxonInvocator.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.print(transform(instance, args[1], args[2]));
}
public static String transform(XmlObject input, String xqFile, String xqParameter) {
String result = null;
try {
proc = new Processor(false);
proc.getUnderlyingConfiguration().getOptimizer().setOptimizationLevel(0);
ctx = proc.getUnderlyingConfiguration().newStaticQueryContext();
ctx.setModuleURIResolver(new ModuleURIResolver() {
#Override
public StreamSource[] resolve(String moduleURI, String baseURI, String[] locations) throws XPathException {
StreamSource[] modules = new StreamSource[locations.length];
for (int i = 0; i < locations.length; i++) {
modules[i] = new StreamSource(getResourceAsStream(locations[i]));
}
return modules;
}
});
db = proc.newDocumentBuilder();
XQueryCompiler comp = proc.newXQueryCompiler();
XQueryExecutable exp = comp.compile(getResourceAsStream(xqFile));
xqe = exp.load();
ByteArrayInputStream bais = new ByteArrayInputStream(input.xmlText().getBytes("UTF-8"));
StreamSource ss = new StreamSource(bais);
XdmNode node = db.build(ss);
xqe.setExternalVariable(
new QName(xqParameter), node);
result = xqe.evaluate().toString();
} catch (SaxonApiException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static InputStream getResourceAsStream(String resource) {
InputStream stream = SaxonInvocator.class.getResourceAsStream("/" + resource);
if (stream == null) {
stream = SaxonInvocator.class.getResourceAsStream(resource);
}
if (stream == null) {
stream = SaxonInvocator.class.getResourceAsStream("my/project/" + resource);
}
if (stream == null) {
stream = SaxonInvocator.class.getResourceAsStream("/my/project/" + resource);
}
return stream;
}
}
If a change it into a relative path like
import module namespace common = "http://my-xquery-utils" at "common.xquery";
I get
Error on line 22 column 1
XQST0059: java.io.FileNotFoundException
I am not sure how the ModuleURIResolver should be used.
Saxon questions are best asked on the Saxon forum at http://saxonica.plan.io - questions asked here will probably be noticed eventually but sometimes, like this time, they aren't our first priority.
The basic answer is that for the relative URI to resolve, the base URI needs to be known, which means that you need to ensure that the baseURI property in the XQueryCompiler is set. This happens automatically if you compile the query from a File, but not if you compile it from an InputStream.
If you don't know a suitable base URI to set, the alternative is to write a ModuleURIResolver, which could for example fetch the module by making another call on getResourceAsStream().