Java Cant find Trusted Certificate (JKS) - web-services

I need to consume a service using CXF and I am facing the following issue.
Even though I had my Java key store (JKS) workig o SOAP UI, for example, when I use it on my java program it always give me the message
sun.security.validator.ValidatorException: No trusted certificate found
I have checked the JKS file and the certificate is in there, so when I put it on the SOAPUI project, it is recognized and the service successful called, with no problems. I am using as base the code provided by the cxf web site (http://svn.apache.org/viewvc/cxf/trunk/distribution/src/main/release/samples/wsdl_first_https/src/main/java/demo/hw_https/client/ClientNonSpring.java?view=log) , as follow:
public static void setupTLS(Object port) throws FileNotFoundException, IOException, GeneralSecurityException
{
final String keyStoreLoc = "d:/certs/mykeystore.jks";
HTTPConduit httpConduit = (HTTPConduit) ClientProxy.getClient(port).getConduit();
TLSClientParameters tlsCP = new TLSClientParameters();
final String keyPassword ="password";
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(new FileInputStream(keyStoreLoc), keyPassword.toCharArray());
KeyManager[] myKeyManagers = getKeyManagers(keyStore, keyPassword);
tlsCP.setKeyManagers(myKeyManagers);
KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(new FileInputStream(keyStoreLoc), keyPassword.toCharArray());
TrustManager[] myTrustStoreKeyManagers = getTrustManagers(trustStore);
tlsCP.setTrustManagers(myTrustStoreKeyManagers);
httpConduit.setTlsClientParameters(tlsCP);
}
private static TrustManager[] getTrustManagers(KeyStore trustStore)
throws NoSuchAlgorithmException, KeyStoreException
{
String alg = KeyManagerFactory.getDefaultAlgorithm();
TrustManagerFactory fac = TrustManagerFactory.getInstance(alg);
fac.init(trustStore);
return fac.getTrustManagers();
}
private static KeyManager[] getKeyManagers(KeyStore keyStore, String keyPassword)
throws GeneralSecurityException, IOException
{
String alg = KeyManagerFactory.getDefaultAlgorithm();
char[] keyPass = keyPassword != null ? keyPassword.toCharArray() : null;
KeyManagerFactory fac = KeyManagerFactory.getInstance(alg);
fac.init(keyStore, keyPass);
return fac.getKeyManagers();
}
When debugging, I can see that the certs are loaded and the keystore and keystrustmanagers are populated accordingly, so after days trying to figure out what is happening, I am running out of ideas. So if you guys have any tip that can help,please help me out.
Thanks in advance.

After running some more tests it was clear that the certificate was the problem. I changed the jks for a valid one and now its running perfectly.
For the ones that need a solution like that, the example that I based my solution (http://svn.apache.org/viewvc/cxf/trunk/distribution/src/main/release/samples/wsdl_first_https/src/main/java/demo/hw_https/client/ClientNonSpring.java?view=log) works like a charm.

Related

Error : Metadata contains reference that cannot be resolved: Dynamics 365 online

I'm trying to create web service (ASMX) to connect with the D365.
But when I'm trying to connect to the D365, I got this error message :-
I tried to change the DLL to the latest version but still gave me same error. For more details about my code :-
public class CRMConnection
{
public OrganizationServiceProxy service;
private ClientCredentials credentials;
private String UserName = WebConfigurationManager.AppSettings["CRM_Username"];
private String Password = WebConfigurationManager.AppSettings["CRM_Password"];
public CRMConnection()
{
Uri OrganizationUri = new Uri(WebConfigurationManager.AppSettings["CRM_URL"]);
credentials = new ClientCredentials();
credentials.UserName.UserName = UserName;
credentials.UserName.Password = Password;
service = new OrganizationServiceProxy(OrganizationUri, null, credentials, null);
}
}
Error comes in this line :
service = new OrganizationServiceProxy(OrganizationUri, null, credentials, null);
My project Target Framework is 4.5.2
Note : I used same code with other project (Windows Application) and it's working fine.
Your help in this regard will be highly appreciated!
Thanks ..
This case has been resolved. The issue was because of the proxy settings .

Two Private keys on Weblogic

How to access two private keys on Web logic server or via Java code.
Any pointers would help.
Below is the piece of code, but it throws key is tampered or password is wrong.
Similar code works if i pass the the truststore or keystore location as direct location like .trustStoreFile("C:\Test\XYZTrust.jks")
If i change the code like below it throws
/* Get the JKS contents */
final KeyStore keyStore = KeyStore.getInstance("JKS");
try (final InputStream is = new FileInputStream(fullPathOfKeyStore())) {
keyStore.load(is, JKS_PASSWORD);
}
final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory
.getDefaultAlgorithm());
kmf.init(keyStore, KEY_PASSWORD);
final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory
.getDefaultAlgorithm());
tmf.init(keyStore);
/*
* Creates a socket factory for HttpsURLConnection using JKS
* contents
*/
final SSLContext sc = SSLContext.getInstance("TLS");
sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new java.security.SecureRandom());
final SSLSocketFactory socketFactory = sc.getSocketFactory();
HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
Error :- Keystore was tampered with, or password was incorrect
Note:- Password and keystore are 1000 % correct.
You can find your Keystore using Admin-console.
Got to Environment -> Servers -> AdminServer.
You should see something like this:
In the field "Custom identity Keystore"is the path to your Keystore file,
and in the field "Custom Trust Keystore" is the path to your Trust key.
In case you don't have the correct Password you can use the following link to decrypt them.
http://techtapas.blogspot.de/2011/05/how-to-decrypt-weblogic-passwords-with.html?m=1
If you are using default passwords then most of the chances that this is one of those:
https://itguykelly.wordpress.com/2010/05/20/default-weblogic-keystore-passwordpassphrase/

why NotFound error occur in REST services with windows Phone app?

i tried to connect REST web servie from windows phone 8 application.
it was working proberly for weeks but after no change in it I get this generic error :
System.Net.WebException: The remote server returned an error:
NotFound.
i tried to test it by online REST Clients and services works properly
i tried to handle Exception and parse it as webException by this code :
var we = ex.InnerException as WebException;
if (we != null)
{
var resp = we.Response as HttpWebResponse;
response.StatusCode = resp.StatusCode;
and i get no more information and final response code is : "NotFound"
any one have any idea about what may cause this error?
there is already a trusted Certificate implemented on the server . the one who has the server suggested to have a DNS entry for the server, this entry should be at the customer DNS or in the phone hosts file .that what i done and worked for awhile but now it doesn't work however i checked that there is no thing changed
this is sample for Get Request it works proberly on Windwos Store apps :
async Task<object> GetHttps(string uri, string parRequest, Type returnType, params string[] parameters)
{
try
{
string strRequest = ConstructRequest(parRequest, parameters);
string encodedRequest = HttpUtility.UrlEncode(strRequest);
string requestURL = BackEndURL + uri + encodedRequest;
HttpWebRequest request = HttpWebRequest.Create(new Uri(requestURL, UriKind.Absolute)) as HttpWebRequest;
request.Headers["applicationName"] = AppName;
request.Headers["applicationPassword"] = AppPassword;
if (AppVersion > 1)
request.Headers["applicationVersion"] = AppVersion.ToString();
request.Method = "GET";
request.CookieContainer = cookieContainer;
var factory = new TaskFactory();
var getResponseTask = factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
HttpWebResponse response = await getResponseTask as HttpWebResponse;
// string s = response.GetResponseStream().ToString();
if (response.StatusCode == HttpStatusCode.OK)
{
XmlSerializer serializer = new XmlSerializer(returnType);
object obj = serializer.Deserialize(response.GetResponseStream());
return obj;
}
else
{
var Instance = Activator.CreateInstance(returnType);
(Instance as ResponseBase).NetworkError = true;
(Instance as ResponseBase).StatusCode = response.StatusCode;
return Instance;
}
}
catch (Exception ex)
{
return HandleException(ex, returnType);
}
}
i tried to monitor connections from Emulator and i found this error in connection :
**
Authentication failed because the remote party has closed the
transport stream.
**
You saw the client implement a server side certificate in the service. Did you have that certificate installed on the phone? That can be the cause of the NotFound error. Please, can you try to navigate to the service in the phone or emulator internet explorer prior to testing the app? If you do that, you can see the service working in the emulator/phone internet explorer? Maybe at that point internet explorer ask you about installing the certificate and then you can open your app, and it works.
Also remember if you are testing this in the emulator, every time you close it, the state is lost so you need to repeat the operation of installing the certificate again.
Hope this helps.
If you plan to use SSL in production in general public application (not company-distribution app), you need to ensure your certificate has one of the following root authorities:
SSL root certificates for Windows Phone OS 7.1.
When we had same issue, we purchased SSL certificate from one of those providers and after installing it on server we were able to make HTTPS requests to our services with no problem.
If you have company-distribution app, you can use any certificate from company's Root CA.

Having Separate Certificates Running Under GlassFish 2

Can anyone please explain how i can have more than one X.509 Certificates in my GlassFish application server?
The main challenge for me is that GlassFish uses just one alias which is 's1as'.
You can pull additional certificates from external key files to create an SSLContext and then SSLSocketFactory, which you can feed into your external HTTPS calls.
E.g.:
KeyStore cKeyStore = KeyStore.getInstance("PKCS12");
try (InputStream clientCertKeyInput = new FileInputStream("my.pfx")) {
cKeyStore.load(clientCertKeyInput, "password".toCharArray());
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(cKeyStore, "password".toCharArray());
SSLContext sslCtx = SSLContext.getInstance("TLS");
sslCtx.init(keyManagerFactory.getKeyManagers(),
null, // default javax.net.ssl.trustStore
new SecureRandom());
SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
You may then configure an HttpsURLConnection with it:
httpsConn.setSSLSocketFactory(sslSocketFactory);
Or if you're using JAXWS set it as a property of the BindingProvider's context:
Map<String, Object> ctxt = ((BindingProvider) port).getRequestContext();
ctxt.put(JAXWSProperties.SSL_SOCKET_FACTORY, sslSocketFactory);
Hope this helps.

MonoTouch Web Service Request over SSL Gets 'authentication or decryption has failed'

A web service request over SSL raises a WebException on Monotouch v4.0.4.1:
'Error getting response stream (Write: The authentication or decryption has failed)'
Since the server's SSL certificate is self-signed (and btw I think it is not X.509), I am bypassing the certificate validation using ServicePointManager.ServerCertificateValidationCallback. The exact same code works fine on Windows .NET, where the web service call returns the correct result. On Monotouch adding a Writeline shows that the ServerCertificateValidationCallback delegate code is never reached.
Note: Although probably not relevant, the content of the request is SOAP with embedded WS-Security UsernameToken.
Has anyone got something like this to work on MonoTouch? Have seen reports of similar symptom but no resolution. The code and stacktrace are below, any comment appreciated. Can email a self-contained test case if wanted.
I gather there is an alternative approach using certmgr.exe to store the self-signed server certificate in the local trust store, but can't seem to find that app in the MonoTouch distribution. Could anyone point me to it?
..
public class Application
{
static void Main (string[] args)
{
UIApplication.Main (args);
}
}
// The name AppDelegate is referenced in the MainWindow.xib file.
public partial class AppDelegate : UIApplicationDelegate
{
// This method is invoked when the application has loaded its UI and its ready to run
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// If you have defined a view, add it here:
// window.AddSubview (navigationController.View);
string soapResponse;
string soapRequest = #" SOAP envelope is here but omitted for brevity ";
soapResponse = WebService.Invoke("myOperation", soapRequest);
window.MakeKeyAndVisible ();
return true;
}
// This method is required in iPhoneOS 3.0
public override void OnActivated (UIApplication application)
{
}
}
public class WebService
{
public static string Invoke(string operation, string soapRequest)
// Input parameters:
// operation = WS operation name
// soapRequest = SOAP XML request
// Output parameter:
// SOAP XML response
{
HttpWebResponse response;
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, ssl) => true;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://myserver.com:7570/MyEndpoint");
request.Method = "POST";
request.Headers.Add("SOAPAction", "/MyEndpoint/" + operation);
request.ContentType = "text/xml;charset=UTF-8";
request.UserAgent = "Smartphone";
request.ContentLength = soapRequest.Length;
request.GetRequestStream().Write(System.Text.Encoding.UTF8.GetBytes(soapRequest), 0, soapRequest.Length);
request.GetRequestStream().Close();
response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
catch (WebException e)
{
throw new WebException(e.Message);
}
}
}
Stack trace (some names changed to protect the innocent, original available on request):
WS.WebService.Invoke (operation="myOperation", soapRequest="<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" \n\txmlns:ns1=\"http://mycompany/Common/Primitives/v1\" \n\txmlns:ns2=\"http://mycompany/Common/actions/externals/Order/v1\" \n\txmlns:ns3=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">\n\t<SOAP-ENV:Header> <wsse:Security SOAP-ENV:mustUnderstand=\"1\" \n\txmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"> \n\t<wsse:UsernameToken wsu:Id=\"UsernameToken-1\" \n\txmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> \n\t<wsse:Username>myusername</wsse:Username> <wsse:Password \n\tType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">mypw</wsse:Password> \n\t<wsse:Nonce>{0}</wsse:Nonce> \n\t<wsu:Created xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">{1}</wsu:Created> \n\t</wsse:UsernameToken> </wsse:Security> \n\t</SOAP-ENV:Header><SOAP-ENV:Body><ns2:tp_getOrderDetailRequest><ns2:header><ns1:source>TEAM</ns1:source>\n\t<ns1:userAccessKey>12345678901234567</ns1:userAccessKey></ns2:header>\n\t<ns2:OrderId>myid1</ns2:OrderId>\n\t<ns2:OrderId>myid2</ns2:OrderId>\n\t</ns2:tp_getOrderDetailRequest>\n\t</SOAP-ENV:Body>\n\t</SOAP-ENV:Envelope>") in /Users/billf/Projects/WS/WS/Main.cs:103
WS.AppDelegate.FinishedLaunching (app={MonoTouch.UIKit.UIApplication}, options=(null)) in /Users/billf/Projects/WS/WS/Main.cs:52
MonoTouch.UIKit.UIApplication.Main (args={string[0]}, principalClassName=(null), delegateClassName=(null)) in /Developer/MonoTouch/Source/monotouch/monotouch/UIKit/UIApplication.cs:26
MonoTouch.UIKit.UIApplication.Main (args={string[0]}) in /Developer/MonoTouch/Source/monotouch/monotouch/UIKit/UIApplication.cs:31
WS.Application.Main (args={string[0]}) in /Users/billf/Projects/WS/WS/Main.cs:18
MonoTouch (just like Mono) does not support TLS_DH* cipher suites (like TLS_DHE_DSS_WITH_AES_128_CBC_SHA).
When a server is configured to accept only them then the negotiation stage fails very early (an Alert is received from the server after the Client Hello message is sent) which explains why the callback was never called.
Ensure your server allows the more traditional cipher suites, e.g. the very secure (but slow) TLS_RSA_WITH_AES_256_CBC_SHA or the faster (and very common) Cipher Suite: TLS_RSA_WITH_RC4_128_[MD5|SHA], and Mono[Touch] should work well using them.
Note that this is unrelated to SOAP or web-services (and even X.509 certificates) - it's just plain SSL.
1) An untrusted root certificate is not the only problem that could result in this exception.
ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, ssl) => true;
Add a Console.WriteLine in there so you'll see if it gets called (or not).
throw new WebException(e.Message);
and another here, with full stack trace (not just the Message property).
2) Each application is isolated. This means that:
applications cannot updates the global iOS certificate stores (that would create security issues);
if a certmgr tool existed (for MT) it could only use a local (mono) store that would be usable only for itself (which would not be of any help for your own apps)