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:com.zotoh.crypto.CryptoUte.java

/**
 * @param key//w ww .j av  a  2s  .c om
 * @param part
 * @return
 * @throws MessagingException
 * @throws GeneralSecurityException
 * @throws IOException
 */
public static StreamData smimeDecrypt(PrivateKey key, BodyPart part)
        throws MessagingException, GeneralSecurityException, IOException {

    tstArgIsType("bodypart", part, MimeBodyPart.class);
    tstObjArg("private-key", key);
    CMSTypedStream cms = null;
    try {
        SMIMEEnveloped env = new SMIMEEnveloped((MimeBodyPart) part);
        cms = smime_decrypt(key, env);
    } catch (CMSException e) {
        throw new GeneralSecurityException(e);
    }
    if (cms == null) {
        throw new GeneralSecurityException("Failed to decrypt: no matching decryption key");
    }
    //else
    return readStream(cms.getContentStream());
}

From source file:org.apache.nifi.processors.standard.util.crypto.scrypt.Scrypt.java

/**
 * Implementation of PBKDF2 (RFC2898)./* w w w.  ja va 2s. c o m*/
 *
 * @param mac   the pre-initialized {@link Mac} instance to use
 * @param s     the salt
 * @param c     the iteration count
 * @param dk    the byte array that derived key will be placed in
 * @param dkLen the intended length, in octets, of the derived key
 * @throws GeneralSecurityException if the key length is too long
 */
private static void pbkdf2(Mac mac, byte[] s, int c, byte[] dk, int dkLen) throws GeneralSecurityException {
    int hLen = mac.getMacLength();

    if (dkLen > (Math.pow(2, 32) - 1) * hLen) {
        throw new GeneralSecurityException("Requested key length too long");
    }

    byte[] U = new byte[hLen];
    byte[] T = new byte[hLen];
    byte[] block1 = new byte[s.length + 4];

    int l = (int) Math.ceil((double) dkLen / hLen);
    int r = dkLen - (l - 1) * hLen;

    arraycopy(s, 0, block1, 0, s.length);

    for (int i = 1; i <= l; i++) {
        block1[s.length + 0] = (byte) (i >> 24 & 0xff);
        block1[s.length + 1] = (byte) (i >> 16 & 0xff);
        block1[s.length + 2] = (byte) (i >> 8 & 0xff);
        block1[s.length + 3] = (byte) (i >> 0 & 0xff);

        mac.update(block1);
        mac.doFinal(U, 0);
        arraycopy(U, 0, T, 0, hLen);

        for (int j = 1; j < c; j++) {
            mac.update(U);
            mac.doFinal(U, 0);

            for (int k = 0; k < hLen; k++) {
                T[k] ^= U[k];
            }
        }

        arraycopy(T, 0, dk, (i - 1) * hLen, (i == l ? r : hLen));
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.HopsworksRMAppSecurityActions.java

private void notConfigured(String methodName, String mechanism) throws GeneralSecurityException {
    throw new GeneralSecurityException("Called method " + methodName + " of "
            + HopsworksRMAppSecurityActions.class.getSimpleName() + " but " + mechanism + " is not configured");
}

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

/**
 * @param keys//from   w  w w.  ja v  a 2  s .co  m
 * @param msg
 * @return
 * @throws GeneralSecurityException
 * @throws MessagingException
 * @throws IOException
 */
public static StreamData smimeDecryptAsStream(PrivateKey[] keys, MimeMessage msg)
        throws GeneralSecurityException, MessagingException, IOException {

    tstObjArg("mime-message", msg);
    tstObjArg("private-key(s)", keys);

    CMSTypedStream cms = null;
    SMIMEEnveloped env;
    try {
        env = new SMIMEEnveloped(msg);
    } catch (CMSException e) {
        throw new GeneralSecurityException(e);
    }

    for (int n = 0; n < keys.length; ++n) {
        cms = smime_decrypt(keys[n], env);
        if (cms != null) {
            break;
        }
        cms = null;
    }

    if (cms == null) {
        throw new GeneralSecurityException("Failed to decrypt: no matching decryption key");
    }
    //else
    return readStream(cms.getContentStream());
}

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

/**
 * @param mp/*w w  w.ja v  a 2  s  .c  om*/
 * @return
 * @throws IOException
 * @throws MessagingException
 * @throws GeneralSecurityException
 */
public static Object peekSmimeSignedContent(Multipart mp)
        throws IOException, MessagingException, GeneralSecurityException {

    tstArgIsType("mulitpart", mp, MimeMultipart.class);
    try {
        return new SMIMESignedParser((MimeMultipart) mp, getCharset(mp.getContentType(), "binary")).getContent()
                .getContent();
    } catch (CMSException e) {
        throw new GeneralSecurityException(e);
    }
}

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

/**
 * @param mp/*from   w  w w . j  a va 2 s .  c om*/
 * @param certs
 * @param cte
 * @return
 * @throws MessagingException
 * @throws GeneralSecurityException
 * @throws IOException
 * @throws CertificateEncodingException
 */
public static Tuple verifySmimeDigSig(Multipart mp, Certificate[] certs, String cte)
        throws MessagingException, GeneralSecurityException, IOException, CertificateEncodingException {

    tstArgIsType("multipart", mp, MimeMultipart.class);
    tstObjArg("certs", certs);

    MimeMultipart mmp = (MimeMultipart) mp;
    SMIMESigned sc;
    SignerInformation si;
    byte[] digest = null;

    try {
        sc = isEmpty(cte) ? new SMIMESigned(mmp) : new SMIMESigned(mmp, cte);
    } catch (CMSException e) {
        throw new GeneralSecurityException(e);
    }

    Provider prov = Crypto.getInstance().getProvider();
    Store s = new JcaCertStore(asList(true, certs));
    Collection<?> c;
    JcaSimpleSignerInfoVerifierBuilder bdr;
    for (Object obj : sc.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 verify signature: no matching certificate");
    }
    //else
    return new Tuple(sc.getContentAsMimeMessage(newSession()).getContent(), digest);
}

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

/**
 * @param inp//  ww  w . j a v  a 2s  .com
 * @return
 * @throws GeneralSecurityException
 * @throws IOException
 */
public static StreamData decompressAsStream(InputStream inp) throws GeneralSecurityException, IOException {
    CMSTypedStream cms = null;
    StreamData r = null;

    if (inp != null)
        try {
            cms = new CMSCompressedDataParser(inp).getContent(new ZlibExpanderProvider());
            if (cms == null) {
                throw new GeneralSecurityException("Failed to decompress stream: corrupted content");
            }
            r = readStream(cms.getContentStream());
        } catch (CMSException e) {
            throw new GeneralSecurityException(e);
        }

    return r != null ? r : new StreamData();
}

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

public SSLContext getSSLContext(String clientCertConfig, X509TrustManager trustManager)
        throws GeneralSecurityException {
    try {/*from   w  ww  .  j a  v a 2s .co m*/
        if (clientCertConfig == null)
            return getSSLContext(trustManager);

        CertificateConfigEntry entry = null;
        for (CertificateConfigEntry e : getClientAuthCertificateConfigs()) {
            if (e.getId().equals(clientCertConfig)) {
                entry = e;
                break;
            }
        }
        if (entry == null)
            throw new GeneralSecurityException(
                    "Client certificate config with id <" + clientCertConfig + "> not found.");

        final KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
        kmf.init(new KeyStoreBuilderParameters(loadKeyStore(entry)));

        return getSSLContext(kmf.getKeyManagers(), trustManager);
    } catch (Exception e) {
        throw new GeneralSecurityException("Cannot init SSLContext", e);
    }
}

From source file:net.i2p.util.I2PSSLSocketFactory.java

/**
 *  Loads certs from//from  w w  w .j  a  v  a2 s. co  m
 *  the ~/.i2p/certificates/ and $I2P/certificates/ directories.
 */
private static SSLSocketFactory initSSLContext(I2PAppContext context, boolean loadSystemCerts,
        String relativeCertPath) throws GeneralSecurityException {
    Log log = context.logManager().getLog(I2PSSLSocketFactory.class);
    KeyStore ks;
    if (loadSystemCerts) {
        ks = KeyStoreUtil.loadSystemKeyStore();
        if (ks == null)
            throw new GeneralSecurityException("Key Store init error");
    } else {
        try {
            ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(null, "".toCharArray());
        } catch (IOException ioe) {
            throw new GeneralSecurityException("Key Store init error", ioe);
        }
    }

    File dir = new File(context.getConfigDir(), relativeCertPath);
    int adds = KeyStoreUtil.addCerts(dir, ks);
    int totalAdds = adds;
    if (adds > 0) {
        if (log.shouldLog(Log.INFO))
            log.info("Loaded " + adds + " trusted certificates from " + dir.getAbsolutePath());
    }

    File dir2 = new File(context.getBaseDir(), relativeCertPath);
    if (!dir.getAbsolutePath().equals(dir2.getAbsolutePath())) {
        adds = KeyStoreUtil.addCerts(dir2, ks);
        totalAdds += adds;
        if (adds > 0) {
            if (log.shouldLog(Log.INFO))
                log.info("Loaded " + adds + " trusted certificates from " + dir.getAbsolutePath());
        }
    }
    if (totalAdds > 0 || loadSystemCerts) {
        if (log.shouldLog(Log.INFO))
            log.info("Loaded total of " + totalAdds + " new trusted certificates");
    } else {
        String msg = "No trusted certificates loaded (looked in " + dir.getAbsolutePath()
                + (dir.getAbsolutePath().equals(dir2.getAbsolutePath()) ? ""
                        : (" and " + dir2.getAbsolutePath()))
                + ", SSL connections will fail. " + "Copy the cert in " + relativeCertPath
                + " from the router to the directory.";
        // don't continue, since we didn't load the system keystore, we have nothing.
        throw new GeneralSecurityException(msg);
    }

    SSLContext sslc = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    sslc.init(null, tmf.getTrustManagers(), context.random());
    return sslc.getSocketFactory();
}

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

/**
 * @param cert/*w  w w .j av  a2  s .  c  o m*/
 * @param algo
 * @param bp
 * @return
 * @throws NoSuchAlgorithmException
 * @throws CertificateEncodingException
 * @throws GeneralSecurityException
 */
public static MimeBodyPart smimeEncrypt(Certificate cert, EncryptionAlgo algo, BodyPart bp)
        throws NoSuchAlgorithmException, CertificateEncodingException, GeneralSecurityException {

    tstArgIsType("body-part", bp, MimeBodyPart.class);
    tstObjArg("cert", cert);
    tstObjArg("algo", algo);

    SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator();
    Provider prov = Crypto.getInstance().getProvider();
    RecipientInfoGenerator g;
    try {
        g = new JceKeyTransRecipientInfoGenerator((X509Certificate) cert).setProvider(prov);
        gen.addRecipientInfoGenerator(g);
        return gen.generate((MimeBodyPart) bp,
                new JceCMSContentEncryptorBuilder(algo.getOID()).setProvider(prov).build());
    } catch (OperatorCreationException e) {
        throw new GeneralSecurityException(e);
    } catch (CMSException e) {
        throw new GeneralSecurityException(e);
    } catch (SMIMEException e) {
        throw new GeneralSecurityException(e);
    }

}