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.dcache.srm.client.GsiConnectionSocketFactory.java

License:Open Source License

private void delegate(Socket socket, HttpClientTransport.Delegation delegation, X509Credential credential)
        throws IOException {
    if (delegation != null) {
        switch (delegation) {
        case SKIP:
            break;
        case NONE:
            socket.getOutputStream().write('0');
            socket.getOutputStream().flush();
            break;
        case LIMITED:
        case FULL:
            socket.getOutputStream().write('D');
            socket.getOutputStream().flush();
            try {
                // read csr
                ASN1InputStream dIn = new ASN1InputStream(socket.getInputStream());
                PKCS10CertificationRequest csr = new PKCS10CertificationRequest(
                        CertificationRequest.getInstance(dIn.readObject()));

                // generate proxy
                ProxyRequestOptions options = new ProxyRequestOptions(credential.getCertificateChain(), csr);
                options.setLimited(delegation == HttpClientTransport.Delegation.LIMITED);
                X509Certificate[] chain = ProxyGenerator.generate(options, credential.getKey());

                // send to server
                socket.getOutputStream().write(chain[0].getEncoded());
                socket.getOutputStream().flush();
            } catch (SignatureException | NoSuchProviderException | CertificateEncodingException
                    | InvalidKeyException | NoSuchAlgorithmException | CertificateParsingException e) {
                throw new IOException("Failed to signed CSR during delegation: " + e.getMessage(), e);
            }/*  w  w  w  .j a va 2 s.co  m*/
            break;
        }
    }
}

From source file:org.dcache.xrootd.plugins.authn.gsi.DHSession.java

License:Open Source License

/**
 * Creates an DHParameterSpec object from the DER-encoded byte sequence
 * @param der the DER-encoded byte sequence
 * @return the DHParameterSpec object/*from  w  ww .j  a  va2 s  .c o m*/
 * @throws IOException if the deserialisation goes wrong
 */
private static DHParameterSpec fromDER(byte[] der) throws IOException {
    ByteArrayInputStream inStream = new ByteArrayInputStream(der);
    ASN1InputStream derInputStream = new ASN1InputStream(inStream);
    DHParameter dhparam = DHParameter.getInstance(derInputStream.readObject());
    return new DHParameterSpec(dhparam.getP(), dhparam.getG());
}

From source file:org.demoiselle.signer.core.extension.BasicCertificate.java

License:Open Source License

/**
 * Gets the contents of a given OID/*  w w  w . ja v a 2s .co m*/
 *
 * @param oid Object Identifier (OID) 
 *
 * @return org.bouncycastle.asn1.ASN1Primitive Content related to the reported OID
 */
public ASN1Primitive getExtensionValue(String oid) {
    try {
        byte[] extensionValue = certificate.getExtensionValue(oid);
        if (extensionValue == null) {
            return null;
        }
        varASN1InputStream = new ASN1InputStream(extensionValue);
        DEROctetString oct = (DEROctetString) varASN1InputStream.readObject();
        varASN1InputStream = new ASN1InputStream(oct.getOctets());
        return varASN1InputStream.readObject();
    } catch (Exception e) {
        logger.info(e.getMessage());
        return null;
    }
}

From source file:org.demoiselle.signer.core.oid.OIDGeneric.java

License:Open Source License

/**
 * Instance for OIDGeneric./*ww w.ja  va  2 s.c  o m*/
 *
 * @param data
 *            Set of bytes with the contents of the certificate.
 * @return Object GenericOID
 * @throws IOException exception of input/output
 * @throws Exception general exception
 */
public static OIDGeneric getInstance(byte[] data) throws IOException, Exception {
    is = new ASN1InputStream(data);
    DLSequence sequence = (DLSequence) is.readObject();
    ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) sequence.getObjectAt(0);
    DERTaggedObject taggedObject = (DERTaggedObject) sequence.getObjectAt(1);
    DERTaggedObject taggedObject2 = (DERTaggedObject) taggedObject.getObject();

    DEROctetString octet = null;
    DERPrintableString print = null;
    DERUTF8String utf8 = null;
    DERIA5String ia5 = null;

    try {
        octet = (DEROctetString) taggedObject2.getObject();
    } catch (Exception e) {
        try {
            print = (DERPrintableString) taggedObject2.getObject();
        } catch (Exception e1) {
            try {
                utf8 = (DERUTF8String) taggedObject2.getObject();
            } catch (Exception e2) {
                ia5 = (DERIA5String) taggedObject2.getObject();
            }
        }
    }

    String className = getPackageName() + oid.getId().replaceAll("[.]", "_");
    OIDGeneric oidGenerico;
    try {
        oidGenerico = (OIDGeneric) Class.forName(className).newInstance();
    } catch (InstantiationException e) {
        throw new Exception(coreMessagesBundle.getString("error.class.instance", className), e);
    } catch (IllegalAccessException e) {
        throw new Exception(coreMessagesBundle.getString("error.class.illegal.access", className), e);
    } catch (ClassNotFoundException e) {
        oidGenerico = new OIDGeneric();
    }

    oidGenerico.oid = oid.getId();

    if (octet != null) {
        oidGenerico.data = new String(octet.getOctets());
    } else {
        if (print != null) {
            oidGenerico.data = print.getString();
        } else {
            if (utf8 != null) {
                oidGenerico.data = utf8.getString();
            } else {
                oidGenerico.data = ia5.getString();
            }
        }
    }

    oidGenerico.initialize();

    return oidGenerico;
}

From source file:org.demoiselle.signer.policy.engine.factory.PolicyFactory.java

License:Open Source License

private ASN1Primitive readANS1FromStream(InputStream is) {
    ASN1InputStream asn1is = new ASN1InputStream(is);
    ASN1Primitive primitive = null;/*from w  w w . j  av a2  s .c o m*/
    try {
        primitive = asn1is.readObject();
    } catch (IOException error) {
        LOGGER.getLevel();
        LOGGER.log(Level.ERROR, "Error reading stream.", error);
        throw new RuntimeException(error);
    } finally {
        try {
            asn1is.close();
        } catch (IOException error) {
            throw new RuntimeException(error);
        }
    }
    return primitive;
}

From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESTimeStampSigner.java

License:Open Source License

private Timestamp checkTimeStamp(byte[] timeStamp, byte[] content, byte[] hash) {
    try {// ww  w .j  a  va  2 s .  c om
        Security.addProvider(new BouncyCastleProvider());
        ais = new ASN1InputStream(new ByteArrayInputStream(timeStamp));
        ASN1Sequence seq = (ASN1Sequence) ais.readObject();
        Attribute attributeTimeStamp = new Attribute((ASN1ObjectIdentifier) seq.getObjectAt(0),
                (ASN1Set) seq.getObjectAt(1));
        byte[] varTimeStamp = attributeTimeStamp.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded();
        TimeStampOperator timeStampOperator = new TimeStampOperator();
        if (content != null) {
            timeStampOperator.validate(content, varTimeStamp, null);
        } else {
            timeStampOperator.validate(null, varTimeStamp, hash);
        }
        TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp));
        Timestamp timeStampSigner = new Timestamp(timeStampToken);
        return timeStampSigner;
    } catch (CertificateCoreException | IOException | TSPException | CMSException e) {
        throw new SignerException(e);
    }

}

From source file:org.dihedron.crypto.certificates.Certificates.java

License:Open Source License

/**
 * @param certificate   /*from   ww  w.j a  v  a 2s . c  o  m*/
 *   the certificate in which to look to the extension value.
 * @param oid 
 *   the Object Identifier of the extension.
 * @return   
 *   the extension value as an {@code ASN1Primitive} object.
 * @throws IOException
 */
public static ASN1Primitive getExtensionValue(X509Certificate certificate, String oid) throws IOException {
    byte[] bytes = certificate.getExtensionValue(oid);
    if (bytes == null) {
        return null;
    }
    ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(bytes));
    ASN1OctetString octets = (ASN1OctetString) stream.readObject();
    stream = new ASN1InputStream(new ByteArrayInputStream(octets.getOctets()));
    return stream.readObject();
}

From source file:org.dihedron.crypto.crl.CRL.java

License:Open Source License

/**
 * Extracts all CRL distribution point URLs from the "CRL Distribution Point" 
 * extension in a X.509 certificate. If CRL distribution point extension is 
 * unavailable, returns an empty list.//from  ww  w . j  a  va 2  s  .  c  om
 */
public static List<String> getCrlDistributionPoints(X509Certificate certificate)
        throws CertificateParsingException, IOException {

    List<String> urls = new ArrayList<>();

    byte[] extension = certificate.getExtensionValue(Extension.cRLDistributionPoints.getId());
    if (extension == null) {
        // return an empty list
        return urls;
    }

    try (ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(extension))) {
        byte[] crldpExtOctets = ((DEROctetString) oAsnInStream.readObject()).getOctets();
        try (ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(crldpExtOctets))) {
            for (DistributionPoint dp : CRLDistPoint.getInstance(oAsnInStream2.readObject())
                    .getDistributionPoints()) {
                DistributionPointName name = dp.getDistributionPoint();
                // look for URIs in fullName
                if (name != null && name.getType() == DistributionPointName.FULL_NAME) {
                    GeneralName[] generalNames = GeneralNames.getInstance(name.getName()).getNames();
                    // look for an URI
                    for (GeneralName generalName : generalNames) {
                        if (generalName.getTagNo() == GeneralName.uniformResourceIdentifier) {
                            String url = DERIA5String.getInstance(generalName.getName()).getString();
                            urls.add(url);
                        }
                    }
                }
            }
            return urls;
        }
    }
}

From source file:org.ebayopensource.fido.uaf.crypto.Asn1.java

License:Apache License

/**
 * DER - From byte[] to Big Integer rs/*from w  ww.  j ava  2s .  co m*/
 * UAF_ALG_SIGN_SECP256K1_ECDSA_SHA256_DER 0x06 DER [ITU-X690-2008] encoded
 * ECDSA signature [RFC5480] on the secp256k1 curve. I.e. a DER encoded
 * SEQUENCE { r INTEGER, s INTEGER }
 * 
 * @param signature
 * @return
 * @throws IOException
 */
public static BigInteger[] decodeToBigIntegerArray(byte[] signature) throws IOException {
    ASN1InputStream decoder = new ASN1InputStream(signature);
    DLSequence seq = (DLSequence) decoder.readObject();
    ASN1Integer r = (ASN1Integer) seq.getObjectAt(0);
    ASN1Integer s = (ASN1Integer) seq.getObjectAt(1);
    decoder.close();
    BigInteger[] ret = new BigInteger[2];
    ret[0] = r.getPositiveValue();
    ret[1] = s.getPositiveValue();
    return ret;
}

From source file:org.eclipse.andmore.android.certmanager.core.KeyStoreUtils.java

License:Apache License

/**
 * Create a new X509 certificate for a given KeyPair
 * //  w  w  w .  j  a  va 2  s .  co m
 * @param keyPair
 *            the {@link KeyPair} used to create the certificate,
 *            RSAPublicKey and RSAPrivateKey are mandatory on keyPair,
 *            IllegalArgumentExeption will be thrown otherwise.
 * @param issuerName
 *            The issuer name to be used on the certificate
 * @param ownerName
 *            The owner name to be used on the certificate
 * @param expireDate
 *            The expire date
 * @return The {@link X509Certificate}
 * @throws IOException
 * @throws OperatorCreationException
 * @throws CertificateException
 */
public static X509Certificate createX509Certificate(KeyPair keyPair, CertificateDetailsInfo certDetails)
        throws IOException, OperatorCreationException, CertificateException {

    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();
    if (!(publicKey instanceof RSAPublicKey) || !(privateKey instanceof RSAPrivateKey)) {
        throw new IllegalArgumentException(CertificateManagerNLS.KeyStoreUtils_RSA_Keys_Expected);
    }

    RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
    RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;

    // Transform the PublicKey into the BouncyCastle expected format
    ASN1InputStream asn1InputStream = null;
    X509Certificate x509Certificate = null;

    try {
        asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(rsaPublicKey.getEncoded()));
        SubjectPublicKeyInfo pubKey = new SubjectPublicKeyInfo((ASN1Sequence) asn1InputStream.readObject());

        X500NameBuilder nameBuilder = new X500NameBuilder(new BCStrictStyle());
        addField(BCStyle.C, certDetails.getCountry(), nameBuilder);
        addField(BCStyle.ST, certDetails.getState(), nameBuilder);
        addField(BCStyle.L, certDetails.getLocality(), nameBuilder);
        addField(BCStyle.O, certDetails.getOrganization(), nameBuilder);
        addField(BCStyle.OU, certDetails.getOrganizationUnit(), nameBuilder);
        addField(BCStyle.CN, certDetails.getCommonName(), nameBuilder);

        X500Name subjectName = nameBuilder.build();
        X500Name issuerName = subjectName;
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuerName,
                BigInteger.valueOf(new SecureRandom().nextInt()), Calendar.getInstance().getTime(),
                certDetails.getExpirationDate(), subjectName, pubKey);

        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); //$NON-NLS-1$
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        BcContentSignerBuilder sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);

        // Create RSAKeyParameters, the private key format expected by
        // Bouncy Castle
        RSAKeyParameters keyParams = new RSAKeyParameters(true, rsaPrivateKey.getPrivateExponent(),
                rsaPrivateKey.getModulus());

        ContentSigner contentSigner = sigGen.build(keyParams);
        X509CertificateHolder certificateHolder = certBuilder.build(contentSigner);

        // Convert the X509Certificate from BouncyCastle format to the
        // java.security format
        JcaX509CertificateConverter certConverter = new JcaX509CertificateConverter();
        x509Certificate = certConverter.getCertificate(certificateHolder);
    } finally {
        if (asn1InputStream != null) {
            try {
                asn1InputStream.close();
            } catch (IOException e) {
                AndmoreLogger
                        .error("Could not close stream while creating X509 certificate. " + e.getMessage());
            }
        }
    }

    return x509Certificate;
}