Java tutorial
//package com.java2s; /* * Copyright 2006-2015 WebPKI.org (http://webpki.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ import java.io.IOException; import java.security.cert.X509Certificate; import java.security.GeneralSecurityException; import javax.security.auth.x500.X500Principal; public class Main { public static X509Certificate[] getSortedPath(X509Certificate[] inpath) throws IOException { try { // Build/check path int n = 0; int[] idx = new int[inpath.length]; int[] jidx = new int[inpath.length]; boolean[] done = new boolean[inpath.length]; for (int i = 0; i < inpath.length; i++) { X500Principal p = inpath[i].getIssuerX500Principal(); idx[i] = -1; for (int j = 0; j < inpath.length; j++) { if (j == i || done[j]) continue; if (p.equals(inpath[j].getSubjectX500Principal())) // J is certifying I { n++; idx[i] = j; jidx[j] = i; done[j] = true; inpath[i].verify(inpath[j].getPublicKey()); break; } } } if (n != (inpath.length - 1)) { throw new IOException("X509Certificate elements contain multiple or broken cert paths"); } // Path OK, now sort it X509Certificate[] certpath = new X509Certificate[inpath.length]; for (int i = 0; i < inpath.length; i++) { if (idx[i] < 0) // Must be the highest { certpath[n] = inpath[i]; while (--n >= 0) { certpath[n] = inpath[i = jidx[i]]; } break; } } return certpath; } catch (GeneralSecurityException gse) { throw new IOException(gse); } } }