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:net.bioclipse.opentox.api.MolecularDescriptorAlgorithm.java

public static String calculate(String service, String descriptor, String dataSetURI, IProgressMonitor monitor)
        throws HttpException, IOException, InterruptedException, GeneralSecurityException {
    if (monitor == null)
        monitor = new NullProgressMonitor();

    HttpClient client = new HttpClient();
    dataSetURI = Dataset.normalizeURI(dataSetURI);
    PostMethod method = new PostMethod(descriptor);

    HttpMethodHelper.addMethodHeaders(method, new HashMap<String, String>() {
        {//ww  w .  ja  v a 2s.co m
            put("Accept", "text/uri-list");
        }
    });
    method.setParameter("dataset_uri", dataSetURI);
    method.setParameter("dataset_service", service + "dataset");
    logger.debug("Calculating: " + descriptor);
    logger.debug("  with data set: " + dataSetURI);
    client.executeMethod(method);
    int status = method.getStatusCode();
    logger.debug("  -> return status: " + status);
    String dataset = "";
    // FIXME: I should really start using the RDF response...
    String responseString = method.getResponseBodyAsString();
    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("OK, we got a task assigned: " + task);
            Thread.sleep(andABit(500)); // let's be friendly, and wait 1 sec
            TaskState state = Task.getState(task);
            while (!state.isFinished() && !monitor.isCanceled()) {
                // 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("  new task, 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
            dataset = state.getResults();
        } else {
            // OK, that was quick!
            dataset = responseString;
        }
    } else if (status == 401) {
        throw new GeneralSecurityException("Not authenticated");
    } else if (status == 403) {
        throw new GeneralSecurityException("Not authorized");
    } else {
        throw new IllegalStateException("Service error: " + status);
    }
    method.releaseConnection();
    dataset = dataset.replaceAll("\n", "");
    return dataset;
}

From source file:org.apache.shindig.common.crypto.Crypto.java

/**
 * Verifies an HMAC SHA1 hash.  Throws if the verification fails.
 * //from w  w  w. j a va2s. co  m
 * @param key
 * @param in
 * @param expected
 * @throws GeneralSecurityException
 */
public static void hmacSha1Verify(byte[] key, byte[] in, byte[] expected) throws GeneralSecurityException {
    Mac hmac = Mac.getInstance(HMAC_TYPE);
    Key hmacKey = new SecretKeySpec(key, HMAC_TYPE);
    hmac.init(hmacKey);
    hmac.update(in);
    byte actual[] = hmac.doFinal();
    if (actual.length != expected.length) {
        throw new GeneralSecurityException("HMAC verification failure");
    }
    for (int i = 0; i < actual.length; i++) {
        if (actual[i] != expected[i]) {
            throw new GeneralSecurityException("HMAC verification failure");
        }
    }
}

From source file:org.glite.slcs.pki.bouncycastle.PKCS10.java

/**
 * //  ww  w  . j a v  a  2  s  .c  om
 * @param subject
 * @param publicKey
 * @param privateKey
 * @param x509Extensions
 * @throws GeneralSecurityException
 */
public PKCS10(String subject, PublicKey publicKey, PrivateKey privateKey, X509Extensions x509Extensions)
        throws GeneralSecurityException {
    // subject DN
    X509PrincipalUtil util = new X509PrincipalUtil();
    X509Principal principal = util.createX509Principal(subject);
    LOG.debug("X509Principal: " + principal);
    // extensions
    ASN1Set attributes = new DERSet();
    if (x509Extensions != null) {
        // PKCS9 extensions
        DERSet extensions = new DERSet(x509Extensions);
        Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensions);
        attributes = new DERSet(attribute);
    }
    // create CSR
    bcPKCS10_ = new PKCS10CertificationRequest(SIGNATURE_ALGORITHM, principal, publicKey, attributes,
            privateKey);
    // verify
    if (!bcPKCS10_.verify()) {
        LOG.error("Failed to verify the PKCS#10");
        throw new GeneralSecurityException("PKCS#10 verification failed");
    }

}

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

/**
 * Loads an X.509 certificate from the specified file. The certificate file
 * must be in PEM/Base64 format and start with "BEGIN CERTIFICATE" and end
 * with "END CERTIFICATE" line./*from ww  w . j  a va 2s .  c om*/
 *
 * @param file the file to load the certificate from.
 * @return <code>java.security.cert.X509Certificate</code> the loaded
 *         certificate.
 * @throws IOException              if I/O error occurs
 * @throws GeneralSecurityException if security problems occurs.
 */
public static X509Certificate loadCertificate(String file) throws IOException, GeneralSecurityException {

    if (file == null) {
        throw new IllegalArgumentException("Certificate file is null");
        //i18n
        //  .getMessage("certFileNull"));
    }

    X509Certificate cert = null;

    BufferedReader reader = new BufferedReader(new FileReader(file));
    try {
        cert = readCertificate(reader);
    } finally {
        reader.close();
    }

    if (cert == null) {
        throw new GeneralSecurityException("No certificate data");
        //i18n.getMessage("noCertData"));
    }

    return cert;
}

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

@SuppressWarnings("serial")
public static String calculate(String service, String model, String dataSetURI, IProgressMonitor monitor)
        throws HttpException, IOException, InterruptedException, GeneralSecurityException {
    if (monitor == null)
        monitor = new NullProgressMonitor();
    int worked = 0;

    HttpClient client = new HttpClient();
    dataSetURI = Dataset.normalizeURI(dataSetURI);
    PostMethod method = new PostMethod(model);
    HttpMethodHelper.addMethodHeaders(method, new HashMap<String, String>() {
        {//from ww w.j  av a 2s  .co m
            put("Accept", "text/uri-list");
        }
    });
    method.setParameter("dataset_uri", dataSetURI);
    method.setParameter("dataset_service", service + "dataset");
    client.executeMethod(method);
    int status = method.getStatusCode();
    String dataset = "";
    // 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
            dataset = state.getResults();
        } else {
            // OK, that was quick!
            dataset = responseString;
            logger.debug("No Task, Data set: " + dataset);
            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();
    dataset = dataset.replaceAll("\n", "");
    return dataset;
}

From source file:labr_client.Public.encryption.java

public static String encode(String dec) throws GeneralSecurityException {
    // Generate 128 bits of random data for use as the IV. It is important to use a different IV for
    // each encrypted block of text, to ensure that the same string encrypted by two different people
    // does not give the same encrypted text string - that leads to obvious attack possibilities. Note
    // however that the IV does not need to be kept secret; it is a little bit like a 'salt' for a
    // password, which improves security even when the salt is stored in plaintext in a database or
    // prefixed to the encrypted file.
    byte[] ivData = new byte[AES_NIVBITS / 8]; //Hoe groot is deze array -> 128/8 = 16
    Random r = new Random(); // Note: no  seed here, ie these values are truly random
    r.nextBytes(ivData);//from ww  w .j  a  v a2 s  .  c o m
    ////        try {
    ////            System.out.println(new String(ivData, "UTF-8")); // for UTF-8 encoding
    ////        } catch (UnsupportedEncodingException ex) {
    ////            Logger.getLogger(encryption.class.getName()).log(Level.SEVERE, null, ex);
    ////        }
    //        ivData[0] = Byte.valueOf("100");
    //        ivData[1] = Byte.valueOf("1");
    //        ivData[2] = Byte.valueOf("15");
    //        ivData[3] = Byte.valueOf("50");
    //        ivData[4] = Byte.valueOf("70");
    //        ivData[5] = Byte.valueOf("80");
    //        ivData[6] = Byte.valueOf("5");
    //        ivData[7] = Byte.valueOf("45");
    //        ivData[8] = Byte.valueOf("100");
    //        ivData[9] = Byte.valueOf("1");
    //        ivData[10] = Byte.valueOf("15");
    //        ivData[11] = Byte.valueOf("50");
    //        ivData[12] = Byte.valueOf("70");
    //        ivData[13] = Byte.valueOf("80");
    //        ivData[14] = Byte.valueOf("5");
    //        ivData[15] = Byte.valueOf("45");
    // Select encryption algorithm and padding : AES with CBC and PCKS#7

    //byte[] ivData = new sun.misc.BASE64Decoder().decodeBuffer(salt);
    BlockCipherPadding padding = new PKCS7Padding();
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);

    // Encrypt the input string using key + iv
    KeyParameter keyParam = getAesKey();
    CipherParameters params = new ParametersWithIV(keyParam, ivData);

    cipher.reset();
    cipher.init(true, params); // first param = encode/decode

    byte[] bytesDec = dec.getBytes(UTF8); // data to decode

    byte[] bytesEnc;
    try {
        int buflen = cipher.getOutputSize(bytesDec.length);
        bytesEnc = new byte[buflen];
        int nBytesEnc = cipher.processBytes(bytesDec, 0, bytesDec.length, bytesEnc, 0);
        nBytesEnc += cipher.doFinal(bytesEnc, nBytesEnc);

        if (nBytesEnc != bytesEnc.length) {
            throw new IllegalStateException("Unexpected behaviour : getOutputSize value incorrect");
        }
    } catch (InvalidCipherTextException | RuntimeException e) {
        throw new GeneralSecurityException("encryption failed");
    }

    // Return a base-64-encoded string containing IV + encrypted input string
    byte[] bytesAll = new byte[ivData.length + bytesEnc.length];
    arraycopy(ivData, 0, bytesAll, 0, ivData.length);
    arraycopy(bytesEnc, 0, bytesAll, ivData.length, bytesEnc.length);
    out.println(new String(encodeBase64(bytesAll), UTF8));
    return new String(encodeBase64(bytesAll), UTF8);
}

From source file:org.globus.gsi.bc.BouncyCastleOpenSSLKey.java

protected PrivateKey getKey(String alg, byte[] data) throws GeneralSecurityException {
    if (alg.equals("RSA")) {
        try {// w w w. j  a v a  2s  . co  m
            if (data.length == 0) {
                throw new GeneralSecurityException("Cannot process empty byte stream.");
            }
            ByteArrayInputStream bis = new ByteArrayInputStream(data);
            ASN1InputStream derin = new ASN1InputStream(bis);
            ASN1Primitive keyInfo = derin.readObject();

            DERObjectIdentifier rsaOid = PKCSObjectIdentifiers.rsaEncryption;
            AlgorithmIdentifier rsa = new AlgorithmIdentifier(rsaOid);
            PrivateKeyInfo pkeyinfo = new PrivateKeyInfo(rsa, keyInfo);
            ASN1Primitive derkey = pkeyinfo.toASN1Primitive();
            byte[] keyData = BouncyCastleUtil.toByteArray(derkey);
            // The DER object needs to be mangled to
            // create a proper ProvateKeyInfo object
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyData);
            KeyFactory kfac = KeyFactory.getInstance("RSA");

            return kfac.generatePrivate(spec);
        } catch (IOException e) {
            // that should never happen
            return null;
        }

    } else {
        return null;
    }
}

From source file:org.carewebframework.api.security.CipherUtil.java

/**
 * Validates the timestamp and insures that it falls within the specified duration.
 * //ww w .  j  a v a 2 s  . c om
 * @param timestamp Timestamp in yyyyMMddHHmmssz format.
 * @param duration Validity duration in minutes.
 * @throws Exception Unspecified exception.
 */
public static void validateTime(String timestamp, int duration) throws Exception {
    Date date = getTimestampFormatter().parse(timestamp);
    long sign_time = date.getTime();
    long now_time = System.currentTimeMillis();
    long diff = now_time - sign_time;
    long min_diff = diff / (60 * 1000);

    if (min_diff >= duration) {
        throw new GeneralSecurityException("Authorization token has expired.");
    }
}

From source file:piecework.security.concrete.ExampleBouncyCastleEncryptionService.java

@Override
public Secret encrypt(String text)
        throws InvalidCipherTextException, UnsupportedEncodingException, GeneralSecurityException {
    BufferedBlockCipher cipher = cipher();

    SecretKeyRing secretKeyRing = keyProvider.getEncryptionKeyRing(null, null);

    byte[] key = secretKeyRing.getSecretKey().getEncoded();
    byte[] iv = new byte[cipher.getBlockSize()];

    // Generate a random initialization vector for this encryption
    random.nextBytes(iv);/*from   www  .j  av a2s.c o m*/

    cipher.init(true, new ParametersWithIV(new KeyParameter(key), iv));

    byte[] clear = text.getBytes("UTF-8");
    int outputSize = cipher.getOutputSize(clear.length);
    byte[] hidden = new byte[outputSize];
    int bytesProcessed = cipher.processBytes(clear, 0, clear.length, hidden, 0);
    bytesProcessed += cipher.doFinal(hidden, bytesProcessed);

    if (bytesProcessed != hidden.length)
        throw new GeneralSecurityException("Unable to correctly encrypt input data");

    return new Secret.Builder().id(uuidGenerator.getNextId()).name(secretKeyRing.getKeyName()).date(new Date())
            .ciphertext(Base64.encode(hidden)).iv(Base64.encode(iv)).build();
}

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

@Override
public void init() throws MalformedURLException, GeneralSecurityException {
    Security.addProvider(new BouncyCastleProvider());
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(KEY_ALGORITHM, "BC");
    kpg.initialize(KEY_SIZE);/*from  w  w w.  j a va  2s . c  o  m*/
    caKeyPair = kpg.genKeyPair();

    X500NameBuilder subjectBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    subjectBuilder.addRDN(BCStyle.CN, "RootCA");

    try {
        sigGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider("BC")
                .build(caKeyPair.getPrivate());
        X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(subjectBuilder.build(),
                BigInteger.ONE, new Date(), new Date(System.currentTimeMillis() + 600000),
                subjectBuilder.build(), caKeyPair.getPublic());
        caCert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));

        caCert.checkValidity();
        caCert.verify(caKeyPair.getPublic());
        caCert.verify(caCert.getPublicKey());
    } catch (OperatorCreationException ex) {
        throw new GeneralSecurityException(ex);
    }
}