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:net.wstech2.me.httpsclient.CertificateValidatorUtils.java

License:Apache License

/**
 * Retrieves the list of alternative DNS names for this certificate, if any.
 * //from  w w w . j a  v a2s  .  c  o m
 * @param cert
 *            The certificate from which the issuer name is to the
 *            extracted.
 * @return A list with all alternative DNS names included in the
 *         certificate.
 * @throws IOException
 */
public static List extractSubjectAlternativeNameList(org.bouncycastle.asn1.x509.Certificate cert)
        throws IOException {
    List dnsNames = new ArrayList();
    dnsNames.add(CertificateValidatorUtils.extractCommonName(cert, true));
    Extension subjectAlternativeName = cert.getTBSCertificate().getExtensions()
            .getExtension(Extension.subjectAlternativeName);
    if (subjectAlternativeName == null) {
        return dnsNames;
    }
    ASN1OctetString oct = subjectAlternativeName.getExtnValue();
    ASN1InputStream extIn = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets()));
    GeneralNames gn = GeneralNames.getInstance(extIn.readObject());
    extIn.close();
    ASN1Sequence sq = (ASN1Sequence) gn.toASN1Primitive();
    for (int i = 0; i != sq.size(); i++) {
        GeneralName n = GeneralName.getInstance(sq.getObjectAt(i));
        dnsNames.add(n.getName().toString());

    }
    return dnsNames;
}

From source file:net.wstech2.me.httpsclient.CertificateValidatorUtils.java

License:Apache License

private static Boolean isHostAunthenticationCertificate(Certificate cert) throws IOException {

    Extension extKeyUsageExtension = cert.getTBSCertificate().getExtensions()
            .getExtension(Extension.extendedKeyUsage);
    if (extKeyUsageExtension == null) {
        return Boolean.FALSE;
    }/*  ww  w  .  j a v  a2 s.c o m*/
    ASN1OctetString oct = extKeyUsageExtension.getExtnValue();
    ASN1InputStream extIn = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets()));
    ExtendedKeyUsage extKeyUsages = ExtendedKeyUsage.getInstance(extIn.readObject());
    extIn.close();
    KeyPurposeId[] keyPurposeIds = extKeyUsages.getUsages();
    for (int i = 0; i < keyPurposeIds.length; i++) {
        if (keyPurposeIds[i].equals(KeyPurposeId.id_kp_serverAuth)) {
            return Boolean.TRUE;
        }
    }
    return Boolean.FALSE;
}

From source file:nl.uva.vlet.grid.voms.VomsProxyCredential.java

License:Apache License

/**
 * Contacts the VOMS server to get an AttributeCertificate
 * /* w w  w.j  a  v  a2  s .  c  om*/
 * @return true if successful, false if not
 * @throws GSSException
 * @throws IOException
 */
private boolean createAC() throws Exception {
    String hostid = vo.getDefaultHost() + ":" + vo.getDefaultPort();

    infoPrintf("Contacting VOMS server [" + hostid + "] for vo:" + vo.getVoName() + "\n");

    // System.out.println("Contacting VOMS server [" + vo.getHost() + " on
    // port "+ vo.getPort()+ " ]...");
    GSSManager manager = new GlobusGSSManagerImpl();

    Authorization authorization = new IdentityAuthorization(vo.getDefaultHostDN());

    GSSCredential clientCreds = (GSSCredential) new GlobusGSSCredentialImpl(plainProxy,
            GSSCredential.INITIATE_ONLY);

    ExtendedGSSContext context = (ExtendedGSSContext) manager.createContext(null, GSSConstants.MECH_OID,
            clientCreds, GSSContext.DEFAULT_LIFETIME);

    context.requestMutualAuth(true);
    context.requestCredDeleg(false);
    context.requestConf(true);
    context.requestAnonymity(false);

    context.setOption(GSSConstants.GSS_MODE, GSIConstants.MODE_GSI);
    context.setOption(GSSConstants.REJECT_LIMITED_PROXY, new Boolean(false));

    GssSocket socket = null;
    OutputStream out = null;
    InputStream in = null;
    //
    // P.T. de Boer:
    // Nest exception and add usefull information to exception:
    //

    try {
        socket = (GssSocket) GssSocketFactory.getDefault().createSocket(vo.getDefaultHost(),
                vo.getDefaultPort(), context);
        socket.setWrapMode(GssSocket.GSI_MODE);
        socket.setAuthorization(authorization);

        out = ((Socket) socket).getOutputStream();
        in = ((Socket) socket).getInputStream();
    }
    //
    // NoRoute= wrong port and/or hostname
    catch (java.net.NoRouteToHostException e) {
        // Wrap as nested VL Exception and provide better
        // information:
        throw new VlIOException(
                "Communication Error. Adres or port is wrong or server is not reachable:" + hostid, e);
    } catch (java.net.ConnectException e) {
        // Wrap as nested VL Exception and provide better
        // information:
        throw new VlIOException("Connection Error. Adres or port is wrong or server is not reachable:" + hostid,
                e);
    } catch (java.net.SocketException e) {
        // Generic Socket Exception. 
        // Wrap as nested VL Exception and provide better
        // information:
        // when authentication fails, the socket is closed also.
        throw new VlIOException(
                "Communication Error. Either SSL authentication failed or the adres or port is wrong (server not reachable):"
                        + hostid,
                e);
    }

    /*
     * if (socket.isConnected()==false) { throw new IOException("Socket not
     * connected:"+socket.getInetAddress()+":"+socket.getPort()); }
     */
    if (in == null) {
        // VlException
        throw new VlIOException(
                "Couldn't read from socket:" + socket.getInetAddress() + ":" + socket.getPort());

    }
    String msg = new String("<?xml version=\"1.0\" encoding = \"US-ASCII\"?>" + "<voms>" + "<command>" + command
            + "</command>" + "<lifetime>" + lifetimeInSeconds + "</lifetime>" + "</voms>");

    debugPrintf("Sending message to:%s\n--- START ---\n%s\n--- END ---\n", hostid, msg);

    byte[] outToken = msg.getBytes();

    out.write(outToken);
    out.flush();

    StringBuffer voms_server_answer = new StringBuffer();

    BufferedReader buff = new BufferedReader(new InputStreamReader(in));

    char[] buf = new char[1024];
    int numRead = 0;
    //
    // read loop:
    //
    do {
        numRead = buff.read(buf);
        if (numRead > 0) {
            voms_server_answer.append(buf, 0, numRead);
        }
    } while (numRead >= 0); // while not EOF

    if (voms_server_answer.length() <= 0) {
        errorPrintf("empty or null voms_server_answer\n");

        // P.T. de Boer: Do error checking !
        throw new VlIOException("NULL reply from socket (command=" + command + "):" + socket.getInetAddress()
                + ":" + socket.getPort());
    }
    // String answer = buff.readLine();

    out.close();
    in.close();
    buff.close();

    String answer = voms_server_answer.toString();

    if (answer.indexOf("<error>") > 0) {
        String errormsg = answer.substring(answer.indexOf("<message>") + 9, answer.indexOf("</message>"));
        infoPrintf("Received error message from server:%s\n", errormsg);

        // P.T. de Boer:
        // This is NOT a warning: myLogger.warn("VOMS server returned an
        // error => " + errormsg);
        // throw error:
        throw new VlServerException("Error when communicating with:" + hostid + ".\nError=" + errormsg);
    }

    String encoded;
    try {
        encoded = answer.substring(answer.indexOf("<ac>") + 4, answer.indexOf("</ac>"));
    } catch (IndexOutOfBoundsException e) {
        // P.T. de Boer. This is an error as well: Nest Exception:
        throw new VlServerException("Message Error. Could not find encoded voms proxy in server answer.", e);
    }

    // System.out.println(" succes " + encoded);

    try {
        byte[] payload = VincenzoBase64.decode(encoded);
        // byte[] payload = Base64Coder.decode(encoded);
        //Debug(4,"Payload="(new String(payload))
        ByteArrayInputStream is = new ByteArrayInputStream(payload);
        ASN1InputStream asnInStream = new ASN1InputStream(is);

        // org.bouncycastle.asn1.BERTaggedObjectParser btp =
        // (org.bouncycastle.asn1.BERTaggedObjectParser)asnInStream.readObject();
        ASN1Sequence acseq = (ASN1Sequence) asnInStream.readObject();
        ac = new AttributeCertificate(acseq);
        return true;
    } catch (Exception e) {
        // P.T. de Boer nested VlException
        throw new VlException("DecodingError", "Couldn't decode server answer\n" + encoded, e);
    }
}

From source file:nl.uva.vlet.grid.voms.VomsUtil.java

License:Apache License

/**
 * Static method that returns all included AttributesCertificates of a
 * GlobusCredential. In general we are only interested in the first one.
 * // ww w.jav  a  2 s .c o  m
 * @param vomsProxy
 *            the voms enabled proxy credential
 * @return all AttributeCertificates
 */
public static ArrayList<AttributeCertificate> extractVOMSACs(X509Certificate[] x509s) {

    // the aim of this is to retrieve all VOMS ACs
    ArrayList<AttributeCertificate> acArrayList = new ArrayList<AttributeCertificate>();

    for (int x = 0; x < x509s.length; x++) {
        logger.debugPrintf(" - Checking certificate[" + x + "]\n");

        try {

            byte[] payload = x509s[x].getExtensionValue(VomsUtil.CERT_VOMS_EXTENSION_OID);
            if (payload == null) {
                logger.debugPrintf(" - #%d: No VOMS AC extension.\n", x);
                continue;
            } else
                logger.debugPrintf(" - #d: Found VOMS AC extension.\n", x);

            // Octet String encapsulation - see RFC 3280 section 4.1
            payload = ((ASN1OctetString) new ASN1InputStream(new ByteArrayInputStream(payload)).readObject())
                    .getOctets();

            ASN1Sequence acSequence = (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(payload))
                    .readObject();

            for (Enumeration e1 = acSequence.getObjects(); e1.hasMoreElements();) {

                ASN1Sequence seq2 = (ASN1Sequence) e1.nextElement();

                for (Enumeration e2 = seq2.getObjects(); e2.hasMoreElements();) {
                    AttributeCertificate ac = new AttributeCertificate((ASN1Sequence) e2.nextElement());

                    acArrayList.add(ac);
                }
            }
        } catch (Exception pe) {
            logger.logException(ClassLogger.DEBUG, pe, " - #%d: This part of the chain has no AC\n", x);
        }
    }

    return acArrayList;
}

From source file:org.apache.ace.authentication.processor.clientcert.MemoryKeyStore.java

License:Apache License

private SubjectPublicKeyInfo convertToSubjectPublicKeyInfo(PublicKey key) throws IOException {
    try (ASN1InputStream is = new ASN1InputStream(key.getEncoded())) {
        return SubjectPublicKeyInfo.getInstance(is.readObject());
    }/*  w  w  w  .  j av a  2 s  . c om*/
}

From source file:org.apache.airavata.gfac.bes.security.X509SecurityContext.java

License:Apache License

public KeyAndCertCredential generateShortLivedCredential(String userDN, String caCertPath, String caKeyPath,
        String caPwd) throws Exception {
    final long CredentialGoodFromOffset = 1000L * 60L * 15L; // 15 minutes
    // ago/*from   w ww  . ja  va  2s  .  co  m*/

    final long startTime = System.currentTimeMillis() - CredentialGoodFromOffset;
    final long endTime = startTime + 30 * 3600 * 1000;

    String keyLengthProp = "1024";
    int keyLength = Integer.parseInt(keyLengthProp);
    String signatureAlgorithm = "SHA1withRSA";

    KeyAndCertCredential caCred = getCACredential(caCertPath, caKeyPath, caPwd);

    KeyPairGenerator kpg = KeyPairGenerator.getInstance(caCred.getKey().getAlgorithm());
    kpg.initialize(keyLength);
    KeyPair pair = kpg.generateKeyPair();

    X500Principal subjectDN = new X500Principal(userDN);
    Random rand = new Random();

    SubjectPublicKeyInfo publicKeyInfo;
    try {
        publicKeyInfo = SubjectPublicKeyInfo
                .getInstance(new ASN1InputStream(pair.getPublic().getEncoded()).readObject());
    } catch (IOException e) {
        throw new InvalidKeyException(
                "Can not parse the public key" + "being included in the short lived certificate", e);
    }

    X500Name issuerX500Name = CertificateHelpers.toX500Name(caCred.getCertificate().getSubjectX500Principal());

    X500Name subjectX500Name = CertificateHelpers.toX500Name(subjectDN);

    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuerX500Name,
            new BigInteger(20, rand), new Date(startTime), new Date(endTime), subjectX500Name, publicKeyInfo);

    AlgorithmIdentifier sigAlgId = X509v3CertificateBuilder.extractAlgorithmId(caCred.getCertificate());

    X509Certificate certificate = certBuilder.build(caCred.getKey(), sigAlgId, signatureAlgorithm, null, null);

    certificate.checkValidity(new Date());
    certificate.verify(caCred.getCertificate().getPublicKey());
    KeyAndCertCredential result = new KeyAndCertCredential(pair.getPrivate(),
            new X509Certificate[] { certificate, caCred.getCertificate() });

    return result;
}

From source file:org.apache.airavata.gfac.bes.utils.SecurityUtils.java

License:Apache License

public static final KeyAndCertCredential generateShortLivedCertificate(String userDN, String caCertPath,
        String caKeyPath, String caPwd) throws Exception {
    final long CredentialGoodFromOffset = 1000L * 60L * 15L; // 15 minutes
    // ago/*  w ww. j a  va  2s .c  o  m*/

    final long startTime = System.currentTimeMillis() - CredentialGoodFromOffset;
    final long endTime = startTime + 30 * 3600 * 1000;

    final String keyLengthProp = "1024";
    int keyLength = Integer.parseInt(keyLengthProp);
    final String signatureAlgorithm = "SHA1withRSA";

    KeyAndCertCredential caCred = getCACredential(caCertPath, caKeyPath, caPwd);

    KeyPairGenerator kpg = KeyPairGenerator.getInstance(caCred.getKey().getAlgorithm());
    kpg.initialize(keyLength);
    KeyPair pair = kpg.generateKeyPair();

    X500Principal subjectDN = new X500Principal(userDN);
    Random rand = new Random();

    SubjectPublicKeyInfo publicKeyInfo;
    try {
        publicKeyInfo = SubjectPublicKeyInfo
                .getInstance(new ASN1InputStream(pair.getPublic().getEncoded()).readObject());
    } catch (IOException e) {
        throw new InvalidKeyException(
                "Can not parse the public key" + "being included in the short lived certificate", e);
    }

    X500Name issuerX500Name = CertificateHelpers.toX500Name(caCred.getCertificate().getSubjectX500Principal());

    X500Name subjectX500Name = CertificateHelpers.toX500Name(subjectDN);

    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuerX500Name,
            new BigInteger(20, rand), new Date(startTime), new Date(endTime), subjectX500Name, publicKeyInfo);

    AlgorithmIdentifier sigAlgId = X509v3CertificateBuilder.extractAlgorithmId(caCred.getCertificate());

    X509Certificate certificate = certBuilder.build(caCred.getKey(), sigAlgId, signatureAlgorithm, null, null);

    certificate.checkValidity(new Date());
    certificate.verify(caCred.getCertificate().getPublicKey());
    KeyAndCertCredential result = new KeyAndCertCredential(pair.getPrivate(),
            new X509Certificate[] { certificate, caCred.getCertificate() });

    return result;
}

From source file:org.apache.catalina.realm.X509SubjectAlternativeNameRetriever.java

License:Apache License

/**
 * The method converts ASNDerEncodedByteArray into String
 * @param byteArray//  w  ww  . j  a  v  a  2 s .c o m
 * @return String 
 */
private String getStringFromASNDerEncodedByteArray(byte[] byteArray) {
    if (logger.isDebugEnabled()) {
        logger.debug("getStringFromASNDerEncodedByteArray(byte[]) - start");
    }

    String ret = null;
    try {
        ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(byteArray));
        DERObject derObject = asn1InputStream.readObject();
        ASN1Sequence asn1Sequence = ASN1Sequence.getInstance(derObject);
        Object objectValue = asn1Sequence.getObjectAt(1);
        if (objectValue instanceof ASN1TaggedObject) {
            ASN1TaggedObject asn1TaggedObject = (ASN1TaggedObject) objectValue;
            try {
                if (logger.isDebugEnabled()) {
                    logger.debug("Try to get string from DERUTF8String.");
                }
                DERObject derTaggedObject = asn1TaggedObject.getObject();
                DERUTF8String derUtf8String = DERUTF8String.getInstance(derTaggedObject);
                ret = derUtf8String.getString();
            } catch (IllegalArgumentException e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Can not get String From DERUTF8String, [" + e.getMessage() + "].");
                }
            }
        }
    } catch (Exception e) {
        if (logger.isInfoEnabled()) {
            logger.info("Can not get String From ASNDerEncoded ByteArray, [" + e.getMessage() + "].");
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("getStringFromASNDerEncodedByteArray(byte[]) - end. Ret is [" + ret + "].");
    }
    return ret;

}

From source file:org.apache.cxf.ws.security.sts.provider.cert.CRLVerifier.java

License:Apache 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 w  ww.ja  v a  2  s  .co m
public static List<String> getCrlDistributionPoints(X509Certificate cert)
        throws CertificateParsingException, IOException {
    byte[] crldpExt = cert.getExtensionValue(X509Extensions.CRLDistributionPoints.getId());
    if (crldpExt == null) {
        List<String> emptyList = new ArrayList<String>();
        return emptyList;
    }
    ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(crldpExt));
    DERObject derObjCrlDP = oAsnInStream.readObject();
    DEROctetString dosCrlDP = (DEROctetString) derObjCrlDP;
    byte[] crldpExtOctets = dosCrlDP.getOctets();
    ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(crldpExtOctets));
    DERObject derObj2 = oAsnInStream2.readObject();
    CRLDistPoint distPoint = CRLDistPoint.getInstance(derObj2);
    List<String> crlUrls = new ArrayList<String>();
    for (DistributionPoint dp : distPoint.getDistributionPoints()) {
        DistributionPointName dpn = dp.getDistributionPoint();
        // Look for URIs in fullName
        if (dpn != null) {
            if (dpn.getType() == DistributionPointName.FULL_NAME) {
                GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames();
                // Look for an URI
                for (int j = 0; j < genNames.length; j++) {
                    if (genNames[j].getTagNo() == GeneralName.uniformResourceIdentifier) {
                        String url = DERIA5String.getInstance(genNames[j].getName()).getString();
                        crlUrls.add(url);
                    }
                }
            }
        }
    }
    return crlUrls;
}

From source file:org.apache.felix.deploymentadmin.itest.util.CertificateUtil.java

License:Apache License

private static X509Certificate createSelfSignedCert(String commonName, KeyPair keypair) throws Exception {
    PublicKey publicKey = keypair.getPublic();
    String keyAlg = DPSigner.getSignatureAlgorithm(publicKey);

    X500Name issuer = new X500Name(commonName);
    BigInteger serial = BigInteger.probablePrime(16, new Random());
    Date notBefore = new Date(System.currentTimeMillis() - 1000);
    Date notAfter = new Date(notBefore.getTime() + 6000);

    SubjectPublicKeyInfo pubKeyInfo;/*from   ww  w.j  av a2  s.co m*/
    try (ASN1InputStream is = new ASN1InputStream(publicKey.getEncoded())) {
        pubKeyInfo = SubjectPublicKeyInfo.getInstance(is.readObject());
    }

    X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, issuer,
            pubKeyInfo);
    builder.addExtension(
            new Extension(Extension.basicConstraints, true, new DEROctetString(new BasicConstraints(false))));

    X509CertificateHolder certHolder = builder
            .build(new JcaContentSignerBuilder(keyAlg).build(keypair.getPrivate()));
    return new JcaX509CertificateConverter().getCertificate(certHolder);
}