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:org.globus.gsi.util.CertificateLoadUtil.java

public static X509CRL loadCrl(String file) throws IOException, GeneralSecurityException {

    if (file == null) {
        throw new IllegalArgumentException("crlFileNull");
        //i18n.getMessage("crlFileNull"));
    }/*from w  w  w. j  a  v a  2 s  . c  o m*/

    boolean isCrl = false;
    X509CRL crl = null;

    BufferedReader reader;

    String line;
    StringBuffer buff = new StringBuffer();

    reader = new BufferedReader(new FileReader(file));

    try {
        while ((line = reader.readLine()) != null) {
            if (line.indexOf("BEGIN X509 CRL") != -1) {
                isCrl = true;
            } else if (isCrl && line.indexOf("END X509 CRL") != -1) {
                byte[] data = Base64.decode(buff.toString().getBytes());
                crl = loadCrl(new ByteArrayInputStream(data));
            } else if (isCrl) {
                buff.append(line);
            }
        }
    } finally {
        reader.close();
    }

    if (crl == null) {
        throw new GeneralSecurityException("noCrlsData");
        //i18n.getMessage("noCrlData"));
    }

    return crl;
}

From source file:uk.ac.ox.webauth.Token.java

/**
 * Initialise a token with a base64 encoded Webauth token.
 * @param   tokenData   The data to be decrypted.
 * @param   sessionKey  The session key to use for the AES and Hmac.
 * @throws  GeneralSecurityException    if there was a problem with the security code used.
 *//*from  www  .ja  v a  2s  .  c  om*/
public Token(byte[] tokenData, Key sessionKey) throws GeneralSecurityException {
    // a token is:
    // {key-hint}{nonce   }{hmac    }{token-attributes     }{padding         }
    // {4 bytes }{16 bytes}{20 bytes}{make the data into multiple of 16 bytes}
    // everything after the key hint is aes encrypted

    try {
        // set up some streams
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tokenData);
        DataInputStream dataInputStream = new DataInputStream(byteArrayInputStream);

        // read the key hint
        int keyHint = dataInputStream.readInt();

        // prepare to AES decrypt the rest
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(DECRYPT_MODE, sessionKey, IV);
        CipherInputStream decrypt = new CipherInputStream(byteArrayInputStream, cipher);

        // throw away the nonce
        if (decrypt.read(new byte[16]) != 16) {
            throw new GeneralSecurityException("Failed to read nonce from token.");
        }

        // read the HMACSHA1 checksum
        byte[] checksum = new byte[20];
        if (decrypt.read(checksum) != 20) {
            throw new GeneralSecurityException("Failed to read HMAC SHA1 checksum from token.");
        }

        // read in the rest of the data
        ByteArrayOutputStream tokenByteArrayOutputStream = new ByteArrayOutputStream();
        for (int b = decrypt.read(); b != -1; b = decrypt.read()) {
            tokenByteArrayOutputStream.write(b);
        }
        byte[] data = tokenByteArrayOutputStream.toByteArray();
        decrypt.close();

        // check the hmacsha1
        Mac hmacSHA1 = Mac.getInstance("HmacSHA1");
        hmacSHA1.init(sessionKey);
        if (!Arrays.equals(checksum, hmacSHA1.doFinal(data))) {
            throw new GeneralSecurityException("Invalid token, checksum mismatch.");
        }

        // create all the key-value pairs
        for (int i = 0, start = 0; (i = indexOf(SEMI_COLON, data, i)) != -1;) {
            i++;
            if (i < data.length && data[i] == SEMI_COLON) {
                i++;
                continue;
            }
            byte[] keyValuePairArray = new byte[i - start];
            System.arraycopy(data, start, keyValuePairArray, 0, keyValuePairArray.length);
            KeyValuePair kvp = new KeyValuePair(keyValuePairArray);
            kv.put(new String(kvp.key(), "US-ASCII"), kvp);
            start = i;
        }
    } catch (IOException ioe) {
        /* should never happen as it's a ByteArrayInputStream */
        ioe.printStackTrace();
    }
    valid = true;

    // create the Stringifier to use
    stringifier = new WebauthTokenStringifier();
}

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

private void createTrustManagers(SSLFactory.Mode mode) throws IOException, GeneralSecurityException {
    String truststoreType = conf.get(resolvePropertyName(mode, SSL_TRUSTSTORE_TYPE_TPL_KEY),
            DEFAULT_KEYSTORE_TYPE);//from  ww  w  .  ja  va 2  s. c o  m

    String locationProperty = resolvePropertyName(mode, SSL_TRUSTSTORE_LOCATION_TPL_KEY);
    String truststoreLocation = conf.get(locationProperty, "");

    String passwordFileLocationProperty = resolvePropertyName(mode, SSL_PASSWORDFILE_LOCATION_TPL_KEY);
    String passwordFileLocation = conf.get(passwordFileLocationProperty, null);

    if (!truststoreLocation.isEmpty()) {
        String passwordProperty = resolvePropertyName(mode, SSL_TRUSTSTORE_PASSWORD_TPL_KEY);
        String truststorePassword = getPassword(conf, passwordProperty, "");
        if (truststorePassword.isEmpty()) {
            throw new GeneralSecurityException(
                    "The property '" + passwordProperty + "' has not been set in the ssl configuration file.");
        }
        long truststoreReloadInterval = conf.getLong(
                resolvePropertyName(mode, SSL_TRUSTSTORE_RELOAD_INTERVAL_TPL_KEY),
                DEFAULT_SSL_TRUSTSTORE_RELOAD_INTERVAL);

        if (LOG.isDebugEnabled()) {
            LOG.debug(mode.toString() + " TrustStore: " + truststoreLocation);
        }

        trustManager = new ReloadingX509TrustManager(truststoreType, truststoreLocation, truststorePassword,
                passwordFileLocation, truststoreReloadInterval);
        trustManager.init();
        if (LOG.isDebugEnabled()) {
            LOG.debug(mode.toString() + " Loaded TrustStore: " + truststoreLocation);
        }
        trustManagers = new TrustManager[] { trustManager };
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("The property '" + locationProperty + "' has not been set, "
                    + "no TrustStore will be loaded");
        }
        trustManagers = null;
    }
}

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

/**
 * Encrypt the given data with our key, prepending saltLength random
 * characters./* w w  w  .jav  a 2s  .c  o m*/
        
 * @return Base64 encoded representation of the encrypted data.
 */
String encrypt(String data, int saltLength) throws GeneralSecurityException {
    log("encrypt()");
    try {
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    } catch (InvalidKeyException ike) {
        throw new GeneralSecurityException("InvalidKeyException: " + ike.getLocalizedMessage()
                + "\nYou (probably) need to " + "install the \"Java Cryptography Extension (JCE) "
                + "Unlimited Strength Jurisdiction Policy\" files.  Go to "
                + "http://java.sun.com/javase/downloads/index.jsp, download them, "
                + "and follow the instructions.");
    }
    String salted = saltString(saltLength, data);
    byte[] crypted;
    byte[] saltedBytes;
    try {
        saltedBytes = salted.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new GeneralSecurityException(e.getLocalizedMessage());
    }
    crypted = cipher.doFinal(saltedBytes);
    return Base64.encodeBytes(crypted);
}

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

/**
 * @param key//from  w w  w . j  a  v  a 2  s  .  co  m
 * @param certs
 * @param algo
 * @param mp
 * @return
 * @throws NoSuchAlgorithmException
 * @throws CertStoreException
 * @throws InvalidAlgorithmParameterException
 * @throws MessagingException
 * @throws CertificateEncodingException
 * @throws GeneralSecurityException
 */
public static Multipart smimeDigSig(PrivateKey key, Certificate[] certs, SigningAlgo algo, Multipart mp)
        throws NoSuchAlgorithmException, CertStoreException, InvalidAlgorithmParameterException,
        MessagingException, CertificateEncodingException, GeneralSecurityException {

    tstObjArg("certificate(s)", certs);
    tstObjArg("private-key", key);
    tstObjArg("multipart", mp);
    tstObjArg("algo", algo);

    SMIMESignedGenerator gen = makeSignerGentor(key, certs, algo);
    MimeMessage mm = newMimeMsg();
    mm.setContent(mp);
    try {
        mp = gen.generate(mm, Crypto.getInstance().getProvider());
    } catch (SMIMEException e) {
        throw new GeneralSecurityException(e);
    }
    /*                
            MimeBodyPart dummy= new MimeBodyPart();
            dummy.setContent(mp);
            mp= gen.generate(dummy, PROV);
    */
    return mp;
}

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

String decrypt(String cryptext) throws GeneralSecurityException {
    log("decrypt()");
    try {//from  www.j a  va2  s.  c  o  m
        cipher.init(Cipher.DECRYPT_MODE, key, iv);
    } catch (InvalidKeyException ike) {
        throw new GeneralSecurityException("InvalidKeyException: " + ike.getLocalizedMessage()
                + "\nYou (probably) need to " + "install the \"Java Cryptography Extension (JCE) "
                + "Unlimited Strength Jurisdiction Policy\" files.  Go to "
                + "http://java.sun.com/javase/downloads/index.jsp, download them, "
                + "and follow the instructions.");
    }
    byte[] crypted;
    try {
        crypted = Base64.decode(cryptext);
    } catch (IOException e) {
        throw new GeneralSecurityException(e.getLocalizedMessage());
    }
    byte[] decrypted = cipher.doFinal(crypted);
    String salted;
    try {
        salted = new String(decrypted, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new GeneralSecurityException(e.getLocalizedMessage());
    }
    // Remove any leading non-JSON salt characters
    return salted.replaceAll("^[^\\{]*\\{", "{");
}

From source file:org.auscope.portal.server.web.controllers.GridLoginController.java

/**
 * Processes the SLCS response and tries to generate a grid proxy from
 * the extracted certificate and key./* w  w  w  . j  a va 2  s.co m*/
 */
private void processSlcsResponse(HttpServletRequest request) throws GeneralSecurityException, Exception {

    String slcsResponse = extractSlcsResponse(request);
    logger.debug("SLCSResponse:\n" + slcsResponse);
    RequestData rd = parseRequestData(slcsResponse);

    String certCN = rd.certDN.split("CN=")[1];
    String shibCN = (String) request.getSession().getAttribute("Shib-Person-commonName") + " "
            + (String) request.getSession().getAttribute("Shib-Shared-Token");
    logger.info("SessionID: |" + request.getSession().getId() + "|;  shibCN: |" + shibCN + "|");
    if (!certCN.equals(shibCN)) {
        logger.error(certCN + " != " + shibCN);
        throw new GeneralSecurityException("Certificate is not for current user!");
    }

    CertificateKeys certKeys = new CertificateKeys(2048, new char[0]);
    CertificateRequest req = new CertificateRequest(certKeys, rd.certDN, rd.certExtensions);

    logger.info("Requesting signed certificate...");
    URL certRespURL = new URL(SLCS_URL + "certificate?AuthorizationToken=" + rd.authToken
            + "&CertificateSigningRequest=" + URLEncoder.encode(req.getPEMEncoded(), "UTF-8"));
    BufferedReader certRespReader = new BufferedReader(new InputStreamReader(certRespURL.openStream()));
    StringBuffer certResp = new StringBuffer();

    String inputLine;
    while ((inputLine = certRespReader.readLine()) != null) {
        certResp.append(inputLine);
        certResp.append('\n');
    }
    certRespReader.close();

    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(certResp.toString().trim()));
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(is);
    String status = doc.getElementsByTagName("Status").item(0).getFirstChild().getNodeValue();

    logger.info("Response status: " + status);
    if (!status.equals("Error")) {
        String certStr = doc.getElementsByTagName("Certificate").item(0).getFirstChild().getNodeValue();
        InputStream in = new ByteArrayInputStream(certStr.getBytes());
        X509Certificate certificate = CertUtil.loadCertificate(in);

        Object credential = gridAccess.initProxy(certKeys.getPrivate(), certificate, PROXY_LIFETIME);
        if (credential == null) {
            throw new Exception("Proxy generation failed");
        } else {
            logger.info("Storing credentials in session.");
            request.getSession().setAttribute("userCred", credential);
        }
    }
    logger.debug("certDN: " + rd.certDN);
    request.getSession().setAttribute("certDN", rd.certDN);
}

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

protected void loadMasterJWT() throws GeneralSecurityException {
    masterToken = sslConf.get(YarnConfiguration.RM_JWT_MASTER_TOKEN);
    if (masterToken == null) {
        throw new GeneralSecurityException("Could not parse JWT from configuration");
    }//  w  w w .ja  va2  s. c o  m
    authHeader.set(createAuthenticationHeader(masterToken));
    try {
        JWT jwt = JWTParser.parse(masterToken);
        masterTokenExpiration = DateUtils.date2LocalDateTime(jwt.getJWTClaimsSet().getExpirationTime());
    } catch (ParseException ex) {
        throw new GeneralSecurityException("Could not parse master JWT", ex);
    }
}

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

/**
 * @param key//  ww w  .j  av  a2s .  c  o m
 * @param certs
 * @param algo
 * @param bp
 * @return
 * @throws NoSuchAlgorithmException
 * @throws CertStoreException
 * @throws InvalidAlgorithmParameterException
 * @throws CertificateEncodingException
 * @throws GeneralSecurityException
 */
public static Multipart smimeDigSig(PrivateKey key, Certificate[] certs, SigningAlgo algo, BodyPart bp)
        throws NoSuchAlgorithmException, CertStoreException, InvalidAlgorithmParameterException,
        CertificateEncodingException, GeneralSecurityException {

    tstArgIsType("bodypart", bp, MimeBodyPart.class);
    tstObjArg("certificate(s)", certs);
    tstObjArg("private-key", key);
    tstObjArg("algo", algo);

    try {
        return makeSignerGentor(key, certs, algo).generate((MimeBodyPart) bp,
                Crypto.getInstance().getProvider());
    } catch (SMIMEException e) {
        throw new GeneralSecurityException(e);
    }
}

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

protected void loadRenewalJWTs() throws GeneralSecurityException {
    String renewToken = null;/*from  w  w  w.j av  a  2  s . c  o m*/
    List<String> renewalTokens = new ArrayList<>();
    int idx = 0;
    while (true) {
        String renewTokenKey = String.format(YarnConfiguration.RM_JWT_RENEW_TOKEN_PATTERN, idx);
        renewToken = sslConf.get(renewTokenKey, "");
        if (renewToken.isEmpty()) {
            break;
        }
        renewalTokens.add(renewToken);
        idx++;
    }
    if (renewalTokens.isEmpty()) {
        throw new GeneralSecurityException("Could not load one-time renewal JWTs");
    }
    this.renewalTokens = renewalTokens.toArray(new String[renewalTokens.size()]);
}