/*
* This file is part of rockframework.
*
* rockframework is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* rockframework is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>;.
*/
package br.net.woodstock.rockframework.security.cert.impl;
import java.io.InputStream;
import java.io.Serializable;
import java.security.cert.Certificate;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cms.CMSSignedData;
import br.net.woodstock.rockframework.core.RockFrameworkVersion;
import br.net.woodstock.rockframework.core.utils.Collections;
import br.net.woodstock.rockframework.security.cert.CertificateException;
import br.net.woodstock.rockframework.security.cert.CertificateReader;
import br.net.woodstock.rockframework.security.util.BouncyCastleProviderHelper;
public class BouncyCastlePKCS7CertificateReader implements CertificateReader, Serializable {
private static final long serialVersionUID = RockFrameworkVersion.VERSION;
public BouncyCastlePKCS7CertificateReader() {
super();
}
@Override
@SuppressWarnings("unchecked")
public Certificate[] read(final InputStream inputStream) {
try {
CMSSignedData cmsSignedData = new CMSSignedData(inputStream);
Collection<X509CertificateHolder> certificates = cmsSignedData.getCertificates().getMatches(null);
List<Certificate> list = new LinkedList<Certificate>();
if (certificates.size() > 0) {
X509CertificateHolder principal = certificates.iterator().next();
Certificate principalCertificate = BouncyCastleProviderHelper.getCertificate(principal);
list.add(principalCertificate);
X509CertificateHolder issuer = this.getIssuer(principal.getIssuer(), certificates);
while (issuer != null) {
Certificate issuerCertificate = BouncyCastleProviderHelper.getCertificate(issuer);
list.add(issuerCertificate);
if (issuer.getIssuer().equals(issuer.getSubject())) {
break;
}
issuer = this.getIssuer(issuer.getIssuer(), certificates);
}
}
return Collections.toArray(list, Certificate.class);
} catch (Exception e) {
throw new CertificateException(e);
}
}
private X509CertificateHolder getIssuer(final X500Name name, final Collection<X509CertificateHolder> certificates) {
for (X509CertificateHolder holder : certificates) {
if (holder.getSubject().equals(name)) {
return holder;
}
}
return null;
}
}