Example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

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

Introduction

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

Prototype

public ASN1InputStream(byte[] input) 

Source Link

Document

Create an ASN1InputStream based on the input byte array.

Usage

From source file:org.cesecore.certificates.certificate.certextensions.BasicCertificateExtensionTest.java

License:Open Source License

/**
 * Test with dynamic=true and value specified with key 1.2.3.value=.
 *//*from  w  w  w . ja  v  a  2 s .  c o m*/
@Test
public void test18DynamicValueValue() 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);
    EndEntityInformation userData = new EndEntityInformation();
    userData.setExtendedinformation(new ExtendedInformation());

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

From source file:org.cesecore.certificates.certificate.certextensions.BasicCertificateExtensionTest.java

License:Open Source License

@Test
public void test20CertExtensionEncoding() throws Exception {
    Properties props = new Properties();
    props.put("id1.property.encoding", "DERIA5STRING");
    props.put("id1.property.value", "This is a printable string");

    BasicCertificateExtension baseExt = new BasicCertificateExtension();
    baseExt.init(1, "1.2.3", false, props);

    byte[] value = baseExt.getValueEncoded(null, null, null, null, null, null);

    ExtensionsGenerator extgen = new ExtensionsGenerator();
    extgen.addExtension(new ASN1ObjectIdentifier(baseExt.getOID()), baseExt.isCriticalFlag(), value);
    Extensions exts = extgen.generate();
    ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(baseExt.getOID());
    Extension ext = exts.getExtension(oid);
    assertNotNull(ext);/*from ww w  . j  av a 2 s.  c  om*/
    // Read the extension value, it's a DERIA5String wrapped in an ASN1OctetString
    ASN1OctetString str = ext.getExtnValue();
    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(str.getOctets()));
    DERIA5String ia5str = (DERIA5String) aIn.readObject();
    aIn.close();
    assertEquals("This is a printable string", ia5str.getString());
}

From source file:org.cesecore.certificates.certificate.certextensions.QcStatementTest.java

License:Open Source License

@Test
public void testQcStatement() throws CertificateExtensionException, IOException {
    CertificateProfile prof = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    prof.setUseQCStatement(true);//from   w  w w.  ja v  a 2s.c  o m
    prof.setUseQCEtsiQCCompliance(true);
    prof.setUseQCEtsiSignatureDevice(true);
    prof.setQCEtsiType("0.4.0.1862.1.6.1");
    prof.setQCEtsiPds(Arrays.asList(new PKIDisclosureStatement("http://qcs.localhost/QcPDS", "en")));
    QcStatement statement = new QcStatement();
    byte[] value = statement.getValueEncoded(null, null, prof, null, null, null);
    @SuppressWarnings("resource")
    final String dump = ASN1Dump.dumpAsString(new ASN1InputStream(value).readObject(), true);
    log.info(dump);
    // Hex dump can be used in Custom Certificate Extensions
    log.info(new String(Hex.encode(value)));
    // Dump included IDs
    final ASN1Sequence seq = (ASN1Sequence) ASN1Sequence.fromByteArray(value);
    // This is just a loop to get all the statement IDs in the QcStatements extension, so we can view them and count them
    ArrayList<String> oids = new ArrayList<>();
    for (int i = 0; i < seq.size(); i++) {
        final QCStatement qc = QCStatement.getInstance(seq.getObjectAt(i));
        final ASN1ObjectIdentifier oid = qc.getStatementId();
        if (oid != null) {
            oids.add(oid.getId());
        } else {
            fail("QC statements have empty statement");
        }
    }
    log.info(oids);
    // Check that all OIDs we set exist
    assertEquals("Not all QC statement Ids were included", 4, oids.size());
    assertTrue(oids.contains(ETSIQCObjectIdentifiers.id_etsi_qcs_QcCompliance.getId()));
    assertTrue(oids.contains(ETSIQCObjectIdentifiers.id_etsi_qcs_QcSSCD.getId()));
    assertTrue(oids.contains("0.4.0.1862.1.6")); // ETSIQCObjectIdentifiers.id_etsi_qcs_QcType
    assertTrue(oids.contains("0.4.0.1862.1.5")); // ETSIQCObjectIdentifiers.id_etsi_qcs_QcPds
    // Check the values we set
    assertEquals("0.4.0.1862.1.6.1", QCStatementExtension.getStatementStringValue(seq, "0.4.0.1862.1.6", 0));
    assertEquals("[http://qcs.localhost/QcPDS, en]",
            QCStatementExtension.getStatementStringValue(seq, "0.4.0.1862.1.5", 0));

}

From source file:org.cesecore.certificates.certificate.certextensions.standard.AuthorityKeyIdentifier.java

License:Open Source License

@Override
public ASN1Encodable getValue(final EndEntityInformation subject, final CA ca,
        final CertificateProfile certProfile, final PublicKey userPublicKey, final PublicKey caPublicKey,
        CertificateValidity val) throws CertificateExtensionException {
    org.bouncycastle.asn1.x509.AuthorityKeyIdentifier ret = null;
    // Default value is that we calculate it from scratch!
    // (If this is a root CA we must calculate the AuthorityKeyIdentifier from scratch)
    // (If the CA signing this cert does not have a SubjectKeyIdentifier we must calculate the AuthorityKeyIdentifier from scratch)
    final byte[] keybytes = caPublicKey.getEncoded();
    ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(keybytes));
    try {//ww w. j  a  v  a2s.c o  m
        try {
            final SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) inputStream.readObject());
            ret = new org.bouncycastle.asn1.x509.AuthorityKeyIdentifier(apki);

            // If we have a CA-certificate (i.e. this is not a Root CA), we must take the authority key identifier from
            // the CA-certificates SubjectKeyIdentifier if it exists. If we don't do that we will get the wrong identifier if the
            // CA does not follow RFC3280 (guess if MS-CA follows RFC3280?)
            final X509Certificate cacert = (X509Certificate) ca.getCACertificate();
            final boolean isRootCA = (certProfile.getType() == CertificateConstants.CERTTYPE_ROOTCA);
            if ((cacert != null) && (!isRootCA)) {
                byte[] akibytes;
                akibytes = CertTools.getSubjectKeyId(cacert);
                if (akibytes != null) {
                    // TODO: The code below is snipped from AuthorityKeyIdentifier.java in BC 1.36, because there is no method there
                    // to set only a pre-computed key identifier
                    // This should be replaced when such a method is added to BC
                    final ASN1OctetString keyidentifier = new DEROctetString(akibytes);
                    final ASN1EncodableVector v = new ASN1EncodableVector();
                    v.add(new DERTaggedObject(false, 0, keyidentifier));
                    final ASN1Sequence seq = new DERSequence(v);
                    ret = org.bouncycastle.asn1.x509.AuthorityKeyIdentifier.getInstance(seq);
                    if (log.isDebugEnabled()) {
                        log.debug("Using AuthorityKeyIdentifier from CA-certificates SubjectKeyIdentifier.");
                    }
                }
            }
        } finally {
            inputStream.close();
        }
    } catch (IOException e) {
        throw new CertificateExtensionException("IOException parsing CA public key: " + e.getMessage(), e);
    }

    return ret;
}

From source file:org.cesecore.certificates.certificate.certextensions.standard.SubjectKeyIdentifier.java

License:Open Source License

@Override
public ASN1Encodable getValue(final EndEntityInformation subject, final CA ca,
        final CertificateProfile certProfile, final PublicKey userPublicKey, final PublicKey caPublicKey,
        CertificateValidity val) throws CertificateExtensionException {
    SubjectPublicKeyInfo spki;//from w  w  w.  j  a  v a  2  s.c o m
    try {
        spki = new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(userPublicKey.getEncoded()))
                        .readObject());
    } catch (IOException e) {
        throw new CertificateExtensionException("IOException parsing user public key: " + e.getMessage(), e);
    }

    X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils();
    return x509ExtensionUtils.createSubjectKeyIdentifier(spki);
}

From source file:org.cesecore.certificates.certificate.request.RequestMessageUtils.java

License:Open Source License

public static RequestMessage getSimpleRequestMessageFromType(final String username, final String password,
        final String req, final int reqType) throws SignRequestSignatureException, InvalidKeyException,
        NoSuchAlgorithmException, NoSuchProviderException, IOException, SignatureException,
        InvalidKeySpecException, ParseException, ConstructionException, NoSuchFieldException {
    RequestMessage ret = null;//w w  w  .j av a  2s. c  o m
    if (reqType == CertificateConstants.CERT_REQ_TYPE_PKCS10) {
        final RequestMessage pkcs10req = RequestMessageUtils.genPKCS10RequestMessage(req.getBytes());
        final PublicKey pubKey = pkcs10req.getRequestPublicKey();
        SimpleRequestMessage simplereq = new SimpleRequestMessage(pubKey, username, password);
        final Extensions ext = pkcs10req.getRequestExtensions();
        simplereq.setRequestExtensions(ext);
        ret = simplereq;
    } else if (reqType == CertificateConstants.CERT_REQ_TYPE_SPKAC) {
        byte[] reqBytes = req.getBytes();
        if (reqBytes != null) {
            if (log.isDebugEnabled()) {
                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) {
                if (log.isDebugEnabled()) {
                    log.debug("SPKAC POPO verification Failed");
                }
                throw new SignRequestSignatureException(
                        "Invalid signature in NetscapeCertRequest, popo-verification failed.");
            }
            if (log.isDebugEnabled()) {
                log.debug("POPO verification successful");
            }
            PublicKey pubKey = nscr.getPublicKey();
            ret = new SimpleRequestMessage(pubKey, username, password);
        }
    } else if (reqType == CertificateConstants.CERT_REQ_TYPE_CRMF) {
        byte[] request = Base64.decode(req.getBytes());
        ASN1InputStream in = new ASN1InputStream(request);
        try {
            ASN1Sequence crmfSeq = (ASN1Sequence) in.readObject();
            ASN1Sequence reqSeq = (ASN1Sequence) ((ASN1Sequence) crmfSeq.getObjectAt(0)).getObjectAt(0);
            CertRequest certReq = CertRequest.getInstance(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
            SimpleRequestMessage simplereq = new SimpleRequestMessage(pubKey, username, password);
            Extensions ext = certReq.getCertTemplate().getExtensions();
            simplereq.setRequestExtensions(ext);
            ret = simplereq;
        } finally {
            in.close();
        }
        // 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 == CertificateConstants.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 (DecoderException de) {
                throw new IOException("Base64 decode fails, message not base64 encoded: " + de.getMessage());
            }
        }
        final PublicKey pubKey = KeyTools.getPublicKeyFromBytes(request);
        ret = new SimpleRequestMessage(pubKey, username, password);
    } else if (reqType == CertificateConstants.CERT_REQ_TYPE_CVC) {
        CVCObject parsedObject = CertificateParser.parseCVCObject(Base64.decode(req.getBytes()));
        // We will handle both the case if the request is an authenticated request, i.e. with an outer signature
        // and when the request is missing the (optional) outer signature.
        CVCertificate cvccert = null;
        if (parsedObject instanceof CVCAuthenticatedRequest) {
            CVCAuthenticatedRequest cvcreq = (CVCAuthenticatedRequest) parsedObject;
            cvccert = cvcreq.getRequest();
        } else {
            cvccert = (CVCertificate) parsedObject;
        }
        CVCRequestMessage reqmsg = new CVCRequestMessage(cvccert.getDEREncoded());
        reqmsg.setUsername(username);
        reqmsg.setPassword(password);
        // Popo is really actually verified by the CA (in SignSessionBean) as well
        if (reqmsg.verify() == false) {
            if (log.isDebugEnabled()) {
                log.debug("CVC POPO verification Failed");
            }
            throw new SignRequestSignatureException(
                    "Invalid inner signature in CVCRequest, popo-verification failed.");
        } else {
            if (log.isDebugEnabled()) {
                log.debug("POPO verification successful");
            }
        }
        ret = reqmsg;
    }
    return ret;
}

From source file:org.cesecore.certificates.crl.CrlCreateSessionCRLTest.java

License:Open Source License

/**
 * Tests the extension CRL Distribution Point on CRLs
 *//*from   w w w  .ja  va  2  s  .  c o  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);
    crlCreateSession.forceCRL(roleMgmgToken, testx509ca.getCAId());
    x509crl = CertTools.getCRLfromByteArray(crlStoreSession.getLastCRL(cainfo.getSubjectDN(), false));
    cdpDER = x509crl.getExtensionValue(X509Extensions.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 = new IssuingDistributionPoint((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);
    crlCreateSession.forceCRL(roleMgmgToken, testx509ca.getCAId());
    x509crl = CertTools.getCRLfromByteArray(crlStoreSession.getLastCRL(cainfo.getSubjectDN(), false));
    assertNull("CRL has distribution points",
            x509crl.getExtensionValue(X509Extensions.CRLDistributionPoints.getId()));
}

From source file:org.cesecore.certificates.crl.CrlCreateSessionCRLTest.java

License:Open Source License

/**
 * Tests the extension Freshest CRL DP./* ww  w. j av a2s . c  o m*/
 */
@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);
    crlCreateSession.forceCRL(roleMgmgToken, testx509ca.getCAId());
    x509crl = CertTools.getCRLfromByteArray(crlStoreSession.getLastCRL(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());
}

From source file:org.cesecore.certificates.crl.CrlCreateSessionTest.java

License:Open Source License

private void checkCrlAkid(X509CA subca, final byte[] crl) throws Exception {
    assertNotNull(crl);/*from www  .j  a va  2s . c  o  m*/

    // First, check that it is signed by the correct public key
    final X509CRL xcrl = CertTools.getCRLfromByteArray(crl);
    final PublicKey pubK = subca.getCACertificate().getPublicKey();
    xcrl.verify(pubK);

    // Check that the correct AKID is used
    final byte[] akidExtBytes = xcrl.getExtensionValue(Extension.authorityKeyIdentifier.getId());
    ASN1InputStream octAis = new ASN1InputStream(new ByteArrayInputStream(akidExtBytes));
    DEROctetString oct = (DEROctetString) (octAis.readObject());
    ASN1InputStream keyidAis = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets()));
    AuthorityKeyIdentifier akid = AuthorityKeyIdentifier.getInstance((ASN1Sequence) keyidAis.readObject());
    keyidAis.close();
    octAis.close();
    assertArrayEquals("Incorrect Authority Key Id in CRL.", TEST_AKID, akid.getKeyIdentifier());
}

From source file:org.cesecore.certificates.ocsp.CanLogCache.java

License:Open Source License

private BasicOCSPRespGenerator createOcspResponseGenerator(OCSPReq req, X509Certificate respondercert,
        int respIdType) throws OCSPException, NotSupportedException {
    if (null == req) {
        throw new IllegalArgumentException();
    }/*  w w  w . java 2  s.c o  m*/
    BasicOCSPRespGenerator res = null;
    if (respIdType == OcspConfiguration.RESPONDERIDTYPE_NAME) {
        res = new BasicOCSPRespGenerator(new RespID(respondercert.getSubjectX500Principal()));
    } else {
        res = new BasicOCSPRespGenerator(respondercert.getPublicKey());
    }
    X509Extensions reqexts = req.getRequestExtensions();
    if (reqexts != null) {
        X509Extension ext = reqexts.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_response);
        if (null != ext) {
            // log.debug("Found extension AcceptableResponses");
            ASN1OctetString oct = ext.getValue();
            try {
                ASN1Sequence seq = ASN1Sequence.getInstance(
                        new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())).readObject());
                @SuppressWarnings("unchecked")
                Enumeration<DERObjectIdentifier> en = seq.getObjects();
                boolean supportsResponseType = false;
                while (en.hasMoreElements()) {
                    DERObjectIdentifier oid = en.nextElement();
                    // log.debug("Found oid: "+oid.getId());
                    if (oid.equals(OCSPObjectIdentifiers.id_pkix_ocsp_basic)) {
                        // This is the response type we support, so we are happy! Break the loop.
                        supportsResponseType = true;
                        log.debug("Response type supported: " + oid.getId());
                        continue;
                    }
                }
                if (!supportsResponseType) {
                    throw new NotSupportedException(
                            "Required response type not supported, this responder only supports id-pkix-ocsp-basic.");
                }
            } catch (IOException e) {
            }
        }
    }
    return res;
}