Example usage for org.bouncycastle.asn1.cmp CertResponse CertResponse

List of usage examples for org.bouncycastle.asn1.cmp CertResponse CertResponse

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.cmp CertResponse CertResponse.

Prototype

public CertResponse(ASN1Integer certReqId, PKIStatusInfo status, CertifiedKeyPair certifiedKeyPair,
            ASN1OctetString rspInfo) 

Source Link

Usage

From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java

License:Open Source License

private byte[] createInitializationRespons1(byte[] senderNonce, byte[] transactionId) throws CMPException,
        CertificateEncodingException, OperatorCreationException, PKICMPMessageException, IOException {
    X509CertificateHolder x509CertificateHolder = new JcaX509CertificateHolder(pki.getTestUser3Cert());

    // Body/*from  w  ww.j a va 2 s. com*/
    CertResponse certResponse = new CertResponse(new ASN1Integer(0), new PKIStatusInfo(PKIStatus.granted),
            new CertifiedKeyPair(
                    new CertOrEncCert(new CMPCertificate(x509CertificateHolder.toASN1Structure()))),
            null);
    CertResponse[] certResponses = new CertResponse[1];
    certResponses[0] = certResponse;

    PKIBody pkiBody = new PKIBody(PKIBody.TYPE_INIT_REP,
            new CertRepMessage(pkiKeyStoreCA.getCMPCertificateChain(), certResponses));

    return createProtectedPKIMessage(senderNonce, transactionId, pkiBody);

}

From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java

License:Open Source License

private byte[] createInitializationRespons2(byte[] senderNonce, byte[] transactionId) throws CMPException,
        CertificateEncodingException, OperatorException, PKICMPMessageException, IOException, CRMFException {
    X509CertificateHolder x509CertificateHolder = new JcaX509CertificateHolder(pki.getTestUser3Cert());

    //encrypt Private Key
    KeyWrapper keyWrapper = new JceAsymmetricKeyWrapper(pkiKeyStoreCA.getRecipientCertificate().getPublicKey())
            .setProvider("BC");
    OutputEncryptor encryptor = new JceCRMFEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider("BC")
            .build();/*from   w  w w.  ja  v a2 s.co  m*/
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    OutputStream eOut = encryptor.getOutputStream(bOut);
    eOut.write(pki.getTestUser3CertPrivateKey().getEncoded());
    eOut.close();

    AlgorithmIdentifier intendedAlg = null;
    AlgorithmIdentifier symmAlg = encryptor.getAlgorithmIdentifier();
    DERBitString encSymmKey;
    keyWrapper.generateWrappedKey(encryptor.getKey());
    encSymmKey = new DERBitString(keyWrapper.generateWrappedKey(encryptor.getKey()));

    AlgorithmIdentifier keyAlg = keyWrapper.getAlgorithmIdentifier();
    ASN1OctetString valueHint = null;
    DERBitString encValue = new DERBitString(bOut.toByteArray());

    EncryptedValue encryptedPrivateKey = new EncryptedValue(intendedAlg, symmAlg, encSymmKey, keyAlg, valueHint,
            encValue);

    // Body
    CertResponse certResponse = new CertResponse(new ASN1Integer(0), new PKIStatusInfo(PKIStatus.granted),
            new CertifiedKeyPair(new CertOrEncCert(new CMPCertificate(x509CertificateHolder.toASN1Structure())),
                    encryptedPrivateKey, null),
            null);
    CertResponse[] certResponses = new CertResponse[1];
    certResponses[0] = certResponse;

    PKIBody pkiBody = new PKIBody(PKIBody.TYPE_INIT_REP,
            new CertRepMessage(pkiKeyStoreCA.getCMPCertificateChain(), certResponses));

    return createProtectedPKIMessage(senderNonce, transactionId, pkiBody);

}

From source file:org.ejbca.core.protocol.cmp.CmpResponseMessage.java

License:Open Source License

@Override
public boolean create() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    boolean ret = false;
    // Some general stuff, common for all types of messages
    String issuer = null;/*w  ww .  j  a va  2s. co m*/
    String subject = null;
    if (cert != null) {
        X509Certificate x509cert = (X509Certificate) cert;
        issuer = x509cert.getIssuerDN().getName();
        subject = x509cert.getSubjectDN().getName();
    } else if ((signCertChain != null) && (signCertChain.size() > 0)) {
        issuer = ((X509Certificate) signCertChain.iterator().next()).getSubjectDN().getName();
        subject = "CN=fooSubject";
    } else {
        issuer = "CN=fooIssuer";
        subject = "CN=fooSubject";
    }

    final GeneralName issuerName = new GeneralName(new X500Name(issuer));
    final GeneralName subjectName = new GeneralName(new X500Name(subject));
    final PKIHeaderBuilder myPKIHeader = CmpMessageHelper.createPKIHeaderBuilder(issuerName, subjectName,
            senderNonce, recipientNonce, transactionId);
    PKIBody myPKIBody = null;
    final PKIMessage myPKIMessage;

    try {
        if (status.equals(ResponseStatus.SUCCESS)) {
            if (cert != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Creating a CertRepMessage 'accepted'");
                }
                PKIStatusInfo myPKIStatusInfo = new PKIStatusInfo(PKIStatus.granted); // 0 = accepted
                ASN1InputStream certASN1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(cert.getEncoded()));
                ASN1InputStream cacertASN1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(cacert.getEncoded()));
                try {
                    try {
                        CMPCertificate cmpcert = CMPCertificate.getInstance(certASN1InputStream.readObject());
                        CertOrEncCert retCert = new CertOrEncCert(cmpcert);
                        CertifiedKeyPair myCertifiedKeyPair = new CertifiedKeyPair(retCert);
                        CertResponse myCertResponse = new CertResponse(new ASN1Integer(requestId),
                                myPKIStatusInfo, myCertifiedKeyPair, null);

                        CertResponse[] certRespos = { myCertResponse };
                        CMPCertificate[] caPubs = {
                                CMPCertificate.getInstance(cacertASN1InputStream.readObject()) };

                        CertRepMessage myCertRepMessage = new CertRepMessage(caPubs, certRespos);

                        int respType = requestType + 1; // 1 = intitialization response, 3 = certification response etc
                        if (log.isDebugEnabled()) {
                            log.debug("Creating response body of type " + respType);
                        }
                        myPKIBody = new PKIBody(respType, myCertRepMessage);
                    } finally {
                        certASN1InputStream.close();
                        cacertASN1InputStream.close();
                    }
                } catch (IOException e) {
                    throw new IllegalStateException("Unexpected IOException caught.", e);
                }
            }
        } else if (status.equals(ResponseStatus.FAILURE)) {
            if (log.isDebugEnabled()) {
                log.debug("Creating a CertRepMessage 'rejected'");
            }
            // Create a failure message
            ASN1EncodableVector statusInfoV = new ASN1EncodableVector();
            statusInfoV.add(ASN1Integer.getInstance(PKIStatus.rejection.toASN1Primitive()));
            if (failText != null) {
                statusInfoV.add(new PKIFreeText(new DERUTF8String(failText)));
            }
            statusInfoV.add(CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
            PKIStatusInfo myPKIStatusInfo = PKIStatusInfo
                    .getInstance(ASN1Sequence.getInstance(new DERSequence(statusInfoV)));
            myPKIBody = CmpMessageHelper.createCertRequestRejectBody(myPKIStatusInfo, requestId, requestType);

        } else {
            if (log.isDebugEnabled()) {
                log.debug("Creating a 'waiting' message?");
            }
            // Not supported, lets create a PKIError failure instead
            // Create a failure message
            ASN1EncodableVector statusInfoV = new ASN1EncodableVector();
            statusInfoV.add(PKIStatus.rejection); // 2 = rejection
            if (failText != null) {
                statusInfoV.add(new PKIFreeText(new DERUTF8String(failText)));
            }
            statusInfoV.add(CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
            PKIStatusInfo myPKIStatusInfo = PKIStatusInfo.getInstance(new DERSequence(statusInfoV));

            ErrorMsgContent myErrorContent = new ErrorMsgContent(myPKIStatusInfo);
            myPKIBody = new PKIBody(23, myErrorContent); // 23 = error                
        }

        if ((pbeKeyId != null) && (pbeKey != null) && (pbeDigestAlg != null) && (pbeMacAlg != null)) {
            myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(CMPObjectIdentifiers.passwordBasedMac));
            PKIHeader header = myPKIHeader.build();
            myPKIMessage = new PKIMessage(header, myPKIBody);
            responseMessage = CmpMessageHelper.protectPKIMessageWithPBE(myPKIMessage, pbeKeyId, pbeKey,
                    pbeDigestAlg, pbeMacAlg, pbeIterationCount);
        } else {
            myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(digest));
            PKIHeader header = myPKIHeader.build();
            myPKIMessage = new PKIMessage(header, myPKIBody);
            responseMessage = CmpMessageHelper.signPKIMessage(myPKIMessage, signCertChain, signKey, digest,
                    provider);
        }

        ret = true;

    } catch (CertificateEncodingException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (InvalidKeyException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (NoSuchProviderException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (NoSuchAlgorithmException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (SecurityException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (SignatureException e) {
        log.error("Error creating CertRepMessage: ", e);
    }

    return ret;
}

From source file:org.xipki.ca.server.impl.X509CACmpResponder.java

License:Open Source License

private CertResponse generateCertificate(final CmpRequestorInfo requestor, final String user,
        final ASN1OctetString tid, final ASN1Integer certReqId, final X500Name subject,
        final SubjectPublicKeyInfo publicKeyInfo, final OptionalValidity validity, final Extensions extensions,
        final String certprofileName, final boolean keyUpdate, final long confirmWaitTime,
        final AuditChildEvent childAuditEvent) throws InsuffientPermissionException {
    checkPermission(requestor, certprofileName);

    Date notBefore = null;/*from   w  ww.ja va  2  s  .c  o m*/
    Date notAfter = null;
    if (validity != null) {
        Time t = validity.getNotBefore();
        if (t != null) {
            notBefore = t.getDate();
        }
        t = validity.getNotAfter();
        if (t != null) {
            notAfter = t.getDate();
        }
    }

    try {
        X509CA ca = getCA();
        X509CertificateInfo certInfo;
        if (keyUpdate) {
            certInfo = ca.regenerateCertificate(requestor.isRA(), requestor, certprofileName, user, subject,
                    publicKeyInfo, notBefore, notAfter, extensions);
        } else {
            certInfo = ca.generateCertificate(requestor.isRA(), requestor, certprofileName, user, subject,
                    publicKeyInfo, notBefore, notAfter, extensions);
        }
        certInfo.setRequestor(requestor);
        certInfo.setUser(user);

        if (childAuditEvent != null) {
            childAuditEvent.addEventData(new AuditEventData("subject", certInfo.getCert().getSubject()));
        }

        pendingCertPool.addCertificate(tid.getOctets(), certReqId.getPositiveValue(), certInfo,
                System.currentTimeMillis() + confirmWaitTime);
        String warningMsg = certInfo.getWarningMessage();

        PKIStatusInfo statusInfo;
        if (StringUtil.isBlank(warningMsg)) {
            if (certInfo.isAlreadyIssued()) {
                statusInfo = new PKIStatusInfo(PKIStatus.grantedWithMods, new PKIFreeText("ALREADY_ISSUED"));
            } else {
                statusInfo = new PKIStatusInfo(PKIStatus.granted);
            }
        } else {
            statusInfo = new PKIStatusInfo(PKIStatus.grantedWithMods, new PKIFreeText(warningMsg));
        }

        if (childAuditEvent != null) {
            childAuditEvent.setStatus(AuditStatus.SUCCESSFUL);
        }

        CertOrEncCert cec = new CertOrEncCert(CMPCertificate.getInstance(certInfo.getCert().getEncodedCert()));
        CertifiedKeyPair kp = new CertifiedKeyPair(cec);
        CertResponse certResp = new CertResponse(certReqId, statusInfo, kp, null);
        return certResp;
    } catch (OperationException e) {
        ErrorCode code = e.getErrorCode();
        LOG.warn("generate certificate, OperationException: code={}, message={}", code.name(),
                e.getErrorMessage());

        String auditMessage;

        int failureInfo;
        switch (code) {
        case ALREADY_ISSUED:
            failureInfo = PKIFailureInfo.badRequest;
            auditMessage = "ALREADY_ISSUED";
            break;
        case BAD_CERT_TEMPLATE:
            failureInfo = PKIFailureInfo.badCertTemplate;
            auditMessage = "BAD_CERT_TEMPLATE";
            break;
        case BAD_REQUEST:
            failureInfo = PKIFailureInfo.badRequest;
            auditMessage = "BAD_REQUEST";
        case CERT_REVOKED:
            failureInfo = PKIFailureInfo.certRevoked;
            auditMessage = "CERT_REVOKED";
            break;
        case CRL_FAILURE:
            failureInfo = PKIFailureInfo.systemFailure;
            auditMessage = "CRL_FAILURE";
            break;
        case DATABASE_FAILURE:
            failureInfo = PKIFailureInfo.systemFailure;
            auditMessage = "DATABASE_FAILURE";
            break;
        case NOT_PERMITTED:
            failureInfo = PKIFailureInfo.notAuthorized;
            auditMessage = "NOT_PERMITTED";
            break;
        case INSUFFICIENT_PERMISSION:
            failureInfo = PKIFailureInfo.notAuthorized;
            auditMessage = "INSUFFICIENT_PERMISSION";
            break;
        case INVALID_EXTENSION:
            failureInfo = PKIFailureInfo.systemFailure;
            auditMessage = "INVALID_EXTENSION";
            break;
        case SYSTEM_FAILURE:
            failureInfo = PKIFailureInfo.systemFailure;
            auditMessage = "System_Failure";
            break;
        case SYSTEM_UNAVAILABLE:
            failureInfo = PKIFailureInfo.systemUnavail;
            auditMessage = "System_Unavailable";
            break;
        case UNKNOWN_CERT:
            failureInfo = PKIFailureInfo.badCertId;
            auditMessage = "UNKNOWN_CERT";
            break;
        case UNKNOWN_CERT_PROFILE:
            failureInfo = PKIFailureInfo.badCertTemplate;
            auditMessage = "UNKNOWN_CERT_PROFILE";
            break;
        default:
            failureInfo = PKIFailureInfo.systemFailure;
            auditMessage = "InternalErrorCode " + e.getErrorCode();
            break;
        } // end switch(code)

        if (childAuditEvent != null) {
            childAuditEvent.setStatus(AuditStatus.FAILED);
            childAuditEvent.addEventData(new AuditEventData("message", auditMessage));
        }

        String errorMessage;
        switch (code) {
        case DATABASE_FAILURE:
        case SYSTEM_FAILURE:
            errorMessage = code.name();
            break;
        default:
            errorMessage = code.name() + ": " + e.getErrorMessage();
            break;
        } // end switch code
        PKIStatusInfo status = generateCmpRejectionStatus(failureInfo, errorMessage);
        return new CertResponse(certReqId, status);
    }
}

From source file:org.xipki.pki.ca.server.impl.cmp.X509CaCmpResponder.java

License:Open Source License

private CertResponse postProcessCertInfo(ASN1Integer certReqId, X509CertificateInfo certInfo,
        ASN1OctetString tid, CmpControl cmpControl) {
    if (cmpControl.isConfirmCert()) {
        pendingCertPool.addCertificate(tid.getOctets(), certReqId.getPositiveValue(), certInfo,
                System.currentTimeMillis() + cmpControl.getConfirmWaitTimeMs());
    }//from  w  ww. j av a 2  s  .c o  m

    String warningMsg = certInfo.getWarningMessage();

    PKIStatusInfo statusInfo;
    if (StringUtil.isBlank(warningMsg)) {
        statusInfo = certInfo.isAlreadyIssued()
                ? new PKIStatusInfo(PKIStatus.grantedWithMods, new PKIFreeText("ALREADY_ISSUED"))
                : new PKIStatusInfo(PKIStatus.granted);
    } else {
        statusInfo = new PKIStatusInfo(PKIStatus.grantedWithMods, new PKIFreeText(warningMsg));
    }

    CertOrEncCert cec = new CertOrEncCert(CMPCertificate.getInstance(certInfo.getCert().getEncodedCert()));
    CertifiedKeyPair kp = new CertifiedKeyPair(cec);
    return new CertResponse(certReqId, statusInfo, kp, null);
}