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:de.elomagic.carafile.server.bl.SeedBean.java

public void seedChunk(final InputStream inputStream, final String chunkId)
        throws IOException, GeneralSecurityException, JMSException {
    LOG.debug("Seeding chunk " + chunkId);
    Chunk chunk = chunkDAO.findByIdentifier(chunkId);

    if (chunk == null) {
        throw new FileNotFoundException(
                "Chunk id " + chunkId + " not found. File already registered at registry?");
    }//from  w  w w.  j a va 2  s  .c o m

    byte[] buf = new byte[chunk.getFileMeta().getChunkSize()];
    int bufferSize;
    try (InputStream in = inputStream) {
        bufferSize = readBlock(in, buf);
    } catch (IOException ex) {
        throw ex;
    }

    // Check SHA-1
    String sha1 = Hex.encodeHexString(DigestUtils.sha1(Arrays.copyOf(buf, bufferSize)));
    if (!chunk.getHash().equalsIgnoreCase(sha1)) {
        throw new GeneralSecurityException(
                "Chunk SHA-1 validation failed (Expected " + chunk.getHash() + ", but is " + sha1 + ")");
    }

    repositoryBean.writeChunk(chunkId, buf, bufferSize);

    LOG.debug("Chunk id " + chunkId + " seed");

    // Initiate to register at tracker
    LOG.debug("Queue up new file for registration.");
    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer messageProducer = session.createProducer(chunkQueue);

    TextMessage message = session.createTextMessage(chunkId);
    messageProducer.send(message);
    connection.close();
}

From source file:labr_client.Public.encryption.java

/**
 * Decode a string which has first been encrypted with AES, and then
 * base64-encoded.//from  www. j  a  v a  2s  .c  om
 */
public static String decodeBase64Aes(String enc) throws GeneralSecurityException {
    byte[] bytesEnc = decodeBase64(enc.getBytes(UTF8));

    // Extract the IV, which is stored in the next N bytes
    int nIvBytes = AES_NIVBITS / 8;
    byte[] ivBytes = new byte[nIvBytes];
    arraycopy(bytesEnc, 0, ivBytes, 0, nIvBytes);

    // Select encryption algorithm and padding : AES with CBC and PCKS#7.
    // Note that the "encryption strength" (128 or 256 bit key) is set by the KeyParameter object.
    KeyParameter keyParam = getAesKey();
    CipherParameters params = new ParametersWithIV(keyParam, ivBytes);
    BlockCipherPadding padding = new PKCS7Padding();
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);

    // Decrypt all bytes that follow the IV
    cipher.reset();
    cipher.init(false, params); // first param = encode/decode

    byte[] bytesDec;

    try {
        int buflen = cipher.getOutputSize(bytesEnc.length - nIvBytes);
        byte[] workingBuffer = new byte[buflen];
        int len = cipher.processBytes(bytesEnc, nIvBytes, bytesEnc.length - nIvBytes, workingBuffer, 0);
        len += cipher.doFinal(workingBuffer, len);

        // Note that getOutputSize returns a number which includes space for "padding" bytes to be stored in.
        // However we don't want these padding bytes; the "len" variable contains the length of the *real* data
        // (which is always less than the return value of getOutputSize.
        bytesDec = new byte[len];
        arraycopy(workingBuffer, 0, bytesDec, 0, len);
    } catch (InvalidCipherTextException e) {
        throw new GeneralSecurityException("decode failed");
    } catch (RuntimeException e) {
        throw new GeneralSecurityException("encryption failed");
    }

    // And convert the result to a string
    out.println(new String(bytesDec, UTF8));
    return new String(bytesDec, UTF8);
}

From source file:org.apache.hadoop.security.ssl.SSLFactory.java

public static HostnameVerifier getHostnameVerifier(String verifier)
        throws GeneralSecurityException, IOException {
    HostnameVerifier hostnameVerifier;
    if (verifier.equals("DEFAULT")) {
        hostnameVerifier = SSLHostnameVerifier.DEFAULT;
    } else if (verifier.equals("DEFAULT_AND_LOCALHOST")) {
        hostnameVerifier = SSLHostnameVerifier.DEFAULT_AND_LOCALHOST;
    } else if (verifier.equals("STRICT")) {
        hostnameVerifier = SSLHostnameVerifier.STRICT;
    } else if (verifier.equals("STRICT_IE6")) {
        hostnameVerifier = SSLHostnameVerifier.STRICT_IE6;
    } else if (verifier.equals("ALLOW_ALL")) {
        hostnameVerifier = SSLHostnameVerifier.ALLOW_ALL;
    } else {/*from   w  ww  .j a v a2s .  c o m*/
        throw new GeneralSecurityException("Invalid hostname verifier: " + verifier);
    }
    return hostnameVerifier;
}

From source file:org.apache.hadoop.security.ssl.FileBasedKeyStoresFactory.java

private void createKeyManagers(SSLFactory.Mode mode) throws IOException, GeneralSecurityException {
    boolean requireClientCert = conf.getBoolean(SSLFactory.SSL_REQUIRE_CLIENT_CERT_KEY,
            SSLFactory.DEFAULT_SSL_REQUIRE_CLIENT_CERT);

    String keystoreType = conf.get(resolvePropertyName(mode, SSL_KEYSTORE_TYPE_TPL_KEY), DEFAULT_KEYSTORE_TYPE);

    if (requireClientCert || mode == SSLFactory.Mode.SERVER) {
        String locationProperty = resolvePropertyName(mode, SSL_KEYSTORE_LOCATION_TPL_KEY);
        String keystoreLocation = conf.get(locationProperty, "");
        if (keystoreLocation.isEmpty()) {
            throw new GeneralSecurityException(
                    "The property '" + locationProperty + "' has not been set in the ssl configuration file.");
        }/*from   www.j  av a2  s. co m*/
        String passwordProperty = resolvePropertyName(mode, SSL_KEYSTORE_PASSWORD_TPL_KEY);
        String keystorePassword = getPassword(conf, passwordProperty, "");
        if (keystorePassword.isEmpty()) {
            throw new GeneralSecurityException(
                    "The property '" + passwordProperty + "' has not been set in the ssl configuration file.");
        }
        String keyPasswordProperty = resolvePropertyName(mode, SSL_KEYSTORE_KEYPASSWORD_TPL_KEY);
        // Key password defaults to the same value as store password for
        // compatibility with legacy configurations that did not use a separate
        // configuration property for key password.
        String keystoreKeyPassword = getPassword(conf, keyPasswordProperty, keystorePassword);
        if (LOG.isDebugEnabled()) {
            LOG.debug(mode.toString() + " KeyStore: " + keystoreLocation);
        }

        long keyStoreReloadInterval = conf.getLong(
                resolvePropertyName(mode, SSL_KEYSTORE_RELOAD_INTERVAL_TPL_KEY),
                DEFAULT_SSL_KEYSTORE_RELOAD_INTERVAL);
        String timeUnitStr = conf.get(resolvePropertyName(mode, SSL_KEYSTORE_RELOAD_TIMEUNIT_TPL_KEY),
                DEFAULT_SSL_KEYSTORE_RELOAD_TIMEUNIT);
        TimeUnit reloadTimeUnit = TimeUnit.valueOf(timeUnitStr.toUpperCase());

        String passwordFileLocationProperty = resolvePropertyName(mode, SSL_PASSWORDFILE_LOCATION_TPL_KEY);
        String passwordFileLocation = conf.get(passwordFileLocationProperty, null);
        keyManager = new ReloadingX509KeyManager(keystoreType, keystoreLocation, keystorePassword,
                passwordFileLocation, keystoreKeyPassword, keyStoreReloadInterval, reloadTimeUnit);

        keyManager.init();
        if (LOG.isDebugEnabled()) {
            LOG.debug(mode.toString() + " Loaded KeyStore: " + keystoreLocation);
        }
        keyManagers = new KeyManager[] { keyManager };
    } else {
        // Deal with it
        KeyStore keyStore = KeyStore.getInstance(keystoreType);
        keyStore.load(null, null);
        KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance(SSLFactory.SSLCERTIFICATE);
        keyMgrFactory.init(keyStore, null);
        keyManagers = keyMgrFactory.getKeyManagers();
    }
}

From source file:edu.ucsb.eucalyptus.keys.AbstractKeyStore.java

public String getCertificateAlias(X509Certificate cert) throws GeneralSecurityException {
    String alias = this.keyStore.getCertificateAlias(cert);
    if (alias == null)
        throw new GeneralSecurityException("No Such Certificate!");
    return alias;
}

From source file:uk.ac.ox.webauth.crypto.DesCbcCrc.java

/**
 * From RFC 3961://from  ww  w.  ja  v  a  2s . c o m
 * <pre>
 *   +-----------+----------+---------+-----+
 *   |confounder | checksum | msg-seq | pad |
 *   +-----------+----------+---------+-----+
 * </pre>
 */
@Override
public ASN1Encodable decrypt(byte[] cipherData) throws IOException, GeneralSecurityException {
    // decrypt the data
    Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding");
    IvParameterSpec iv = new IvParameterSpec(key.getEncoded());
    cipher.init(DECRYPT_MODE, key, iv);
    byte[] data = cipher.doFinal(cipherData);

    // split out the CRC checksum (4 bytes) and check it
    byte[] checksum = new byte[4];
    System.arraycopy(data, cipher.getBlockSize(), checksum, 0, checksum.length);
    Arrays.fill(data, cipher.getBlockSize(), cipher.getBlockSize() + checksum.length, (byte) 0);
    if (!Arrays.equals(checksum, modifiedCRC32(data))) {
        throw new GeneralSecurityException("Checksum failure.");
    }

    // return an ASN.1 object
    InputStream is = new ByteArrayInputStream(data);
    is.skip(cipher.getBlockSize() + checksum.length);
    ASN1InputStream ais = new ASN1InputStream(is);

    return (ASN1Encodable) ais.readObject();
}

From source file:org.artifactory.security.crypto.CryptoHelper.java

public static String generateUniqueApiKey() throws GeneralSecurityException {
    byte[] hmacData;

    try {//from  w w  w .  j  a  v  a  2  s .  co m
        SecretKeySpec secretKey = new SecretKeySpec("secretKey".getBytes("UTF-8"), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(secretKey);
        String data = UUID.randomUUID().toString();
        hmacData = mac.doFinal(data.getBytes("UTF-8"));
        return new Base64Encoder().encode(hmacData);
    } catch (UnsupportedEncodingException e) {
        throw new GeneralSecurityException(e);
    }
}

From source file:org.globus.gsi.util.CertificateLoadUtil.java

/**
 * Loads a X.509 certificate from the specified reader. The certificate
 * contents must start with "BEGIN CERTIFICATE" line and end with "END
 * CERTIFICATE" line, and be in PEM/Base64 format.
 * <p/>/*from   w  w  w . jav a  2 s. c o  m*/
 * This function does not close the input stream.
 *
 * @param reader the stream from which load the certificate.
 * @return the loaded certificate or null if there was no certificate in the
 *         stream or the stream is closed.
 * @throws IOException              if I/O error occurs
 * @throws GeneralSecurityException if security problems occurs.
 */
public static X509Certificate readCertificate(BufferedReader reader)
        throws IOException, GeneralSecurityException {
    String line;
    StringBuffer buff = new StringBuffer();
    boolean isCert = false;
    boolean isKey = false;
    boolean notNull = false;
    while ((line = reader.readLine()) != null) {
        // Skip key info, if any
        if (line.indexOf("BEGIN RSA PRIVATE KEY") != -1 || line.indexOf("BEGIN PRIVATE KEY") != -1) {
            isKey = true;
            continue;
        } else if (isKey
                && (line.indexOf("END RSA PRIVATE KEY") != -1 || line.indexOf("END PRIVATE KEY") != -1)) {
            isKey = false;
            continue;
        } else if (isKey)
            continue;

        notNull = true;
        if (line.indexOf("BEGIN CERTIFICATE") != -1) {
            isCert = true;
        } else if (isCert && line.indexOf("END CERTIFICATE") != -1) {
            byte[] data = Base64.decode(buff.toString().getBytes());
            return loadCertificate(new ByteArrayInputStream(data));
        } else if (isCert) {
            buff.append(line);
        }
    }
    if (notNull && !isCert) {
        throw new GeneralSecurityException("Certificate needs to start with " + " BEGIN CERTIFICATE");
    }
    return null;
}

From source file:com.otisbean.keyring.Ring.java

/**
 * Initialize the cipher object and create the key object.
 * //from w ww . j  a  v  a  2s.c o m
 * @param password
 * @return A checkData string, which can be compared against the existing
 * one to determine if the password is valid.
 * @throws GeneralSecurityException
 */
private String initCipher(char[] password) throws GeneralSecurityException {
    log("initCipher()");
    String base64Key = null;
    try {
        // Convert a char array into a UTF-8 byte array
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStreamWriter out = new OutputStreamWriter(baos, "UTF-8");
        try {
            out.write(password);
            out.close();
        } catch (IOException e) {
            // the only reason this would throw is an encoding problem.
            throw new RuntimeException(e.getLocalizedMessage());
        }
        byte[] passwordBytes = baos.toByteArray();

        /* The following code looks like a lot of monkey-motion, but it yields
         * results compatible with the on-phone Keyring Javascript and Mojo code.
         * 
         * In newPassword() in ring.js, we have this (around line 165):
         * this._key = b64_sha256(this._salt + newPassword); */
        byte[] saltBytes = salt.getBytes("UTF-8");
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(saltBytes, 0, saltBytes.length);
        md.update(passwordBytes, 0, passwordBytes.length);
        byte[] keyHash = md.digest();
        String paddedBase64Key = Base64.encodeBytes(keyHash);
        /* The Javascript SHA-256 library used in Keyring doesn't pad base64 output,
         * so we need to trim off any trailing "=" signs. */
        base64Key = paddedBase64Key.replace("=", "");
        byte[] keyBytes = base64Key.getBytes("UTF-8");

        /* Keyring passes data to Mojo.Model.encrypt(key, data), which eventually
         * make a JNI call to OpenSSL's blowfish api.  The following is the
         * equivalent in straight up JCE. */
        key = new SecretKeySpec(keyBytes, "Blowfish");
        iv = new IvParameterSpec(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 });
    } catch (UnsupportedEncodingException e) {
        // This is a bit dodgy, but handling a UEE elsewhere is foolish
        throw new GeneralSecurityException(e.getLocalizedMessage());
    }
    return "{" + base64Key + "}";
}

From source file:net.bioclipse.opentox.api.ModelAlgorithm.java

@SuppressWarnings("serial")
public static String createModel(String algoURI, String datasetURI, List<String> featureURIs,
        String predictionFeatureURI, IProgressMonitor monitor)
        throws HttpException, IOException, InterruptedException, GeneralSecurityException {
    if (monitor == null)
        monitor = new NullProgressMonitor();
    int worked = 0;

    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(algoURI);
    HttpMethodHelper.addMethodHeaders(method, new HashMap<String, String>() {
        {//from   w w w  .j a va2s  . com
            put("Accept", "text/uri-list");
        }
    });
    // add the features etc to the URI
    datasetURI = datasetURI + "?" + asFeatureURIString(featureURIs) + "&max=100";
    logger.debug("create model, datasetURI: " + datasetURI);
    method.setParameter("dataset_uri", datasetURI);
    method.setParameter("prediction_feature", predictionFeatureURI);
    client.executeMethod(method);
    int status = method.getStatusCode();
    String modelURI = "";
    // FIXME: I should really start using the RDF response...
    String responseString = method.getResponseBodyAsString();
    logger.debug("Status: " + status);
    int tailing = 1;
    if (status == 200 || status == 202) {
        if (responseString.contains("/task/")) {
            // OK, we got a task... let's wait until it is done
            String task = responseString;
            logger.debug("response: " + task);
            Thread.sleep(andABit(500)); // let's be friendly, and wait 1 sec
            TaskState state = Task.getState(task);
            while (!state.isFinished() && !monitor.isCanceled()) {
                int onlineWorked = (int) state.getPercentageCompleted();
                if (onlineWorked > worked) {
                    // work done is difference between done before and online done
                    monitor.worked(onlineWorked - worked);
                    worked = onlineWorked;
                }
                // let's be friendly, and wait 2 secs and a bit and increase
                // that time after each wait
                int waitingTime = andABit(2000 * tailing);
                logger.debug("Waiting " + waitingTime + "ms.");
                waitUnlessInterrupted(waitingTime, monitor);
                state = Task.getState(task);
                if (state.isRedirected()) {
                    task = state.getResults();
                    logger.debug("Got a Task redirect. New task:" + task);
                }
                // but wait at most 20 secs and a bit
                if (tailing < 10)
                    tailing++;
            }
            if (monitor.isCanceled())
                Task.delete(task);
            // OK, it should be finished now
            modelURI = state.getResults();
        } else {
            // OK, that was quick!
            modelURI = responseString;
            logger.debug("No Task, Data set: " + modelURI);
            monitor.worked(100);
        }
    } else if (status == 401) {
        throw new GeneralSecurityException("Not authenticated");
    } else if (status == 403) {
        throw new GeneralSecurityException("Not authorized");
    } else if (status == 404) {
        logger.debug("Model not found (404): " + responseString);
        throw new UnsupportedOperationException("Service not found");
    } else {
        logger.debug("Model error (" + status + "): " + responseString);
        throw new IllegalStateException("Service error: " + status);
    }
    method.releaseConnection();
    modelURI = modelURI.replaceAll("\n", "");
    return modelURI;
}