public static X509Certificate[] orderX509CertChain(X509Certificate certs[]){
  if (certs == null) {
    return new X509Certificate[0];
  }
  if (certs.length <= 1) {
    return certs;
  }
  ArrayList<ArrayList<X509Certificate>> paths=new ArrayList<ArrayList<X509Certificate>>();
  for (int i=0; i < certs.length; i++) {
    ArrayList<X509Certificate> path=new ArrayList<X509Certificate>();
    X509Certificate issuerCert=certs[i];
    path.add(issuerCert);
    X509Certificate newIssuer=null;
    while ((newIssuer=findIssuedCert(issuerCert,certs)) != null) {
      issuerCert=newIssuer;
      path.add(0,newIssuer);
    }
    paths.add(path);
  }
  ArrayList<X509Certificate> longestPath=paths.get(0);
  for (int i=1; i < paths.size(); i++) {
    ArrayList<X509Certificate> path=paths.get(i);
    if (path.size() > longestPath.size()) {
      longestPath=path;
    }
  }
  return longestPath.toArray(new X509Certificate[longestPath.size()]);
}

public static X509Certificate [ ] orderX509CertChain ( X509Certificate certs [ ] ) { if ( certs == null ) { return new X509Certificate [ 0 ] ; } if ( certs . length <= 1 ) { return certs ; } ArrayList < ArrayList < X509Certificate > > paths = new ArrayList < ArrayList < X509Certificate > > ( ) ; for ( int i = 0 ; i < certs . length ; i ++ ) { ArrayList < X509Certificate > path = new ArrayList < X509Certificate > ( ) ; X509Certificate issuerCert = certs [ i ] ; path . add ( issuerCert ) ; X509Certificate newIssuer = null ; while ( ( newIssuer = findIssuedCert ( issuerCert , certs ) ) != null ) { issuerCert = newIssuer ; path . add ( 0 , newIssuer ) ; } paths . add ( path ) ; } ArrayList < X509Certificate > longestPath = paths . get ( 0 ) ; for ( int i = 1 ; i < paths . size ( ) ; i ++ ) { ArrayList < X509Certificate > path = paths . get ( i ) ; if ( path . size ( ) > longestPath . size ( ) ) { longestPath = path ; } } return longestPath . toArray ( new X509Certificate [ longestPath . size ( ) ] ) ; }
order the supplied array of x . 509 certificates in issued to issuer order .
