Example usage for org.bouncycastle.asn1 ASN1EncodableVector ASN1EncodableVector

List of usage examples for org.bouncycastle.asn1 ASN1EncodableVector ASN1EncodableVector

Introduction

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

Prototype

public ASN1EncodableVector() 

Source Link

Usage

From source file:org.ejbca.extra.ra.ScepRequestGenerator.java

License:Open Source License

/** Generates a SCEP CertReq. Keys must have been set in the generator for this to succeed 
 * /*from  w w w . ja  va  2  s.  c o m*/
 */
public byte[] generateCertReq(String dn, String password, X509Certificate ca)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException,
        IOException, CMSException, InvalidAlgorithmParameterException, CertStoreException,
        CertificateEncodingException, IllegalStateException {
    this.cacert = ca;
    this.reqdn = dn;

    // Create challenge password attribute for PKCS10
    // Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}
    //
    // Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {
    //    type    ATTRIBUTE.&id({IOSet}),
    //    values  SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{\@type})
    // }
    ASN1EncodableVector challpwdattr = new ASN1EncodableVector();
    // Challenge password attribute
    challpwdattr.add(PKCSObjectIdentifiers.pkcs_9_at_challengePassword);
    ASN1EncodableVector pwdvalues = new ASN1EncodableVector();
    pwdvalues.add(new DERUTF8String(password));
    challpwdattr.add(new DERSet(pwdvalues));
    // Requested extensions attribute
    ASN1EncodableVector extensionattr = new ASN1EncodableVector();
    extensionattr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    // AltNames
    GeneralNames san = CertTools.getGeneralNamesFromAltName("dNSName=foo.bar.com,iPAddress=10.0.0.1");
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    try {
        dOut.writeObject(san);
    } catch (IOException e) {
        throw new IllegalArgumentException("error encoding value: " + e);
    }
    Vector oidvec = new Vector();
    oidvec.add(X509Extensions.SubjectAlternativeName);
    Vector valuevec = new Vector();
    valuevec.add(new X509Extension(false, new DEROctetString(bOut.toByteArray())));
    X509Extensions exts = new X509Extensions(oidvec, valuevec);
    extensionattr.add(new DERSet(exts));
    // Complete the Attribute section of the request, the set (Attributes) contains two sequences (Attribute)
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new DERSequence(challpwdattr));
    v.add(new DERSequence(extensionattr));
    DERSet attributes = new DERSet(v);
    // Create PKCS#10 certificate request
    p10request = new PKCS10CertificationRequest("SHA1WithRSA", CertTools.stringToBcX509Name(reqdn),
            keys.getPublic(), attributes, keys.getPrivate());

    // Create self signed cert, validity 1 day
    cert = CertTools.genSelfCert(reqdn, 24 * 60 * 60 * 1000, null, keys.getPrivate(), keys.getPublic(),
            AlgorithmConstants.SIGALG_SHA1_WITH_RSA, false);

    // wrap message in pkcs#7
    byte[] msg = wrap(p10request.getEncoded(), "19");
    return msg;
}

From source file:org.ejbca.extra.ra.ScepRequestGenerator.java

License:Open Source License

public byte[] generateGetCertInitial(String dn, X509Certificate ca)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException,
        CertStoreException, IOException, CMSException {
    this.cacert = ca;
    this.reqdn = dn;

    ASN1EncodableVector vec = new ASN1EncodableVector();
    vec.add(new DERUTF8String(ca.getIssuerDN().getName()));
    vec.add(new DERUTF8String(dn));
    DERSequence seq = new DERSequence(vec);

    // wrap message in pkcs#7
    byte[] msg = wrap(seq.getEncoded(), "20");
    return msg;// w  ww  . jav  a2s.  c  o  m
}

From source file:org.ejbca.ui.cmpclient.CmpClientMessageHelper.java

License:Open Source License

/**
 * Converts the header and the body of a PKIMessage to an ASN1Encodable and 
 * returns the as a byte array/*from  ww  w . ja  va  2s  .c o  m*/
 *  
 * @param header
 * @param body
 * @return the PKIMessage's header and body in byte array
 */
private byte[] getProtectedBytes(PKIHeader header, PKIBody body) {
    byte[] res = null;
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(header);
    v.add(body);
    ASN1Encodable protectedPart = new DERSequence(v);
    try {
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(protectedPart);
        res = bao.toByteArray();
    } catch (Exception ex) {
        log.error(ex.getLocalizedMessage(), ex);
    }
    return res;
}

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

License:Open Source License

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

    final boolean verbose = parameters.containsKey(VERBOSE_KEY);

    final X500Name userDN = new X500Name("CN=foo");
    String issuer = parameters.get(ISSUERDN_KEY);
    if (issuer == null) {
        issuer = "CN=foobar";
        log.info("Using default issuerDN: " + issuer);
    }//from   w w w. j a v  a2  s.c o  m
    final X500Name issuerDN = new X500Name(issuer);

    if (verbose) {
        log.info("Creating confirmation request with: SubjectDN=" + userDN.toString());
        log.info("Creating confirmation request with: IssuerDN=" + issuerDN.toString());
    }

    byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce();
    byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce();
    byte[] hash = new byte[0];

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

    CertStatus cs = new CertStatus(hash, new BigInteger("0"));

    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(cs);
    CertConfirmContent cc = CertConfirmContent.getInstance(new DERSequence(v));

    PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_CERT_CONFIRM, cc); // Cert Confirm
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    return myPKIMessage;
}

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  w  w. j  av a  2  s  .c  o  m*/

    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  v a 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.ejbca.ui.cmpclient.commands.RevocationRequestCommand.java

License:Open Source License

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

    final X500Name userDN = new X500Name("CN=foo");
    final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY));
    BigInteger serno = new BigInteger(parameters.get(SERNO_KEY), 16);

    if (verbose) {
        log.info("Creating revocation request with: SubjectDN=" + userDN.toString());
        log.info("Creating revocation request with: IssuerDN=" + issuerDN.toString());
        log.info("Creating revocation request with: CertSerno=" + serno.toString(16));
    }//from   w  w w .j ava2s  .com

    byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce();
    byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce();

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setIssuer(issuerDN);
    myCertTemplate.setSubject(userDN);
    myCertTemplate.setSerialNumber(new ASN1Integer(serno));

    ExtensionsGenerator extgen = new ExtensionsGenerator();
    extgen.addExtension(Extension.reasonCode, false, getCRLReason(parameters.get(REVOCATION_REASON_KEY)));

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

    RevReqContent myRevReqContent = new RevReqContent(myRevDetails);

    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(PKIBody.TYPE_REVOCATION_REQ, myRevReqContent); // revocation request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    return myPKIMessage;
}

From source file:org.ejbca.util.cert.SubjectDirAttrExtension.java

License:Open Source License

/**
 * From subjectDirAttributes string as defined in getSubjectDirAttribute 
 * @param dirAttr string of SubjectDirectoryAttributes
 * @return A Collection of ASN.1 Attribute (org.bouncycastle.asn1.x509), or an empty Collection, never null
 * @see #getSubjectDirectoryAttributes(Certificate)
 *//*from   w  w  w  .j  a v  a  2s. co  m*/
public static Collection<Attribute> getSubjectDirectoryAttributes(String dirAttr) {
    ArrayList<Attribute> ret = new ArrayList<Attribute>();
    Attribute attr = null;
    String value = CertTools.getPartFromDN(dirAttr, "countryOfResidence");
    if (!StringUtils.isEmpty(value)) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(new DERPrintableString(value));
        attr = new Attribute(new DERObjectIdentifier(id_pda_countryOfResidence), new DERSet(vec));
        ret.add(attr);
    }
    value = CertTools.getPartFromDN(dirAttr, "countryOfCitizenship");
    if (!StringUtils.isEmpty(value)) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(new DERPrintableString(value));
        attr = new Attribute(new DERObjectIdentifier(id_pda_countryOfCitizenship), new DERSet(vec));
        ret.add(attr);
    }
    value = CertTools.getPartFromDN(dirAttr, "gender");
    if (!StringUtils.isEmpty(value)) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(new DERPrintableString(value));
        attr = new Attribute(new DERObjectIdentifier(id_pda_gender), new DERSet(vec));
        ret.add(attr);
    }
    value = CertTools.getPartFromDN(dirAttr, "placeOfBirth");
    if (!StringUtils.isEmpty(value)) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        X509DefaultEntryConverter conv = new X509DefaultEntryConverter();
        DERObject obj = conv.getConvertedValue(new DERObjectIdentifier(id_pda_placeOfBirth), value);
        vec.add(obj);
        attr = new Attribute(new DERObjectIdentifier(id_pda_placeOfBirth), new DERSet(vec));
        ret.add(attr);
    }
    // dateOfBirth that is a GeneralizedTime
    // The correct format for this is YYYYMMDD, it will be padded to YYYYMMDD120000Z
    value = CertTools.getPartFromDN(dirAttr, "dateOfBirth");
    if (!StringUtils.isEmpty(value)) {
        if (value.length() == 8) {
            value += "120000Z"; // standard format according to rfc3739
            ASN1EncodableVector vec = new ASN1EncodableVector();
            vec.add(new DERGeneralizedTime(value));
            attr = new Attribute(new DERObjectIdentifier(id_pda_dateOfBirth), new DERSet(vec));
            ret.add(attr);
        } else {
            log.error("Wrong length of data for 'dateOfBirth', should be of format YYYYMMDD, skipping...");
        }
    }
    return ret;
}

From source file:org.ejbca.util.CertTools.java

License:Open Source License

/**
 * From an altName string as defined in getSubjectAlternativeName 
 * @param altName//from  w ww.  ja va2  s .  c  om
 * @return ASN.1 GeneralNames
 * @see #getSubjectAlternativeName
 */
public static GeneralNames getGeneralNamesFromAltName(String altName) {
    if (log.isTraceEnabled()) {
        log.trace(">getGeneralNamesFromAltName: " + altName);
    }
    ASN1EncodableVector vec = new ASN1EncodableVector();

    ArrayList<String> emails = CertTools.getEmailFromDN(altName);
    if (!emails.isEmpty()) {
        Iterator<String> iter = emails.iterator();
        while (iter.hasNext()) {
            GeneralName gn = new GeneralName(1, new DERIA5String((String) iter.next()));
            vec.add(gn);
        }
    }

    ArrayList<String> dns = CertTools.getPartsFromDN(altName, CertTools.DNS);
    if (!dns.isEmpty()) {
        Iterator<String> iter = dns.iterator();
        while (iter.hasNext()) {
            GeneralName gn = new GeneralName(2, new DERIA5String((String) iter.next()));
            vec.add(gn);
        }
    }

    String directoryName = getDirectoryStringFromAltName(altName);
    if (directoryName != null) {
        X509Name x509DirectoryName = new X509Name(directoryName);
        GeneralName gn = new GeneralName(4, x509DirectoryName);
        vec.add(gn);
    }

    ArrayList<String> uri = CertTools.getPartsFromDN(altName, CertTools.URI);
    if (!uri.isEmpty()) {
        Iterator<String> iter = uri.iterator();
        while (iter.hasNext()) {
            GeneralName gn = new GeneralName(6, new DERIA5String((String) iter.next()));
            vec.add(gn);
        }
    }
    uri = CertTools.getPartsFromDN(altName, CertTools.URI1);
    if (!uri.isEmpty()) {
        Iterator<String> iter = uri.iterator();
        while (iter.hasNext()) {
            GeneralName gn = new GeneralName(6, new DERIA5String((String) iter.next()));
            vec.add(gn);
        }
    }
    uri = CertTools.getPartsFromDN(altName, CertTools.URI2);
    if (!uri.isEmpty()) {
        Iterator<String> iter = uri.iterator();
        while (iter.hasNext()) {
            GeneralName gn = new GeneralName(6, new DERIA5String((String) iter.next()));
            vec.add(gn);
        }
    }

    ArrayList<String> ipstr = CertTools.getPartsFromDN(altName, CertTools.IPADDR);
    if (!ipstr.isEmpty()) {
        Iterator<String> iter = ipstr.iterator();
        while (iter.hasNext()) {
            byte[] ipoctets = StringTools.ipStringToOctets((String) iter.next());
            GeneralName gn = new GeneralName(7, new DEROctetString(ipoctets));
            vec.add(gn);
        }
    }

    // UPN is an OtherName see method getUpn... for asn.1 definition
    ArrayList<String> upn = CertTools.getPartsFromDN(altName, CertTools.UPN);
    if (!upn.isEmpty()) {
        Iterator<String> iter = upn.iterator();
        while (iter.hasNext()) {
            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new DERObjectIdentifier(CertTools.UPN_OBJECTID));
            v.add(new DERTaggedObject(true, 0, new DERUTF8String((String) iter.next())));
            //GeneralName gn = new GeneralName(new DERSequence(v), 0);
            DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v));
            vec.add(gn);
        }
    }

    ArrayList<String> guid = CertTools.getPartsFromDN(altName, CertTools.GUID);
    if (!guid.isEmpty()) {
        Iterator<String> iter = guid.iterator();
        while (iter.hasNext()) {
            ASN1EncodableVector v = new ASN1EncodableVector();
            byte[] guidbytes = Hex.decode((String) iter.next());
            if (guidbytes != null) {
                v.add(new DERObjectIdentifier(CertTools.GUID_OBJECTID));
                v.add(new DERTaggedObject(true, 0, new DEROctetString(guidbytes)));
                DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v));
                vec.add(gn);
            } else {
                log.error("Cannot decode hexadecimal guid: " + guid);
            }
        }
    }

    // Krb5PrincipalName is an OtherName, see method getKrb5Principal...for ASN.1 definition
    ArrayList<String> krb5principalname = CertTools.getPartsFromDN(altName, CertTools.KRB5PRINCIPAL);
    if (!krb5principalname.isEmpty()) {
        Iterator<String> iter = krb5principalname.iterator();
        while (iter.hasNext()) {
            // Start by parsing the input string to separate it in different parts
            String principalString = (String) iter.next();
            if (log.isDebugEnabled()) {
                log.debug("principalString: " + principalString);
            }
            // The realm is the last part moving back until an @
            int index = principalString.lastIndexOf('@');
            String realm = "";
            if (index > 0) {
                realm = principalString.substring(index + 1);
            }
            if (log.isDebugEnabled()) {
                log.debug("realm: " + realm);
            }
            // Now we can have several principals separated by /
            ArrayList<String> principalarr = new ArrayList<String>();
            int jndex = 0;
            int bindex = 0;
            while (jndex < index) {
                // Loop and add all strings separated by /
                jndex = principalString.indexOf('/', bindex);
                if (jndex == -1) {
                    jndex = index;
                }
                String s = principalString.substring(bindex, jndex);
                if (log.isDebugEnabled()) {
                    log.debug("adding principal name: " + s);
                }
                principalarr.add(s);
                bindex = jndex + 1;
            }

            // Now we must construct the rather complex asn.1...
            ASN1EncodableVector v = new ASN1EncodableVector(); // this is the OtherName
            v.add(new DERObjectIdentifier(CertTools.KRB5PRINCIPAL_OBJECTID));

            // First the Krb5PrincipalName sequence
            ASN1EncodableVector krb5p = new ASN1EncodableVector();
            // The realm is the first tagged GeneralString
            krb5p.add(new DERTaggedObject(true, 0, new DERGeneralString(realm)));
            // Second is the sequence of principal names, which is at tagged position 1 in the krb5p 
            ASN1EncodableVector principals = new ASN1EncodableVector();
            // According to rfc4210 the type NT-UNKNOWN is 0, and according to some other rfc this type should be used...
            principals.add(new DERTaggedObject(true, 0, new DERInteger(0)));
            // The names themselves are yet another sequence
            Iterator<String> i = principalarr.iterator();
            ASN1EncodableVector names = new ASN1EncodableVector();
            while (i.hasNext()) {
                String principalName = (String) i.next();
                names.add(new DERGeneralString(principalName));
            }
            principals.add(new DERTaggedObject(true, 1, new DERSequence(names)));
            krb5p.add(new DERTaggedObject(true, 1, new DERSequence(principals)));

            v.add(new DERTaggedObject(true, 0, new DERSequence(krb5p)));
            DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v));
            vec.add(gn);
        }
    }

    // To support custom OIDs in altNames, they must be added as an OtherName of plain type UTF8String
    ArrayList<String> customoids = CertTools.getCustomOids(altName);
    if (!customoids.isEmpty()) {
        Iterator<String> iter = customoids.iterator();
        while (iter.hasNext()) {
            String oid = (String) iter.next();
            ArrayList<String> oidval = CertTools.getPartsFromDN(altName, oid);
            if (!oidval.isEmpty()) {
                Iterator<String> valiter = oidval.iterator();
                while (valiter.hasNext()) {
                    ASN1EncodableVector v = new ASN1EncodableVector();
                    v.add(new DERObjectIdentifier(oid));
                    v.add(new DERTaggedObject(true, 0, new DERUTF8String((String) valiter.next())));
                    DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v));
                    vec.add(gn);
                }
            }
        }
    }

    GeneralNames ret = null;
    if (vec.size() > 0) {
        ret = new GeneralNames(new DERSequence(vec));
    }
    return ret;
}

From source file:org.ejbca.util.NonEjbTestTools.java

License:Open Source License

public static byte[] generatePKCS10Req(String dn, String password)
        throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException,
        InvalidAlgorithmParameterException, IOException, OperatorCreationException {
    // Generate keys
    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);

    // Create challenge password attribute for PKCS10
    // Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}
    //// www . j  av a 2s .  c  o m
    // Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {
    //    type    ATTRIBUTE.&id({IOSet}),
    //    values  SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{\@type})
    // }
    ASN1EncodableVector vec = new ASN1EncodableVector();
    vec.add(PKCSObjectIdentifiers.pkcs_9_at_challengePassword);
    ASN1EncodableVector values = new ASN1EncodableVector();
    values.add(new DERUTF8String(password));
    vec.add(new DERSet(values));
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new DERSequence(vec));
    DERSet set = new DERSet(v);
    // Create PKCS#10 certificate request
    PKCS10CertificationRequest p10request = CertTools.genPKCS10CertificationRequest("SHA1WithRSA",
            CertTools.stringToBcX500Name(dn), keys.getPublic(), set, keys.getPrivate(), null);
    return p10request.toASN1Structure().getEncoded();
}