Search in sources :

Example 21 with ContentInfo

use of com.github.zhenwei.pkix.util.asn1.cms.ContentInfo in project xipki by xipki.

the class ScepResponder method servicePkiOperation0.

private PkiMessage servicePkiOperation0(DecodedPkiMessage req, AuditEvent event) throws CaException {
    TransactionId tid = req.getTransactionId();
    PkiMessage rep = new PkiMessage(tid, MessageType.CertRep, Nonce.randomNonce());
    rep.setPkiStatus(PkiStatus.SUCCESS);
    rep.setRecipientNonce(req.getSenderNonce());
    if (req.getFailureMessage() != null) {
        return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
    }
    Boolean bo = req.isSignatureValid();
    if (bo != null && !bo) {
        return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badMessageCheck);
    }
    bo = req.isDecryptionSuccessful();
    if (bo != null && !bo) {
        return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
    }
    Date signingTime = req.getSigningTime();
    if (maxSigningTimeBiasInMs > 0) {
        boolean isTimeBad;
        if (signingTime == null) {
            isTimeBad = true;
        } else {
            long now = System.currentTimeMillis();
            long diff = now - signingTime.getTime();
            if (diff < 0) {
                diff = -1 * diff;
            }
            isTimeBad = diff > maxSigningTimeBiasInMs;
        }
        if (isTimeBad) {
            return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badTime);
        }
    }
    // check the digest algorithm
    HashAlgo hashAlgo = req.getDigestAlgorithm();
    boolean supported = false;
    if (hashAlgo == HashAlgo.SHA1) {
        if (caCaps.containsCapability(CaCapability.SHA1)) {
            supported = true;
        }
    } else if (hashAlgo == HashAlgo.SHA256) {
        if (caCaps.containsCapability(CaCapability.SHA256)) {
            supported = true;
        }
    } else if (hashAlgo == HashAlgo.SHA512) {
        if (caCaps.containsCapability(CaCapability.SHA512)) {
            supported = true;
        }
    }
    if (!supported) {
        LOG.warn("tid={}: unsupported digest algorithm {}", tid, hashAlgo);
        return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
    }
    // end if
    // check the content encryption algorithm
    ASN1ObjectIdentifier encOid = req.getContentEncryptionAlgorithm();
    if (CMSAlgorithm.DES_EDE3_CBC.equals(encOid)) {
        if (!caCaps.containsCapability(CaCapability.DES3)) {
            LOG.warn("tid={}: encryption with DES3 algorithm {} is not permitted", tid, encOid);
            return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
        }
    } else if (AES_ENC_ALGS.contains(encOid)) {
        if (!caCaps.containsCapability(CaCapability.AES)) {
            LOG.warn("tid={}: encryption with AES algorithm {} is not permitted", tid, encOid);
            return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
        }
    } else if (CMSAlgorithm.DES_CBC.equals(encOid)) {
        if (!control.isUseInsecureAlg()) {
            LOG.warn("tid={}: encryption with DES algorithm {} is not permitted", tid, encOid);
            return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
        }
    } else {
        LOG.warn("tid={}: encryption with algorithm {} is not permitted", tid, encOid);
        return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
    }
    if (rep.getPkiStatus() == PkiStatus.FAILURE) {
        return rep;
    }
    MessageType messageType = req.getMessageType();
    switch(messageType) {
        case PKCSReq:
            boolean selfSigned = req.getSignatureCert().isSelfSigned();
            CertificationRequest csr = CertificationRequest.getInstance(req.getMessageData());
            if (selfSigned) {
                X500Name name = req.getSignatureCert().getSubject();
                if (!name.equals(csr.getCertificationRequestInfo().getSubject())) {
                    LOG.warn("tid={}: self-signed cert.subject != CSR.subject", tid);
                    return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
                }
            }
            String challengePwd = getChallengePassword(csr.getCertificationRequestInfo());
            if (!control.getSecret().equals(challengePwd)) {
                LOG.warn("challengePassword is not trusted");
                return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
            }
            X509Cert cert;
            try {
                cert = caEmulator.generateCert(csr);
            } catch (Exception ex) {
                throw new CaException("system failure: " + ex.getMessage(), ex);
            }
            if (cert != null && control.isPendingCert()) {
                rep.setPkiStatus(PkiStatus.PENDING);
            } else if (cert != null) {
                ContentInfo messageData = createSignedData(cert);
                rep.setMessageData(messageData);
            } else {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
            }
            break;
        case CertPoll:
            IssuerAndSubject is = IssuerAndSubject.getInstance(req.getMessageData());
            cert = caEmulator.pollCert(is.getIssuer(), is.getSubject());
            if (cert != null) {
                rep.setMessageData(createSignedData(cert));
            } else {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
            }
            break;
        case GetCert:
            IssuerAndSerialNumber isn = IssuerAndSerialNumber.getInstance(req.getMessageData());
            cert = caEmulator.getCert(isn.getName(), isn.getSerialNumber().getValue());
            if (cert != null) {
                rep.setMessageData(createSignedData(cert));
            } else {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
            }
            break;
        case RenewalReq:
            if (!caCaps.containsCapability(CaCapability.Renewal)) {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
            } else {
                csr = CertificationRequest.getInstance(req.getMessageData());
                try {
                    cert = caEmulator.generateCert(csr);
                } catch (Exception ex) {
                    throw new CaException("system failure: " + ex.getMessage(), ex);
                }
                if (cert != null) {
                    rep.setMessageData(createSignedData(cert));
                } else {
                    rep.setPkiStatus(PkiStatus.FAILURE);
                    rep.setFailInfo(FailInfo.badCertId);
                }
            }
            break;
        case UpdateReq:
            if (!caCaps.containsCapability(CaCapability.Update)) {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
            } else {
                csr = CertificationRequest.getInstance(req.getMessageData());
                try {
                    cert = caEmulator.generateCert(csr);
                } catch (Exception ex) {
                    throw new CaException("system failure: " + ex.getMessage(), ex);
                }
                if (cert != null) {
                    rep.setMessageData(createSignedData(cert));
                } else {
                    buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
                }
            }
            break;
        case GetCRL:
            isn = IssuerAndSerialNumber.getInstance(req.getMessageData());
            CertificateList crl;
            try {
                crl = caEmulator.getCrl(isn.getName(), isn.getSerialNumber().getValue());
            } catch (Exception ex) {
                throw new CaException("system failure: " + ex.getMessage(), ex);
            }
            if (crl != null) {
                rep.setMessageData(createSignedData(crl));
            } else {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
            }
            break;
        default:
            buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
    }
    return rep;
}
Also used : IssuerAndSerialNumber(org.bouncycastle.asn1.cms.IssuerAndSerialNumber) HashAlgo(org.xipki.security.HashAlgo) CertificateList(org.bouncycastle.asn1.x509.CertificateList) X500Name(org.bouncycastle.asn1.x500.X500Name) ASN1String(org.bouncycastle.asn1.ASN1String) Date(java.util.Date) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) X509Cert(org.xipki.security.X509Cert) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest)

Example 22 with ContentInfo

use of com.github.zhenwei.pkix.util.asn1.cms.ContentInfo in project ddf by codice.

the class KeystoreEditor method addToStore.

private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data, String type, String fileName, String path, String storepass, KeyStore store) throws KeystoreEditorException {
    OutputStream fos = null;
    try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) {
        if (StringUtils.isBlank(alias)) {
            throw new IllegalArgumentException(NULL_ALIAS_MSG);
        }
        Path storeFile = Paths.get(path);
        // check the two most common key/cert stores first (pkcs12 and jks)
        if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) {
            // priv key + cert chain
            KeyStore pkcs12Store = KeyStore.getInstance("PKCS12");
            pkcs12Store.load(inputStream, storePassword.toCharArray());
            Certificate[] chain = pkcs12Store.getCertificateChain(alias);
            Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray());
            if (key != null) {
                store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain);
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        } else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) {
            // java keystore file
            KeyStore jks = KeyStore.getInstance("jks");
            jks.load(inputStream, storePassword.toCharArray());
            Enumeration<String> aliases = jks.aliases();
            // we are going to store all entries from the jks regardless of the passed in alias
            while (aliases.hasMoreElements()) {
                String jksAlias = aliases.nextElement();
                if (jks.isKeyEntry(jksAlias)) {
                    Key key = jks.getKey(jksAlias, keyPassword.toCharArray());
                    Certificate[] certificateChain = jks.getCertificateChain(jksAlias);
                    store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain);
                } else {
                    Certificate certificate = jks.getCertificate(jksAlias);
                    store.setCertificateEntry(jksAlias, certificate);
                }
            }
            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
        // need to parse der separately from pem, der has the same mime type but is binary hence
        // checking both
        } else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) {
            ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream);
            ASN1Primitive asn1Primitive = asn1InputStream.readObject();
            X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded());
            CertificateFactory certificateFactory = CertificateFactory.getInstance(X509, "BC");
            Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
            X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
            RDN cn = x500name.getRDNs(BCStyle.CN)[0];
            String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
            if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                store.setCertificateEntry(cnStr, certificate);
            }
            store.setCertificateEntry(alias, certificate);
            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
        // if it isn't one of the stores we support, it might be a key or cert by itself
        } else if (isPemParsable(type, fileName)) {
            // This is the catch all case for PEM, P7B, etc. with common file extensions if the mime
            // type isn't read correctly in the browser
            Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            PEMParser pemParser = new PEMParser(reader);
            Object object;
            boolean setEntry = false;
            while ((object = pemParser.readObject()) != null) {
                if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) {
                    PEMKeyPair pemKeyPair;
                    if (object instanceof PEMEncryptedKeyPair) {
                        PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object;
                        JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
                        pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair(jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray()));
                    } else {
                        pemKeyPair = (PEMKeyPair) object;
                    }
                    KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair);
                    PrivateKey privateKey = keyPair.getPrivate();
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain);
                    setEntry = true;
                } else if (object instanceof X509CertificateHolder) {
                    X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object;
                    CertificateFactory certificateFactory = CertificateFactory.getInstance(X509, "BC");
                    Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
                    X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
                    RDN cn = x500name.getRDNs(BCStyle.CN)[0];
                    String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
                    if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                        store.setCertificateEntry(cnStr, certificate);
                    }
                    store.setCertificateEntry(alias, certificate);
                    setEntry = true;
                } else if (object instanceof ContentInfo) {
                    ContentInfo contentInfo = (ContentInfo) object;
                    if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) {
                        CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo);
                        OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure();
                        ASN1Set certificates = originatorInfo.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    } else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) {
                        SignedData signedData = SignedData.getInstance(contentInfo.getContent());
                        ASN1Set certificates = signedData.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    }
                } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
                    PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    try {
                        store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain);
                        setEntry = true;
                    } catch (KeyStoreException keyEx) {
                        try {
                            PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(), keyPassword.toCharArray());
                            store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(), chain);
                            setEntry = true;
                        } catch (GeneralSecurityException e) {
                            LOGGER.info("Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.", e);
                            throw keyEx;
                        }
                    }
                }
            }
            if (setEntry) {
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        }
    } catch (Exception e) {
        LOGGER.info("Unable to add entry {} to store", alias, e);
        throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ignore) {
            }
        }
    }
    init();
}
Also used : OriginatorInfo(org.bouncycastle.asn1.cms.OriginatorInfo) PrivateKey(java.security.PrivateKey) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) X500Name(org.bouncycastle.asn1.x500.X500Name) JcePEMDecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder) CertificateFactory(java.security.cert.CertificateFactory) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) PEMParser(org.bouncycastle.openssl.PEMParser) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) RDN(org.bouncycastle.asn1.x500.RDN) Path(java.nio.file.Path) PKCS8Key(org.apache.commons.ssl.PKCS8Key) CMSEnvelopedData(org.bouncycastle.cms.CMSEnvelopedData) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) KeyPair(java.security.KeyPair) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) Enumeration(java.util.Enumeration) InputStreamReader(java.io.InputStreamReader) SignedData(org.bouncycastle.asn1.cms.SignedData) ByteArrayInputStream(java.io.ByteArrayInputStream) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) InputStream(java.io.InputStream) GeneralSecurityException(java.security.GeneralSecurityException) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) InstanceAlreadyExistsException(javax.management.InstanceAlreadyExistsException) KeyManagementException(java.security.KeyManagementException) MalformedObjectNameException(javax.management.MalformedObjectNameException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) ASN1Set(org.bouncycastle.asn1.ASN1Set) ByteArrayInputStream(java.io.ByteArrayInputStream) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BufferedReader(java.io.BufferedReader) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) Key(java.security.Key) PrivateKey(java.security.PrivateKey) PKCS8Key(org.apache.commons.ssl.PKCS8Key) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 23 with ContentInfo

use of com.github.zhenwei.pkix.util.asn1.cms.ContentInfo in project xipki by xipki.

the class CmsEnveloperTest method passwordTest.

private void passwordTest(String algorithm, PasswordRecipient.PRF prf, char[] password) throws Exception {
    byte[] data = Hex.decode("1234567890abcdef");
    byte[] salt = new byte[20];
    int iterationCOunt = 10000;
    CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
    edGen.addRecipientInfoGenerator(new BcPasswordRecipientInfoGenerator(new ASN1ObjectIdentifier(algorithm), password).setPRF(prf).setSaltAndIterationCount(salt, iterationCOunt));
    CMSEnvelopedData ed0 = edGen.generate(new CMSProcessableByteArray(data), new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).build());
    EnvelopedData ed1 = (EnvelopedData) ed0.toASN1Structure().getContent();
    ContentInfo ci = new ContentInfo(CMSObjectIdentifiers.envelopedData, ed1);
    CMSEnvelopedData ed = new CMSEnvelopedData(ci);
    RecipientInformationStore recipients = ed.getRecipientInfos();
    Iterator<RecipientInformation> it = recipients.getRecipients().iterator();
    PasswordRecipientInformation recipient = (PasswordRecipientInformation) it.next();
    byte[] recData = recipient.getContent(new BcPasswordEnvelopedRecipient(password));
    Assert.assertArrayEquals(recData, data);
}
Also used : BcPasswordRecipientInfoGenerator(org.bouncycastle.cms.bc.BcPasswordRecipientInfoGenerator) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) EnvelopedData(org.bouncycastle.asn1.cms.EnvelopedData) BcPasswordEnvelopedRecipient(org.bouncycastle.cms.bc.BcPasswordEnvelopedRecipient)

Example 24 with ContentInfo

use of com.github.zhenwei.pkix.util.asn1.cms.ContentInfo in project xipki by xipki.

the class ScepResponder method servicePkiOperation0.

private PkiMessage servicePkiOperation0(DecodedPkiMessage req) throws CaException {
    TransactionId tid = req.getTransactionId();
    PkiMessage rep = new PkiMessage(tid, MessageType.CertRep, Nonce.randomNonce());
    rep.setPkiStatus(PkiStatus.SUCCESS);
    rep.setRecipientNonce(req.getSenderNonce());
    if (req.getFailureMessage() != null) {
        return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
    }
    Boolean bo = req.isSignatureValid();
    if (bo != null && !bo) {
        return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badMessageCheck);
    }
    bo = req.isDecryptionSuccessful();
    if (bo != null && !bo) {
        return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
    }
    Date signingTime = req.getSigningTime();
    if (maxSigningTimeBiasInMs > 0) {
        boolean isTimeBad;
        if (signingTime == null) {
            isTimeBad = true;
        } else {
            long now = System.currentTimeMillis();
            long diff = now - signingTime.getTime();
            if (diff < 0) {
                diff = -1 * diff;
            }
            isTimeBad = diff > maxSigningTimeBiasInMs;
        }
        if (isTimeBad) {
            return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badTime);
        }
    }
    // check the digest algorithm
    HashAlgo hashAlgo = req.getDigestAlgorithm();
    boolean supported = false;
    if (hashAlgo == HashAlgo.SHA1) {
        if (caCaps.supportsSHA1()) {
            supported = true;
        }
    } else if (hashAlgo == HashAlgo.SHA256) {
        if (caCaps.supportsSHA256()) {
            supported = true;
        }
    } else if (hashAlgo == HashAlgo.SHA512) {
        if (caCaps.supportsSHA512()) {
            supported = true;
        }
    }
    if (!supported) {
        LOG.warn("tid={}: unsupported digest algorithm {}", tid, hashAlgo);
        return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
    }
    // end if
    // check the content encryption algorithm
    ASN1ObjectIdentifier encOid = req.getContentEncryptionAlgorithm();
    if (CMSAlgorithm.DES_EDE3_CBC.equals(encOid)) {
        if (!caCaps.supportsDES3()) {
            LOG.warn("tid={}: encryption with DES3 algorithm {} is not permitted", tid, encOid);
            return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
        }
    } else if (CMSAlgorithm.AES128_CBC.equals(encOid)) {
        if (!caCaps.supportsAES()) {
            LOG.warn("tid={}: encryption with AES algorithm {} is not permitted", tid, encOid);
            return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
        }
    } else {
        LOG.warn("tid={}: encryption with algorithm {} is not permitted", tid, encOid);
        return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
    }
    if (rep.getPkiStatus() == PkiStatus.FAILURE) {
        return rep;
    }
    MessageType messageType = req.getMessageType();
    switch(messageType) {
        case PKCSReq:
            boolean selfSigned = req.getSignatureCert().isSelfSigned();
            CertificationRequest csr = CertificationRequest.getInstance(req.getMessageData());
            if (selfSigned) {
                X500Name name = req.getSignatureCert().getSubject();
                if (!name.equals(csr.getCertificationRequestInfo().getSubject())) {
                    LOG.warn("tid={}: self-signed cert.subject != CSR.subject", tid);
                    return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
                }
            }
            String challengePwd = getChallengePassword(csr.getCertificationRequestInfo());
            if (!control.getSecret().equals(challengePwd)) {
                LOG.warn("challengePassword is not trusted");
                return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
            }
            X509Cert cert;
            try {
                cert = caEmulator.generateCert(csr);
            } catch (Exception ex) {
                throw new CaException("system failure: " + ex.getMessage(), ex);
            }
            if (cert != null && control.isPendingCert()) {
                rep.setPkiStatus(PkiStatus.PENDING);
            } else if (cert != null) {
                ContentInfo messageData = createSignedData(cert);
                rep.setMessageData(messageData);
            } else {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
            }
            break;
        case CertPoll:
            IssuerAndSubject is = IssuerAndSubject.getInstance(req.getMessageData());
            cert = caEmulator.pollCert(is.getIssuer(), is.getSubject());
            if (cert != null) {
                rep.setMessageData(createSignedData(cert));
            } else {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
            }
            break;
        case GetCert:
            IssuerAndSerialNumber isn = IssuerAndSerialNumber.getInstance(req.getMessageData());
            cert = caEmulator.getCert(isn.getName(), isn.getSerialNumber().getValue());
            if (cert != null) {
                rep.setMessageData(createSignedData(cert));
            } else {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
            }
            break;
        case RenewalReq:
            if (!caCaps.supportsRenewal()) {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
            } else {
                csr = CertificationRequest.getInstance(req.getMessageData());
                try {
                    cert = caEmulator.generateCert(csr);
                } catch (Exception ex) {
                    throw new CaException("system failure: " + ex.getMessage(), ex);
                }
                if (cert != null) {
                    rep.setMessageData(createSignedData(cert));
                } else {
                    rep.setPkiStatus(PkiStatus.FAILURE);
                    rep.setFailInfo(FailInfo.badCertId);
                }
            }
            break;
        case GetCRL:
            isn = IssuerAndSerialNumber.getInstance(req.getMessageData());
            CertificateList crl;
            try {
                crl = caEmulator.getCrl(isn.getName(), isn.getSerialNumber().getValue());
            } catch (Exception ex) {
                throw new CaException("system failure: " + ex.getMessage(), ex);
            }
            if (crl != null) {
                rep.setMessageData(createSignedData(crl));
            } else {
                buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
            }
            break;
        default:
            buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
    }
    return rep;
}
Also used : IssuerAndSerialNumber(org.bouncycastle.asn1.cms.IssuerAndSerialNumber) HashAlgo(org.xipki.security.HashAlgo) CertificateList(org.bouncycastle.asn1.x509.CertificateList) X500Name(org.bouncycastle.asn1.x500.X500Name) ASN1String(org.bouncycastle.asn1.ASN1String) Date(java.util.Date) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) X509Cert(org.xipki.security.X509Cert) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest)

Example 25 with ContentInfo

use of com.github.zhenwei.pkix.util.asn1.cms.ContentInfo in project xipki by xipki.

the class Client method scepGetCrl.

public X509CRLHolder scepGetCrl(PrivateKey identityKey, X509Cert identityCert, X500Name issuer, BigInteger serialNumber) throws ScepClientException {
    Args.notNull(identityKey, "identityKey");
    Args.notNull(identityCert, "identityCert");
    Args.notNull(issuer, "issuer");
    Args.notNull(serialNumber, "serialNumber");
    initIfNotInited();
    PkiMessage pkiMessage = new PkiMessage(TransactionId.randomTransactionId(), MessageType.GetCRL);
    IssuerAndSerialNumber isn = new IssuerAndSerialNumber(issuer, serialNumber);
    pkiMessage.setMessageData(isn);
    ContentInfo request = encryptThenSign(pkiMessage, identityKey, identityCert);
    ScepHttpResponse httpResp = httpSend(Operation.PKIOperation, request);
    CMSSignedData cmsSignedData = parsePkiMessage(httpResp.getContentBytes());
    PkiMessage response = decode(cmsSignedData, identityKey, identityCert);
    if (response.getPkiStatus() != PkiStatus.SUCCESS) {
        throw new ScepClientException("server returned " + response.getPkiStatus());
    }
    ContentInfo messageData = ContentInfo.getInstance(response.getMessageData());
    try {
        return ScepUtil.getCrlFromPkiMessage(SignedData.getInstance(messageData.getContent()));
    } catch (CRLException ex) {
        throw new ScepClientException(ex.getMessage(), ex);
    }
}
Also used : IssuerAndSerialNumber(org.bouncycastle.asn1.cms.IssuerAndSerialNumber) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CRLException(java.security.cert.CRLException)

Aggregations

ContentInfo (org.bouncycastle.asn1.cms.ContentInfo)60 IOException (java.io.IOException)28 CMSSignedData (org.bouncycastle.cms.CMSSignedData)22 ContentInfo (com.github.zhenwei.pkix.util.asn1.cms.ContentInfo)18 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)15 OutputStream (java.io.OutputStream)12 X509Certificate (java.security.cert.X509Certificate)12 ArrayList (java.util.ArrayList)12 SignedData (org.bouncycastle.asn1.cms.SignedData)12 Iterator (java.util.Iterator)11 ASN1Set (org.bouncycastle.asn1.ASN1Set)11 ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)10 ASN1Set (com.github.zhenwei.core.asn1.ASN1Set)10 ASN1OctetString (com.github.zhenwei.core.asn1.ASN1OctetString)9 ByteArrayInputStream (java.io.ByteArrayInputStream)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)9 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)9 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)9 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)9 DERSet (org.bouncycastle.asn1.DERSet)9