Example usage for org.bouncycastle.asn1 ASN1InputStream readObject

List of usage examples for org.bouncycastle.asn1 ASN1InputStream readObject

Introduction

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

Prototype

public ASN1Primitive readObject() throws IOException 

Source Link

Usage

From source file:org.ejbca.core.ejb.ca.crl.CreateCRLSessionTest.java

License:Open Source License

/**
 * Tests the extension Freshest CRL DP.//from w w w .  ja  v  a2  s  . c  o m
 * 
 * @throws Exception
 *             in case of error.
 */
public void test07CRLFreshestCRL() throws Exception {
    log.trace(">test07CRLFreshestCRL()");

    final String cdpURL = "http://www.ejbca.org/foo/bar.crl";
    final String freshestCdpURL = "http://www.ejbca.org/foo/delta.crl";
    X509CAInfo cainfo = (X509CAInfo) caAdminSession.getCAInfo(admin, caid);
    X509CRL x509crl;
    byte[] cFreshestDpDER;

    cainfo.setUseCrlDistributionPointOnCrl(true);
    cainfo.setDefaultCRLDistPoint(cdpURL);
    cainfo.setCADefinedFreshestCRL(freshestCdpURL);
    caAdminSession.editCA(admin, cainfo);
    ca = caSession.getCA(admin, caid);
    crlCreateSession.run(admin, ca);
    x509crl = CertTools.getCRLfromByteArray(crlSession.getLastCRL(admin, cainfo.getSubjectDN(), false));
    cFreshestDpDER = x509crl.getExtensionValue(X509Extensions.FreshestCRL.getId());
    assertNotNull("CRL has no Freshest Distribution Point", cFreshestDpDER);

    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(cFreshestDpDER));
    ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    CRLDistPoint cdp = new CRLDistPoint((ASN1Sequence) aIn.readObject());
    DistributionPoint[] distpoints = cdp.getDistributionPoints();

    assertEquals("More CRL Freshest distributions points than expected", 1, distpoints.length);
    assertEquals("Freshest CRL distribution point is different", freshestCdpURL,
            ((DERIA5String) ((GeneralNames) distpoints[0].getDistributionPoint().getName()).getNames()[0]
                    .getName()).getString());

    log.trace("<test07CRLFreshestCRL()");
}

From source file:org.ejbca.core.ejb.ca.sign.RSASignSessionBean.java

License:Open Source License

@Override
public IResponseMessage createCertificate(Admin admin, IRequestMessage req, Class responseClass,
        UserDataVO suppliedUserData) throws EjbcaException {
    if (log.isTraceEnabled()) {
        log.trace(">createCertificate(IRequestMessage)");
    }/*from w w w  .  j a  v a  2  s.c  o  m*/
    // Get CA that will receive request
    UserDataVO data = null;
    IResponseMessage ret = null;
    CA ca;
    if (suppliedUserData == null) {
        ca = getCAFromRequest(admin, req);
    } else {
        ca = caSession.getCA(admin, suppliedUserData.getCAId()); // Take the CAId from the supplied userdata, if any
    }
    try {
        CATokenContainer catoken = ca.getCAToken();

        // See if we need some key material to decrypt request
        if (req.requireKeyInfo()) {
            // You go figure...scep encrypts message with the public CA-cert
            req.setKeyInfo(ca.getCACertificate(), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN),
                    catoken.getJCEProvider());
        }
        // Verify the request
        if (req.verify() == false) {
            String msg = intres.getLocalizedMessage("signsession.popverificationfailed");
            logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(),
                    null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, msg);
            throw new SignRequestSignatureException(msg);
        }

        if (ca.isUseUserStorage() && req.getUsername() == null) {
            String msg = intres.getLocalizedMessage("signsession.nouserinrequest", req.getRequestDN());
            logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(),
                    null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, msg);
            throw new SignRequestException(msg);
            //ret.setFailInfo(FailInfo.BAD_REQUEST);
            //ret.setStatus(ResponseStatus.FAILURE);
        } else if (ca.isUseUserStorage() && req.getPassword() == null) {
            String msg = intres.getLocalizedMessage("signsession.nopasswordinrequest");
            logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(),
                    null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, msg);
            throw new SignRequestException(msg);
        } else {
            ResponseStatus status = ResponseStatus.SUCCESS;
            FailInfo failInfo = null;
            String failText = null;
            Certificate cert = null;
            try {
                // If we haven't done so yet, authenticate user. (Only if we store UserData for this CA.)
                if (ca.isUseUserStorage()) {
                    data = authUser(admin, req.getUsername(), req.getPassword());
                } else {
                    data = suppliedUserData;
                }
                PublicKey reqpk = req.getRequestPublicKey();
                if (reqpk == null) {
                    logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(),
                            req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE,
                            intres.getLocalizedMessage("signsession.nokeyinrequest"));
                    throw new InvalidKeyException("Key is null!");
                }
                // We need to make sure we use the users registered CA here
                if (data.getCAId() != ca.getCAId()) {
                    failText = intres.getLocalizedMessage("signsession.wrongauthority",
                            Integer.valueOf(ca.getCAId()), Integer.valueOf(data.getCAId()));
                    status = ResponseStatus.FAILURE;
                    failInfo = FailInfo.WRONG_AUTHORITY;
                    logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(),
                            req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, failText);
                }

                if (status.equals(ResponseStatus.SUCCESS)) {
                    Date notBefore = req.getRequestValidityNotBefore(); // Optionally requested validity
                    Date notAfter = req.getRequestValidityNotAfter(); // Optionally requested validity
                    X509Extensions exts = req.getRequestExtensions(); // Optionally requested extensions
                    int keyusage = -1;
                    if (exts != null) {
                        if (log.isDebugEnabled()) {
                            log.debug(
                                    "we have extensions, see if we can override KeyUsage by looking for a KeyUsage extension in request");
                        }
                        X509Extension ext = exts.getExtension(X509Extensions.KeyUsage);
                        if (ext != null) {
                            ASN1OctetString os = ext.getValue();
                            ByteArrayInputStream bIs = new ByteArrayInputStream(os.getOctets());
                            ASN1InputStream dIs = new ASN1InputStream(bIs);
                            DERObject dob = dIs.readObject();
                            DERBitString bs = DERBitString.getInstance(dob);
                            keyusage = bs.intValue();
                            if (log.isDebugEnabled()) {
                                log.debug("We have a key usage request extension: " + keyusage);
                            }
                        }
                    }
                    String sequence = null;
                    byte[] ki = req.getRequestKeyInfo();
                    if ((ki != null) && (ki.length > 0)) {
                        sequence = new String(ki);
                    }
                    cert = createCertificate(admin, data, req.getRequestX509Name(), ca, reqpk, keyusage,
                            notBefore, notAfter, exts, sequence);
                }
            } catch (ObjectNotFoundException oe) {
                // If we didn't find the entity return error message
                log.error("User not found: ", oe);
                failText = intres.getLocalizedMessage("signsession.nosuchuser", req.getUsername());
                status = ResponseStatus.FAILURE;
                failInfo = FailInfo.INCORRECT_DATA;
                logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(),
                        req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, failText);
            }

            //Create the response message with all nonces and checks etc
            ret = req.createResponseMessage(responseClass, req, ca.getCACertificate(),
                    catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), catoken.getProvider());

            if ((cert == null) && (status == ResponseStatus.SUCCESS)) {
                status = ResponseStatus.FAILURE;
                failInfo = FailInfo.BAD_REQUEST;
            } else {
                ret.setCertificate(cert);
            }
            ret.setStatus(status);
            if (failInfo != null) {
                ret.setFailInfo(failInfo);
                ret.setFailText(failText);
            }
        }
        ret.create();
        // Call authentication session and tell that we are finished with this user. (Only if we store UserData for this CA.)
        if (ca.isUseUserStorage() && data != null) {
            finishUser(ca, data);
        }
    } catch (NoUniqueCertSerialNumberIndexException e) {
        cleanUserCertDataSN(data);
        throw e.ejbcaException;
    } catch (IllegalKeyException ke) {
        log.error("Key is of unknown type: ", ke);
        throw ke;
    } catch (CATokenOfflineException ctoe) {
        String msg = intres.getLocalizedMessage("error.catokenoffline", ca.getSubjectDN());
        CATokenOfflineException ex = new CATokenOfflineException(msg);
        ex.initCause(ctoe);
        throw ex;
        //} catch (EjbcaException e) {
        //    throw e;
    } catch (NoSuchProviderException e) {
        log.error("NoSuchProvider provider: ", e);
    } catch (InvalidKeyException e) {
        log.error("Invalid key in request: ", e);
    } catch (NoSuchAlgorithmException e) {
        log.error("No such algorithm: ", e);
    } catch (IOException e) {
        log.error("Cannot create response message: ", e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<createCertificate(IRequestMessage)");
    }
    return ret;
}

From source file:org.ejbca.core.ejb.crl.PublishingCrlSessionTest.java

License:Open Source License

/**
 * Tests the extension CRL Distribution Point on CRLs
 *///from   w ww. jav a  2s.co  m
@Test
public void testCRLDistPointOnCRL() throws Exception {
    final String cdpURL = "http://www.ejbca.org/foo/bar.crl";
    X509CAInfo cainfo = (X509CAInfo) testx509ca.getCAInfo();
    X509CRL x509crl;
    byte[] cdpDER;

    cainfo.setUseCrlDistributionPointOnCrl(true);
    cainfo.setDefaultCRLDistPoint(cdpURL);
    caSession.editCA(roleMgmgToken, cainfo);
    publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId());
    x509crl = CertTools.getCRLfromByteArray(crlStoreSession.getLastCRL(cainfo.getSubjectDN(), false));
    cdpDER = x509crl.getExtensionValue(Extension.issuingDistributionPoint.getId());
    assertNotNull("CRL has no distribution points", cdpDER);

    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(cdpDER));
    ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    IssuingDistributionPoint cdp = IssuingDistributionPoint.getInstance((ASN1Sequence) aIn.readObject());
    DistributionPointName distpoint = cdp.getDistributionPoint();

    assertEquals("CRL distribution point is different", cdpURL,
            ((DERIA5String) ((GeneralNames) distpoint.getName()).getNames()[0].getName()).getString());

    cainfo.setUseCrlDistributionPointOnCrl(false);
    cainfo.setDefaultCRLDistPoint("");
    caSession.editCA(roleMgmgToken, cainfo);
    publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId());
    x509crl = CertTools.getCRLfromByteArray(crlStoreSession.getLastCRL(cainfo.getSubjectDN(), false));
    assertNull("CRL has distribution points",
            x509crl.getExtensionValue(Extension.cRLDistributionPoints.getId()));
}

From source file:org.ejbca.core.ejb.crl.PublishingCrlSessionTest.java

License:Open Source License

/**
 * Tests the extension Freshest CRL DP./*  www.  ja  va 2  s .  c  om*/
 */
@Test
public void testCRLFreshestCRL() throws Exception {
    final String cdpURL = "http://www.ejbca.org/foo/bar.crl";
    final String freshestCdpURL = "http://www.ejbca.org/foo/delta.crl";
    X509CAInfo cainfo = (X509CAInfo) testx509ca.getCAInfo();
    X509CRL x509crl;
    byte[] cFreshestDpDER;

    cainfo.setUseCrlDistributionPointOnCrl(true);
    cainfo.setDefaultCRLDistPoint(cdpURL);
    cainfo.setCADefinedFreshestCRL(freshestCdpURL);
    caSession.editCA(roleMgmgToken, cainfo);
    publishingCrlSessionRemote.forceCRL(roleMgmgToken, testx509ca.getCAId());
    x509crl = CertTools.getCRLfromByteArray(crlStoreSession.getLastCRL(cainfo.getSubjectDN(), false));
    cFreshestDpDER = x509crl.getExtensionValue(Extension.freshestCRL.getId());
    assertNotNull("CRL has no Freshest Distribution Point", cFreshestDpDER);

    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(cFreshestDpDER));
    ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    CRLDistPoint cdp = CRLDistPoint.getInstance((ASN1Sequence) aIn.readObject());
    DistributionPoint[] distpoints = cdp.getDistributionPoints();

    assertEquals("More CRL Freshest distributions points than expected", 1, distpoints.length);
    assertEquals("Freshest CRL distribution point is different", freshestCdpURL,
            ((DERIA5String) ((GeneralNames) distpoints[0].getDistributionPoint().getName()).getNames()[0]
                    .getName()).getString());
}

From source file:org.ejbca.core.ejb.ra.CertificateRequestSessionBean.java

License:Open Source License

@Override
public byte[] processCertReq(Admin admin, UserDataVO userdata, String req, int reqType, String hardTokenSN,
        int responseType) throws CADoesntExistsException, AuthorizationDeniedException, NotFoundException,
        InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException,
        SignatureException, IOException, ObjectNotFoundException, CertificateException,
        UserDoesntFullfillEndEntityProfile, ApprovalException, EjbcaException {
    byte[] retval = null;

    // Check tokentype
    if (userdata.getTokenType() != SecConst.TOKEN_SOFT_BROWSERGEN) {
        throw new WrongTokenTypeException(
                "Error: Wrong Token Type of user, must be 'USERGENERATED' for PKCS10/SPKAC/CRMF/CVC requests");
    }//  w w  w.j  a v a 2 s .c  o  m
    // This is the secret sauce, do the end entity handling automagically here before we get the cert
    addOrEditUser(admin, userdata, false, true);
    // Process request
    try {
        String password = userdata.getPassword();
        String username = userdata.getUsername();
        IRequestMessage imsg = null;
        if (reqType == SecConst.CERT_REQ_TYPE_PKCS10) {
            IRequestMessage pkcs10req = RequestMessageUtils.genPKCS10RequestMessage(req.getBytes());
            PublicKey pubKey = pkcs10req.getRequestPublicKey();
            imsg = new SimpleRequestMessage(pubKey, username, password);
        } else if (reqType == SecConst.CERT_REQ_TYPE_SPKAC) {
            // parts copied from request helper.
            byte[] reqBytes = req.getBytes();
            if (reqBytes != null) {
                log.debug("Received NS request: " + new String(reqBytes));
                byte[] buffer = Base64.decode(reqBytes);
                if (buffer == null) {
                    return null;
                }
                ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(buffer));
                ASN1Sequence spkacSeq = (ASN1Sequence) in.readObject();
                in.close();
                NetscapeCertRequest nscr = new NetscapeCertRequest(spkacSeq);
                // Verify POPO, we don't care about the challenge, it's not important.
                nscr.setChallenge("challenge");
                if (nscr.verify("challenge") == false) {
                    log.debug("POPO verification Failed");
                    throw new SignRequestSignatureException(
                            "Invalid signature in NetscapeCertRequest, popo-verification failed.");
                }
                log.debug("POPO verification successful");
                PublicKey pubKey = nscr.getPublicKey();
                imsg = new SimpleRequestMessage(pubKey, username, password);
            }
        } else if (reqType == SecConst.CERT_REQ_TYPE_CRMF) {
            byte[] request = Base64.decode(req.getBytes());
            ASN1InputStream in = new ASN1InputStream(request);
            ASN1Sequence crmfSeq = (ASN1Sequence) in.readObject();
            ASN1Sequence reqSeq = (ASN1Sequence) ((ASN1Sequence) crmfSeq.getObjectAt(0)).getObjectAt(0);
            CertRequest certReq = new CertRequest(reqSeq);
            SubjectPublicKeyInfo pKeyInfo = certReq.getCertTemplate().getPublicKey();
            KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC");
            KeySpec keySpec = new X509EncodedKeySpec(pKeyInfo.getEncoded());
            PublicKey pubKey = keyFact.generatePublic(keySpec); // just check it's ok
            imsg = new SimpleRequestMessage(pubKey, username, password);
            // a simple crmf is not a complete PKI message, as desired by the CrmfRequestMessage class
            //PKIMessage msg = PKIMessage.getInstance(new ASN1InputStream(new ByteArrayInputStream(request)).readObject());
            //CrmfRequestMessage reqmsg = new CrmfRequestMessage(msg, null, true, null);
            //imsg = reqmsg;
        } else if (reqType == SecConst.CERT_REQ_TYPE_PUBLICKEY) {
            byte[] request;
            // Request can be Base64 encoded or in PEM format
            try {
                request = FileTools.getBytesFromPEM(req.getBytes(), CertTools.BEGIN_PUBLIC_KEY,
                        CertTools.END_PUBLIC_KEY);
            } catch (IOException ex) {
                try {
                    request = Base64.decode(req.getBytes());
                    if (request == null) {
                        throw new IOException("Base64 decode of buffer returns null");
                    }
                } catch (ArrayIndexOutOfBoundsException ae) {
                    throw new IOException(
                            "Base64 decode fails, message not base64 encoded: " + ae.getMessage());
                }
            }
            final ASN1InputStream in = new ASN1InputStream(request);
            final SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(in.readObject());
            final AlgorithmIdentifier keyAlg = keyInfo.getAlgorithmId();
            final X509EncodedKeySpec xKeySpec = new X509EncodedKeySpec(new DERBitString(keyInfo).getBytes());
            final KeyFactory keyFact = KeyFactory.getInstance(keyAlg.getObjectId().getId(), "BC");
            final PublicKey pubKey = keyFact.generatePublic(xKeySpec);
            imsg = new SimpleRequestMessage(pubKey, username, password);
        }
        if (imsg != null) {
            retval = getCertResponseFromPublicKey(admin, imsg, hardTokenSN, responseType, userdata);
        }
    } catch (NotFoundException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (InvalidKeyException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (NoSuchAlgorithmException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (InvalidKeySpecException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (NoSuchProviderException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (SignatureException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (IOException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (CertificateException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (EjbcaException e) {
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    }
    return retval;
}

From source file:org.ejbca.core.model.ca.certextensions.BasicCertificateExtension.java

License:Open Source License

/**
 * Tries to read the hex-string as an DERObject. If it contains more than one DEREncodable object, return a DERSequence of the objects.
 *//*from   w ww.java 2  s  . co  m*/
private DEREncodable parseHexEncodedDERObject(String value) throws CertificateExtentionConfigurationException {
    DEREncodable retval = null;
    if (value.matches("^\\p{XDigit}*")) {
        byte[] bytes = Hex.decode(value);
        try {
            ASN1InputStream ais = new ASN1InputStream(bytes);
            DEREncodable firstObject = ais.readObject();
            if (ais.available() > 0) {
                ASN1EncodableVector ev = new ASN1EncodableVector();
                ev.add(firstObject);
                while (ais.available() > 0) {
                    ev.add(ais.readObject());
                }
                retval = new DERSequence(ev);
            } else {
                retval = firstObject;
            }
        } catch (Exception e) {
            throw new CertificateExtentionConfigurationException(intres.getLocalizedMessage(
                    "certext.basic.illegalvalue", value, Integer.valueOf(getId()), getOID()));
        }
    } else {
        throw new CertificateExtentionConfigurationException(intres
                .getLocalizedMessage("certext.basic.illegalvalue", value, Integer.valueOf(getId()), getOID()));
    }
    return retval;
}

From source file:org.ejbca.core.model.ca.certextensions.BasicCertificateExtensionTest.java

License:Open Source License

/**
 * Test with dynamic=true and no static value specified.
 *
 * There should be an exception if no value was specified in ExtendedInformation.
 * But it should succeed if an value was specified in ExtendedInformation.
 *//*w  w w .j  a  va 2  s.c  om*/
public void test13DynamicTrueNoStatic() throws Exception {
    Properties props = new Properties();
    props.put("id1.property.encoding", "DERPRINTABLESTRING");
    props.put("id1.property.dynamic", "true");
    BasicCertificateExtension baseExt = new BasicCertificateExtension();
    baseExt.init(1, "1.2.3", false, props);
    UserDataVO userData = new UserDataVO();
    userData.setExtendedinformation(new ExtendedInformation());

    // Fail without value specified
    try {
        baseExt.getValueEncoded(userData, null, null, null, null);
        fail("Should have failed as no value was specified in EI.");
    } catch (CertificateExtentionConfigurationException ex) {
        assertEquals(intres.getLocalizedMessage("certext.basic.incorrectvalue", 1, "1.2.3"), ex.getMessage());
    }

    // Success with value specified
    userData.getExtendedinformation().setExtensionData("1.2.3", "The value 123");
    ASN1InputStream in = new ASN1InputStream(
            new ByteArrayInputStream(baseExt.getValueEncoded(userData, null, null, null, null)));
    DEREncodable value1 = in.readObject();
    assertTrue(value1.getClass().toString(), value1 instanceof DERPrintableString);
    assertEquals("The value 123", ((DERPrintableString) value1).getString());
}

From source file:org.ejbca.core.model.ca.certextensions.BasicCertificateExtensionTest.java

License:Open Source License

/**
 * Test with dynamic=true and and a static value specified.
 *
 * The static value should be used if no value was specified in ExtendedInformation.
 * The value from ExtendedInformation should be used if present.
 *//*w ww.  j a  v  a2 s  .c om*/
public void test14DynamicTrueStatic() throws Exception {
    Properties props = new Properties();
    props.put("id1.property.encoding", "DERPRINTABLESTRING");
    props.put("id1.property.dynamic", "true");
    props.put("id1.property.value", "The static value 123");
    BasicCertificateExtension baseExt = new BasicCertificateExtension();
    baseExt.init(1, "1.2.3", false, props);
    UserDataVO userData = new UserDataVO();
    userData.setExtendedinformation(new ExtendedInformation());

    // Without value in userdata, the static value is used
    ASN1InputStream in = new ASN1InputStream(
            new ByteArrayInputStream(baseExt.getValueEncoded(userData, null, null, null, null)));
    DEREncodable value1 = in.readObject();
    assertTrue(value1.getClass().toString(), value1 instanceof DERPrintableString);
    assertEquals("The static value 123", ((DERPrintableString) value1).getString());

    // With value in userdata, that value is used
    userData.getExtendedinformation().setExtensionData("1.2.3", "A dynamic value 123");
    in = new ASN1InputStream(
            new ByteArrayInputStream(baseExt.getValueEncoded(userData, null, null, null, null)));
    value1 = in.readObject();
    assertTrue(value1.getClass().toString(), value1 instanceof DERPrintableString);
    assertEquals("A dynamic value 123", ((DERPrintableString) value1).getString());
}

From source file:org.ejbca.core.model.ca.certextensions.BasicCertificateExtensionTest.java

License:Open Source License

/**
 * Test with dynamic=true and and a static value specified where nvalues are used.
 *
 * The static values should be used if no value was specified in ExtendedInformation.
 * The values from ExtendedInformation should be used if present.
 *///w  w  w .j  ava2 s .  c o m
public void test15DynamicTrueStaticNvalues() throws Exception {
    Properties props = new Properties();
    props.put("id1.property.encoding", "DERPRINTABLESTRING");
    props.put("id1.property.dynamic", "true");
    props.put("id1.property.nvalues", "3");
    props.put("id1.property.value1", "The static value 1");
    props.put("id1.property.value2", "The static value 2");
    props.put("id1.property.value3", "The static value 3");
    BasicCertificateExtension baseExt = new BasicCertificateExtension();
    baseExt.init(1, "1.2.3", false, props);
    UserDataVO userData = new UserDataVO();
    userData.setExtendedinformation(new ExtendedInformation());

    // Without value in userdata, the static values is used
    ASN1InputStream in = new ASN1InputStream(
            new ByteArrayInputStream(baseExt.getValueEncoded(userData, null, null, null, null)));
    DEREncodable value = in.readObject();
    assertTrue(value.getClass().toString(), value instanceof DERSequence);
    DERSequence seq = (DERSequence) value;
    assertEquals(3, seq.size());
    Enumeration e = seq.getObjects();
    int i = 1;
    while (e.hasMoreElements()) {
        DEREncodable v = (DEREncodable) e.nextElement();
        assertTrue(v.getClass().toString(), v instanceof DERPrintableString);
        String str = ((DERPrintableString) v).getString();
        assertEquals(str, "The static value " + i++);
    }

    // With values in userdata, that values is used
    userData.getExtendedinformation().setExtensionData("1.2.3.value1", "A dynamic value 1");
    userData.getExtendedinformation().setExtensionData("1.2.3.value2", "A dynamic value 2");
    userData.getExtendedinformation().setExtensionData("1.2.3.value3", "A dynamic value 3");
    in = new ASN1InputStream(
            new ByteArrayInputStream(baseExt.getValueEncoded(userData, null, null, null, null)));
    value = in.readObject();
    assertTrue(value.getClass().toString(), value instanceof DERSequence);
    seq = (DERSequence) value;
    assertEquals(3, seq.size());
    e = seq.getObjects();
    i = 1;
    while (e.hasMoreElements()) {
        DEREncodable v = (DEREncodable) e.nextElement();
        assertTrue(v.getClass().toString(), v instanceof DERPrintableString);
        String str = ((DERPrintableString) v).getString();
        assertEquals(str, "A dynamic value " + i++);
    }
}

From source file:org.ejbca.core.model.ca.certextensions.BasicCertificateExtensionTest.java

License:Open Source License

/**
 * Test that without dynamic specified it defaults to dynamic=false.
 *
 * The static value should be used regardless of there was a value in 
 * ExtendedInformation or not.// w  w w.  j  a v a  2 s  . co  m
 */
public void test16DynamicDefaultsToFalse() throws Exception {
    Properties props = new Properties();
    props.put("id1.property.encoding", "DERPRINTABLESTRING");
    props.put("id1.property.value", "The static value");
    BasicCertificateExtension baseExt = new BasicCertificateExtension();
    baseExt.init(1, "1.2.3", false, props);
    UserDataVO userData = new UserDataVO();
    userData.setExtendedinformation(new ExtendedInformation());

    // Ok without value specified
    ASN1InputStream in = new ASN1InputStream(
            new ByteArrayInputStream(baseExt.getValueEncoded(userData, null, null, null, null)));
    DEREncodable value1 = in.readObject();
    assertTrue(value1.getClass().toString(), value1 instanceof DERPrintableString);
    assertEquals("The static value", ((DERPrintableString) value1).getString());

    // Ignoring dynamic value specified
    userData.getExtendedinformation().setExtensionData("1.2.3", "The value 123");
    in = new ASN1InputStream(
            new ByteArrayInputStream(baseExt.getValueEncoded(userData, null, null, null, null)));
    value1 = in.readObject();
    assertTrue(value1.getClass().toString(), value1 instanceof DERPrintableString);
    assertEquals("The static value", ((DERPrintableString) value1).getString());
}