use of java.security.cert.CertificateEncodingException in project Small by wequick.
the class BundleParser method verifyAndExtract.
public boolean verifyAndExtract(Bundle bundle, BundleExtractor extractor) {
WeakReference<byte[]> readBufferRef;
byte[] readBuffer = null;
synchronized (this.getClass()) {
readBufferRef = mReadBuffer;
if (readBufferRef != null) {
mReadBuffer = null;
readBuffer = readBufferRef.get();
}
if (readBuffer == null) {
readBuffer = new byte[8192];
readBufferRef = new WeakReference<byte[]>(readBuffer);
}
}
if (sHostCerts == null) {
// Collect host certificates
PackageManager pm = mContext.getPackageManager();
try {
Signature[] ss = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_SIGNATURES).signatures;
if (ss != null) {
int N = ss.length;
sHostCerts = new byte[N][];
for (int i = 0; i < N; i++) {
sHostCerts[i] = ss[i].toByteArray();
}
}
} catch (PackageManager.NameNotFoundException ignored) {
}
}
byte[][] hostCerts = sHostCerts;
CrcVerifier crcVerifier = new CrcVerifier(mContext, bundle.getPackageName(), hostCerts);
try {
JarFile jarFile = new JarFile(mArchiveSourcePath);
Enumeration entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry je = (JarEntry) entries.nextElement();
if (je.isDirectory())
continue;
String name = je.getName();
if (name.startsWith("META-INF/"))
continue;
if (mLibDir != null && name.startsWith("lib/") && !name.startsWith(mLibDir)) {
// Ignore unused ABIs
continue;
}
// Verify CRC first
int hash = name.hashCode();
int crc = crcVerifier.getObscuredCrc(je.getCrc());
if (crcVerifier.verifyCrc(hash, crc)) {
continue;
}
// Verify certificates
Certificate[] localCerts = loadCertificates(jarFile, je, readBuffer);
if (localCerts == null) {
Log.e(TAG, "Package " + mPackageName + " has no certificates at entry " + name + "; ignoring!");
crcVerifier.close();
jarFile.close();
return false;
} else {
// Ensure all certificates match.
for (int i = 0; i < hostCerts.length; i++) {
boolean found = false;
for (int j = 0; j < localCerts.length; j++) {
if (hostCerts[i] != null && Arrays.equals(hostCerts[i], localCerts[j].getEncoded())) {
found = true;
break;
}
}
if (!found || hostCerts.length != localCerts.length) {
Log.e(TAG, "Package " + mPackageName + " has mismatched certificates at entry " + name + "; ignoring!");
crcVerifier.close();
jarFile.close();
return false;
}
}
}
// Extract file if needed
File extractFile = extractor.getExtractFile(bundle, name);
if (extractFile != null) {
if (mZipFile == null) {
mZipFile = new ZipFile(mArchiveSourcePath);
}
postExtractFile(mZipFile, je, extractFile);
}
// Record the new crc
crcVerifier.recordCrc(hash, crc);
}
postSaveCrcs(crcVerifier);
jarFile.close();
synchronized (this.getClass()) {
mReadBuffer = readBufferRef;
}
} catch (CertificateEncodingException e) {
Log.w(TAG, "Exception reading " + mArchiveSourcePath, e);
return false;
} catch (IOException e) {
Log.w(TAG, "Exception reading " + mArchiveSourcePath, e);
return false;
} catch (RuntimeException e) {
Log.w(TAG, "Exception reading " + mArchiveSourcePath, e);
return false;
}
return true;
}
use of java.security.cert.CertificateEncodingException 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.CertificateEncodingException in project robovm by robovm.
the class CertificateEncodingExceptionTest method testCertificateEncodingException08.
/**
* Test for <code>CertificateEncodingException(String, Throwable)</code>
* constructor Assertion: constructs CertificateEncodingException when
* <code>cause</code> is not null <code>msg</code> is null
*/
public void testCertificateEncodingException08() {
CertificateEncodingException tE = new CertificateEncodingException(null, tCause);
if (tE.getMessage() != null) {
String toS = tCause.toString();
String getM = tE.getMessage();
assertTrue("getMessage() must should ".concat(toS), (getM.indexOf(toS) != -1));
}
assertNotNull("getCause() must not return null", tE.getCause());
assertEquals("getCause() must return ".concat(tCause.toString()), tE.getCause(), tCause);
}
use of java.security.cert.CertificateEncodingException in project robovm by robovm.
the class CertificateEncodingExceptionTest method testCertificateEncodingException02.
/**
* Test for <code>CertificateEncodingException(String)</code> constructor
* Assertion: constructs CertificateEncodingException with detail message
* msg. Parameter <code>msg</code> is not null.
*/
public void testCertificateEncodingException02() {
CertificateEncodingException tE;
for (int i = 0; i < msgs.length; i++) {
tE = new CertificateEncodingException(msgs[i]);
assertEquals("getMessage() must return: ".concat(msgs[i]), tE.getMessage(), msgs[i]);
assertNull("getCause() must return null", tE.getCause());
}
}
use of java.security.cert.CertificateEncodingException in project robovm by robovm.
the class CertificateEncodingExceptionTest method testCertificateEncodingException09.
/**
* Test for <code>CertificateEncodingException(String, Throwable)</code>
* constructor Assertion: constructs CertificateEncodingException when
* <code>cause</code> is not null <code>msg</code> is not null
*/
public void testCertificateEncodingException09() {
CertificateEncodingException tE;
for (int i = 0; i < msgs.length; i++) {
tE = new CertificateEncodingException(msgs[i], tCause);
String getM = tE.getMessage();
String toS = tCause.toString();
if (msgs[i].length() > 0) {
assertTrue("getMessage() must contain ".concat(msgs[i]), getM.indexOf(msgs[i]) != -1);
if (!getM.equals(msgs[i])) {
assertTrue("getMessage() should contain ".concat(toS), getM.indexOf(toS) != -1);
}
}
assertNotNull("getCause() must not return null", tE.getCause());
assertEquals("getCause() must return ".concat(tCause.toString()), tE.getCause(), tCause);
}
}
Aggregations