Example usage for java.security GeneralSecurityException GeneralSecurityException

List of usage examples for java.security GeneralSecurityException GeneralSecurityException

Introduction

In this page you can find the example usage for java.security GeneralSecurityException GeneralSecurityException.

Prototype

public GeneralSecurityException(Throwable cause) 

Source Link

Document

Creates a GeneralSecurityException with the specified cause and a detail message of (cause==null ?

Usage

From source file:edu.uiuc.ncsa.myproxy.MyProxyLogon.java

public void getCredentials(byte[] derEncodedCertRequest) throws IOException, GeneralSecurityException {
    try {/*from w  ww. jav a  2s  .  c o m*/

        if (this.state != State.LOGGEDON) {
            this.logon();
        }

        this.socketOut.write(derEncodedCertRequest);
        this.socketOut.flush();
        int numCertificates = this.socketIn.read();
        if (numCertificates == -1) {
            System.err.println("connection aborted");
            throw new IOException("Error: connection aborted");
        } else if (numCertificates == 0 || numCertificates < 0) {
            System.err.print("bad number of certificates sent by server: ");
            System.err.println(Integer.toString(numCertificates));
            throw new GeneralSecurityException("Error: bad number of certificates sent by server");
        }
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        this.certificateChain = (Collection<X509Certificate>) certFactory.generateCertificates(this.socketIn);
        this.state = State.DONE;
    } catch (Throwable t) {
        handleException(t, getClass().getSimpleName() + " failure getting the credential.");
    }
}

From source file:com.zotoh.crypto.CryptoUte.java

/**
 * @param cert//from  w  w w. j  a  v  a 2 s  .c  o  m
 * @param algo
 * @param mp
 * @return
 * @throws MessagingException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws GeneralSecurityException
 * @throws CertificateEncodingException
 */
public static MimeBodyPart smimeEncrypt(Certificate cert, EncryptionAlgo algo, Multipart mp)
        throws MessagingException, NoSuchAlgorithmException, NoSuchProviderException, GeneralSecurityException,
        CertificateEncodingException {

    tstObjArg("multi-part", mp);
    tstObjArg("cert", cert);
    tstObjArg("algo", algo);

    try {

        SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator();
        Provider prov = Crypto.getInstance().getProvider();
        RecipientInfoGenerator g = new JceKeyTransRecipientInfoGenerator((X509Certificate) cert)
                .setProvider(prov);
        gen.addRecipientInfoGenerator(g);
        MimeMessage mm = newMimeMsg();
        mm.setContent(mp);

        return gen.generate(mm, new JceCMSContentEncryptorBuilder(algo.getOID()).setProvider(prov).build());
    } catch (OperatorCreationException e) {
        throw new GeneralSecurityException(e);
    } catch (SMIMEException e) {
        throw new GeneralSecurityException(e);
    } catch (CMSException e) {
        throw new GeneralSecurityException(e);
    }
}

From source file:com.zotoh.crypto.CryptoUte.java

/**
 * @param contentType//from   www.j  av  a 2  s .c  o m
 * @param msg
 * @return
 * @throws IOException
 * @throws MessagingException
 * @throws GeneralSecurityException
 */
public static MimeBodyPart compressContent(String contentType, StreamData msg)
        throws IOException, MessagingException, GeneralSecurityException {

    tstEStrArg("content-type", contentType);
    tstObjArg("input-content", msg);

    SMIMECompressedGenerator gen = new SMIMECompressedGenerator();
    MimeBodyPart bp = new MimeBodyPart();
    SmDataSource ds;

    if (msg.isDiskFile()) {
        ds = new SmDataSource(msg.getFileRef(), contentType);
    } else {
        ds = new SmDataSource(msg.getBytes(), contentType);
    }

    bp.setDataHandler(new DataHandler(ds));
    try {
        return gen.generate(bp, SMIMECompressedGenerator.ZLIB);
    } catch (SMIMEException e) {
        throw new GeneralSecurityException(e);
    }
}

From source file:net.java.sip.communicator.impl.certificate.CertificateServiceImpl.java

public X509TrustManager getTrustManager(final Iterable<String> identitiesToTest,
        final CertificateMatcher clientVerifier, final CertificateMatcher serverVerifier)
        throws GeneralSecurityException {
    // obtain the default X509 trust manager
    X509TrustManager defaultTm = null;
    TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

    //workaround for https://bugs.openjdk.java.net/browse/JDK-6672015
    KeyStore ks = null;/*w  w w. j a  v a  2  s  .co  m*/
    String tsType = System.getProperty("javax.net.ssl.trustStoreType", null);
    if ("Windows-ROOT".equals(tsType)) {
        try {
            ks = KeyStore.getInstance(tsType);
            ks.load(null, null);
            int numEntries = keyStoreAppendIndex(ks);
            logger.info(
                    "Using Windows-ROOT. Aliases sucessfully renamed on " + numEntries + " root certificates.");
        } catch (Exception e) {
            logger.error("Could not rename Windows-ROOT aliases", e);
        }
    }

    tmFactory.init(ks);
    for (TrustManager m : tmFactory.getTrustManagers()) {
        if (m instanceof X509TrustManager) {
            defaultTm = (X509TrustManager) m;
            break;
        }
    }
    if (defaultTm == null)
        throw new GeneralSecurityException("No default X509 trust manager found");

    final X509TrustManager tm = defaultTm;

    return new X509TrustManager() {
        private boolean serverCheck;

        public X509Certificate[] getAcceptedIssuers() {
            return tm.getAcceptedIssuers();
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            serverCheck = true;
            checkCertTrusted(chain, authType);
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            serverCheck = false;
            checkCertTrusted(chain, authType);
        }

        private void checkCertTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // check and default configurations for property
            // if missing default is null - false
            String defaultAlwaysTrustMode = CertificateVerificationActivator.getResources()
                    .getSettingsString(CertificateService.PNAME_ALWAYS_TRUST);

            if (config.getBoolean(PNAME_ALWAYS_TRUST, Boolean.parseBoolean(defaultAlwaysTrustMode)))
                return;

            try {
                // check the certificate itself (issuer, validity)
                try {
                    chain = tryBuildChain(chain);
                } catch (Exception e) {
                } // don't care and take the chain as is

                if (serverCheck)
                    tm.checkServerTrusted(chain, authType);
                else
                    tm.checkClientTrusted(chain, authType);

                if (identitiesToTest == null || !identitiesToTest.iterator().hasNext())
                    return;
                else if (serverCheck)
                    serverVerifier.verify(identitiesToTest, chain[0]);
                else
                    clientVerifier.verify(identitiesToTest, chain[0]);

                // ok, globally valid cert
            } catch (CertificateException e) {
                String thumbprint = getThumbprint(chain[0], THUMBPRINT_HASH_ALGORITHM);
                String message = null;
                List<String> propNames = new LinkedList<String>();
                List<String> storedCerts = new LinkedList<String>();
                String appName = R.getSettingsString("service.gui.APPLICATION_NAME");

                if (identitiesToTest == null || !identitiesToTest.iterator().hasNext()) {
                    String propName = PNAME_CERT_TRUST_PREFIX + ".server." + thumbprint;
                    propNames.add(propName);

                    message = R.getI18NString("service.gui." + "CERT_DIALOG_DESCRIPTION_TXT_NOHOST",
                            new String[] { appName });

                    // get the thumbprints from the permanent allowances
                    String hashes = config.getString(propName);
                    if (hashes != null)
                        for (String h : hashes.split(","))
                            storedCerts.add(h);

                    // get the thumbprints from the session allowances
                    List<String> sessionCerts = sessionAllowedCertificates.get(propName);
                    if (sessionCerts != null)
                        storedCerts.addAll(sessionCerts);
                } else {
                    if (serverCheck) {
                        message = R.getI18NString("service.gui." + "CERT_DIALOG_DESCRIPTION_TXT",
                                new String[] { appName, identitiesToTest.toString() });
                    } else {
                        message = R.getI18NString("service.gui." + "CERT_DIALOG_PEER_DESCRIPTION_TXT",
                                new String[] { appName, identitiesToTest.toString() });
                    }
                    for (String identity : identitiesToTest) {
                        String propName = PNAME_CERT_TRUST_PREFIX + ".param." + identity;
                        propNames.add(propName);

                        // get the thumbprints from the permanent allowances
                        String hashes = config.getString(propName);
                        if (hashes != null)
                            for (String h : hashes.split(","))
                                storedCerts.add(h);

                        // get the thumbprints from the session allowances
                        List<String> sessionCerts = sessionAllowedCertificates.get(propName);
                        if (sessionCerts != null)
                            storedCerts.addAll(sessionCerts);
                    }
                }

                if (!storedCerts.contains(thumbprint)) {
                    switch (verify(chain, message)) {
                    case DO_NOT_TRUST:
                        logger.info("Untrusted certificate", e);
                        throw new CertificateException("The peer provided certificate with Subject <"
                                + chain[0].getSubjectDN() + "> is not trusted", e);
                    case TRUST_ALWAYS:
                        for (String propName : propNames) {
                            String current = config.getString(propName);
                            String newValue = thumbprint;
                            if (current != null)
                                newValue += "," + current;
                            config.setProperty(propName, newValue);
                        }
                        break;
                    case TRUST_THIS_SESSION_ONLY:
                        for (String propName : propNames)
                            getSessionCertEntry(propName).add(thumbprint);
                        break;
                    }
                }
                // ok, we've seen this certificate before
            }
        }

        private X509Certificate[] tryBuildChain(X509Certificate[] chain)
                throws IOException, URISyntaxException, CertificateException {
            // Only try to build chains for servers that send only their
            // own cert, but no issuer. This also matches self signed (will
            // be ignored later) and Root-CA signed certs. In this case we
            // throw the Root-CA away after the lookup
            if (chain.length != 1)
                return chain;

            // ignore self signed certs
            if (chain[0].getIssuerDN().equals(chain[0].getSubjectDN()))
                return chain;

            // prepare for the newly created chain
            List<X509Certificate> newChain = new ArrayList<X509Certificate>(chain.length + 4);
            for (X509Certificate cert : chain) {
                newChain.add(cert);
            }

            // search from the topmost certificate upwards
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            X509Certificate current = chain[chain.length - 1];
            boolean foundParent;
            int chainLookupCount = 0;
            do {
                foundParent = false;
                // extract the url(s) where the parent certificate can be
                // found
                byte[] aiaBytes = current.getExtensionValue(Extension.authorityInfoAccess.getId());
                if (aiaBytes == null)
                    break;

                AuthorityInformationAccess aia = AuthorityInformationAccess
                        .getInstance(X509ExtensionUtil.fromExtensionValue(aiaBytes));

                // the AIA may contain different URLs and types, try all
                // of them
                for (AccessDescription ad : aia.getAccessDescriptions()) {
                    // we are only interested in the issuer certificate,
                    // not in OCSP urls the like
                    if (!ad.getAccessMethod().equals(AccessDescription.id_ad_caIssuers))
                        continue;

                    GeneralName gn = ad.getAccessLocation();
                    if (!(gn.getTagNo() == GeneralName.uniformResourceIdentifier
                            && gn.getName() instanceof DERIA5String))
                        continue;

                    URI uri = new URI(((DERIA5String) gn.getName()).getString());
                    // only http(s) urls; LDAP is taken care of in the
                    // default implementation
                    if (!(uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equals("https")))
                        continue;

                    X509Certificate cert = null;

                    // try to get cert from cache first to avoid consecutive
                    // (slow) http lookups
                    AiaCacheEntry cache = aiaCache.get(uri);
                    if (cache != null && cache.cacheDate.after(new Date())) {
                        cert = cache.cert;
                    } else {
                        // download if no cache entry or if it is expired
                        if (logger.isDebugEnabled())
                            logger.debug("Downloading parent certificate for <" + current.getSubjectDN()
                                    + "> from <" + uri + ">");
                        try {
                            InputStream is = HttpUtils.openURLConnection(uri.toString()).getContent();
                            cert = (X509Certificate) certFactory.generateCertificate(is);
                        } catch (Exception e) {
                            logger.debug("Could not download from <" + uri + ">");
                        }
                        // cache for 10mins
                        aiaCache.put(uri,
                                new AiaCacheEntry(new Date(new Date().getTime() + 10 * 60 * 1000), cert));
                    }
                    if (cert != null) {
                        if (!cert.getIssuerDN().equals(cert.getSubjectDN())) {
                            newChain.add(cert);
                            foundParent = true;
                            current = cert;
                            break; // an AD was valid, ignore others
                        } else
                            logger.debug("Parent is self-signed, ignoring");
                    }
                }
                chainLookupCount++;
            } while (foundParent && chainLookupCount < 10);
            chain = newChain.toArray(chain);
            return chain;
        }
    };
}

From source file:com.zotoh.crypto.CryptoUte.java

/**
 * @param msg//  w  w w.j ava 2 s  . c  o  m
 * @return
 * @throws GeneralSecurityException
 */
public static MimeBodyPart compressContent(MimeMessage msg) throws GeneralSecurityException {
    tstObjArg("mime-message", msg);
    try {
        return new SMIMECompressedGenerator().generate(msg, SMIMECompressedGenerator.ZLIB);
    } catch (SMIMEException e) {
        throw new GeneralSecurityException(e);
    }
}

From source file:com.zotoh.crypto.CryptoUte.java

/**
 * @param cType// ww w  .j  av  a2 s.  c om
 * @param cte
 * @param contentLoc
 * @param cid
 * @param msg
 * @return
 * @throws MessagingException
 * @throws IOException
 * @throws GeneralSecurityException
 */
public static MimeBodyPart compressContent(String cType, String cte, String contentLoc, String cid,
        StreamData msg) throws MessagingException, IOException, GeneralSecurityException {

    tstEStrArg("content-type", cType);
    tstEStrArg("content-id", cid);
    tstObjArg("input-content", msg);

    SMIMECompressedGenerator gen = new SMIMECompressedGenerator();
    MimeBodyPart bp = new MimeBodyPart();
    SmDataSource ds;

    if (msg.isDiskFile()) {
        ds = new SmDataSource(msg.getFileRef(), cType);
    } else {
        ds = new SmDataSource(msg.getBytes(), cType);
    }

    if (!isEmpty(contentLoc)) {
        bp.setHeader("content-location", contentLoc);
    }

    try {
        bp.setHeader("content-id", cid);
        bp.setDataHandler(new DataHandler(ds));
        bp = gen.generate(bp, SMIMECompressedGenerator.ZLIB);
    } catch (SMIMEException e) {
        throw new GeneralSecurityException(e);
    }

    if (true) {
        int pos = cid.lastIndexOf(">");
        if (pos >= 0) {
            cid = cid.substring(0, pos) + "--z>";
        } else {
            cid = cid + "--z";
        }
    }

    if (!isEmpty(contentLoc)) {
        bp.setHeader("content-location", contentLoc);
    }
    bp.setHeader("content-id", cid);

    // always base64
    cte = "base64";

    if (!isEmpty(cte)) {
        bp.setHeader("content-transfer-encoding", cte);
    }

    return bp;
}

From source file:com.zotoh.crypto.CryptoUte.java

/**
 * @param key//w  w w  .jav a  2 s.c  o  m
 * @param certs
 * @param algo
 * @param data
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidAlgorithmParameterException
 * @throws CertStoreException
 * @throws IOException
 * @throws CertificateEncodingException
 * @throws GeneralSecurityException
 */
public static byte[] pkcsDigSig(PrivateKey key, Certificate[] certs, SigningAlgo algo, StreamData data)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, CertStoreException, IOException,
        CertificateEncodingException, GeneralSecurityException {

    tstObjArg("input-content", data);
    tstObjArg("private-key", key);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    Provider prov = Crypto.getInstance().getProvider();
    List<Certificate> lst = asList(true, certs);
    CMSTypedData cms;
    X509Certificate cert = (X509Certificate) lst.get(0);

    try {
        ContentSigner cs = new JcaContentSignerBuilder(algo.toString()).setProvider(prov).build(key);

        JcaSignerInfoGeneratorBuilder bdr = new JcaSignerInfoGeneratorBuilder(
                new JcaDigestCalculatorProviderBuilder().setProvider(prov).build());
        bdr.setDirectSignature(true);

        gen.addSignerInfoGenerator(bdr.build(cs, cert));
        gen.addCertificates(new JcaCertStore(lst));

        if (data.isDiskFile()) {
            cms = new CMSProcessableFile(data.getFileRef());
        } else {
            cms = new CMSProcessableByteArray(data.getBytes());
        }

        return gen.generate(cms, false).getEncoded();
    } catch (OperatorCreationException e) {
        throw new GeneralSecurityException(e);
    } catch (CMSException e) {
        throw new GeneralSecurityException(e);
    }

}

From source file:com.zotoh.crypto.CryptoUte.java

/**
 * @param cert/*  w  ww .  java2  s  . c  o  m*/
 * @param data
 * @param signature
 * @return
 * @throws GeneralSecurityException
 * @throws IOException
 * @throws CertificateEncodingException
 */
public static byte[] verifyPkcsDigSig(Certificate cert, StreamData data, byte[] signature)
        throws GeneralSecurityException, IOException, CertificateEncodingException {

    tstObjArg("digital-signature", signature);
    tstObjArg("cert", cert);
    tstObjArg("input-content", data);

    Provider prov = Crypto.getInstance().getProvider();
    SignerInformation si;
    CMSProcessable cproc;
    CMSSignedData cms;
    byte[] digest;

    if (data.isDiskFile()) {
        cproc = new CMSProcessableFile(data.getFileRef());
    } else {
        cproc = new CMSProcessableByteArray(data.getBytes());
    }

    try {
        cms = new CMSSignedData(cproc, signature);
        digest = null;
    } catch (CMSException e) {
        throw new GeneralSecurityException(e);
    }

    List<Certificate> cl = LT();
    cl.add(cert);
    Store s = new JcaCertStore(cl);
    Collection<?> c;
    JcaSimpleSignerInfoVerifierBuilder bdr;

    for (Object obj : cms.getSignerInfos().getSigners())
        try {
            si = (SignerInformation) obj;
            c = s.getMatches(si.getSID());
            for (Iterator<?> it = c.iterator(); it.hasNext();) {
                bdr = new JcaSimpleSignerInfoVerifierBuilder().setProvider(prov);
                if (si.verify(bdr.build((X509CertificateHolder) it.next()))) {
                    digest = si.getContentDigest();
                    break;
                }
            }
            if (digest != null) {
                break;
            }
        } catch (Exception e) {
        }

    if (digest == null) {
        throw new GeneralSecurityException("Failed to decode signature: no matching certificate");
    }
    // else
    return digest;
}

From source file:info.guardianproject.onionkit.trust.StrongTrustManager.java

private void checkKeyUsage(X509Certificate cert) throws GeneralSecurityException {
    try {/*  ww  w. ja  v  a2  s  .c  o  m*/
        Object bsVal = getExtensionValue(cert, X509Extensions.KeyUsage.getId(), KeyUsage.class);

        if (bsVal != null && bsVal instanceof KeyUsage) {
            KeyUsage keyUsage = (KeyUsage) bsVal;
            // SSLCA: CERT_SIGN; SSL_CA;+
            //                debug("KeyUsage=" + keyUsage.intValue() + ";" + keyUsage.getString());

            if (keyUsage.hasUsages(KeyUsage.cRLSign) && keyUsage.hasUsages(KeyUsage.keyCertSign)) {
                // we okay
            } else
                throw new GeneralSecurityException("KeyUsage = not set for signing");

        }
    } catch (IOException e) {
        throw new GeneralSecurityException("Basic Constraints CA = error reading extension");
    }
}

From source file:info.guardianproject.onionkit.trust.StrongTrustManager.java

private void checkBasicConstraints(X509Certificate cert) throws GeneralSecurityException {
    // check basic constraints
    int bConLen = cert.getBasicConstraints();
    if (bConLen == -1) {
        throw new GeneralSecurityException("Basic Constraints CA not set for issuer in chain");
    } else {//w  w  w.j  a va2  s.  c  o  m
        /*
         * basicConstraints=CA:TRUE basicConstraints=CA:FALSE
         * basicConstraints=critical,CA:TRUE, pathlen:0
         */
        // String OID_BASIC_CONSTRAINTS = "2.5.29.19";

        try {
            Object bsVal = getExtensionValue(cert, X509Extensions.BasicConstraints.getId(),
                    BasicConstraints.class);

            if (bsVal != null && bsVal instanceof BasicConstraints) {
                BasicConstraints basicConstraints = (BasicConstraints) bsVal;
                // BasicConstraints.getInstance(ASN1Object.fromByteArray(bsValBytes));

                debug("Basic Constraints=CA:" + basicConstraints.isCA());

                if (basicConstraints.getPathLenConstraint() != null)
                    debug("Basic Constraints: pathLen=" + basicConstraints.getPathLenConstraint().intValue());

                if (!basicConstraints.isCA())
                    throw new GeneralSecurityException(
                            "Basic Constraints CA = true not set for issuer in chain");
            } else {
                throw new GeneralSecurityException("Basic Constraints CA = true not set for issuer in chain");
            }
        } catch (IOException e) {
            throw new GeneralSecurityException("Basic Constraints CA = error reading extension");
        }

    }
}