Example usage for org.bouncycastle.asn1.cmp PKIHeaderBuilder setProtectionAlg

List of usage examples for org.bouncycastle.asn1.cmp PKIHeaderBuilder setProtectionAlg

Introduction

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

Prototype

public PKIHeaderBuilder setProtectionAlg(AlgorithmIdentifier aid) 

Source Link

Usage

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

License:Open Source License

@Override
public boolean create() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    final PKIHeaderBuilder myPKIHeader = CmpMessageHelper.createPKIHeaderBuilder(getSender(), getRecipient(),
            getSenderNonce(), getRecipientNonce(), getTransactionId());
    final PKIBody myPKIBody = new PKIBody(19, DERNull.INSTANCE);
    PKIMessage myPKIMessage = null;/*  w w  w .j  a  v  a  2s  .  c o  m*/

    if ((getPbeDigestAlg() != null) && (getPbeMacAlg() != null) && (getPbeKeyId() != null)
            && (getPbeKey() != null)) {
        myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(getPbeDigestAlg()));
        myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
        responseMessage = CmpMessageHelper.protectPKIMessageWithPBE(myPKIMessage, getPbeKeyId(), getPbeKey(),
                getPbeDigestAlg(), getPbeMacAlg(), getPbeIterationCount());
    } else {
        if ((signCertChain != null) && (signCertChain.size() > 0) && (signKey != null)) {
            try {
                myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(digestAlg));
                myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
                responseMessage = CmpMessageHelper.signPKIMessage(myPKIMessage, signCertChain, signKey,
                        digestAlg, provider);
            } catch (CertificateEncodingException e) {
                log.error("Error creating CmpConfirmMessage: ", e);
            } catch (SecurityException e) {
                log.error("Error creating CmpConfirmMessage: ", e);
            } catch (SignatureException e) {
                log.error("Error creating CmpConfirmMessage: ", e);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Not signing CMP Confirm Response, because signCert or signKey is not set.");
            }
        }
        // If we could not create the signed response message, create a non-protected one instead.
        if (responseMessage == null) {
            responseMessage = CmpMessageHelper.pkiMessageToByteArray(myPKIMessage);
        }
    }
    return true;
}

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

License:Open Source License

@Override
public boolean create() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    final PKIHeaderBuilder myPKIHeaderBuilder = CmpMessageHelper.createPKIHeaderBuilder(getSender(),
            getRecipient(), getSenderNonce(), getRecipientNonce(), getTransactionId());
    boolean pbeProtected = (getPbeDigestAlg() != null) && (getPbeMacAlg() != null) && (getPbeKeyId() != null)
            && (getPbeKey() != null);
    if (pbeProtected) {
        myPKIHeaderBuilder.setProtectionAlg(new AlgorithmIdentifier(CMPObjectIdentifiers.passwordBasedMac));
    }//from w  ww .j ava2s.  c  o m
    final PKIHeader myPKIHeader = myPKIHeaderBuilder.build();

    PKIStatusInfo myPKIStatusInfo = new PKIStatusInfo(PKIStatus.rejection);
    if (failInfo != null && failText != null) {
        myPKIStatusInfo = new PKIStatusInfo(PKIStatus.rejection, new PKIFreeText(new DERUTF8String(failText)),
                CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
    } else if (failText != null) {
        myPKIStatusInfo = new PKIStatusInfo(PKIStatus.rejection, new PKIFreeText(new DERUTF8String(failText)));
    }

    PKIBody myPKIBody = null;
    log.debug("Create error message from requestType: " + requestType);
    if (requestType == 0 || requestType == 2) {
        myPKIBody = CmpMessageHelper.createCertRequestRejectBody(myPKIStatusInfo, requestId, requestType);
    } else {
        ErrorMsgContent myErrorContent = new ErrorMsgContent(myPKIStatusInfo);
        myPKIBody = new PKIBody(23, myErrorContent); // 23 = error                  
    }
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader, myPKIBody);
    if (pbeProtected) {
        responseMessage = CmpMessageHelper.protectPKIMessageWithPBE(myPKIMessage, getPbeKeyId(), getPbeKey(),
                getPbeDigestAlg(), getPbeMacAlg(), getPbeIterationCount());
    } else {
        responseMessage = CmpMessageHelper.pkiMessageToByteArray(myPKIMessage);
    }
    return true;
}

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

License:Open Source License

public static PKIMessage buildCertBasedPKIProtection(PKIMessage pKIMessage, CMPCertificate[] extraCerts,
        PrivateKey key, String digestAlg, String provider) throws NoSuchProviderException,
        NoSuchAlgorithmException, SecurityException, SignatureException, InvalidKeyException {
    // Select which signature algorithm we should use for the response, based on the digest algorithm and key type.
    ASN1ObjectIdentifier oid = AlgorithmTools.getSignAlgOidFromDigestAndKey(digestAlg, key.getAlgorithm());
    if (LOG.isDebugEnabled()) {
        LOG.debug("Selected signature alg oid: " + oid.getId() + ", key algorithm: " + key.getAlgorithm());
    }/*from ww  w.  j  a v  a2  s  .  c om*/
    // According to PKCS#1 AlgorithmIdentifier for RSA-PKCS#1 has null Parameters, this means a DER Null (asn.1 encoding of null), not Java null.
    // For the RSA signature algorithms specified above RFC3447 states "...the parameters MUST be present and MUST be NULL."
    PKIHeaderBuilder headerBuilder = getHeaderBuilder(pKIMessage.getHeader());
    AlgorithmIdentifier pAlg = null;
    if ("RSA".equalsIgnoreCase(key.getAlgorithm())) {
        pAlg = new AlgorithmIdentifier(oid, DERNull.INSTANCE);
    } else {
        pAlg = new AlgorithmIdentifier(oid);
    }
    headerBuilder.setProtectionAlg(pAlg);
    // Most PKCS#11 providers don't like to be fed an OID as signature algorithm, so 
    // we use BC classes to translate it into a signature algorithm name instead
    PKIHeader head = headerBuilder.build();
    String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromOID(oid);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Signing CMP message with signature alg: " + signatureAlgorithmName);
    }
    Signature sig = Signature.getInstance(signatureAlgorithmName, provider);
    sig.initSign(key);
    sig.update(CmpMessageHelper.getProtectedBytes(head, pKIMessage.getBody()));

    if ((extraCerts != null) && (extraCerts.length > 0)) {
        pKIMessage = new PKIMessage(head, pKIMessage.getBody(), new DERBitString(sig.sign()), extraCerts);
    } else {
        pKIMessage = new PKIMessage(head, pKIMessage.getBody(), new DERBitString(sig.sign()));
    }
    return pKIMessage;
}

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

License:Open Source License

public static byte[] protectPKIMessageWithPBE(PKIMessage msg, String keyId, String raSecret, String digestAlgId,
        String macAlgId, int iterationCount)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
    if (LOG.isTraceEnabled()) {
        LOG.trace(">protectPKIMessageWithPBE()");
    }/*from w  ww  . j a  v a2s .  co m*/
    // Create the PasswordBased protection of the message
    PKIHeaderBuilder head = getHeaderBuilder(msg.getHeader());
    byte[] keyIdBytes;
    try {
        keyIdBytes = keyId.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        keyIdBytes = keyId.getBytes();
        LOG.info("UTF-8 not available, using platform default encoding for keyIdBytes.");
    }
    head.setSenderKID(new DEROctetString(keyIdBytes));
    // SHA1
    AlgorithmIdentifier owfAlg = new AlgorithmIdentifier(digestAlgId);
    // iterations, usually something like 1024
    ASN1Integer iteration = new ASN1Integer(iterationCount);
    // HMAC/SHA1
    AlgorithmIdentifier macAlg = new AlgorithmIdentifier(macAlgId);
    // We need some random bytes for the nonce
    byte[] saltbytes = createSenderNonce();
    DEROctetString derSalt = new DEROctetString(saltbytes);

    // Create the new protected return message
    //String objectId = "1.2.840.113533.7.66.13" = passwordBasedMac;
    String objectId = CMPObjectIdentifiers.passwordBasedMac.getId();
    PBMParameter pp = new PBMParameter(derSalt, owfAlg, iteration, macAlg);
    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(new ASN1ObjectIdentifier(objectId), pp);
    head.setProtectionAlg(pAlg);

    // Calculate the protection bits
    byte[] rasecret = raSecret.getBytes();
    byte[] basekey = new byte[rasecret.length + saltbytes.length];
    System.arraycopy(rasecret, 0, basekey, 0, rasecret.length);
    System.arraycopy(saltbytes, 0, basekey, rasecret.length, saltbytes.length);
    // Construct the base key according to rfc4210, section 5.1.3.1
    MessageDigest dig = MessageDigest.getInstance(owfAlg.getAlgorithm().getId(), "BC");
    for (int i = 0; i < iterationCount; i++) {
        basekey = dig.digest(basekey);
        dig.reset();
    }

    PKIHeader pkiHeader = head.build();
    // Do the mac
    String macOid = macAlg.getAlgorithm().getId();
    byte[] protectedBytes = CmpMessageHelper.getProtectedBytes(pkiHeader, msg.getBody()); //ret.getProtectedBytes();
    Mac mac = Mac.getInstance(macOid, "BC");
    SecretKey key = new SecretKeySpec(basekey, macOid);
    mac.init(key);
    mac.reset();
    mac.update(protectedBytes, 0, protectedBytes.length);
    byte[] out = mac.doFinal();
    DERBitString bs = new DERBitString(out);

    if (LOG.isTraceEnabled()) {
        LOG.trace("<protectPKIMessageWithPBE()");
    }
    // Return response as byte array 
    return CmpMessageHelper
            .pkiMessageToByteArray(new PKIMessage(pkiHeader, msg.getBody(), bs, msg.getExtraCerts()));
}

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

License:Open Source License

@Test
public void testLegacyEncodedRequestOverride() throws Exception {
    reconfigureCA(false, false, false);//from  w w  w .  j  av  a 2  s  .c  o  m
    // Setup "Allow subject DN override" and "Allow certificate serial number override" in used cert profile
    reconfigureCertificateProfile(true, true);
    final String issuerDn = CertTools.getSubjectDN(getTestCACert(TESTCA_NAME));
    final X500Name issuerX500Name = new X500Name(issuerDn);
    final org.bouncycastle.asn1.crmf.CertTemplateBuilder certTemplate = new org.bouncycastle.asn1.crmf.CertTemplateBuilder();
    certTemplate.setIssuer(issuerX500Name);
    final KeyPair keyPair = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);
    final String serialNumber = "88883311121333FF33012345";
    final byte[] transactionId = new byte[16];
    final byte[] senderNonce = new byte[16];
    final Random random = new Random();
    random.nextBytes(transactionId);
    random.nextBytes(senderNonce);
    final String subjectDn = "C=SE,O=PrimeKey,OU=Labs,CN=Sec_" + serialNumber;
    final X500Name subjectX500Name = CertTools.stringToBcX500Name(subjectDn, new TeletexNamingStyle(), false);
    certTemplate.setSubject(subjectX500Name);
    final byte[] bytes = keyPair.getPublic().getEncoded();
    final ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    final org.bouncycastle.asn1.ASN1InputStream asn1InputStream = new org.bouncycastle.asn1.ASN1InputStream(
            bIn);
    final org.bouncycastle.asn1.x509.SubjectPublicKeyInfo keyInfo = new org.bouncycastle.asn1.x509.SubjectPublicKeyInfo(
            (org.bouncycastle.asn1.ASN1Sequence) asn1InputStream.readObject());
    asn1InputStream.close();
    certTemplate.setPublicKey(keyInfo);
    // Request a custom certificate serial number
    certTemplate.setSerialNumber(new ASN1Integer(new BigInteger(serialNumber, 16)));
    final org.bouncycastle.asn1.crmf.ProofOfPossession myProofOfPossession = new org.bouncycastle.asn1.crmf.ProofOfPossession();
    final CertRequest certRequest = new CertRequest(4, certTemplate.build(), null);
    final AttributeTypeAndValue[] avs = { new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String(PBE_SECRET)) };
    final CertReqMsg certReqMsg = new CertReqMsg(certRequest, myProofOfPossession, avs);
    final CertReqMessages certReqMessages = new CertReqMessages(certReqMsg);
    PKIHeaderBuilder pkiHeader = new PKIHeaderBuilder(2, new GeneralName(subjectX500Name),
            new GeneralName(new X500Name(issuerDn)));
    pkiHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    pkiHeader.setSenderNonce(new DEROctetString(senderNonce));
    pkiHeader.setTransactionID(new DEROctetString(transactionId));
    pkiHeader.setProtectionAlg(null);
    final DEROctetString senderKID = null;
    pkiHeader.setSenderKID(senderKID);
    final PKIBody pkiBody = new PKIBody(0, certReqMessages);
    final PKIMessage pkiMessage = new PKIMessage(pkiHeader.build(), pkiBody);
    final PKIMessage req = protectPKIMessage(pkiMessage, false, PBE_SECRET, "unusedKeyId", 567);
    assertNotNull("Request was not created properly.", req);
    final CertReqMessages initializationRequest = (CertReqMessages) req.getBody().getContent();
    final int requestId = initializationRequest.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue()
            .intValue();
    final byte[] reqBytes = req.getEncoded();
    final byte[] cmpResponse = sendCmpHttp(reqBytes, 200, configAlias);
    final X509Certificate cert = checkCmpCertRepMessage(subjectX500Name, this.caCertificate, cmpResponse,
            requestId);
    LOG.debug("Request:\n" + new String(CertTools.getPEMFromCertificateRequest(certRequest.getEncoded())));
    LOG.debug("Result:\n" + new String(
            CertTools.getPemFromCertificateChain(new ArrayList<Certificate>(Arrays.asList(cert)))));
    final byte[] requestSubjectyX500Principal = cert.getSubjectX500Principal().getEncoded();
    final byte[] responeSubjectyX500Principal = subjectX500Name.getEncoded();
    assertTrue("Requested X500Name was not returned the same way as requested.",
            Arrays.equals(requestSubjectyX500Principal, responeSubjectyX500Principal));
    // We cannot assume that the unique serial number index is enabled, and hence we cant be sure that our serial number override was allowed, but at least we can print it
    LOG.info("Requested serial number: " + serialNumber);
    LOG.info("Response serial number:  " + CertTools.getSerialNumberAsString(cert));
}

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;/*from   w  w w .  j ava  2s .c om*/
    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.ejbca.core.protocol.cmp.CmpRevokeResponseMessage.java

License:Open Source License

@Override
public boolean create() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    final PKIHeaderBuilder myPKIHeader = CmpMessageHelper.createPKIHeaderBuilder(getSender(), getRecipient(),
            getSenderNonce(), getRecipientNonce(), getTransactionId());
    PKIStatusInfo myPKIStatusInfo = new PKIStatusInfo(PKIStatus.granted); // 0 = accepted
    if (status != ResponseStatus.SUCCESS && status != ResponseStatus.GRANTED_WITH_MODS) {
        if (log.isDebugEnabled()) {
            log.debug("Creating a rejection message");
        }/*from   ww  w.ja  v a  2  s.  c o  m*/
        myPKIStatusInfo = new PKIStatusInfo(PKIStatus.rejection, null,
                CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
        if (failText != null && failInfo != null) {
            myPKIStatusInfo = new PKIStatusInfo(PKIStatus.rejection, new PKIFreeText(failText),
                    CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
        }
    }
    RevRepContentBuilder revBuilder = new RevRepContentBuilder();
    revBuilder.add(myPKIStatusInfo);
    RevRepContent myRevrepMessage = revBuilder.build();

    PKIBody myPKIBody = new PKIBody(CmpPKIBodyConstants.REVOCATIONRESPONSE, myRevrepMessage);
    PKIMessage myPKIMessage;

    if ((getPbeDigestAlg() != null) && (getPbeMacAlg() != null) && (getPbeKeyId() != null)
            && (getPbeKey() != null)) {
        myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(CMPObjectIdentifiers.passwordBasedMac));
        myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
        responseMessage = CmpMessageHelper.protectPKIMessageWithPBE(myPKIMessage, getPbeKeyId(), getPbeKey(),
                getPbeDigestAlg(), getPbeMacAlg(), getPbeIterationCount());
    } else {
        myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(digestAlg));
        myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
        try {
            responseMessage = CmpMessageHelper.signPKIMessage(myPKIMessage, signCertChain, signKey, digestAlg,
                    provider);
        } catch (CertificateEncodingException e) {
            log.error("Failed to sign CMPRevokeResponseMessage");
            log.error(e.getLocalizedMessage(), e);
            responseMessage = getUnprotectedResponseMessage(myPKIMessage);
        } catch (SecurityException e) {
            log.error("Failed to sign CMPRevokeResponseMessage");
            log.error(e.getLocalizedMessage(), e);
            responseMessage = getUnprotectedResponseMessage(myPKIMessage);
        } catch (SignatureException e) {
            log.error("Failed to sign CMPRevokeResponseMessage");
            log.error(e.getLocalizedMessage(), e);
            responseMessage = getUnprotectedResponseMessage(myPKIMessage);
        }
    }
    return true;
}

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

License:Open Source License

protected static PKIMessage genCertReq(String issuerDN, X500Name userDN, String altNames, KeyPair keys,
        Certificate cacert, byte[] nonce, byte[] transid, boolean raVerifiedPopo, Extensions extensions,
        Date notBefore, Date notAfter, BigInteger customCertSerno, AlgorithmIdentifier pAlg,
        DEROctetString senderKID) throws NoSuchAlgorithmException, NoSuchProviderException, IOException,
        InvalidKeyException, SignatureException {
    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(
            new DERGeneralizedTime("20030211002120Z"));
    if (notBefore != null) {
        nb = new org.bouncycastle.asn1.x509.Time(notBefore);
    }//from  w ww.  j a  v  a2  s.co  m
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date());
    if (notAfter != null) {
        na = new org.bouncycastle.asn1.x509.Time(notAfter);
    }
    optionalValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV));

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setValidity(myOptionalValidity);
    if (issuerDN != null) {
        myCertTemplate.setIssuer(new X500Name(issuerDN));
    }
    myCertTemplate.setSubject(userDN);
    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
    dIn.close();
    myCertTemplate.setPublicKey(keyInfo);
    // If we did not pass any extensions as parameter, we will create some of our own, standard ones
    Extensions exts = extensions;
    if (exts == null) {

        // SubjectAltName
        // Some altNames
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        ASN1OutputStream dOut = new ASN1OutputStream(bOut);
        ExtensionsGenerator extgen = new ExtensionsGenerator();
        if (altNames != null) {
            GeneralNames san = CertTools.getGeneralNamesFromAltName(altNames);
            dOut.writeObject(san);
            byte[] value = bOut.toByteArray();
            extgen.addExtension(Extension.subjectAlternativeName, false, value);
        }

        // KeyUsage
        int bcku = 0;
        bcku = KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation;
        KeyUsage ku = new KeyUsage(bcku);
        extgen.addExtension(Extension.keyUsage, false, new DERBitString(ku));

        // Make the complete extension package
        exts = extgen.generate();
    }
    myCertTemplate.setExtensions(exts);
    if (customCertSerno != null) {
        // Add serialNumber to the certTemplate, it is defined as a MUST NOT be used in RFC4211, but we will use it anyway in order
        // to request a custom certificate serial number (something not standard anyway)
        myCertTemplate.setSerialNumber(new ASN1Integer(customCertSerno));
    }

    CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null);

    // POPO
    /*
     * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8,
     * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 }));
     * 
     * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new
     * byte[] { 44 }), 2); //take choice pos tag 2
     * 
     * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput(
     * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2,
     * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 }));
     */
    ProofOfPossession myProofOfPossession = null;
    if (raVerifiedPopo) {
        // raVerified POPO (meaning there is no POPO)
        myProofOfPossession = new ProofOfPossession();
    } else {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DEROutputStream mout = new DEROutputStream(baos);
        mout.writeObject(myCertRequest);
        mout.close();
        byte[] popoProtectionBytes = baos.toByteArray();
        String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm())
                .getId();
        Signature sig = Signature.getInstance(sigalg, "BC");
        sig.initSign(keys.getPrivate());
        sig.update(popoProtectionBytes);
        DERBitString bs = new DERBitString(sig.sign());
        POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null,
                new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs);
        myProofOfPossession = new ProofOfPossession(myPOPOSigningKey);
    }

    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String("foo123"));
    AttributeTypeAndValue[] avs = { av };

    CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs);

    CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(
            new X500Name(issuerDN != null ? issuerDN : ((X509Certificate) cacert).getSubjectDN().getName())));

    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(pAlg);
    myPKIHeader.setSenderKID(senderKID);

    PKIBody myPKIBody = new PKIBody(0, myCertReqMessages); // initialization
                                                           // request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    return myPKIMessage;
}

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

License:Open Source License

protected static PKIMessage genRevReq(String issuerDN, X500Name userDN, BigInteger serNo, Certificate cacert,
        byte[] nonce, byte[] transid, boolean crlEntryExtension, AlgorithmIdentifier pAlg,
        DEROctetString senderKID) throws IOException {
    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setIssuer(new X500Name(issuerDN));
    myCertTemplate.setSubject(userDN);// ww  w. j ava 2 s  .c om
    myCertTemplate.setSerialNumber(new ASN1Integer(serNo));

    ExtensionsGenerator extgen = new ExtensionsGenerator();
    CRLReason crlReason;
    if (crlEntryExtension) {
        crlReason = CRLReason.lookup(CRLReason.cessationOfOperation);
    } else {
        crlReason = CRLReason.lookup(CRLReason.keyCompromise);
    }
    extgen.addExtension(Extension.reasonCode, false, crlReason);

    Extensions exts = extgen.generate();

    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(myCertTemplate.build());
    v.add(exts);
    ASN1Sequence seq = new DERSequence(v);

    RevDetails myRevDetails = RevDetails.getInstance(seq); //new RevDetails(myCertTemplate.build(), exts);

    RevReqContent myRevReqContent = new RevReqContent(myRevDetails);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN),
            new GeneralName(new X500Name(((X509Certificate) cacert).getSubjectDN().getName())));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(pAlg);
    myPKIHeader.setSenderKID(senderKID);

    PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_REVOCATION_REQ, myRevReqContent); // revocation request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    return myPKIMessage;
}

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

License:Open Source License

protected static PKIMessage genRenewalReq(X500Name userDN, Certificate cacert, byte[] nonce, byte[] transid,
        KeyPair keys, boolean raVerifiedPopo, X500Name reqSubjectDN, String reqIssuerDN,
        AlgorithmIdentifier pAlg, DEROctetString senderKID) throws IOException, NoSuchAlgorithmException,
        InvalidKeyException, SignatureException, CertificateEncodingException {

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();

    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(
            new DERGeneralizedTime("20030211002120Z"));
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date());
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    optionalValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV));

    myCertTemplate.setValidity(myOptionalValidity);

    if (reqSubjectDN != null) {
        myCertTemplate.setSubject(reqSubjectDN);
    }//from   w  w w . j  av a2 s. co m
    if (reqIssuerDN != null) {
        myCertTemplate.setIssuer(new X500Name(reqIssuerDN));
    }

    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    try {
        SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
        myCertTemplate.setPublicKey(keyInfo);
    } finally {
        dIn.close();
    }

    CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null);

    // POPO
    /*
     * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8,
     * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 }));
     * 
     * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new
     * byte[] { 44 }), 2); //take choice pos tag 2
     * 
     * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput(
     * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2,
     * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 }));
     */
    ProofOfPossession myProofOfPossession = null;
    if (raVerifiedPopo) {
        // raVerified POPO (meaning there is no POPO)
        myProofOfPossession = new ProofOfPossession();
    } else {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DEROutputStream mout = new DEROutputStream(baos);
        mout.writeObject(myCertRequest);
        mout.close();
        byte[] popoProtectionBytes = baos.toByteArray();
        String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm())
                .getId();
        Signature sig = Signature.getInstance(sigalg);
        sig.initSign(keys.getPrivate());
        sig.update(popoProtectionBytes);

        DERBitString bs = new DERBitString(sig.sign());

        POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null,
                new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs);
        myProofOfPossession = new ProofOfPossession(myPOPOSigningKey);
    }

    // myCertReqMsg.addRegInfo(new AttributeTypeAndValue(new
    // ASN1ObjectIdentifier("1.3.6.2.2.2.2.3.1"), new
    // DERInteger(1122334455)));
    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String("foo123"));
    AttributeTypeAndValue[] avs = { av };

    CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs);

    CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN),
            new GeneralName(new JcaX509CertificateHolder((X509Certificate) cacert).getSubject()));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(pAlg);
    myPKIHeader.setSenderKID(senderKID);

    PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_KEY_UPDATE_REQ, myCertReqMessages); // Key Update Request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);

    return myPKIMessage;

}