OCSP Revocation on client certificate - java

How do I manually check for certificate revocation status in java using OCSP, given just a client's java.security.cert.X509Certificate? I can't see a clear way to do it.
Alternatively, can I make tomcat do it for me automatically, and how do you know your solution to be true?

I found a most excellent solution:
http://www.docjar.com/html/api/sun/security/provider/certpath/OCSP.java.html
/**
54 * This is a class that checks the revocation status of a certificate(s) using
55 * OCSP. It is not a PKIXCertPathChecker and therefore can be used outside of
56 * the CertPathValidator framework. It is useful when you want to
57 * just check the revocation status of a certificate, and you don't want to
58 * incur the overhead of validating all of the certificates in the
59 * associated certificate chain.
60 *
61 * #author Sean Mullan
62 */
It has a method check(X509Certificate clientCert, X509Certificate issuerCert) that does the trick!

It appears there is a patch for Tomcat here to enable ocsp validation.
If you choose to do it manually:
Security.setProperty("ocsp.enable", "true")
Or set it via a command-line argument. See here:
This property's value is either true or false. If true, OCSP checking is enabled when doing certificate revocation checking; if false or not set, OCSP checking is disabled.
And here's some code that I think works:
interface ValidationStrategy {
boolean validate(X509Certificate certificate, CertPath certPath,
PKIXParameters parameters) throws GeneralSecurityException;
}
class SunOCSPValidationStrategy implements ValidationStrategy {
#Override
public boolean validate(X509Certificate certificate, CertPath certPath,
PKIXParameters parameters) throws GeneralSecurityException {
try {
CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv
.validate(certPath, parameters);
Signature.LOG.debug("Validation result is: " + result);
return true; // if no exception is thrown
} catch (CertPathValidatorException cpve) {
// if the exception is (or is caused by)
// CertificateRevokedException, return false;
// otherwise re-throw, because this indicates a failure to perform
// the validation
Throwable cause = ExceptionUtils.getRootCause(cpve);
Class<? extends Throwable> exceptionClass = cause != null ? cause.getClass()
: cpve.getClass();
if (exceptionClass.getSimpleName().equals("CertificateRevokedException")) {
return false;
}
throw cpve;
}
}
}

Here's the relevant code from Jetty 7 that takes an array of certificates pulled from the servletRequest request and validates them via the certpath API with OCSP.
http://grepcode.com/file/repo1.maven.org/maven2/org.eclipse.jetty/jetty-util/7.4.0.v20110414/org/eclipse/jetty/util/security/CertificateValidator.java#189

import org.bouncycastle.util.io.pem.PemReader;
import sun.security.provider.certpath.OCSP;
import sun.security.x509.X509CertImpl;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.cert.CertPathValidatorException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;
public void test() throws IOException, CertPathValidatorException, java.security.cert.CertificateException {
X509Certificate userCert = getX509Cert("path_to_user_cert");
X509Certificate caCert = getX509Cert("path_to_CA_cert");
OCSP.RevocationStatus ocsp = OCSP.check(userCert, caCert, URI.create("URL to OCSP, but this can be read from USER Cert(AuthorityInfoAccess) As well"), caCert, new Date());
System.out.println(ocsp);
}
private X509CertImpl getX509Cert(final String path) throws CertificateException, IOException {
return new X509CertImpl(
new PemReader(
new StringReader(
new String(
Files.readAllBytes(
Paths.get(path)))))
.readPemObject()
.getContent());
}

Related

Export certificate chain from .cer certificate

I have .cer certificate. When I'm opening it, it shows me certificate chain.
Using this code, I read the certificate to x509certificate file.
File certificateFile = new File("C:\\Users\\grish\\Desktop\\certificateForValidation.cer");
InputStream inputStream = new FileInputStream(certificateFile);
X509Certificate certificate = new X509CertImpl(inputStream);
I want to get certificate chain from that file ! (end-entity, CA, Root)
How can I do that programmatically in java.
With C#, this is much more easy
X509Chain ch = new X509Chain();
ch.ChainPolicy.RevocationMode = X509RevocationMode.Online;
ch.Build (certificate);
And then I can get all certificates from ch.
First of all make sure you are using the java.security.cert package; see JDK 17 API doc for java.security.cert.
Avoid using javax.security.cert. The package is marked as deprecated an will be removed in future releases; see JDK 17 API doc for javax.security.cert.
The following code will return a collection of java.security.cert.X509Certificate objects. In the case of your example with the certificate of medium.com the list will contain three items; one for every certificate in the chain.
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.List;
public static void main(String[] args) {
try (InputStream inStream = new FileInputStream("C:\\Users\\grish\\Desktop\\Coding Space\\Certificates\\certificateForValidation.p7b")) {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
List<X509Certificate> certs = (List<X509Certificate>) cf.generateCertificates(inStream);
} catch (Exception ex) {
ex.printStackTrace();
}
}
I tested it with a PEM formated chain but it should work with PCKS#7 (.p7b file extension) as well; see the documentation of the generateCertificates(InputStream inStream) method.
Find more information about x.509 encoding and conversion here

how to check SSL certificate expiration date programmatically in Java

I need to extract expiration date from SSL certificate on web site in Java,should support both
trusted and self-signed certificate,such as:
1.trusted
https://github.com
2.self-signed
https://mms.nw.ru/
I already copy some code as:
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class SSLTest {
public static void main(String [] args) throws Exception {
// configure the SSLContext with a TrustManager
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
SSLContext.setDefault(ctx);
URL url = new URL("https://github.com");//https://mms.nw.ru
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
System.out.println(conn.getResponseCode());
Certificate[] certs = conn.getServerCertificates();
for (Certificate cert :certs){
System.out.println(cert.getType());
System.out.println(cert);
}
conn.disconnect();
}
private static class DefaultTrustManager implements X509TrustManager {
#Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
#Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
#Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
}
The questions are:
How to parse the expiration date from the certificate, in my code the toString() did output the date,but it is hard to parse.
How to determine the certificate chain, eg, the github certificate with chains 3, how did i know which certificate to get the expiration date from?
How to parse the expiration date from the certificate
Cast it to an X509Certificate and call getNotAfter().
How to determine the certificate chain, eg, the github certificate with chains
You've got it. That's what the Certificate[] array is, as it says in the Javadoc.
How did i know which certificate to get the expiration date from?
Read the Javadoc. "The peer's own certificate first followed by any certificate authorities".
However I don't know why you're doing any of this. Java should already do it all for you.
And please throw away that insecure and incorrect TrustManager implementation. The correct way to handle self-signed certificates is to import them into the client truststore. Please also throw away your insecure HostnameVerifier, and use the default one, or a secure one. Why use HTTPS at all if you don't want it to be secure?
Make sure you append Begin/End lines to PEM format otherwise java does not understand it.
public class CertTest {
public static final String cert = "-----BEGIN CERTIFICATE-----\n<CERT_DATA>\n-----END CERTIFICATE-----";
public static void main(String[] args){
try {
X509Certificate myCert = (X509Certificate)CertificateFactory
.getInstance("X509")
.generateCertificate(
// string encoded with default charset
new ByteArrayInputStream(cert.getBytes())
);
System.out.println(myCert.getNotAfter());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
In Kotlin way, it should look something like this:
fun certInformation(aURL: String) {
val destinationURL = URL(aURL)
val conn = destinationURL.openConnection() as HttpsURLConnection
conn.connect()
val certs = conn.serverCertificates
for (cert in certs) {
println("Certificate is: $cert")
if (cert is X509Certificate) {
println(cert.issuerDN.name)
println(cert.notAfter)
println(cert.notBefore)
}
}
}

could not work ssl connection properly when keystore file changed dynamically through web application

am trying to change the truststore path dynamically using java web application.
am developing struts application and login is based on ldap through secure socket layer (ssl) connection.
To connect with ssl i have created .cer file using java keytool option.
Now i able to connect with ldap and i can retieve user information from ldap.
when i change the ssl certificate(invalid certificate for testing) dynamically it could not give any exceptions. but it works when i restart the tomcat
server.
following is the code that i am trying
try{
java.io.InputStream in = new java.io.FileInputStream("C:\\test.cer");
java.security.cert.Certificate c = java.security.cert.CertificateFactory.getInstance("X.509").generateCertificate(in);
java.security.KeyStore ks = java.security.KeyStore.getInstance("JKS");
ks.load(null);
if (!ks.containsAlias("alias ldap")) {
ks.setCertificateEntry("alias ldap", c);
}
java.io.OutputStream out = new java.io.FileOutputStream("C:\\ldap.jks");
char[] kspass = "changeit".toCharArray();
ks.store(out, kspass);
out.close();
System.setProperty("javax.net.ssl.trustStore", "C:\\ldap.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
}catch(Exception e){
e.printStackTrace();
}
is there any mistake that i made with the code?
does any new code that i need to put to connect dynamically?
Note :
instead of c:\ldap.jks file i gave invalid file dynamically. it does not give any exception.
Edited (checked with custom TrustManager) :
i also implemented TrustManager and ssl context is initialized with custom trust manager.
but i am not able to get the expected behaviour
could u please help me. the code that i tried is
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.UUID;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
public class TestDynamicSSLCert {
public static void main(String[] args)throws NamingException,IOException {
DataInputStream din = new DataInputStream (System.in);
String yes = "yes";
String certpath = "C:\\cert.cer";
String ldappath1 = "C:\\ldap.jks";
String ldappath2 = "C:\\ldap.jks"; // setting valid key store path
while("yes".equalsIgnoreCase(yes.trim())){
System.out.println(" ldappath2 : "+ldappath2);
Hashtable env = new Hashtable();
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL,"uid=admin,ou=system");
env.put(Context.SECURITY_CREDENTIALS, "secret");
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldaps://172.16.12.4:636/ou=system");
try {
java.io.InputStream in = new java.io.FileInputStream(certpath);
java.security.cert.Certificate c = java.security.cert.CertificateFactory.getInstance("X.509").generateCertificate(in);
java.security.KeyStore ks = java.security.KeyStore.getInstance("JKS");
ks.load(null);
if (!ks.containsAlias("alias ldap")) {
ks.setCertificateEntry("alias ldap", c);
}
java.io.OutputStream out = new java.io.FileOutputStream(ldappath1);
char[] kspass = "changeit".toCharArray();
ks.store(out, kspass);
out.close();
System.setProperty("javax.net.ssl.trustStore", ldappath2);
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
// Custorm trust manager
MyX509TrustManager reload = new MyX509TrustManager(ldappath2,c);
TrustManager[] tms = new TrustManager[] { reload };
javax.net.ssl.SSLContext sslCtx = javax.net.ssl.SSLContext.getInstance("SSL");
sslCtx.init(null, tms, null);
// Custom trust manager
} catch (Exception e) {
e.printStackTrace();
}
DirContext ctx = new InitialDirContext(env);
NamingEnumeration enm = ctx.list("");
while (enm.hasMore()) {
System.out.println(enm.next());
}
ctx.close();
System.out.println(" Go again by yes/no :");
yes = din.readLine();
ldappath2 = "C:\\invalidldap.jks"; // setting invalid keystore path
}
}
}
class MyX509TrustManager implements X509TrustManager {
private final String trustStorePath;
private X509TrustManager trustManager;
private List<Certificate> tempCertList = new ArrayList<Certificate>();
public MyX509TrustManager(String tspath,Certificate cert)throws Exception{
this.trustStorePath = tspath;
tempCertList.add(cert);
reloadTrustManager();
}
public MyX509TrustManager(String tspath)
throws Exception {
this.trustStorePath = tspath;
reloadTrustManager();
}
#Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
trustManager.checkClientTrusted(chain, authType);
}
#Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
try {
trustManager.checkServerTrusted(chain, authType);
} catch (CertificateException cx) {
addServerCertAndReload(chain[0], true);
trustManager.checkServerTrusted(chain, authType);
}
}
#Override
public X509Certificate[] getAcceptedIssuers() {
X509Certificate[] issuers = trustManager.getAcceptedIssuers();
return issuers;
}
private void reloadTrustManager() throws Exception {
// load keystore from specified cert store (or default)
KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream in = new FileInputStream(trustStorePath);
try {
ts.load(in, null);
} finally {
in.close();
}
// add all temporary certs to KeyStore (ts)
for (Certificate cert : tempCertList) {
ts.setCertificateEntry(UUID.randomUUID().toString(), cert);
}
// initialize a new TMF with the ts we just loaded
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ts);
// acquire X509 trust manager from factory
TrustManager tms[] = tmf.getTrustManagers();
for (int i = 0; i < tms.length; i++) {
if (tms[i] instanceof X509TrustManager) {
trustManager = (X509TrustManager) tms[i];
return;
}
}
throw new NoSuchAlgorithmException("No X509TrustManager in TrustManagerFactory");
}
private void addServerCertAndReload(Certificate cert,
boolean permanent) {
try {
if (permanent) {
// import the cert into file trust store
// Google "java keytool source" or just ...
Runtime.getRuntime().exec("keytool -importcert ...");
} else {
tempCertList.add(cert);
}
reloadTrustManager();
} catch (Exception ex) { /* ... */ }
}
}
Expected Behaviour :
ldap connection should be successfull with valid keystore file (during first loop ).
if user give yes then invalid keystore is assigned and need to produce exception and should not connect to ldap
Actual Behaviour:
for both valid keystore file i able to retrieve information from ldap.
Note :
if i set String ldappath2 = "C:\invalidldap.jks"; at begining, it gives exception.
Why am doing this ?
#EJP, because, i need to develope module which is based on ldap authentication securely. module should support multiple ldap servers. ldap settings can be inserted from the UI (webpage that has the ui to get the details like ldaphost, port, basedn, and ssl certificate) and this details should go to database. at the same time certificate also present in database. work for module is just retrieve the users from ldap and store it to another table. so if we change the new ldap server setting with new certificate means, System.setProperty("javax.net.ssl.trustStore","truststorepath") will fail. are you okay with my explanation?
You are correct. You have to restart Tomcat when you change the keystore or truststore. You don't need to write code to load client certificates, you just need to make sure you are dealing with servers whose certificates are signed by a CA that you trust. Adding new certificates at runtime is radically insecure.
Is there any other way to connect ldap securely with out using above
steps?
Yes, but why do you think you need to know?
Does the application (tomcat or single java file) should be restarted
whenever trustStore property is updated ?
Yes.

Upload files to SharePoint from Java/J2EE application

We have a requirement to upload large files (may be up to 200 MB) to SharePoint from a Java/J2EE application.
We know there are out of the box SharePoint web services that allows to upload files to SharePoint. However, our main concern is what happens if concurrent users upload files. For example, we would require to read a 200 MB file for each user on Java server (application server), before invoking SharePoint to send that data. Even if there are 5 concurrent users, the memory consumed would be around 1 GB, and there could be high CPU usage too. Are there any suggestions how to handle the server memory, concurrency of file uploads in this scenario?
I think one option is may be to use technologies like Flash/Flex which does not require another server (Java Application server) in between - however, wondering how this can be achieved in J2EE server?
http://servername/sitename/_vti_bin/copy.asmx
Thanks
ok.. so this is what I understood:
You are trying to use Sharepoint Copy Service
And this service requires the stream to be base64encoded in the Soap envelope.
As the file size is huge your SOAP request size becomes huge and demands more memory
I can think of 2 options:
I dont know much about sharepoint, if it is possible to give location of file to be uploaded than sending bytes, then you can ftp/sftp the file to the sharepoint server and then call a webservice with the location of the file.
In Java instead of using the out of the box api for SOAP messages, write a custom api. When user uploads the file save it as base64 encoded file. And then your custom api will create a soap message and stream it instead of loading everything in memory.
For option 2: try if you can send the file content as a soap attachment. its gets a bit complex if you want to send it as part of the message.
Try it out. I am not sure if works.
SharePoint supports WebDAV protocol for reading / writing files.
You can use many WebDAV libraries that would not require loading complete file in memory.
here is the solution
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.security.cert.CertificateException;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.cert.X509Certificate;
import javax.xml.ws.Holder;
import org.apache.cxf.configuration.jsse.TLSClientParameters;
import org.apache.cxf.configuration.security.AuthorizationPolicy;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import com.microsoft.schemas.sharepoint.soap.copy.CopyResultCollection;
import com.microsoft.schemas.sharepoint.soap.copy.CopySoap;
import com.microsoft.schemas.sharepoint.soap.copy.DestinationUrlCollection;
import com.microsoft.schemas.sharepoint.soap.copy.FieldInformation;
import com.microsoft.schemas.sharepoint.soap.copy.FieldInformationCollection;
import com.microsoft.schemas.sharepoint.soap.copy.FieldType;
public class Upload {
private static String username = "yourusrename";
private static String password = "yourpassword";
private static String targetPath = "https://www.yoursite.target/filename";
private static String sourcePath = "file.txt";
private static String portUrl = "https://www.yoursite.com/_vti_bin/Copy.asmx";
private static CopySoap soapInstance;
public static void main(String[] args) {
activate();
CopySoap sqs = getInstance();
String url = targetPath;
String sourceUrl = sourcePath;
DestinationUrlCollection urls = new DestinationUrlCollection();
urls.getString().add(url);
File file = null;
byte[] content = null;
try {
FileInputStream fileStream = new FileInputStream(file = new File(sourceUrl));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for (int readNum; (readNum = fileStream.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
}
content = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
FieldInformation titleInfo = new FieldInformation();
titleInfo.setDisplayName("testpage");
titleInfo.setType(FieldType.TEXT);
titleInfo.setValue("Test Page");
FieldInformationCollection infos = new FieldInformationCollection();
infos.getFieldInformation().add(titleInfo);
CopyResultCollection results = new CopyResultCollection();
Holder<CopyResultCollection> resultHolder = new Holder<CopyResultCollection>(results);
Holder<Long> longHolder = new Holder<Long>(new Long(-1));
if (content != null) {
sqs.copyIntoItems(sourceUrl, urls, infos, content, longHolder, resultHolder);
}
}
private static void activate() {
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(CopySoap.class);
factory.setAddress(portUrl);
factory.getInInterceptors().add(new LoggingInInterceptor());
factory.getOutInterceptors().add(new LoggingOutInterceptor());
soapInstance = (CopySoap) factory.create();
Authenticator.setDefault(new SPAuthenticator());
Client client = ClientProxy.getClient(soapInstance);
HTTPConduit http = (HTTPConduit) client.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(10000);
httpClientPolicy.setAllowChunking(false);
HTTPConduit conduit = (HTTPConduit) client.getConduit();
conduit.setClient(httpClientPolicy);
TLSClientParameters tcp = new TLSClientParameters();
tcp.setTrustManagers(new TrustManager[] { (TrustManager) new TrustAllX509TrustManager() });
conduit.setTlsClientParameters(tcp);
}
public static CopySoap getInstance() {
return soapInstance;
}
static class SPAuthenticator extends Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
System.out.println("hitting SP with username and password for " + getRequestingScheme());
return (new PasswordAuthentication(username, password.toCharArray()));
}
}
/**
* This class allow any X509 certificates to be used to authenticate the
* remote side of a secure socket, including self-signed certificates.
*/
public static class TrustAllX509TrustManager implements X509TrustManager {
/** Empty array of certificate authority certificates. */
private static final X509Certificate[] acceptedIssuers = new X509Certificate[] {};
/**
* Always trust for client SSL chain peer certificate chain with any
* authType authentication types.
*
* #param chain
* the peer certificate chain.
* #param authType`enter
* code here` the authentication type based on the client
* certificate.
*/
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
/**
* Always trust for server SSL chain peer certificate chain with any
* authType exchange algorithm types.
*
* #param chain
* the peer certificate chain.
* #param authType
* the key exchange algorithm used.
*/
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
/**
* Return an empty array of certificate authority certificates which are
* trusted for authenticating peers.
*
* #return a empty array of issuer certificates.
*/
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
#Override
public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}
#Override
public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}
}
}
May be I missed something... but when you let users upload files to your J2EE server, wouldn't you be writing the uploaded content to a temp directory first and then stream it to the server?
As you write the buffers immediately to the disk, you wouldnt have any issues with memory limitations.
or take object take
#Autowired
ServletContext c;
byte[] bytes = file.getBytes();
String UPLOAD_FOLDEdR=c.getRealPath("/images");
Path path = Paths.get(UPLOAD_FOLDEdR+"/"+file.getOriginalFilename());
Files.write(path, bytes);
String Pic_Name =file.getOriginalFilename() ;

Handling an invalid security certificate using MATLAB's urlread command

I'm accessing an internal database using MATLAB's urlread command, everything was working fine until the service was moved to a secure server (i.e. with an HTTPS address rather than an HTTP address). Now urlread no longer successfully retrieves results. It gives an error:
Error downloading URL. Your network connection may be down or your proxy settings improperly configured.
I believe the problem is that the service is using an invalid digital certificate since if I try to access the resource directly in a web browser I get "untrusted connection" warning which I am able to pass through by adding the site to an Exception list. urlread doesn't have an obvious way of handling this problem.
Under the hood urlread is using Java to access web resources, and the error is thrown at this line:
inputStream = urlConnection.getInputStream;
where urlConnection is a Java object: sun.net.www.protocol.https.HttpsURLConnectionImpl.
Anyone suggest a workaround for this problem?
Consider the following Java class. Borrowing from this code: Disabling Certificate Validation in an HTTPS Connection
C:\MATLAB\MyJavaClasses\com\stackoverflow\Downloader.java
package com.stackoverflow;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.net.ssl.HostnameVerifier;
public class Downloader {
public static String getData(String address) throws Exception {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
// Create a host name verifier that always passes
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
// open connection
URL page = new URL(address);
HttpURLConnection conn = (HttpURLConnection) page.openConnection();
BufferedReader buff = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// read text
String line;
StringBuffer text = new StringBuffer();
while ( (line = buff.readLine()) != null ) {
//System.out.println(line);
text.append(line + "\n");
}
buff.close();
return text.toString();
}
public static void main(String[] argv) throws Exception {
String str = getData("https://expired.badssl.com/");
System.out.println(str);
}
}
MATLAB
First we compile the Java class (we must use a JDK version compatible with MATLAB):
>> version -java
>> system('javac C:\MATLAB\MyJavaClasses\com\stackoverflow\Downloader.java');
Next we instantiate and use it MATLAB as:
javaaddpath('C:\MATLAB\MyJavaClasses')
dl = com.stackoverflow.Downloader;
str = char(dl.getData('https://expired.badssl.com/'));
web(['text://' str], '-new')
Here are a few URLs with bad SSL certificates to test:
urls = {
'https://expired.badssl.com/' % expired
'https://wrong.host.badssl.com/' % wrong host
'https://self-signed.badssl.com/' % self-signed
'https://revoked.grc.com/' % revoked
};
UPDATE: I should mention that starting with R2014b, MATLAB has a new function webread that supersedes urlread.
thanks for the solution. It worked, however, sometimes, I had received the following exception "java.io.IOException: The issuer can not be found in the trusted CA list." and I was not able to get rid of this error.
Therefore, I tried an alternative solution that works well. You can use the following Java code in Matlab function:
function str = ReadUrl(url)
is = java.net.URL([], url, sun.net.www.protocol.https.Handler).openConnection().getInputStream();
br = java.io.BufferedReader(java.io.InputStreamReader(is));
str = char(br.readLine());
end
Best,
Jan
Note also that the "canonical" way to solve this issue is to import the certificate into MATLAB's keystore (i.e., not your JVM's keystore).
This is documented here: Mathworks on using untrusted SSL certificates.

Categories