Search in sources :

Example 96 with ASN1InputStream

use of com.android.org.bouncycastle.asn1.ASN1InputStream in project BiglyBT by BiglySoftware.

the class PrincipalUtil method getIssuerX509Principal.

/**
 * return the issuer of the given CRL as an X509PrincipalObject.
 */
public static X509Principal getIssuerX509Principal(X509CRL crl) throws CRLException {
    try {
        ByteArrayInputStream bIn = new ByteArrayInputStream(crl.getTBSCertList());
        ASN1InputStream aIn = new ASN1InputStream(bIn);
        TBSCertList tbsCertList = new TBSCertList((ASN1Sequence) aIn.readObject());
        return new X509Principal(tbsCertList.getIssuer());
    } catch (IOException e) {
        throw new CRLException(e.toString());
    }
}
Also used : ASN1InputStream(org.gudy.bouncycastle.asn1.ASN1InputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) TBSCertList(org.gudy.bouncycastle.asn1.x509.TBSCertList) IOException(java.io.IOException) CRLException(java.security.cert.CRLException)

Example 97 with ASN1InputStream

use of com.android.org.bouncycastle.asn1.ASN1InputStream in project BiglyBT by BiglySoftware.

the class PrincipalUtil method getIssuerX509Principal.

/**
 * return the issuer of the given cert as an X509PrincipalObject.
 */
public static X509Principal getIssuerX509Principal(X509Certificate cert) throws CertificateEncodingException {
    try {
        ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getTBSCertificate());
        ASN1InputStream aIn = new ASN1InputStream(bIn);
        TBSCertificateStructure tbsCert = new TBSCertificateStructure((ASN1Sequence) aIn.readObject());
        return new X509Principal(tbsCert.getIssuer());
    } catch (IOException e) {
        throw new CertificateEncodingException(e.toString());
    }
}
Also used : ASN1InputStream(org.gudy.bouncycastle.asn1.ASN1InputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) TBSCertificateStructure(org.gudy.bouncycastle.asn1.x509.TBSCertificateStructure) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException)

Example 98 with ASN1InputStream

use of com.android.org.bouncycastle.asn1.ASN1InputStream in project xipki by xipki.

the class OcspServerImpl method answer.

@Override
public OcspRespWithCacheInfo answer(Responder responder2, byte[] request, boolean viaGet) {
    ResponderImpl responder = (ResponderImpl) responder2;
    RequestOption reqOpt = responder.getRequestOption();
    int version;
    try {
        version = OcspRequest.readRequestVersion(request);
    } catch (EncodingException ex) {
        String message = "could not extract version from request";
        LOG.warn(message);
        return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
    }
    if (!reqOpt.isVersionAllowed(version)) {
        String message = "invalid request version " + version;
        LOG.warn(message);
        return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
    }
    ResponderSigner signer = responder.getSigner();
    ResponseOption repOpt = responder.getResponseOption();
    try {
        Object reqOrRrrorResp = checkSignature(request, reqOpt);
        if (reqOrRrrorResp instanceof OcspRespWithCacheInfo) {
            return (OcspRespWithCacheInfo) reqOrRrrorResp;
        }
        OcspRequest req = (OcspRequest) reqOrRrrorResp;
        List<CertID> requestList = req.getRequestList();
        int requestsSize = requestList.size();
        if (requestsSize > reqOpt.getMaxRequestListCount()) {
            String message = requestsSize + " entries in RequestList, but maximal " + reqOpt.getMaxRequestListCount() + " is allowed";
            LOG.warn(message);
            return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
        }
        OcspRespControl repControl = new OcspRespControl();
        repControl.canCacheInfo = true;
        List<ExtendedExtension> reqExtensions = req.getExtensions();
        List<Extension> respExtensions = new LinkedList<>();
        ExtendedExtension nonceExtn = removeExtension(reqExtensions, OID.ID_PKIX_OCSP_NONCE);
        if (nonceExtn != null) {
            if (reqOpt.getNonceOccurrence() == TripleState.FORBIDDEN) {
                LOG.warn("nonce forbidden, but is present in the request");
                return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
            }
            int len = nonceExtn.getExtnValueLength();
            int min = reqOpt.getNonceMinLen();
            int max = reqOpt.getNonceMaxLen();
            if (len < min || len > max) {
                LOG.warn("length of nonce {} not within [{},{}]", len, min, max);
                return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
            }
            repControl.canCacheInfo = false;
            respExtensions.add(nonceExtn);
        } else {
            if (reqOpt.getNonceOccurrence() == TripleState.REQUIRED) {
                LOG.warn("nonce required, but is not present in the request");
                return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
            }
        }
        ConcurrentContentSigner concurrentSigner = null;
        if (responder.getResponderOption().getMode() != OcspMode.RFC2560) {
            ExtendedExtension extn = removeExtension(reqExtensions, OID.ID_PKIX_OCSP_PREFSIGALGS);
            if (extn != null) {
                ASN1InputStream asn1Stream = new ASN1InputStream(extn.getExtnValueStream());
                List<AlgorithmIdentifier> prefSigAlgs;
                try {
                    ASN1Sequence seq = ASN1Sequence.getInstance(asn1Stream.readObject());
                    final int size = seq.size();
                    prefSigAlgs = new ArrayList<>(size);
                    for (int i = 0; i < size; i++) {
                        prefSigAlgs.add(AlgorithmIdentifier.getInstance(seq.getObjectAt(i)));
                    }
                } finally {
                    asn1Stream.close();
                }
                concurrentSigner = signer.getSignerForPreferredSigAlgs(prefSigAlgs);
            }
        }
        if (!reqExtensions.isEmpty()) {
            boolean flag = false;
            for (ExtendedExtension m : reqExtensions) {
                if (m.isCritical()) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                if (LOG.isWarnEnabled()) {
                    List<OID> oids = new LinkedList<>();
                    for (ExtendedExtension m : reqExtensions) {
                        if (m.isCritical()) {
                            oids.add(m.getExtnType());
                        }
                    }
                    LOG.warn("could not process critial request extensions: {}", oids);
                }
                return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
            }
        }
        if (concurrentSigner == null) {
            concurrentSigner = signer.getFirstSigner();
        }
        AlgorithmCode cacheDbSigAlgCode = null;
        BigInteger cacheDbSerialNumber = null;
        Integer cacheDbIssuerId = null;
        boolean canCacheDb = (requestsSize == 1) && (responseCacher != null) && (nonceExtn == null) && responseCacher.isOnService();
        if (canCacheDb) {
            // try to find the cached response
            CertID certId = requestList.get(0);
            HashAlgo reqHashAlgo = certId.getIssuer().hashAlgorithm();
            if (!reqOpt.allows(reqHashAlgo)) {
                LOG.warn("CertID.hashAlgorithm {} not allowed", reqHashAlgo != null ? reqHashAlgo : certId.getIssuer().hashAlgorithmOID());
                return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
            }
            cacheDbSigAlgCode = concurrentSigner.getAlgorithmCode();
            cacheDbIssuerId = responseCacher.getIssuerId(certId.getIssuer());
            cacheDbSerialNumber = certId.getSerialNumber();
            if (cacheDbIssuerId != null) {
                OcspRespWithCacheInfo cachedResp = responseCacher.getOcspResponse(cacheDbIssuerId.intValue(), cacheDbSerialNumber, cacheDbSigAlgCode);
                if (cachedResp != null) {
                    return cachedResp;
                }
            } else if (master) {
                // store the issuer certificate in cache database.
                X509Certificate issuerCert = null;
                for (OcspStore store : responder.getStores()) {
                    issuerCert = store.getIssuerCert(certId.getIssuer());
                    if (issuerCert != null) {
                        break;
                    }
                }
                if (issuerCert != null) {
                    cacheDbIssuerId = responseCacher.storeIssuer(issuerCert);
                }
            }
            if (cacheDbIssuerId == null) {
                canCacheDb = false;
            }
        }
        ResponderID responderId = signer.getResponderId(repOpt.isResponderIdByName());
        OCSPRespBuilder builder = new OCSPRespBuilder(responderId);
        for (int i = 0; i < requestsSize; i++) {
            OcspRespWithCacheInfo failureOcspResp = processCertReq(requestList.get(i), builder, responder, reqOpt, repOpt, repControl);
            if (failureOcspResp != null) {
                return failureOcspResp;
            }
        }
        if (repControl.includeExtendedRevokeExtension) {
            respExtensions.add(extension_pkix_ocsp_extendedRevoke);
        }
        if (!respExtensions.isEmpty()) {
            Extensions extns = new Extensions(respExtensions);
            builder.setResponseExtensions(extns);
        }
        TaggedCertSequence certsInResp;
        EmbedCertsMode certsMode = repOpt.getEmbedCertsMode();
        if (certsMode == EmbedCertsMode.SIGNER) {
            certsInResp = signer.getSequenceOfCert();
        } else if (certsMode == EmbedCertsMode.NONE) {
            certsInResp = null;
        } else {
            // certsMode == EmbedCertsMode.SIGNER_AND_CA
            certsInResp = signer.getSequenceOfCertChain();
        }
        byte[] encodeOcspResponse;
        try {
            encodeOcspResponse = builder.buildOCSPResponse(concurrentSigner, certsInResp, new Date());
        } catch (NoIdleSignerException ex) {
            return unsuccesfulOCSPRespMap.get(OcspResponseStatus.tryLater);
        } catch (OCSPException ex) {
            LogUtil.error(LOG, ex, "answer() basicOcspBuilder.build");
            return unsuccesfulOCSPRespMap.get(OcspResponseStatus.internalError);
        }
        // cache response in database
        if (canCacheDb && repControl.canCacheInfo) {
            // Don't cache the response with status UNKNOWN, since this may result in DDoS
            // of storage
            responseCacher.storeOcspResponse(cacheDbIssuerId.intValue(), cacheDbSerialNumber, repControl.cacheThisUpdate, repControl.cacheNextUpdate, cacheDbSigAlgCode, encodeOcspResponse);
        }
        if (viaGet && repControl.canCacheInfo) {
            ResponseCacheInfo cacheInfo = new ResponseCacheInfo(repControl.cacheThisUpdate);
            if (repControl.cacheNextUpdate != Long.MAX_VALUE) {
                cacheInfo.setNextUpdate(repControl.cacheNextUpdate);
            }
            return new OcspRespWithCacheInfo(encodeOcspResponse, cacheInfo);
        } else {
            return new OcspRespWithCacheInfo(encodeOcspResponse, null);
        }
    } catch (Throwable th) {
        LogUtil.error(LOG, th);
        return unsuccesfulOCSPRespMap.get(OcspResponseStatus.internalError);
    }
}
Also used : EncodingException(org.xipki.ocsp.server.impl.type.EncodingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CertID(org.xipki.ocsp.server.impl.type.CertID) ExtendedExtension(org.xipki.ocsp.server.impl.type.ExtendedExtension) HashAlgo(org.xipki.security.HashAlgo) ResponderID(org.xipki.ocsp.server.impl.type.ResponderID) Extensions(org.xipki.ocsp.server.impl.type.Extensions) AlgorithmCode(org.xipki.security.AlgorithmCode) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) OcspStore(org.xipki.ocsp.api.OcspStore) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) OcspRespWithCacheInfo(org.xipki.ocsp.api.OcspRespWithCacheInfo) NoIdleSignerException(org.xipki.security.exception.NoIdleSignerException) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) OID(org.xipki.ocsp.server.impl.type.OID) TaggedCertSequence(org.xipki.ocsp.server.impl.type.TaggedCertSequence) LinkedList(java.util.LinkedList) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) Extension(org.xipki.ocsp.server.impl.type.Extension) WritableOnlyExtension(org.xipki.ocsp.server.impl.type.WritableOnlyExtension) ExtendedExtension(org.xipki.ocsp.server.impl.type.ExtendedExtension) BigInteger(java.math.BigInteger) ConcurrentContentSigner(org.xipki.security.ConcurrentContentSigner) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) EmbedCertsMode(org.xipki.ocsp.server.impl.jaxb.EmbedCertsMode) ResponseCacheInfo(org.xipki.ocsp.api.OcspRespWithCacheInfo.ResponseCacheInfo) BigInteger(java.math.BigInteger) OcspRequest(org.xipki.ocsp.server.impl.type.OcspRequest)

Example 99 with ASN1InputStream

use of com.android.org.bouncycastle.asn1.ASN1InputStream in project certmgr by hdecarne.

the class DERCertReaderWriter method readBinary.

@Override
@Nullable
public CertObjectStore readBinary(IOResource<InputStream> in, PasswordCallback password) throws IOException {
    LOG.debug("Trying to read DER objects from: ''{0}''...", in);
    CertObjectStore certObjects = null;
    try (ASN1InputStream derStream = new ASN1InputStream(in.io())) {
        ASN1Primitive derObject;
        while ((derObject = derStream.readObject()) != null) {
            X509Certificate crt = tryDecodeCRT(derObject);
            if (crt != null) {
                if (certObjects == null) {
                    certObjects = new CertObjectStore();
                }
                certObjects.addCRT(crt);
                continue;
            }
            KeyPair key = tryDecodeKey(derObject, in.resource(), password);
            if (key != null) {
                if (certObjects == null) {
                    certObjects = new CertObjectStore();
                }
                certObjects.addKey(key);
                continue;
            }
            PKCS10CertificateRequest csr = tryDecodeCSR(derObject);
            if (csr != null) {
                if (certObjects == null) {
                    certObjects = new CertObjectStore();
                }
                certObjects.addCSR(csr);
                continue;
            }
            X509CRL crl = tryDecodeCRL(derObject);
            if (crl != null) {
                if (certObjects == null) {
                    certObjects = new CertObjectStore();
                }
                certObjects.addCRL(crl);
                continue;
            }
            LOG.warning(CertIOI18N.STR_DER_UNKNOWN_OBJECT, derObject.getClass().getName());
        }
    } catch (ClassCastException e) {
        // the file is not a DER stream
        throw new CertProviderException(e);
    }
    return certObjects;
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) KeyPair(java.security.KeyPair) X509CRL(java.security.cert.X509CRL) PKCS10CertificateRequest(de.carne.certmgr.certs.x509.PKCS10CertificateRequest) CertObjectStore(de.carne.certmgr.certs.CertObjectStore) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) CertProviderException(de.carne.certmgr.certs.CertProviderException) X509Certificate(java.security.cert.X509Certificate) Nullable(de.carne.check.Nullable)

Example 100 with ASN1InputStream

use of com.android.org.bouncycastle.asn1.ASN1InputStream in project android_packages_apps_Settings by omnirom.

the class CredentialStorage method isHardwareBackedKey.

private boolean isHardwareBackedKey(byte[] keyData) {
    try {
        ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(keyData));
        PrivateKeyInfo pki = PrivateKeyInfo.getInstance(bIn.readObject());
        String algOid = pki.getAlgorithmId().getAlgorithm().getId();
        String algName = new AlgorithmId(new ObjectIdentifier(algOid)).getName();
        return KeyChain.isBoundKeyAlgorithm(algName);
    } catch (IOException e) {
        Log.e(TAG, "Failed to parse key data");
        return false;
    }
}
Also used : ASN1InputStream(com.android.org.bouncycastle.asn1.ASN1InputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) AlgorithmId(sun.security.x509.AlgorithmId) IOException(java.io.IOException) PrivateKeyInfo(com.android.org.bouncycastle.asn1.pkcs.PrivateKeyInfo) ObjectIdentifier(sun.security.util.ObjectIdentifier)

Aggregations

ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)108 IOException (java.io.IOException)90 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)36 ByteArrayInputStream (java.io.ByteArrayInputStream)35 X509Certificate (java.security.cert.X509Certificate)25 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)25 BigInteger (java.math.BigInteger)21 DEROctetString (org.bouncycastle.asn1.DEROctetString)21 ASN1InputStream (com.android.org.bouncycastle.asn1.ASN1InputStream)20 CertificateException (java.security.cert.CertificateException)20 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)18 CertificateParsingException (java.security.cert.CertificateParsingException)18 Enumeration (java.util.Enumeration)17 CertificateEncodingException (java.security.cert.CertificateEncodingException)16 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)16 InvalidKeyException (java.security.InvalidKeyException)14 CRLException (java.security.cert.CRLException)14 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)14 ASN1Primitive (org.bouncycastle.asn1.ASN1Primitive)12 NoSuchProviderException (java.security.NoSuchProviderException)11