Example usage for org.bouncycastle.asn1 DEROctetString getOctets

List of usage examples for org.bouncycastle.asn1 DEROctetString getOctets

Introduction

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

Prototype

public byte[] getOctets() 

Source Link

Document

Return the content of the OCTET STRING as a byte array.

Usage

From source file:org.candlepin.util.X509CRLStreamWriterTest.java

License:Open Source License

@Test
public void testAddEntryToEmptyCRL() throws Exception {
    Date oneHourAgo = new Date(new Date().getTime() - 60L * 60L * 1000L);
    Date oneHourHence = new Date(new Date().getTime() + 60L * 60L * 1000L);

    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, oneHourAgo);
    crlBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(keyPair.getPublic()));
    /* With a CRL number of 127, incrementing it should cause the number of bytes in the length
     * portion of the TLV to increase by one.*/
    crlBuilder.addExtension(X509Extension.cRLNumber, false, new CRLNumber(new BigInteger("127")));
    crlBuilder.setNextUpdate(oneHourHence);
    X509CRLHolder holder = crlBuilder.build(signer);

    File crlToChange = writeCRL(holder);

    File outfile = new File(folder.getRoot(), "new.crl");
    X509CRLStreamWriter stream = new X509CRLStreamWriter(crlToChange, (RSAPrivateKey) keyPair.getPrivate(),
            (RSAPublicKey) keyPair.getPublic());

    // Add enough items to cause the number of length bytes to change
    Set<BigInteger> newSerials = new HashSet<BigInteger>(Arrays.asList(new BigInteger("2358215310"),
            new BigInteger("7231352433"), new BigInteger("8233181205"), new BigInteger("1455615868"),
            new BigInteger("4323487764"), new BigInteger("6673256679")));

    for (BigInteger i : newSerials) {
        stream.add(i, new Date(), CRLReason.privilegeWithdrawn);
    }//from w w  w. j  a v  a2  s.c  o  m

    stream.preScan(crlToChange).lock();
    OutputStream o = new BufferedOutputStream(new FileOutputStream(outfile));
    stream.write(o);
    o.close();

    X509CRL changedCrl = readCRL();

    Set<BigInteger> discoveredSerials = new HashSet<BigInteger>();

    for (X509CRLEntry entry : changedCrl.getRevokedCertificates()) {
        discoveredSerials.add(entry.getSerialNumber());
    }

    X509CRL originalCrl = new JcaX509CRLConverter().setProvider(BC).getCRL(holder);

    assertNotNull(changedCrl.getNextUpdate());

    long changedCrlUpdateDelta = changedCrl.getNextUpdate().getTime() - changedCrl.getThisUpdate().getTime();

    // We're allowing a tolerance of a few milliseconds to deal with minor timing issues
    long deltaTolerance = 3;
    long deltaDiff = changedCrlUpdateDelta - (oneHourHence.getTime() - oneHourAgo.getTime());

    assertTrue(Math.abs(deltaDiff) <= deltaTolerance);
    assertThat(changedCrl.getThisUpdate(), greaterThan(originalCrl.getThisUpdate()));

    assertEquals(newSerials, discoveredSerials);
    assertEquals(originalCrl.getIssuerX500Principal(), changedCrl.getIssuerX500Principal());

    ASN1ObjectIdentifier crlNumberOID = X509Extension.cRLNumber;
    byte[] oldCrlNumberBytes = originalCrl.getExtensionValue(crlNumberOID.getId());
    byte[] newCrlNumberBytes = changedCrl.getExtensionValue(crlNumberOID.getId());

    DEROctetString oldOctet = (DEROctetString) DERTaggedObject.fromByteArray(oldCrlNumberBytes);
    DEROctetString newOctet = (DEROctetString) DERTaggedObject.fromByteArray(newCrlNumberBytes);
    DERInteger oldNumber = (DERInteger) DERTaggedObject.fromByteArray(oldOctet.getOctets());
    DERInteger newNumber = (DERInteger) DERTaggedObject.fromByteArray(newOctet.getOctets());
    assertEquals(oldNumber.getValue().add(BigInteger.ONE), newNumber.getValue());

    ASN1ObjectIdentifier authorityKeyOID = X509Extension.authorityKeyIdentifier;
    byte[] oldAuthorityKeyId = originalCrl.getExtensionValue(authorityKeyOID.getId());
    byte[] newAuthorityKeyId = changedCrl.getExtensionValue(authorityKeyOID.getId());
    assertArrayEquals(oldAuthorityKeyId, newAuthorityKeyId);
}

From source file:org.candlepin.util.X509CRLStreamWriterTest.java

License:Open Source License

@Test
public void testIncrementsExtensions() throws Exception {
    File crlToChange = writeCRL(createCRL());

    X509CRLStreamWriter stream = new X509CRLStreamWriter(crlToChange, (RSAPrivateKey) keyPair.getPrivate(),
            (RSAPublicKey) keyPair.getPublic());
    stream.preScan(crlToChange).lock();/*from  w w  w.  j a  v a  2s .co  m*/
    OutputStream o = new BufferedOutputStream(new FileOutputStream(outfile));
    stream.write(o);
    o.close();

    X509CRL changedCrl = readCRL();

    byte[] val = changedCrl.getExtensionValue(X509Extension.cRLNumber.getId());
    DEROctetString s = (DEROctetString) DERTaggedObject.fromByteArray(val);
    DERInteger i = (DERInteger) DERTaggedObject.fromByteArray(s.getOctets());

    assertTrue("CRL Number not incremented", i.getValue().compareTo(BigInteger.ONE) > 0);
}

From source file:org.ccnx.ccn.impl.security.crypto.MerkleTree.java

License:Open Source License

/**
 * Returns the digest at the specified node.
 * @param nodeIndex 1-based node index/*  www  .jav a2  s .  c  om*/
 * @return the digest for this node
 */
public byte[] get(int nodeIndex) {
    DEROctetString dv = derGet(nodeIndex);
    if (null == dv)
        return null;
    return dv.getOctets();
}

From source file:org.ccnx.ccn.impl.security.crypto.util.CryptoUtil.java

License:Open Source License

/**
 * Helper method to pull SubjectAlternativeNames from a certificate. BouncyCastle has
 * one of these, but it isn't included on all platforms. We get one by default from X509Certificate
 * but it returns us a collection of ? and we can't ever know what the ? is because we might
 * get a different impl class on different platforms. So we have to roll our own.
 * //from   ww  w.  j  av a 2s. c o  m
 * We filter the general names down to ones we can handle.
 * @param certificate
 * @return
 * @throws IOException 
 * @throws CertificateEncodingException 
 */
public static ArrayList<Tuple<Integer, String>> getSubjectAlternativeNames(X509Certificate certificate)
        throws IOException, CertificateEncodingException {

    byte[] encodedExtension = certificate.getExtensionValue(X509Extensions.SubjectAlternativeName.getId());

    ArrayList<Tuple<Integer, String>> list = new ArrayList<Tuple<Integer, String>>();

    if (null == encodedExtension) {
        return list;
    }

    // content of extension is wrapped in a DEROctetString
    DEROctetString content = (DEROctetString) CryptoUtil.decode(encodedExtension);
    byte[] encapsulatedOctetString = content.getOctets();

    ASN1InputStream aIn = new ASN1InputStream(encapsulatedOctetString);
    ASN1Encodable decodedObject = (ASN1Encodable) aIn.readObject();
    ASN1Sequence sequence = (ASN1Sequence) decodedObject.getDERObject();

    Integer tag;
    GeneralName generalName;

    Enumeration<?> it = sequence.getObjects();
    while (it.hasMoreElements()) {
        generalName = GeneralName.getInstance(it.nextElement());
        tag = generalName.getTagNo();

        switch (tag) {
        case GeneralName.dNSName:
        case GeneralName.rfc822Name:
        case GeneralName.uniformResourceIdentifier:
            list.add(new Tuple<Integer, String>(tag, ((DERString) generalName.getName()).getString()));
        default:
            // ignore other types
        }
    }
    return list;
}

From source file:org.ccnx.ccn.impl.security.crypto.util.MinimalCertificateGenerator.java

License:Open Source License

/**
 * Certificate issued under an existing CA.
 * @param subjectDN the distinguished name of the subject.
 * @param subjectPublicKey the public key of the subject.
 * @param issuerCertificate the certificate of the issuer.
 * @param duration the validity duration of the certificate.
 * @param isCA /*from   w  w  w . ja  va  2s . c o m*/
 * @param allUsage if isCA is true, add "regular" KeyUsage flags, for dual-use cert
 * @throws CertificateEncodingException
 * @throws IOException
 */
public MinimalCertificateGenerator(String subjectDN, PublicKey subjectPublicKey,
        X509Certificate issuerCertificate, long duration, boolean isCA, Integer chainLength, boolean allUsage)
        throws CertificateEncodingException, IOException {

    this(subjectDN, subjectPublicKey, issuerCertificate.getSubjectX500Principal(), duration, isCA, chainLength,
            allUsage);
    // Pull the existing subject identifier out of the issuer cert. 
    byte[] subjectKeyID = issuerCertificate.getExtensionValue(X509Extensions.SubjectKeyIdentifier.toString());
    if (null == subjectKeyID) {
        subjectKeyID = CryptoUtil.generateKeyID(subjectPublicKey);

    } else {
        // content of extension is wrapped in a DEROctetString
        DEROctetString content = (DEROctetString) CryptoUtil.decode(subjectKeyID);
        byte[] encapsulatedOctetString = content.getOctets();
        DEROctetString octetStringKeyID = (DEROctetString) CryptoUtil.decode(encapsulatedOctetString);
        subjectKeyID = octetStringKeyID.getOctets();
    }
    _aki = new AuthorityKeyIdentifier(subjectKeyID);
}

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);// w w  w  .  ja  v  a2 s.  co  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.util.CertTools.java

License:Open Source License

/**
 * Get the authority key identifier from a certificate extensions
 * /*from w  ww. ja  v  a2 s  .c o  m*/
 * @param cert certificate containing the extension
 * @return byte[] containing the authority key identifier, or null if it does not exist
 */
public static byte[] getAuthorityKeyId(Certificate cert) {
    if (cert == null) {
        return null;
    }
    if (cert instanceof X509Certificate) {
        X509Certificate x509cert = (X509Certificate) cert;

        byte[] extvalue = x509cert.getExtensionValue("2.5.29.35");
        if (extvalue == null) {
            return null;
        }
        try {
            ASN1InputStream octAsn1InputStream = new ASN1InputStream(new ByteArrayInputStream(extvalue));
            try {
                DEROctetString oct = (DEROctetString) (octAsn1InputStream.readObject());
                ASN1InputStream keyAsn1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(oct.getOctets()));
                try {
                    AuthorityKeyIdentifier keyId = AuthorityKeyIdentifier
                            .getInstance((ASN1Sequence) keyAsn1InputStream.readObject());
                    return keyId.getKeyIdentifier();
                } finally {
                    keyAsn1InputStream.close();
                }
            } finally {
                octAsn1InputStream.close();
            }
        } catch (IOException e) {
            throw new IllegalStateException("Could not parse authority key identifier from certificate.", e);
        }
    }
    return null;
}

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

License:Open Source License

/**
 * Get a certificate policy ID from a certificate policies extension
 * /*from   w w  w  . java2s.c om*/
 * @param cert certificate containing the extension
 * @param pos position of the policy id, if several exist, the first is as pos 0
 * @return String with the certificate policy OID, or null if an id at the given position does not exist
 * @throws IOException if extension can not be parsed
 */
public static String getCertificatePolicyId(Certificate cert, int pos) throws IOException {
    String ret = null;
    if (cert instanceof X509Certificate) {
        X509Certificate x509cert = (X509Certificate) cert;
        byte[] extvalue = x509cert.getExtensionValue(Extension.certificatePolicies.getId());
        if (extvalue == null) {
            return null;
        }
        ASN1InputStream extAsn1InputStream = new ASN1InputStream(new ByteArrayInputStream(extvalue));
        try {
            DEROctetString oct = (DEROctetString) (extAsn1InputStream.readObject());
            ASN1InputStream octAsn1InputStream = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets()));
            try {
                ASN1Sequence seq = (ASN1Sequence) octAsn1InputStream.readObject();
                // Check the size so we don't ArrayIndexOutOfBounds
                if (seq.size() < pos + 1) {
                    return null;
                }
                PolicyInformation pol = PolicyInformation.getInstance((ASN1Sequence) seq.getObjectAt(pos));
                ret = pol.getPolicyIdentifier().getId();
            } finally {
                octAsn1InputStream.close();
            }
        } finally {
            extAsn1InputStream.close();
        }
    }
    return ret;
}

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

License:Open Source License

/** Reads PrivateKeyUsagePeriod extension from a certificate
 * // ww  w .j a v a2 s  . com
 */
public static PrivateKeyUsagePeriod getPrivateKeyUsagePeriod(final X509Certificate cert) {
    PrivateKeyUsagePeriod res = null;
    final byte[] extvalue = cert.getExtensionValue(Extension.privateKeyUsagePeriod.getId());
    if ((extvalue != null) && (extvalue.length > 0)) {
        if (log.isTraceEnabled()) {
            log.trace("Found a PrivateKeyUsagePeriod in the certificate with subject: "
                    + cert.getSubjectDN().toString());
        }
        ASN1InputStream extAsn1InputStream = new ASN1InputStream(new ByteArrayInputStream(extvalue));
        try {
            try {
                final DEROctetString oct = (DEROctetString) (extAsn1InputStream.readObject());
                ASN1InputStream octAsn1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(oct.getOctets()));
                try {
                    res = PrivateKeyUsagePeriod.getInstance((ASN1Sequence) octAsn1InputStream.readObject());
                } finally {
                    octAsn1InputStream.close();
                }
            } finally {
                extAsn1InputStream.close();
            }
        } catch (IOException e) {
            throw new IllegalStateException("Unknown IOException caught when trying to parse certificate.", e);
        }
    }
    return res;
}

From source file:org.dataone.proto.trove.jsse.X509CertificateToolset.java

License:Apache License

/**
 * Retrieves the extension value given by the OID
 *
 * @see http://stackoverflow.com/questions/2409618/how-do-i-decode-a-der-encoded-string-in-java
 * @param X509Certificate// w w w  .j ava 2  s.  com
 * @param oid
 * @return
 * @throws IOException
 */
protected String getExtensionValue(X509Certificate X509Certificate, String oid) throws IOException {
    String decoded = null;
    byte[] extensionValue = X509Certificate.getExtensionValue(oid);
    if (extensionValue != null) {
        ASN1Primitive derObject = toASN1Primitive(extensionValue);
        if (derObject instanceof DEROctetString) {
            DEROctetString derOctetString = (DEROctetString) derObject;
            derObject = toASN1Primitive(derOctetString.getOctets());
            if (derObject instanceof DERUTF8String) {
                DERUTF8String s = DERUTF8String.getInstance(derObject);
                decoded = s.getString();
            }
        }
    }
    return decoded;
}