Example usage for org.bouncycastle.asn1.cmp PKIBody TYPE_KEY_UPDATE_REQ

List of usage examples for org.bouncycastle.asn1.cmp PKIBody TYPE_KEY_UPDATE_REQ

Introduction

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

Prototype

int TYPE_KEY_UPDATE_REQ

To view the source code for org.bouncycastle.asn1.cmp PKIBody TYPE_KEY_UPDATE_REQ.

Click Source Link

Usage

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

License:Open Source License

/**
 * Update a certification request with local key generation
 *
 * @param certificate to be updated/*from   w  w w .  j ava 2s .  co m*/
 * @return return the binary ASN.1 message for a certification request
 * @throws CertificateEncodingException
 * @throws CMSException
 * @throws CRMFException
 * @throws OperatorCreationException
 * @throws CMPException
 * @throws IOException
 */
public byte[] createKeyUpdateMessageWithLocalKey(X509Certificate certificate, KeyPair keyPair)
        throws CertificateEncodingException, CMSException, CRMFException, OperatorCreationException,
        CMPException, IOException, PKICMPMessageException, NoSuchFieldException, IllegalAccessException {
    JcaCertificateRequestMessageBuilder certReqBuild = new JcaCertificateRequestMessageBuilder(BigInteger.ZERO);
    X509CertificateHolder x509CertificateHolder = new JcaX509CertificateHolder(certificate);

    certReqBuild.setSubject(x509CertificateHolder.getSubject());
    certReqBuild.setIssuer(x509CertificateHolder.getIssuer());
    certReqBuild.setSerialNumber(x509CertificateHolder.getSerialNumber());
    if (keyPair != null) {
        certReqBuild.setPublicKey(keyPair.getPublic());
        if (keyPair.getPrivate() != null) {
            certReqBuild.addControl(
                    new JcaPKIArchiveControlBuilder(keyPair.getPrivate(), x509CertificateHolder.getIssuer())
                            .addRecipientGenerator(
                                    new JceKeyTransRecipientInfoGenerator(pkiKeyStore.getRecipientCertificate())
                                            .setProvider(pkiKeyStore.getProvider()))
                            .build(new JceCMSContentEncryptorBuilder(
                                    new ASN1ObjectIdentifier(CMSEnvelopedDataGenerator.DES_EDE3_CBC))
                                            .setProvider(pkiKeyStore.getProvider()).build()));

        }
    } else
        certReqBuild.setPublicKey(x509CertificateHolder.getSubjectPublicKeyInfo());

    if (extensions != null) {
        for (Extension extension : extensions)
            certReqBuild.addExtension(extension.getExtnId(), extension.isCritical(),
                    extension.getParsedValue());
    } else {
        if (x509CertificateHolder.getExtensions() != null) {
            for (ASN1ObjectIdentifier oid : x509CertificateHolder.getExtensions().getExtensionOIDs()) {
                certReqBuild.addExtension(oid,
                        x509CertificateHolder.getExtensions().getExtension(oid).isCritical(),
                        x509CertificateHolder.getExtensions().getExtensionParsedValue(oid));
            }
        }
    }

    OptionalValidity tempOptionalValidity;
    if (optionalValidity != null) {
        tempOptionalValidity = optionalValidity;
    } else {
        tempOptionalValidity = new OptionalValidity(new Time(x509CertificateHolder.getNotBefore()),
                new Time(x509CertificateHolder.getNotAfter()));
    }
    Field field = certReqBuild.getClass().getSuperclass().getDeclaredField("templateBuilder");
    field.setAccessible(true);
    CertTemplateBuilder certTemplateBuilder = (CertTemplateBuilder) field.get(certReqBuild);
    certTemplateBuilder.setValidity(tempOptionalValidity);

    CertReqMessages certReqMsgs = new CertReqMessages(certReqBuild.build().toASN1Structure());

    return createProtectedPKIMessage(new PKIBody(PKIBody.TYPE_KEY_UPDATE_REQ, certReqMsgs));
}

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

License:Open Source License

/**
 * Update a certification request with remote key generation
 *
 * @param certificate to be updated//from   www .j a va2s  .  c o m
 * @return return the binary ASN.1 message for a certification request
 * @throws CertificateEncodingException
 * @throws CMSException
 * @throws CRMFException
 * @throws OperatorCreationException
 * @throws CMPException
 * @throws IOException
 */
public byte[] createKeyUpdateMessageWithRemoteKey(X509Certificate certificate)
        throws CertificateEncodingException, CMSException, CRMFException, OperatorCreationException,
        CMPException, IOException, PKICMPMessageException, NoSuchFieldException, IllegalAccessException {
    JcaCertificateRequestMessageBuilder certReqBuild = new JcaCertificateRequestMessageBuilder(BigInteger.ZERO);
    X509CertificateHolder x509CertificateHolder = new JcaX509CertificateHolder(certificate);

    certReqBuild.setSubject(x509CertificateHolder.getSubject());
    certReqBuild.setIssuer(x509CertificateHolder.getIssuer());
    certReqBuild.setSerialNumber(x509CertificateHolder.getSerialNumber());

    if (extensions != null) {
        for (Extension extension : extensions)
            certReqBuild.addExtension(extension.getExtnId(), extension.isCritical(),
                    extension.getParsedValue());
    } else {
        if (x509CertificateHolder.getExtensions() != null) {
            for (ASN1ObjectIdentifier oid : x509CertificateHolder.getExtensions().getExtensionOIDs()) {
                certReqBuild.addExtension(oid,
                        x509CertificateHolder.getExtensions().getExtension(oid).isCritical(),
                        x509CertificateHolder.getExtensions().getExtensionParsedValue(oid));
            }
        }
    }

    OptionalValidity tempOptionalValidity;
    if (optionalValidity != null) {
        tempOptionalValidity = optionalValidity;
    } else {
        tempOptionalValidity = new OptionalValidity(new Time(x509CertificateHolder.getNotBefore()),
                new Time(x509CertificateHolder.getNotAfter()));
    }
    Field field = certReqBuild.getClass().getSuperclass().getDeclaredField("templateBuilder");
    field.setAccessible(true);
    CertTemplateBuilder certTemplateBuilder = (CertTemplateBuilder) field.get(certReqBuild);
    certTemplateBuilder.setValidity(tempOptionalValidity);

    CertReqMessages certReqMsgs = new CertReqMessages(certReqBuild.build().toASN1Structure());

    return createProtectedPKIMessage(new PKIBody(PKIBody.TYPE_KEY_UPDATE_REQ, certReqMsgs));
}

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

License:Open Source License

/**
 * Test the confirmation message from the certification authority
 *
 * @throws IOException/*  w ww.j  a  v a 2 s  . co  m*/
 * @throws CertificateEncodingException
 * @throws OperatorCreationException
 * @throws CMPException
 */
@Test
public void testKeyUpdateWithLocalKeyChangeKey()
        throws IOException, CertificateEncodingException, OperatorCreationException, CMPException,
        PKICMPMessageException, CRMFException, IllegalAccessException, CMSException, NoSuchFieldException {
    PKICMPMessages pkiMessages = new PKICMPMessages();
    pkiMessages.setPkiKeyStore(pkiKeyStoreRA);
    KeyPair keyPair = new KeyPair(pki.getTestUser2Cert().getPublicKey(), pki.getTestUser2CertPrivateKey());

    byte[] result = pkiMessages.createKeyUpdateMessageWithLocalKey(pki.getTestUser1Cert(), keyPair);

    ASN1InputStream asn1InputStream = new ASN1InputStream(result);
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    PKIMessage pkiMessage = PKIMessage.getInstance(asn1Primitive);

    // Check the Body
    Assert.assertEquals(PKIBody.TYPE_KEY_UPDATE_REQ, pkiMessage.getBody().getType());
    CertReqMsg[] certReqMsgs = CertReqMessages.getInstance(pkiMessage.getBody().getContent())
            .toCertReqMsgArray();
    Assert.assertEquals(BigInteger.ZERO.toString(), certReqMsgs[0].getCertReq().getCertReqId().toString());
    Assert.assertEquals(pki.getTestUser1Cert().getSubjectDN().getName().toString(),
            certReqMsgs[0].getCertReq().getCertTemplate().getSubject().toString());
    Assert.assertEquals(pki.getTestUser1Cert().getSerialNumber(),
            certReqMsgs[0].getCertReq().getCertTemplate().getSerialNumber().getValue());
    Assert.assertEquals(pki.getTestUser1Cert().getIssuerDN().getName().toString(),
            certReqMsgs[0].getCertReq().getCertTemplate().getIssuer().toString());
    // KeyPair check
    Assert.assertArrayEquals(pki.getTestUser2Cert().getPublicKey().getEncoded(),
            certReqMsgs[0].getCertReq().getCertTemplate().getPublicKey().getEncoded());
    AttributeTypeAndValue[] attributeTypeAndValue = certReqMsgs[0].getCertReq().getControls()
            .toAttributeTypeAndValueArray();
    Assert.assertEquals(CRMFObjectIdentifiers.id_regCtrl_pkiArchiveOptions, attributeTypeAndValue[0].getType());
    // Validity
    Assert.assertEquals(pki.getTestUser1Cert().getNotBefore().toString(),
            certReqMsgs[0].getCertReq().getCertTemplate().getValidity().getNotBefore().getDate().toString());
    Assert.assertEquals(pki.getTestUser1Cert().getNotAfter().toString(),
            certReqMsgs[0].getCertReq().getCertTemplate().getValidity().getNotAfter().getDate().toString());
    // Extensions check
    Assert.assertNull(certReqMsgs[0].getCertReq().getCertTemplate().getExtensions());
}

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

License:Open Source License

/**
 * Test the confirmation message from the certification authority
 *
 * @throws IOException//w ww .  j a va  2 s .  c  om
 * @throws CertificateEncodingException
 * @throws OperatorCreationException
 * @throws CMPException
 */
@Test
public void testKeyUpdateWithLocalKeyChangeValidity()
        throws IOException, CertificateEncodingException, OperatorCreationException, CMPException,
        PKICMPMessageException, CRMFException, IllegalAccessException, CMSException, NoSuchFieldException {
    PKICMPMessages pkiMessages = new PKICMPMessages();
    pkiMessages.setPkiKeyStore(pkiKeyStoreRA);
    KeyPair keyPair = new KeyPair(pki.getTestUser2Cert().getPublicKey(), pki.getTestUser2CertPrivateKey());

    Date notBefore = new Date(System.currentTimeMillis() - 500L * 60 * 60 * 24 * 30);
    Date notAfter = new Date(System.currentTimeMillis() + 500L * 60 * 60 * 24 * 30);

    pkiMessages.setValidity(notBefore, notAfter);
    byte[] result = pkiMessages.createKeyUpdateMessageWithLocalKey(pki.getTestUser1Cert(), keyPair);

    ASN1InputStream asn1InputStream = new ASN1InputStream(result);
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    PKIMessage pkiMessage = PKIMessage.getInstance(asn1Primitive);

    // Check the Body
    Assert.assertEquals(PKIBody.TYPE_KEY_UPDATE_REQ, pkiMessage.getBody().getType());
    CertReqMsg[] certReqMsgs = CertReqMessages.getInstance(pkiMessage.getBody().getContent())
            .toCertReqMsgArray();
    // Validity
    Assert.assertEquals(notBefore.toString(),
            certReqMsgs[0].getCertReq().getCertTemplate().getValidity().getNotBefore().getDate().toString());
    Assert.assertEquals(notAfter.toString(),
            certReqMsgs[0].getCertReq().getCertTemplate().getValidity().getNotAfter().getDate().toString());
}

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

License:Open Source License

/**
 * Test the confirmation message from the certification authority
 *
 * @throws IOException//w  ww.  j  a va 2  s.c om
 * @throws CertificateEncodingException
 * @throws OperatorCreationException
 * @throws CMPException
 */
@Test
public void testKeyUpdateWithRemoteKey()
        throws IOException, CertificateEncodingException, OperatorCreationException, CMPException,
        PKICMPMessageException, CRMFException, IllegalAccessException, CMSException, NoSuchFieldException {
    PKICMPMessages pkiMessages = new PKICMPMessages();
    pkiMessages.setPkiKeyStore(pkiKeyStoreRA);

    byte[] result = pkiMessages.createKeyUpdateMessageWithRemoteKey(pki.getTestUser1Cert());

    ASN1InputStream asn1InputStream = new ASN1InputStream(result);
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    PKIMessage pkiMessage = PKIMessage.getInstance(asn1Primitive);

    // Check the Body
    Assert.assertEquals(PKIBody.TYPE_KEY_UPDATE_REQ, pkiMessage.getBody().getType());
    CertReqMsg[] certReqMsgs = CertReqMessages.getInstance(pkiMessage.getBody().getContent())
            .toCertReqMsgArray();
    Assert.assertEquals(BigInteger.ZERO.toString(), certReqMsgs[0].getCertReq().getCertReqId().toString());
    Assert.assertEquals(pki.getTestUser1Cert().getSubjectDN().getName().toString(),
            certReqMsgs[0].getCertReq().getCertTemplate().getSubject().toString());
    Assert.assertEquals(pki.getTestUser1Cert().getSerialNumber(),
            certReqMsgs[0].getCertReq().getCertTemplate().getSerialNumber().getValue());
    Assert.assertEquals(pki.getTestUser1Cert().getIssuerDN().getName().toString(),
            certReqMsgs[0].getCertReq().getCertTemplate().getIssuer().toString());
    // KeyPair check: should be not there
    Assert.assertNull(certReqMsgs[0].getCertReq().getCertTemplate().getPublicKey());
    Assert.assertNull(certReqMsgs[0].getCertReq().getControls());
    // Validity
    Assert.assertEquals(pki.getTestUser1Cert().getNotBefore().toString(),
            certReqMsgs[0].getCertReq().getCertTemplate().getValidity().getNotBefore().getDate().toString());
    Assert.assertEquals(pki.getTestUser1Cert().getNotAfter().toString(),
            certReqMsgs[0].getCertReq().getCertTemplate().getValidity().getNotAfter().getDate().toString());
    // Extensions check
    Assert.assertNull(certReqMsgs[0].getCertReq().getCertTemplate().getExtensions());
}

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);
    }/*  ww  w . j a  v a  2 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;

}

From source file:org.ejbca.ui.cmpclient.commands.KeyUpdateRequestCommand.java

License:Open Source License

@Override
public PKIMessage generatePKIMessage(ParameterContainer parameters) throws Exception {
    boolean verbose = parameters.containsKey(VERBOSE_KEY);

    final X500Name userDN = new X500Name(parameters.get(SUBJECTDN_KEY));
    final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY));
    boolean includePopo = parameters.containsKey(INCLUDE_POPO_KEY);

    if (verbose) {
        log.info("Creating KeyUpdate request with: SubjectDN=" + userDN.toString());
        log.info("Creating KeyUpdate request with: IssuerDN=" + issuerDN.toString());
        log.info("Creating KeyUpdate request with: IncludePopo=" + includePopo);
    }//ww  w .ja va  2s  . co m

    byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce();
    byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce();
    KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);

    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);

    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();
    }

    myCertTemplate.setSubject(userDN);

    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 (includePopo) {
        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);
    } else {
        // raVerified POPO (meaning there is no POPO)
        myProofOfPossession = new ProofOfPossession();
    }

    // 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(""));
    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(issuerDN));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(null);

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

    return myPKIMessage;
}

From source file:org.xipki.ca.client.impl.X509CmpRequestor.java

License:Open Source License

private PKIMessage buildPKIMessage(final EnrollCertRequestType req, final String username) {
    PKIHeader header = buildPKIHeader(implicitConfirm, null, username);

    List<EnrollCertRequestEntryType> reqEntries = req.getRequestEntries();
    CertReqMsg[] certReqMsgs = new CertReqMsg[reqEntries.size()];

    for (int i = 0; i < reqEntries.size(); i++) {
        EnrollCertRequestEntryType reqEntry = reqEntries.get(i);
        CmpUtf8Pairs utf8Pairs = new CmpUtf8Pairs(CmpUtf8Pairs.KEY_CERT_PROFILE, reqEntry.getCertprofile());
        AttributeTypeAndValue certprofileInfo = CmpUtil.buildAttributeTypeAndValue(utf8Pairs);

        certReqMsgs[i] = new CertReqMsg(reqEntry.getCertReq(), reqEntry.getPopo(),
                (certprofileInfo == null) ? null : new AttributeTypeAndValue[] { certprofileInfo });
    }/*from w w  w  .  j ava  2s .  co  m*/

    int bodyType;
    switch (req.getType()) {
    case CERT_REQ:
        bodyType = PKIBody.TYPE_CERT_REQ;
        break;
    case KEY_UPDATE:
        bodyType = PKIBody.TYPE_KEY_UPDATE_REQ;
        break;
    default:
        bodyType = PKIBody.TYPE_CROSS_CERT_REQ;
    }

    PKIBody body = new PKIBody(bodyType, new CertReqMessages(certReqMsgs));

    PKIMessage pkiMessage = new PKIMessage(header, body);
    return pkiMessage;
}

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

License:Open Source License

@Override
protected PKIMessage intern_processPKIMessage(final RequestorInfo requestor, final String user,
        final ASN1OctetString tid, final GeneralPKIMessage message, final AuditEvent auditEvent)
        throws ConfigurationException {
    if (requestor instanceof CmpRequestorInfo == false) {
        throw new IllegalArgumentException("unknown requestor type " + requestor.getClass().getName());
    }//from ww w .j av  a  2  s. co m

    CmpRequestorInfo _requestor = (CmpRequestorInfo) requestor;
    if (_requestor != null && auditEvent != null) {
        auditEvent.addEventData(new AuditEventData("requestor", _requestor.getCert().getSubject()));
    }

    PKIHeader reqHeader = message.getHeader();
    PKIHeaderBuilder respHeader = new PKIHeaderBuilder(reqHeader.getPvno().getValue().intValue(), getSender(),
            reqHeader.getSender());
    respHeader.setTransactionID(tid);

    PKIBody respBody;
    PKIBody reqBody = message.getBody();
    final int type = reqBody.getType();

    CmpControl cmpControl = getCmpControl();

    try {
        switch (type) {
        case PKIBody.TYPE_CERT_REQ:
        case PKIBody.TYPE_KEY_UPDATE_REQ:
        case PKIBody.TYPE_P10_CERT_REQ:
        case PKIBody.TYPE_CROSS_CERT_REQ: {
            respBody = cmpEnrollCert(respHeader, cmpControl, reqHeader, reqBody, _requestor, user, tid,
                    auditEvent);
            break;
        }
        case PKIBody.TYPE_CERT_CONFIRM: {
            addAutitEventType(auditEvent, "CERT_CONFIRM");
            CertConfirmContent certConf = (CertConfirmContent) reqBody.getContent();
            respBody = confirmCertificates(tid, certConf);
            break;
        }
        case PKIBody.TYPE_REVOCATION_REQ: {
            respBody = cmpRevokeOrUnrevokeOrRemoveCertificates(respHeader, cmpControl, reqHeader, reqBody,
                    _requestor, user, tid, auditEvent);
            break;
        }
        case PKIBody.TYPE_CONFIRM: {
            addAutitEventType(auditEvent, "CONFIRM");
            respBody = new PKIBody(PKIBody.TYPE_CONFIRM, DERNull.INSTANCE);
        }
        case PKIBody.TYPE_ERROR: {
            addAutitEventType(auditEvent, "ERROR");
            revokePendingCertificates(tid);
            respBody = new PKIBody(PKIBody.TYPE_CONFIRM, DERNull.INSTANCE);
            break;
        }
        case PKIBody.TYPE_GEN_MSG: {
            respBody = cmpGeneralMsg(respHeader, cmpControl, reqHeader, reqBody, _requestor, user, tid,
                    auditEvent);
            break;
        }
        default: {
            addAutitEventType(auditEvent, "PKIBody." + type);
            respBody = createErrorMsgPKIBody(PKIStatus.rejection, PKIFailureInfo.badRequest,
                    "unsupported type " + type);
            break;
        }
        } // end switch(type)
    } catch (InsuffientPermissionException e) {
        ErrorMsgContent emc = new ErrorMsgContent(new PKIStatusInfo(PKIStatus.rejection,
                new PKIFreeText(e.getMessage()), new PKIFailureInfo(PKIFailureInfo.notAuthorized)));

        respBody = new PKIBody(PKIBody.TYPE_ERROR, emc);
    }

    if (auditEvent != null) {
        if (respBody.getType() == PKIBody.TYPE_ERROR) {
            ErrorMsgContent errorMsgContent = (ErrorMsgContent) respBody.getContent();

            AuditStatus auditStatus = AuditStatus.FAILED;
            org.xipki.ca.common.cmp.PKIStatusInfo pkiStatus = new org.xipki.ca.common.cmp.PKIStatusInfo(
                    errorMsgContent.getPKIStatusInfo());

            if (pkiStatus.getPkiFailureInfo() == PKIFailureInfo.systemFailure) {
                auditStatus = AuditStatus.FAILED;
            }
            auditEvent.setStatus(auditStatus);

            String statusString = pkiStatus.getStatusMessage();
            if (statusString != null) {
                auditEvent.addEventData(new AuditEventData("message", statusString));
            }
        } else if (auditEvent.getStatus() == null) {
            auditEvent.setStatus(AuditStatus.SUCCESSFUL);
        }
    }

    return new PKIMessage(respHeader.build(), respBody);
}

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

License:Open Source License

private PKIBody cmpEnrollCert(final PKIHeaderBuilder respHeader, final CmpControl cmpControl,
        final PKIHeader reqHeader, final PKIBody reqBody, final CmpRequestorInfo requestor, final String user,
        final ASN1OctetString tid, final AuditEvent auditEvent) throws InsuffientPermissionException {
    long confirmWaitTime = cmpControl.getConfirmWaitTime();
    if (confirmWaitTime < 0) {
        confirmWaitTime *= -1;/*from   w  w w.  jav  a  2s .  c  o m*/
    }
    confirmWaitTime *= 1000; // second to millisecond
    boolean sendCaCert = cmpControl.isSendCaCert();

    PKIBody respBody;

    int type = reqBody.getType();
    switch (type) {
    case PKIBody.TYPE_CERT_REQ:
        addAutitEventType(auditEvent, "CERT_REQ");
        checkPermission(requestor, Permission.ENROLL_CERT);
        respBody = processCr(requestor, user, tid, reqHeader, (CertReqMessages) reqBody.getContent(),
                confirmWaitTime, sendCaCert, auditEvent);
        break;
    case PKIBody.TYPE_KEY_UPDATE_REQ:
        addAutitEventType(auditEvent, "KEY_UPDATE");
        checkPermission(requestor, Permission.KEY_UPDATE);
        respBody = processKur(requestor, user, tid, reqHeader, (CertReqMessages) reqBody.getContent(),
                confirmWaitTime, sendCaCert, auditEvent);
        break;
    case PKIBody.TYPE_P10_CERT_REQ:
        addAutitEventType(auditEvent, "CERT_REQ");
        checkPermission(requestor, Permission.ENROLL_CERT);
        respBody = processP10cr(requestor, user, tid, reqHeader, (CertificationRequest) reqBody.getContent(),
                confirmWaitTime, sendCaCert, auditEvent);
        break;
    case PKIBody.TYPE_CROSS_CERT_REQ:
        addAutitEventType(auditEvent, "CROSS_CERT_REQ");
        checkPermission(requestor, Permission.CROSS_CERT_ENROLL);
        respBody = processCcp(requestor, user, tid, reqHeader, (CertReqMessages) reqBody.getContent(),
                confirmWaitTime, sendCaCert, auditEvent);
        break;
    default:
        throw new RuntimeException("should not reach here");
    } // switch type

    InfoTypeAndValue tv = null;
    if (cmpControl.isConfirmCert() == false && CmpUtil.isImplictConfirm(reqHeader)) {
        pendingCertPool.removeCertificates(tid.getOctets());
        tv = CmpUtil.getImplictConfirmGeneralInfo();
    } else {
        Date now = new Date();
        respHeader.setMessageTime(new ASN1GeneralizedTime(now));
        tv = new InfoTypeAndValue(CMPObjectIdentifiers.it_confirmWaitTime,
                new ASN1GeneralizedTime(new Date(System.currentTimeMillis() + confirmWaitTime)));
    }

    respHeader.setGeneralInfo(tv);
    return respBody;
}