use of java.security.cert.CRLException in project XobotOS by xamarin.
the class X509CRLObject method verify.
public void verify(PublicKey key, String sigProvider) throws CRLException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException {
if (!c.getSignatureAlgorithm().equals(c.getTBSCertList().getSignature())) {
throw new CRLException("Signature algorithm on CertificateList does not match TBSCertList.");
}
Signature sig = Signature.getInstance(getSigAlgName(), sigProvider);
sig.initVerify(key);
sig.update(this.getTBSCertList());
if (!sig.verify(this.getSignature())) {
throw new SignatureException("CRL does not verify with supplied public key.");
}
}
use of java.security.cert.CRLException in project nhin-d by DirectProject.
the class CRLRevocationManager method getCrlFromUri.
/**
* Create an X509CRLImpl object from a URL pointing to a valid CRL.
*
* @param crlUrlString
* The URL of a valid CRL.
* @return an X509CRLImpl object representing the CRL.
* @throws Exception
*/
protected X509CRL getCrlFromUri(String crlUrlString) {
if (crlUrlString == null || crlUrlString.trim().length() == 0)
return null;
X509CRL crlImpl = null;
// if memory resources are low
synchronized (cache) {
final SoftReference<X509CRL> crlRef = cache.get(crlUrlString);
if (crlRef != null) {
// make sure the reference is still valid
crlImpl = crlRef.get();
if ((crlImpl != null && crlImpl.getNextUpdate().before(new Date())) || (crlImpl == null)) {
// the CRL either is no longer valid, or the SoftReference has been removed
// either way, remove the SoftReference object from the in memory cache
cache.remove(crlUrlString);
// don't removed if the only the SoftReference was removed
if (crlImpl != null) {
// the CRL is expired
removeCrlCacheFile(crlUrlString);
crlImpl = null;
}
}
}
}
// CRLs distribution point URI
if (crlImpl == null) {
// get the file name
final String uriFileName = getCacheFileName(crlUrlString);
if (!uriFileName.isEmpty()) {
// create a file to load from
final File cacheFile = new File(uriFileName);
InputStream fileInStream = null;
try {
// make sure the file exists before attempting to load
if (cacheFile.exists()) {
synchronized (cache) {
// load the CRL from an input stream
fileInStream = FileUtils.openInputStream(cacheFile);
crlImpl = (X509CRL) certificateFactory.generateCRL(fileInStream);
if (crlImpl == null) {
throw new CRLException("CRL load from cache resulted in null CLR implementation instance.");
}
// close the stream now because we can't delete it on windows
// if the stream is open
IOUtils.closeQuietly(fileInStream);
fileInStream = null;
// make sure the CRL isn't expired
if (crlImpl != null && crlImpl.getNextUpdate().before(new Date())) {
// the CRL has expired, so removed it from the cache and
// delete the file
cache.remove(crlUrlString);
removeCrlCacheFile(crlUrlString);
crlImpl = null;
} else {
// file load successful... add it the cache
cache.put(crlUrlString, new SoftReference<X509CRL>(crlImpl));
}
}
}
} catch (CRLException e) {
synchronized (cache) {
LOGGER.warn("CRL cache file " + uriFileName + " appears to be corrupt. Deleting file.", e);
// have to close the file stream or else we can't delete file on windows
IOUtils.closeQuietly(fileInStream);
removeCrlCacheFile(crlUrlString);
}
} catch (Throwable t) {
LOGGER.warn("Failed to load CRL from cache file " + uriFileName, t);
} finally {
if (fileInStream != null) {
IOUtils.closeQuietly(fileInStream);
}
}
}
}
// could not get file from memory or file cache... load from URL
if (crlImpl == null) {
try {
// create a URL connection object from the distribution point
URLConnection urlConnection = new URL(crlUrlString).openConnection();
urlConnection.setConnectTimeout(CRL_CONNECT_TIMEOUT);
urlConnection.setReadTimeout(CRL_READ_TIMEOUT);
// get the input stream
InputStream crlInputStream = urlConnection.getInputStream();
try {
// load from URI
crlImpl = (X509CRL) certificateFactory.generateCRL(crlInputStream);
} catch (Throwable t) {
LOGGER.warn("Failed to load CRL from URL " + crlUrlString, t);
} finally {
IOUtils.closeQuietly(crlInputStream);
}
if (crlImpl != null) {
// and write it a file
synchronized (cache) {
cache.put(crlUrlString, new SoftReference<X509CRL>(crlImpl));
writeCRLCacheFile(crlUrlString, crlImpl);
}
}
} catch (Exception e) {
LOGGER.warn("Unable to retrieve or parse CRL from URI " + crlUrlString);
}
}
return crlImpl;
}
use of java.security.cert.CRLException in project java-chassis by ServiceComb.
the class KeyStoreUtil method createCRL.
@SuppressWarnings({ "rawtypes", "unchecked" })
public static CRL[] createCRL(String crlfile) {
InputStream is = null;
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
is = new FileInputStream(crlfile);
Collection c = cf.generateCRLs(is);
CRL[] crls = (CRL[]) c.toArray(new CRL[c.size()]);
return crls;
} catch (CertificateException e) {
throw new IllegalArgumentException("bad cert file.");
} catch (FileNotFoundException e) {
throw new IllegalArgumentException("crl file not found.");
} catch (CRLException e) {
throw new IllegalArgumentException("bad crl file.");
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
ignore();
}
}
}
}
use of java.security.cert.CRLException in project poi by apache.
the class XAdESXLSignatureFacet method postSign.
@Override
public void postSign(Document document) throws MarshalException {
LOG.log(POILogger.DEBUG, "XAdES-X-L post sign phase");
QualifyingPropertiesDocument qualDoc = null;
QualifyingPropertiesType qualProps = null;
// check for XAdES-BES
NodeList qualNl = document.getElementsByTagNameNS(XADES_132_NS, "QualifyingProperties");
if (qualNl.getLength() == 1) {
try {
qualDoc = QualifyingPropertiesDocument.Factory.parse(qualNl.item(0), DEFAULT_XML_OPTIONS);
} catch (XmlException e) {
throw new MarshalException(e);
}
qualProps = qualDoc.getQualifyingProperties();
} else {
throw new MarshalException("no XAdES-BES extension present");
}
// create basic XML container structure
UnsignedPropertiesType unsignedProps = qualProps.getUnsignedProperties();
if (unsignedProps == null) {
unsignedProps = qualProps.addNewUnsignedProperties();
}
UnsignedSignaturePropertiesType unsignedSigProps = unsignedProps.getUnsignedSignatureProperties();
if (unsignedSigProps == null) {
unsignedSigProps = unsignedProps.addNewUnsignedSignatureProperties();
}
// create the XAdES-T time-stamp
NodeList nlSigVal = document.getElementsByTagNameNS(XML_DIGSIG_NS, "SignatureValue");
if (nlSigVal.getLength() != 1) {
throw new IllegalArgumentException("SignatureValue is not set.");
}
RevocationData tsaRevocationDataXadesT = new RevocationData();
LOG.log(POILogger.DEBUG, "creating XAdES-T time-stamp");
XAdESTimeStampType signatureTimeStamp = createXAdESTimeStamp(Collections.singletonList(nlSigVal.item(0)), tsaRevocationDataXadesT);
// marshal the XAdES-T extension
unsignedSigProps.addNewSignatureTimeStamp().set(signatureTimeStamp);
// xadesv141::TimeStampValidationData
if (tsaRevocationDataXadesT.hasRevocationDataEntries()) {
ValidationDataType validationData = createValidationData(tsaRevocationDataXadesT);
insertXChild(unsignedSigProps, validationData);
}
if (signatureConfig.getRevocationDataService() == null) {
/*
* Without revocation data service we cannot construct the XAdES-C
* extension.
*/
return;
}
// XAdES-C: complete certificate refs
CompleteCertificateRefsType completeCertificateRefs = unsignedSigProps.addNewCompleteCertificateRefs();
CertIDListType certIdList = completeCertificateRefs.addNewCertRefs();
/*
* We skip the signing certificate itself according to section
* 4.4.3.2 of the XAdES 1.4.1 specification.
*/
List<X509Certificate> certChain = signatureConfig.getSigningCertificateChain();
int chainSize = certChain.size();
if (chainSize > 1) {
for (X509Certificate cert : certChain.subList(1, chainSize)) {
CertIDType certId = certIdList.addNewCert();
XAdESSignatureFacet.setCertID(certId, signatureConfig, false, cert);
}
}
// XAdES-C: complete revocation refs
CompleteRevocationRefsType completeRevocationRefs = unsignedSigProps.addNewCompleteRevocationRefs();
RevocationData revocationData = signatureConfig.getRevocationDataService().getRevocationData(certChain);
if (revocationData.hasCRLs()) {
CRLRefsType crlRefs = completeRevocationRefs.addNewCRLRefs();
completeRevocationRefs.setCRLRefs(crlRefs);
for (byte[] encodedCrl : revocationData.getCRLs()) {
CRLRefType crlRef = crlRefs.addNewCRLRef();
X509CRL crl;
try {
crl = (X509CRL) this.certificateFactory.generateCRL(new ByteArrayInputStream(encodedCrl));
} catch (CRLException e) {
throw new RuntimeException("CRL parse error: " + e.getMessage(), e);
}
CRLIdentifierType crlIdentifier = crlRef.addNewCRLIdentifier();
String issuerName = crl.getIssuerDN().getName().replace(",", ", ");
crlIdentifier.setIssuer(issuerName);
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Z"), Locale.ROOT);
cal.setTime(crl.getThisUpdate());
crlIdentifier.setIssueTime(cal);
crlIdentifier.setNumber(getCrlNumber(crl));
DigestAlgAndValueType digestAlgAndValue = crlRef.addNewDigestAlgAndValue();
XAdESSignatureFacet.setDigestAlgAndValue(digestAlgAndValue, encodedCrl, signatureConfig.getDigestAlgo());
}
}
if (revocationData.hasOCSPs()) {
OCSPRefsType ocspRefs = completeRevocationRefs.addNewOCSPRefs();
for (byte[] ocsp : revocationData.getOCSPs()) {
try {
OCSPRefType ocspRef = ocspRefs.addNewOCSPRef();
DigestAlgAndValueType digestAlgAndValue = ocspRef.addNewDigestAlgAndValue();
XAdESSignatureFacet.setDigestAlgAndValue(digestAlgAndValue, ocsp, signatureConfig.getDigestAlgo());
OCSPIdentifierType ocspIdentifier = ocspRef.addNewOCSPIdentifier();
OCSPResp ocspResp = new OCSPResp(ocsp);
BasicOCSPResp basicOcspResp = (BasicOCSPResp) ocspResp.getResponseObject();
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Z"), Locale.ROOT);
cal.setTime(basicOcspResp.getProducedAt());
ocspIdentifier.setProducedAt(cal);
ResponderIDType responderId = ocspIdentifier.addNewResponderID();
RespID respId = basicOcspResp.getResponderId();
ResponderID ocspResponderId = respId.toASN1Primitive();
DERTaggedObject derTaggedObject = (DERTaggedObject) ocspResponderId.toASN1Primitive();
if (2 == derTaggedObject.getTagNo()) {
ASN1OctetString keyHashOctetString = (ASN1OctetString) derTaggedObject.getObject();
byte[] key = keyHashOctetString.getOctets();
responderId.setByKey(key);
} else {
X500Name name = X500Name.getInstance(derTaggedObject.getObject());
String nameStr = name.toString();
responderId.setByName(nameStr);
}
} catch (Exception e) {
throw new RuntimeException("OCSP decoding error: " + e.getMessage(), e);
}
}
}
// marshal XAdES-C
// XAdES-X Type 1 timestamp
List<Node> timeStampNodesXadesX1 = new ArrayList<Node>();
timeStampNodesXadesX1.add(nlSigVal.item(0));
timeStampNodesXadesX1.add(signatureTimeStamp.getDomNode());
timeStampNodesXadesX1.add(completeCertificateRefs.getDomNode());
timeStampNodesXadesX1.add(completeRevocationRefs.getDomNode());
RevocationData tsaRevocationDataXadesX1 = new RevocationData();
LOG.log(POILogger.DEBUG, "creating XAdES-X time-stamp");
XAdESTimeStampType timeStampXadesX1 = createXAdESTimeStamp(timeStampNodesXadesX1, tsaRevocationDataXadesX1);
if (tsaRevocationDataXadesX1.hasRevocationDataEntries()) {
ValidationDataType timeStampXadesX1ValidationData = createValidationData(tsaRevocationDataXadesX1);
insertXChild(unsignedSigProps, timeStampXadesX1ValidationData);
}
// marshal XAdES-X
unsignedSigProps.addNewSigAndRefsTimeStamp().set(timeStampXadesX1);
// XAdES-X-L
CertificateValuesType certificateValues = unsignedSigProps.addNewCertificateValues();
for (X509Certificate certificate : certChain) {
EncapsulatedPKIDataType encapsulatedPKIDataType = certificateValues.addNewEncapsulatedX509Certificate();
try {
encapsulatedPKIDataType.setByteArrayValue(certificate.getEncoded());
} catch (CertificateEncodingException e) {
throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
}
}
RevocationValuesType revocationValues = unsignedSigProps.addNewRevocationValues();
createRevocationValues(revocationValues, revocationData);
// marshal XAdES-X-L
Node n = document.importNode(qualProps.getDomNode(), true);
qualNl.item(0).getParentNode().replaceChild(n, qualNl.item(0));
}
use of java.security.cert.CRLException in project jdk8u_jdk by JetBrains.
the class PKCS7 method encodeSignedData.
/**
* Encodes the signed data to a DerOutputStream.
*
* @param out the DerOutputStream to write the encoded data to.
* @exception IOException on encoding errors.
*/
public void encodeSignedData(DerOutputStream out) throws IOException {
DerOutputStream signedData = new DerOutputStream();
// version
signedData.putInteger(version);
// digestAlgorithmIds
signedData.putOrderedSetOf(DerValue.tag_Set, digestAlgorithmIds);
// contentInfo
contentInfo.encode(signedData);
// certificates (optional)
if (certificates != null && certificates.length != 0) {
// cast to X509CertImpl[] since X509CertImpl implements DerEncoder
X509CertImpl[] implCerts = new X509CertImpl[certificates.length];
for (int i = 0; i < certificates.length; i++) {
if (certificates[i] instanceof X509CertImpl)
implCerts[i] = (X509CertImpl) certificates[i];
else {
try {
byte[] encoded = certificates[i].getEncoded();
implCerts[i] = new X509CertImpl(encoded);
} catch (CertificateException ce) {
throw new IOException(ce);
}
}
}
// Add the certificate set (tagged with [0] IMPLICIT)
// to the signed data
signedData.putOrderedSetOf((byte) 0xA0, implCerts);
}
// CRLs (optional)
if (crls != null && crls.length != 0) {
// cast to X509CRLImpl[] since X509CRLImpl implements DerEncoder
Set<X509CRLImpl> implCRLs = new HashSet<X509CRLImpl>(crls.length);
for (X509CRL crl : crls) {
if (crl instanceof X509CRLImpl)
implCRLs.add((X509CRLImpl) crl);
else {
try {
byte[] encoded = crl.getEncoded();
implCRLs.add(new X509CRLImpl(encoded));
} catch (CRLException ce) {
throw new IOException(ce);
}
}
}
// Add the CRL set (tagged with [1] IMPLICIT)
// to the signed data
signedData.putOrderedSetOf((byte) 0xA1, implCRLs.toArray(new X509CRLImpl[implCRLs.size()]));
}
// signerInfos
signedData.putOrderedSetOf(DerValue.tag_Set, signerInfos);
// making it a signed data block
DerValue signedDataSeq = new DerValue(DerValue.tag_Sequence, signedData.toByteArray());
// making it a content info sequence
ContentInfo block = new ContentInfo(ContentInfo.SIGNED_DATA_OID, signedDataSeq);
// writing out the contentInfo sequence
block.encode(out);
}
Aggregations