Example usage for org.bouncycastle.asn1.crmf CertReqMsg CertReqMsg

List of usage examples for org.bouncycastle.asn1.crmf CertReqMsg CertReqMsg

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.crmf CertReqMsg CertReqMsg.

Prototype

public CertReqMsg(CertRequest certReq, ProofOfPossession pop, AttributeTypeAndValue[] regInfo) 

Source Link

Document

Creates a new CertReqMsg.

Usage

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

License:Open Source License

/**
 * Parses a CRMF request created with novosec library classes and return a bouncycastle CertReqMsg object
 * //from   w w w . j a  v  a 2s  .  c  om
 * @param messages
 * @return
 */
public static CertReqMsg getNovosecCertReqMsg(CertReqMessages messages) {
    // The encoding of the ProofOfPosession in bouncycastle and novosec is different.
    // Novosec generator explicitly tags the PopoSigningKey while it should be implicitly tagged.
    // Through novosec, the ProofOfPosession comes through as:
    //         Sequence
    //             DERSequence
    //                 DERSequence
    //                     ObjectIdentifier(1.2.840.113549.1.1.5)
    //                 DERBitString[64,0]
    //
    // But it should be:
    //         DERSequence
    //             DERSequence
    //                 ObjectIdentifier(1.2.840.113549.1.1.5)
    //             DERBitString[64,0]
    //
    // The bouncycastle parser expects an implicit tag, so to it, it looks like the sequence is containing a single element.
    //--------------------------------------
    // A comment from bouncycastle that might not effect anything here but maybe effect something else in the future: 
    //         What's happened is the novosec generator has explicitly tagged the PopoSigningKey structure, it should be 
    //         implicitly tagged (this isn't true if it's a POPOPrivKey, but that's because it's a CHOICE item so the tag 
    //         has to be preserved, but that is a different story).

    // Reconstructing the CertRequest
    ASN1Encodable o2 = ((DERSequence) messages.toASN1Primitive()).getObjectAt(0);
    ASN1Encodable o3 = ((DERSequence) o2).getObjectAt(0);
    CertRequest cr = CertRequest.getInstance(o3);

    // Reconstructing the proof-of-posession
    ASN1TaggedObject o4 = (ASN1TaggedObject) ((DERSequence) o2).getObjectAt(1);
    ProofOfPossession pp;
    int tagnr = o4.getTagNo();
    ASN1Encodable o5;
    switch (tagnr) {
    case 0:
        o5 = DERNull.INSTANCE;
        pp = new ProofOfPossession();
        break;
    case 1:
        o5 = POPOSigningKey.getInstance(o4.getObject());
        pp = new ProofOfPossession((POPOSigningKey) o5);
        break;
    case 2:
    case 3:
        o5 = POPOPrivKey.getInstance(o4, false);
        pp = new ProofOfPossession(tagnr, (POPOPrivKey) o5);
        break;
    default:
        throw new IllegalArgumentException("unknown tag: " + tagnr);
    }

    // Reconstructing the regToken
    ASN1Sequence o6 = (ASN1Sequence) ((ASN1Sequence) o2.toASN1Primitive()).getObjectAt(2);
    final AttributeTypeAndValue av = AttributeTypeAndValue.getInstance(((ASN1Sequence) o6).getObjectAt(0));
    final AttributeTypeAndValue[] avs = { av };

    // finally, recreating the CertReqMsg object
    return new CertReqMsg(cr, pp, avs);
}

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

License:Open Source License

@Test
public void testLegacyEncodedRequestOverride() throws Exception {
    reconfigureCA(false, false, false);/* w ww.j  a  v a 2s . c  om*/
    // 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.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  ww w  . ja v  a 2 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 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);
    }//w  w  w . j  a  va 2  s  .  c o  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.core.protocol.cmp.CrmfRequestMessageTest.java

License:Open Source License

private PKIMessage createPKIMessage(final String issuerDN, final String subjectDN)
        throws InvalidAlgorithmParameterException, IOException {
    KeyPair keys = KeyTools.genKeys("1024", "RSA");
    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));

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setValidity(myOptionalValidity);
    myCertTemplate.setIssuer(new X500Name(issuerDN));
    myCertTemplate.setSubject(new X500Name(subjectDN));
    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    try {/*from  w w w. j  a  v a 2 s  .  c om*/
        SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
        myCertTemplate.setPublicKey(keyInfo);
    } finally {
        dIn.close();
    }
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    ExtensionsGenerator extgen = new ExtensionsGenerator();
    int bcku = X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment | X509KeyUsage.nonRepudiation;
    X509KeyUsage ku = new X509KeyUsage(bcku);
    bOut = new ByteArrayOutputStream();
    dOut = new DEROutputStream(bOut);
    dOut.writeObject(ku);
    byte[] value = bOut.toByteArray();
    extgen.addExtension(Extension.keyUsage, false, new DEROctetString(value));
    myCertTemplate.setExtensions(extgen.generate());

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

    ProofOfPossession myProofOfPossession = new ProofOfPossession();
    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(new X500Name("CN=bogusSubject")),
            new GeneralName(new X500Name("CN=bogusIssuer")));
    myPKIHeader.setMessageTime(new DERGeneralizedTime(new Date()));
    myPKIHeader.setSenderNonce(new DEROctetString(CmpMessageHelper.createSenderNonce()));
    myPKIHeader.setTransactionID(new DEROctetString(CmpMessageHelper.createSenderNonce()));

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

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

License:Open Source License

@Test
public void test06NotNestedMessage()
        throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException,
        EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception {

    ASN1EncodableVector optionaValidityV = 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());
    optionaValidityV.add(new DERTaggedObject(true, 0, nb));
    optionaValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionaValidityV));

    KeyPair keys = KeyTools.genKeys("1024", "RSA");
    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setValidity(myOptionalValidity);
    myCertTemplate.setIssuer(new X500Name(this.issuerDN));
    myCertTemplate.setSubject(SUBJECT_DN);
    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    try {/*from w  w w  .ja v  a  2 s  . c o m*/
        SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
        myCertTemplate.setPublicKey(keyInfo);
        // If we did not pass any extensions as parameter, we will create some of our own, standard ones
    } finally {
        dIn.close();
    }
    final Extensions exts;
    {
        // SubjectAltName
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        ExtensionsGenerator extgen = new ExtensionsGenerator();
        // KeyUsage
        int bcku = 0;
        bcku = X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment | X509KeyUsage.nonRepudiation;
        X509KeyUsage ku = new X509KeyUsage(bcku);
        bOut = new ByteArrayOutputStream();
        dOut = new DEROutputStream(bOut);
        dOut.writeObject(ku);
        byte[] value = bOut.toByteArray();
        extgen.addExtension(Extension.keyUsage, false, new DEROctetString(value));

        // Make the complete extension package
        exts = extgen.generate();
    }
    myCertTemplate.setExtensions(exts);
    CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null);
    ProofOfPossession myProofOfPossession = new ProofOfPossession();
    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(SUBJECT_DN),
            new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName())));
    final byte[] nonce = CmpMessageHelper.createSenderNonce();
    final byte[] transid = CmpMessageHelper.createSenderNonce();
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    PKIBody myPKIBody = new PKIBody(20, myCertReqMessages); // nestedMessageContent
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    KeyPair raKeys = KeyTools.genKeys("1024", "RSA");
    createRACertificate("raSignerTest06", "foo123", this.raCertsPath, cmpAlias, raKeys, null, null,
            CMPTESTPROFILE, this.caid);
    myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, null, raKeys.getPrivate(), null,
            "BC");

    assertNotNull("Failed to create PKIHeader", myPKIHeader);
    assertNotNull("Failed to create PKIBody", myPKIBody);
    assertNotNull("Failed to create PKIMessage", myPKIMessage);

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(myPKIMessage);
    final byte[] ba = bao.toByteArray();
    // Send request and receive response
    final byte[] resp = sendCmpHttp(ba, 200, cmpAlias);

    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    PKIBody body = respObject.getBody();
    assertEquals(23, body.getType());
    ErrorMsgContent err = (ErrorMsgContent) body.getContent();
    String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    assertEquals("unknown object in getInstance: org.bouncycastle.asn1.DERSequence", errMsg);
}

From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java

License:Open Source License

private CertReqMsg createCrmfRequest(final String issuerDN, final String userDN, final KeyPair keys,
        final String extensionOid) throws IOException {
    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setIssuer(new X500Name(issuerDN));
    myCertTemplate.setSubject(new X500Name(userDN));
    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    try {//from w w w.j a v  a 2s.co  m
        SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
        myCertTemplate.setPublicKey(keyInfo);
    } finally {
        dIn.close();
    }
    // If we did not pass any extensions as parameter, we will create some of our own, standard ones
    ExtensionsGenerator extgen = new ExtensionsGenerator();
    extgen.addExtension(new ASN1ObjectIdentifier(extensionOid), false, new DEROctetString("foo123".getBytes()));
    myCertTemplate.setExtensions(extgen.generate());
    CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null);
    CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, null, null);
    return myCertReqMsg;
}

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

License:Open Source License

@Override
public PKIMessage generatePKIMessage(final ParameterContainer parameters) throws Exception {

    final boolean verbose = parameters.containsKey(VERBOSE_KEY);

    final X500Name userDN = new X500Name(parameters.get(SUBJECTDN_KEY));
    final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY));

    String authmodule = parameters.get(AUTHENTICATION_MODULE_KEY);
    String endentityPassword = "";
    if (authmodule != null && StringUtils.equals(authmodule, CmpConfiguration.AUTHMODULE_REG_TOKEN_PWD)) {
        endentityPassword = parameters.containsKey(AUTHENTICATION_PARAM_KEY)
                ? parameters.get(AUTHENTICATION_PARAM_KEY)
                : "foo123";
    }// w  ww  . j  a  va 2 s.c om

    String altNames = parameters.get(ALTNAME_KEY);
    String serno = parameters.get(SERNO_KEY);
    BigInteger customCertSerno = null;
    if (serno != null) {
        customCertSerno = new BigInteger(serno, 16);
    }
    boolean includePopo = parameters.containsKey(INCLUDE_POPO_KEY);

    if (verbose) {
        log.info("Creating CRMF request with: SubjectDN=" + userDN.toString());
        log.info("Creating CRMF request with: IssuerDN=" + issuerDN.toString());
        log.info("Creating CRMF request with: AuthenticationModule=" + authmodule);
        log.info("Creating CRMF request with: EndEntityPassword=" + endentityPassword);
        log.info("Creating CRMF request with: SubjectAltName=" + altNames);
        log.info("Creating CRMF request with: CustomCertSerno="
                + (customCertSerno == null ? "" : customCertSerno.toString(16)));
        log.info("Creating CRMF request with: IncludePopo=" + includePopo);
    }

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

    // We should be able to back date the start time when allow validity
    // override is enabled in the certificate profile
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DAY_OF_WEEK, -1);
    cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds
    // in validity
    Date notBefore = cal.getTime();
    cal.add(Calendar.DAY_OF_WEEK, 3);
    cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(notBefore);
    // in validity
    Date notAfter = cal.getTime();
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(notAfter);

    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    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(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);

    // Create standard extensions
    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
    Extensions 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 (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, "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);
    } else {
        // raVerified POPO (meaning there is no POPO)
        myProofOfPossession = new ProofOfPossession();
    }

    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String(endentityPassword));
    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);
    myPKIHeader.setSenderKID(new byte[0]);

    PKIBody myPKIBody = new PKIBody(0, myCertReqMessages); // initialization
    // 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);
    }//from   w  w  w.j a  va  2s  . c  o 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  ww w  .jav a  2  s .  c  om*/

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