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.util.cert.CrlExtensions.java

License:Open Source License

/**
 * Return an Extension ASN1Primitive from a CRL
 *//*  www . ja v a2  s  .co  m*/
protected static ASN1Primitive getExtensionValue(X509CRL crl, String oid) throws IOException {
    if (crl == null) {
        return null;
    }
    byte[] bytes = crl.getExtensionValue(oid);
    if (bytes == null) {
        return null;
    }
    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(bytes));
    ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    return aIn.readObject();
}

From source file:org.cesecore.certificates.util.cert.CrlExtensions.java

License:Open Source License

/** @return the first object found when treating the provided byte array as an ASN1InputStream */
@SuppressWarnings("unchecked")
private static <T> T getAsn1ObjectFromBytes(final byte[] bytes, final Class<T> clazz) {
    T ret = null;/*from  w w  w.  j  a  v a 2  s  .  co m*/
    ASN1InputStream asn1InputStream = null;
    try {
        if (bytes != null) {
            asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(bytes));
            ret = (T) asn1InputStream.readObject();
        }
    } catch (ClassCastException e) {
        // Ignore
        log.info("Failed to extract expected ASN1 object from bytes array.", e);
    } catch (IOException e) {
        // Ignore
        log.info("Failed to extract ASN1 object from bytes array.", e);
    } finally {
        if (asn1InputStream != null) {
            try {
                asn1InputStream.close();
            } catch (IOException e) {
                log.info("Failed to extract expected ASN1 object from bytes array.", e);
            }
        }
    }
    return ret;
}

From source file:org.cesecore.keys.util.KeyTools.java

License:Open Source License

/**
 * create the subject key identifier.//from   w  ww .  j  a  v  a  2 s  .c om
 * 
 * @param pubKey
 *            the public key
 * 
 * @return SubjectKeyIdentifer asn.1 structure
 */
public static SubjectKeyIdentifier createSubjectKeyId(final PublicKey pubKey) {
    try {
        final ASN1Sequence keyASN1Sequence;
        ASN1InputStream pubKeyAsn1InputStream = new ASN1InputStream(
                new ByteArrayInputStream(pubKey.getEncoded()));
        try {
            final Object keyObject = pubKeyAsn1InputStream.readObject();
            if (keyObject instanceof ASN1Sequence) {
                keyASN1Sequence = (ASN1Sequence) keyObject;
            } else {
                // PublicKey key that don't encode to a ASN1Sequence. Fix this by creating a BC object instead.
                final PublicKey altKey = (PublicKey) KeyFactory.getInstance(pubKey.getAlgorithm(), "BC")
                        .translateKey(pubKey);
                ASN1InputStream altKeyAsn1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(altKey.getEncoded()));
                try {
                    keyASN1Sequence = (ASN1Sequence) altKeyAsn1InputStream.readObject();
                } finally {
                    altKeyAsn1InputStream.close();
                }
            }
            X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils();
            return x509ExtensionUtils.createSubjectKeyIdentifier(new SubjectPublicKeyInfo(keyASN1Sequence));
        } finally {
            pubKeyAsn1InputStream.close();
        }
    } catch (Exception e) {
        final RuntimeException e2 = new RuntimeException("error creating key"); // NOPMD
        e2.initCause(e);
        throw e2;
    }
}

From source file:org.cesecore.keys.util.KeyTools.java

License:Open Source License

/** 
 * Get the ASN.1 encoded PublicKey as a Java PublicKey Object.
 * @param the ASN.1 encoded PublicKey/*from w  ww  . ja v  a2s. c om*/
 * @return the ASN.1 encoded PublicKey as a Java Object
 */
public static PublicKey getPublicKeyFromBytes(byte[] asn1EncodedPublicKey) {
    PublicKey pubKey = null;
    final ASN1InputStream in = new ASN1InputStream(asn1EncodedPublicKey);
    try {
        final SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(in.readObject());
        final AlgorithmIdentifier keyAlg = keyInfo.getAlgorithm();
        final X509EncodedKeySpec xKeySpec = new X509EncodedKeySpec(new DERBitString(keyInfo).getBytes());
        final KeyFactory keyFact = KeyFactory.getInstance(keyAlg.getAlgorithm().getId(), "BC");
        pubKey = keyFact.generatePublic(xKeySpec);
    } catch (IOException e) {
        log.debug("Unable to decode PublicKey.", e);
    } catch (NoSuchAlgorithmException e) {
        log.debug("Unable to decode PublicKey.", e);
    } catch (NoSuchProviderException e) {
        log.debug("Unable to decode PublicKey.", e);
    } catch (InvalidKeySpecException e) {
        log.debug("Unable to decode PublicKey.", e);
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            log.debug("Unable to close input stream.");
        }
    }
    return pubKey;
}

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

License:Open Source License

public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId,
        PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage,
        Date privateKeyNotBefore, Date privateKeyNotAfter, String provider, boolean ldapOrder,
        List<Extension> additionalExtensions)
        throws CertificateParsingException, IOException, OperatorCreationException {
    // Create self signed certificate
    Date firstDate = new Date();

    // Set back startdate ten minutes to avoid some problems with wrongly set clocks.
    firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000));

    Date lastDate = new Date();

    // validity in days = validity*24*60*60*1000 milliseconds
    lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000)));

    // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be
    // a CVC public key that is passed as parameter
    PublicKey publicKey = null;//from  w  w  w  .  j  a  va2s.c  o m
    if (pubKey instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pubKey;
        RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent());
        try {
            publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec);
        } catch (InvalidKeySpecException e) {
            log.error("Error creating RSAPublicKey from spec: ", e);
            publicKey = pubKey;
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("RSA was not a known algorithm", e);
        }
    } else if (pubKey instanceof ECPublicKey) {
        ECPublicKey ecpk = (ECPublicKey) pubKey;
        try {
            ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA"
            final String algo = ecpk.getAlgorithm();
            if (algo.equals(AlgorithmConstants.KEYALGORITHM_ECGOST3410)) {
                try {
                    publicKey = KeyFactory.getInstance("ECGOST3410").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("ECGOST3410 was not a known algorithm", e);
                }
            } else if (algo.equals(AlgorithmConstants.KEYALGORITHM_DSTU4145)) {
                try {
                    publicKey = KeyFactory.getInstance("DSTU4145").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("DSTU4145 was not a known algorithm", e);
                }
            } else {
                try {
                    publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("EC was not a known algorithm", e);
                }
            }
        } catch (InvalidKeySpecException e) {
            log.error("Error creating ECPublicKey from spec: ", e);
            publicKey = pubKey;
        } catch (NullPointerException e) {
            log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage());
            publicKey = pubKey;
        }
    } else {
        log.debug("Not converting key of class. " + pubKey.getClass().getName());
        publicKey = pubKey;
    }

    // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this
    // bean is created.
    byte[] serno = new byte[8];
    SecureRandom random;
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("SHA1PRNG was not a known algorithm", e);
    }
    random.setSeed(new Date().getTime());
    random.nextBytes(serno);

    SubjectPublicKeyInfo pkinfo;
    try {
        pkinfo = new SubjectPublicKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded()));
    } catch (IOException e) {
        throw new IllegalArgumentException("Provided public key could not be read to ASN1Primitive", e);
    }
    X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(
            CertTools.stringToBcX500Name(dn, ldapOrder), new BigInteger(serno).abs(), firstDate, lastDate,
            CertTools.stringToBcX500Name(dn, ldapOrder), pkinfo);

    // Basic constranits is always critical and MUST be present at-least in CA-certificates.
    BasicConstraints bc = new BasicConstraints(isCA);
    certbuilder.addExtension(Extension.basicConstraints, true, bc);

    // Put critical KeyUsage in CA-certificates
    if (isCA || keyusage != 0) {
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certbuilder.addExtension(Extension.keyUsage, true, ku);
    }

    if ((privateKeyNotBefore != null) || (privateKeyNotAfter != null)) {
        final ASN1EncodableVector v = new ASN1EncodableVector();
        if (privateKeyNotBefore != null) {
            v.add(new DERTaggedObject(false, 0, new DERGeneralizedTime(privateKeyNotBefore)));
        }
        if (privateKeyNotAfter != null) {
            v.add(new DERTaggedObject(false, 1, new DERGeneralizedTime(privateKeyNotAfter)));
        }
        certbuilder.addExtension(Extension.privateKeyUsagePeriod, false, new DERSequence(v));
    }

    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox.
    try {
        if (isCA) {

            ASN1InputStream sAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            ASN1InputStream aAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            try {
                SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) sAsn1InputStream.readObject());
                X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils();
                SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki);
                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) aAsn1InputStream.readObject());
                AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);

                certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski);
                certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki);
            } finally {
                sAsn1InputStream.close();
                aAsn1InputStream.close();
            }
        }
    } catch (IOException e) { // do nothing
    }

    // CertificatePolicies extension if supplied policy ID, always non-critical
    if (policyId != null) {
        PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId));
        DERSequence seq = new DERSequence(pi);
        certbuilder.addExtension(Extension.certificatePolicies, false, seq);
    }
    // Add any additional
    if (additionalExtensions != null) {
        for (final Extension extension : additionalExtensions) {
            certbuilder.addExtension(extension.getExtnId(), extension.isCritical(), extension.getParsedValue());
        }
    }
    final ContentSigner signer = new BufferingContentSigner(
            new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(privKey), 20480);
    final X509CertificateHolder certHolder = certbuilder.build(signer);
    final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded());

    return selfcert;
}

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

License:Open Source License

/**
 * Get the authority key identifier from a certificate extensions
 * /* w  w  w .  ja  v  a2  s.c om*/
 * @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 the subject key identifier from a certificate extensions
 * /*from  w  ww  .  j  a  v a2s.co m*/
 * @param cert certificate containing the extension
 * @return byte[] containing the subject key identifier, or null if it does not exist
 */
public static byte[] getSubjectKeyId(Certificate cert) {
    if (cert == null) {
        return null;
    }
    if (cert instanceof X509Certificate) {
        X509Certificate x509cert = (X509Certificate) cert;
        byte[] extvalue = x509cert.getExtensionValue("2.5.29.14");
        if (extvalue == null) {
            return null;
        }
        ASN1InputStream extvalueAsn1InputStream = new ASN1InputStream(new ByteArrayInputStream(extvalue));
        try {
            try {
                ASN1OctetString str = ASN1OctetString.getInstance(extvalueAsn1InputStream.readObject());
                ASN1InputStream strAsn1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(str.getOctets()));
                try {
                    SubjectKeyIdentifier keyId = SubjectKeyIdentifier
                            .getInstance(strAsn1InputStream.readObject());
                    return keyId.getKeyIdentifier();
                } finally {
                    strAsn1InputStream.close();
                }
            } finally {
                extvalueAsn1InputStream.close();
            }
        } catch (IOException e) {
            throw new IllegalStateException("Could not parse subject key ID 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
 * // w w w.  ja  v  a  2s .  c o  m
 * @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

private static ASN1Sequence getAltnameSequence(byte[] value) {
    ASN1Primitive oct = null;// ww  w  . ja  v  a 2s . c  om
    try {
        oct = (new ASN1InputStream(new ByteArrayInputStream(value)).readObject());
    } catch (IOException e) {
        throw new RuntimeException("Could not read ASN1InputStream", e);
    }
    if (oct instanceof ASN1TaggedObject) {
        oct = ((ASN1TaggedObject) oct).getObject();
    }
    ASN1Sequence seq = ASN1Sequence.getInstance(oct);
    return seq;
}

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

License:Open Source License

/** Reads PrivateKeyUsagePeriod extension from a certificate
 * //from ww  w . j  a  va  2  s .c  om
 */
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;
}