Search in sources :

Example 21 with CertificationRequest

use of com.github.zhenwei.core.asn1.pkcs.CertificationRequest in project xipki by xipki.

the class DecodedPkiMessage method decode.

@SuppressWarnings("unchecked")
public static DecodedPkiMessage decode(CMSSignedData pkiMessage, EnvelopedDataDecryptor recipient, CollectionStore<X509CertificateHolder> certStore) throws MessageDecodingException {
    Args.notNull(pkiMessage, "pkiMessage");
    Args.notNull(recipient, "recipient");
    SignerInformationStore signerStore = pkiMessage.getSignerInfos();
    Collection<SignerInformation> signerInfos = signerStore.getSigners();
    if (signerInfos.size() != 1) {
        throw new MessageDecodingException("number of signerInfos is not 1, but " + signerInfos.size());
    }
    SignerInformation signerInfo = signerInfos.iterator().next();
    SignerId sid = signerInfo.getSID();
    Collection<?> signedDataCerts = null;
    if (certStore != null) {
        signedDataCerts = certStore.getMatches(sid);
    }
    if (CollectionUtil.isEmpty(signedDataCerts)) {
        signedDataCerts = pkiMessage.getCertificates().getMatches(signerInfo.getSID());
    }
    if (signedDataCerts == null || signedDataCerts.size() != 1) {
        throw new MessageDecodingException("could not find embedded certificate to verify the signature");
    }
    AttributeTable signedAttrs = signerInfo.getSignedAttributes();
    if (signedAttrs == null) {
        throw new MessageDecodingException("missing SCEP attributes");
    }
    Date signingTime = null;
    // signingTime
    ASN1Encodable attrValue = ScepUtil.getFirstAttrValue(signedAttrs, CMSAttributes.signingTime);
    if (attrValue != null) {
        signingTime = ScepUtil.getTime(attrValue);
    }
    // transactionId
    String str = getPrintableStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_TRANSACTION_ID);
    if (StringUtil.isBlank(str)) {
        throw new MessageDecodingException("missing required SCEP attribute transactionId");
    }
    TransactionId transactionId = new TransactionId(str);
    // messageType
    Integer intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_MESSAGE_TYPE);
    if (intValue == null) {
        throw new MessageDecodingException("tid " + transactionId.getId() + ": missing required SCEP attribute messageType");
    }
    MessageType messageType;
    try {
        messageType = MessageType.forValue(intValue);
    } catch (IllegalArgumentException ex) {
        throw new MessageDecodingException("tid " + transactionId.getId() + ": invalid messageType '" + intValue + "'");
    }
    // senderNonce
    Nonce senderNonce = getNonceAttrValue(signedAttrs, ScepObjectIdentifiers.ID_SENDER_NONCE);
    if (senderNonce == null) {
        throw new MessageDecodingException("tid " + transactionId.getId() + ": missing required SCEP attribute senderNonce");
    }
    DecodedPkiMessage ret = new DecodedPkiMessage(transactionId, messageType, senderNonce);
    if (signingTime != null) {
        ret.setSigningTime(signingTime);
    }
    Nonce recipientNonce = null;
    try {
        recipientNonce = getNonceAttrValue(signedAttrs, ScepObjectIdentifiers.ID_RECIPIENT_NONCE);
    } catch (MessageDecodingException ex) {
        ret.setFailureMessage("could not parse recipientNonce: " + ex.getMessage());
    }
    if (recipientNonce != null) {
        ret.setRecipientNonce(recipientNonce);
    }
    PkiStatus pkiStatus = null;
    FailInfo failInfo;
    if (MessageType.CertRep == messageType) {
        // pkiStatus
        try {
            intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_PKI_STATUS);
        } catch (MessageDecodingException ex) {
            ret.setFailureMessage("could not parse pkiStatus: " + ex.getMessage());
            return ret;
        }
        if (intValue == null) {
            ret.setFailureMessage("missing required SCEP attribute pkiStatus");
            return ret;
        }
        try {
            pkiStatus = PkiStatus.forValue(intValue);
        } catch (IllegalArgumentException ex) {
            ret.setFailureMessage("invalid pkiStatus '" + intValue + "'");
            return ret;
        }
        ret.setPkiStatus(pkiStatus);
        // failureInfo
        if (pkiStatus == PkiStatus.FAILURE) {
            try {
                intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_FAILINFO);
            } catch (MessageDecodingException ex) {
                ret.setFailureMessage("could not parse failInfo: " + ex.getMessage());
                return ret;
            }
            if (intValue == null) {
                ret.setFailureMessage("missing required SCEP attribute failInfo");
                return ret;
            }
            try {
                failInfo = FailInfo.forValue(intValue);
            } catch (IllegalArgumentException ex) {
                ret.setFailureMessage("invalid failInfo '" + intValue + "'");
                return ret;
            }
            ret.setFailInfo(failInfo);
            // failInfoText
            ASN1Encodable value = ScepUtil.getFirstAttrValue(signedAttrs, ScepObjectIdentifiers.ID_SCEP_FAILINFOTEXT);
            if (value != null) {
                if (value instanceof ASN1UTF8String) {
                    ret.setFailInfoText(((ASN1UTF8String) value).getString());
                } else if (value != null) {
                    throw new MessageDecodingException("the value of attribute failInfoText " + " is not UTF8String");
                }
            }
        }
    // end if(pkiStatus == PkiStatus.FAILURE)
    }
    // end if (MessageType.CertRep == messageType)
    // other signedAttributes
    Attribute[] attrs = signedAttrs.toASN1Structure().getAttributes();
    for (Attribute attr : attrs) {
        ASN1ObjectIdentifier type = attr.getAttrType();
        if (!SCEP_ATTR_TYPES.contains(type)) {
            ret.addSignendAttribute(type, attr.getAttrValues().getObjectAt(0));
        }
    }
    // unsignedAttributes
    AttributeTable unsignedAttrs = signerInfo.getUnsignedAttributes();
    attrs = (unsignedAttrs == null) ? null : unsignedAttrs.toASN1Structure().getAttributes();
    if (attrs != null) {
        for (Attribute attr : attrs) {
            ASN1ObjectIdentifier type = attr.getAttrType();
            ret.addUnsignendAttribute(type, attr.getAttrValues().getObjectAt(0));
        }
    }
    try {
        HashAlgo digestAlgo = HashAlgo.getInstance(signerInfo.getDigestAlgorithmID());
        ret.setDigestAlgorithm(digestAlgo);
        String sigAlgOid = signerInfo.getEncryptionAlgOID();
        if (!PKCSObjectIdentifiers.rsaEncryption.getId().equals(sigAlgOid)) {
            SignAlgo signAlgo = SignAlgo.getInstance(signerInfo.toASN1Structure().getDigestEncryptionAlgorithm());
            if (digestAlgo != signAlgo.getHashAlgo()) {
                ret.setFailureMessage("digestAlgorithm and encryptionAlgorithm do not use the same digestAlgorithm");
                return ret;
            }
        }
    } catch (NoSuchAlgorithmException ex) {
        String msg = ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }
    X509CertificateHolder signerCert = (X509CertificateHolder) signedDataCerts.iterator().next();
    ret.setSignatureCert(new X509Cert(signerCert));
    // validate the signature
    SignerInformationVerifier verifier;
    try {
        verifier = new JcaSimpleSignerInfoVerifierBuilder().build(signerCert);
    } catch (OperatorCreationException | CertificateException ex) {
        final String msg = "could not build signature verifier: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }
    boolean signatureValid;
    try {
        signatureValid = signerInfo.verify(verifier);
    } catch (CMSException ex) {
        final String msg = "could not verify the signature: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }
    ret.setSignatureValid(signatureValid);
    if (!signatureValid) {
        return ret;
    }
    if (MessageType.CertRep == messageType && (pkiStatus == PkiStatus.FAILURE | pkiStatus == PkiStatus.PENDING)) {
        return ret;
    }
    // MessageData
    CMSTypedData signedContent = pkiMessage.getSignedContent();
    ASN1ObjectIdentifier signedContentType = signedContent.getContentType();
    if (!CMSObjectIdentifiers.envelopedData.equals(signedContentType)) {
        // fall back: some SCEP client, such as JSCEP use id-data
        if (!CMSObjectIdentifiers.data.equals(signedContentType)) {
            ret.setFailureMessage("either id-envelopedData or id-data is excepted, but not '" + signedContentType.getId());
            return ret;
        }
    }
    CMSEnvelopedData envData;
    try {
        envData = new CMSEnvelopedData((byte[]) signedContent.getContent());
    } catch (CMSException ex) {
        final String msg = "could not create the CMSEnvelopedData: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }
    ret.setContentEncryptionAlgorithm(envData.getContentEncryptionAlgorithm().getAlgorithm());
    byte[] encodedMessageData;
    try {
        encodedMessageData = recipient.decrypt(envData);
    } catch (MessageDecodingException ex) {
        final String msg = "could not create the CMSEnvelopedData: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        ret.setDecryptionSuccessful(false);
        return ret;
    }
    ret.setDecryptionSuccessful(true);
    try {
        if (MessageType.PKCSReq == messageType || MessageType.RenewalReq == messageType) {
            CertificationRequest messageData = CertificationRequest.getInstance(encodedMessageData);
            ret.setMessageData(messageData);
        } else if (MessageType.CertPoll == messageType) {
            IssuerAndSubject messageData = IssuerAndSubject.getInstance(encodedMessageData);
            ret.setMessageData(messageData);
        } else if (MessageType.GetCert == messageType || MessageType.GetCRL == messageType) {
            IssuerAndSerialNumber messageData = IssuerAndSerialNumber.getInstance(encodedMessageData);
            ret.setMessageData(messageData);
            ret.setMessageData(messageData);
        } else if (MessageType.CertRep == messageType) {
            ContentInfo ci = ContentInfo.getInstance(encodedMessageData);
            ret.setMessageData(ci);
        } else {
            throw new RuntimeException("should not reach here, unknown messageType " + messageType);
        }
    } catch (Exception ex) {
        final String msg = "could not parse the messageData: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }
    return ret;
}
Also used : HashAlgo(org.xipki.security.HashAlgo) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X509Cert(org.xipki.security.X509Cert) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) Date(java.util.Date) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignAlgo(org.xipki.security.SignAlgo) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest)

Example 22 with CertificationRequest

use of com.github.zhenwei.core.asn1.pkcs.CertificationRequest in project xipki by xipki.

the class Ca2Manager method generateCertificate.

// method generateRootCa
X509Cert generateCertificate(String caName, String profileName, byte[] encodedCsr, Date notBefore, Date notAfter) throws CaMgmtException {
    caName = toNonBlankLower(caName, "caName");
    profileName = toNonBlankLower(profileName, "profileName");
    notNull(encodedCsr, "encodedCsr");
    AuditEvent event = new AuditEvent(new Date());
    event.setApplicationName(APPNAME);
    event.setName(NAME_perf);
    event.addEventType("CAMGMT_CRL_GEN_ONDEMAND");
    X509Ca ca = getX509Ca(caName);
    CertificationRequest csr;
    try {
        csr = X509Util.parseCsr(encodedCsr);
    } catch (Exception ex) {
        throw new CaMgmtException(concat("invalid CSR request. ERROR: ", ex.getMessage()));
    }
    if (!ca.verifyCsr(csr)) {
        throw new CaMgmtException("could not validate POP for the CSR");
    }
    CertificationRequestInfo certTemp = csr.getCertificationRequestInfo();
    Extensions extensions = null;
    ASN1Set attrs = certTemp.getAttributes();
    for (int i = 0; i < attrs.size(); i++) {
        Attribute attr = Attribute.getInstance(attrs.getObjectAt(i));
        if (PKCSObjectIdentifiers.pkcs_9_at_extensionRequest.equals(attr.getAttrType())) {
            extensions = Extensions.getInstance(attr.getAttributeValues()[0]);
        }
    }
    X500Name subject = certTemp.getSubject();
    SubjectPublicKeyInfo publicKeyInfo = certTemp.getSubjectPublicKeyInfo();
    CertTemplateData certTemplateData = new CertTemplateData(subject, publicKeyInfo, notBefore, notAfter, extensions, profileName);
    CertificateInfo certInfo;
    try {
        certInfo = ca.generateCert(certTemplateData, manager.byCaRequestor, RequestType.CA, null, MSGID_ca_mgmt);
    } catch (OperationException ex) {
        throw new CaMgmtException(ex.getMessage(), ex);
    }
    if (ca.getCaInfo().isSaveRequest()) {
        try {
            long dbId = ca.addRequest(encodedCsr);
            ca.addRequestCert(dbId, certInfo.getCert().getCertId());
        } catch (OperationException ex) {
            LogUtil.warn(LOG, ex, "could not save request");
        }
    }
    return certInfo.getCert().getCert();
}
Also used : CertificationRequestInfo(org.bouncycastle.asn1.pkcs.CertificationRequestInfo) Attribute(org.bouncycastle.asn1.pkcs.Attribute) X500Name(org.bouncycastle.asn1.x500.X500Name) Extensions(org.bouncycastle.asn1.x509.Extensions) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) DataAccessException(org.xipki.datasource.DataAccessException) CertificateException(java.security.cert.CertificateException) OperationException(org.xipki.ca.api.OperationException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ASN1Set(org.bouncycastle.asn1.ASN1Set) CertificateInfo(org.xipki.ca.api.CertificateInfo) AuditEvent(org.xipki.audit.AuditEvent) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest) OperationException(org.xipki.ca.api.OperationException)

Example 23 with CertificationRequest

use of com.github.zhenwei.core.asn1.pkcs.CertificationRequest in project LinLong-Java by zhenwei1108.

the class PKCS10CertificationRequestBuilder method build.

/**
 * Generate an PKCS#10 request based on the past in signer.
 *
 * @param signer the content signer to be used to generate the signature validating the
 *               certificate.
 * @return a holder containing the resulting PKCS#10 certification request.
 */
public PKCS10CertificationRequest build(ContentSigner signer) {
    CertificationRequestInfo info;
    if (attributes.isEmpty()) {
        if (leaveOffEmpty) {
            info = new CertificationRequestInfo(subject, publicKeyInfo, null);
        } else {
            info = new CertificationRequestInfo(subject, publicKeyInfo, new DERSet());
        }
    } else {
        ASN1EncodableVector v = new ASN1EncodableVector();
        for (Iterator it = attributes.iterator(); it.hasNext(); ) {
            v.add(Attribute.getInstance(it.next()));
        }
        info = new CertificationRequestInfo(subject, publicKeyInfo, new DERSet(v));
    }
    try {
        OutputStream sOut = signer.getOutputStream();
        sOut.write(info.getEncoded(ASN1Encoding.DER));
        sOut.close();
        return new PKCS10CertificationRequest(new CertificationRequest(info, signer.getAlgorithmIdentifier(), new DERBitString(signer.getSignature())));
    } catch (IOException e) {
        throw new IllegalStateException("cannot produce certification request signature");
    }
}
Also used : CertificationRequestInfo(com.github.zhenwei.core.asn1.pkcs.CertificationRequestInfo) OutputStream(java.io.OutputStream) Iterator(java.util.Iterator) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector) DERBitString(com.github.zhenwei.core.asn1.DERBitString) IOException(java.io.IOException) DERSet(com.github.zhenwei.core.asn1.DERSet) CertificationRequest(com.github.zhenwei.core.asn1.pkcs.CertificationRequest)

Example 24 with CertificationRequest

use of com.github.zhenwei.core.asn1.pkcs.CertificationRequest in project LinLong-Java by zhenwei1108.

the class TaggedCertificationRequest method toASN1Primitive.

public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector(2);
    v.add(bodyPartID);
    v.add(certificationRequest);
    return new DERSequence(v);
}
Also used : DERSequence(com.github.zhenwei.core.asn1.DERSequence) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector)

Example 25 with CertificationRequest

use of com.github.zhenwei.core.asn1.pkcs.CertificationRequest in project interlok by adaptris.

the class CertRequestHandler method createRequest.

/**
 * Create a certificate request based on the provided certificate.
 * <p>
 * The certificate request is returned as a printable string.
 * <p>
 * The default implementation returns a PEM string which is bounded by <code>-----BEGIN NEW CERTIFICATE REQUEST-----</code> and
 * <code>-----END NEW CERTIFICATE REQUEST-----</code> with each line terminated by a \n, e.g.
 * <p>
 *
 * <pre>
 * {@code
 * -----BEGIN NEW CERTIFICATE REQUEST-----
 * MIIC1zCCAb8CAQAwgZMxGTAXBgNVBAMTEEdoaWxhaW5lIFd5bnlhcmQxFTATBgNV
 * BAsTDElyaXMgU3VwcG9ydDENMAsGA1UEChMESXJpczEQMA4GA1UEBxMHRGF0Y2hl
 * dDESMBAGA1UECBMJQmVya3NoaXJlMQswCQYDVQQGEwJVSzEdMBsGCSqGSIb3DQEJ
 * ARYOZ2x3QGlyaXMuY28udWswggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB
 * AQCRQMSX5HCu25aQ+dtozxoGP1QtYC6JXuyGQkQ2MX2JsF1y+WM4NWUvhZvCKjmg
 * jsQL2c/rBzXifZCDRzMuHymOcmWXBaFJJr3b2XZQykzhKZKvTx6X1oU7PPcf+ws0
 * fNRQ3c1ZekPRYTUmSKyswJwIJDmpx4folU348taHwqcnK/LizekgjwrcZwSmFkk6
 * zhGTji2Ris4NMGvm/gDPGGmstxXTQIT62zOP1c61IhkKqxTtMZqmuB2HgQ8MRAza
 * xAxm7uoGbSCgUrWOjb92BHYxvQw8LKKkqKmKWRmDPPQKlBP4iR7vPUqXlb4G/keN
 * jR2EdByCJbkCUCwuVU124lJbAgMBAAEwDQYJKoZIhvcNAQEEBQADggEBADHpHomV
 * ZItNOeXjBDQGWNX9SpA9QV5IvEzm4u5mRI+XFsgYXvybeLMYC6Vrpxl9INVI6hpx
 * Nblq09Cq8lHQusyJNVEW3ibc73T5OZrCSnPTD7DUoKpwLwkDOwze7NHu+7NceUm1
 * pHCdiVe9Q3AC3+qlIdOhXGB3L5/Tn+8rYFNMAV8TQl7yRAz0g4lm+CdXQWaozTLY
 * /1MifSidgYoOq2lCE6l6JsVUv7mBTgaA52GuL0XvfopMOJrEuVUfFy7xVZMqD92L
 * ThcZUaIq5/Z3PUGLi8txXXb0Ga81SkLAHpBljgED0pV06EsrDz/N+12aH75zDcE+
 * Odt/GdYzfpeYvBg=
 * -----END NEW CERTIFICATE REQUEST-----
 * }
 *  </pre>
 *
 * @param c the certificate
 * @param key the private key
 * @return the PEM encoded string
 * @throws AdaptrisSecurityException if any error occurs
 * @see AdaptrisSecurityException
 */
public static String createRequest(Certificate c, PrivateKey key) throws AdaptrisSecurityException {
    String pemRequest = null;
    ByteArrayOutputStream out = null;
    try {
        CertificationRequest req = createCertRequest(c, key);
        out = new ByteArrayOutputStream();
        out.write("-----BEGIN NEW CERTIFICATE REQUEST-----".getBytes());
        out.write(req.getEncoded());
        out.write("-----END NEW CERTIFICATE REQUEST-----".getBytes());
        out.close();
        pemRequest = out.toString();
    } catch (Exception e) {
        throw new CertException(e);
    }
    return pemRequest;
}
Also used : CertException(com.adaptris.security.exc.CertException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest) CertException(com.adaptris.security.exc.CertException) AdaptrisSecurityException(com.adaptris.security.exc.AdaptrisSecurityException)

Aggregations

CertificationRequest (org.bouncycastle.asn1.pkcs.CertificationRequest)24 X500Name (org.bouncycastle.asn1.x500.X500Name)12 X509Certificate (java.security.cert.X509Certificate)9 Date (java.util.Date)9 BigInteger (java.math.BigInteger)8 CertificationRequestInfo (org.bouncycastle.asn1.pkcs.CertificationRequestInfo)8 X509Cert (org.xipki.security.X509Cert)8 Extensions (org.bouncycastle.asn1.x509.Extensions)7 File (java.io.File)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 PrivateKey (java.security.PrivateKey)5 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)5 OperationException (org.xipki.ca.api.OperationException)5 IOException (java.io.IOException)4 CertificateException (java.security.cert.CertificateException)4 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)4 ContentInfo (org.bouncycastle.asn1.cms.ContentInfo)4 IssuerAndSerialNumber (org.bouncycastle.asn1.cms.IssuerAndSerialNumber)4 EnrolmentResponse (org.xipki.scep.client.EnrolmentResponse)4 ScepClient (org.xipki.scep.client.ScepClient)4