Example usage for java.lang SecurityException SecurityException

List of usage examples for java.lang SecurityException SecurityException

Introduction

In this page you can find the example usage for java.lang SecurityException SecurityException.

Prototype

public SecurityException(String message, Throwable cause) 

Source Link

Document

Creates a SecurityException with the specified detail message and cause.

Usage

From source file:org.jolokia.jvmagent.JolokiaHttpHandler.java

/**
 * Handle a request. If the handler is not yet started, an exception is thrown. If running with JAAS
 * security enabled it will run as the given subject.
 *
 * @param pHttpExchange the request/response object
 * @throws IOException if something fails during handling
 * @throws IllegalStateException if the handler has not yet been started
 *///from  www . ja va2s.  co m
public void handle(final HttpExchange pHttpExchange) throws IOException {
    Subject subject = (Subject) pHttpExchange.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE);
    if (subject != null) {
        try {
            Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {
                public Void run() throws IOException {
                    doHandle(pHttpExchange);
                    return null;
                }
            });
        } catch (PrivilegedActionException e) {
            throw new SecurityException("Security exception: " + e.getCause(), e.getCause());
        }
    } else {
        doHandle(pHttpExchange);
    }
}

From source file:edu.internet2.middleware.openid.security.SecurityUtils.java

/**
 * Build the Key-Value Form encoded string of parameters used to calculate a signature. The result of this method is
 * suitable for passing to {@link #calculateSignature(Association, String)}.
 * //w w w. j a  v a 2s .co  m
 * @param parameters message parameter map
 * @param signedFields list of fields to include in the signature data
 * @return Key-Value Form encoded string of parameters
 * @throws SecurityException if unable to build the signature data
 */
public static String buildSignatureData(ParameterMap parameters, List<QName> signedFields)
        throws SecurityException {
    log.debug("building signature data with parameters: {}", signedFields);
    Map<String, String> signedParameters = new LinkedHashMap<String, String>();

    for (QName field : signedFields) {
        String parameterName = EncodingUtils.encodeParameterName(field, parameters.getNamespaces());
        if (field instanceof NamespaceQName) {
            signedParameters.put(parameterName, field.getNamespaceURI());
        } else {
            signedParameters.put(parameterName, parameters.get(field));
        }
    }

    try {
        return KeyValueFormCodec.getInstance().encode(signedParameters);
    } catch (EncodingException e) {
        log.error("Unable to sign data - " + e.getMessage());
        throw new SecurityException("Unable to sign data", e);
    }
}

From source file:org.jolokia.jvmagent.handler.JolokiaHttpHandler.java

private void doHandleAs(Subject subject, final HttpExchange pHttpExchange) {
    try {/*  ww w.j  a v a  2s .c  om*/
        Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {
            public Void run() throws IOException {
                doHandle(pHttpExchange);
                return null;
            }
        });
    } catch (PrivilegedActionException e) {
        throw new SecurityException("Security exception: " + e.getCause(), e.getCause());
    }
}

From source file:com.cws.esolutions.security.utils.PasswordUtils.java

/**
 * Provides one-way (irreversible) encryption of a provided string.
 *
 * @param plainText - The plain text data to encrypt
 * @param salt - The salt value to utilize for the request
 * @param instance - The security instance to utilize
 * @param iterations - The number of times the value should be re-encrypted
 * @param encoding - The text encoding/*w w w.j a  va  2  s  .co m*/
 * @return The encrypted string
 * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing
 */
public static final String encryptText(final String plainText, final String salt, final String instance,
        final int iterations, final String encoding) throws SecurityException {
    final String methodName = PasswordUtils.CNAME
            + "#encryptText(final String plainText, final String salt, final String algorithm, final String instance, final int iterations, final String encoding) throws SecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", plainText);
        DEBUGGER.debug("Value: {}", salt);
        DEBUGGER.debug("Value: {}", instance);
        DEBUGGER.debug("Value: {}", iterations);
        DEBUGGER.debug("Value: {}", encoding);
    }

    String response = null;

    try {
        MessageDigest md = MessageDigest.getInstance(instance);
        md.reset();
        md.update(salt.getBytes(encoding));
        byte[] input = md.digest(plainText.getBytes(encoding));

        for (int x = 0; x < iterations; x++) {
            md.reset();
            input = md.digest(input);
        }

        response = Base64.getEncoder().encodeToString(input);
    } catch (NoSuchAlgorithmException nsx) {
        throw new SecurityException(nsx.getMessage(), nsx);
    } catch (UnsupportedEncodingException uex) {
        throw new SecurityException(uex.getMessage(), uex);
    }

    return response;
}

From source file:edu.internet2.middleware.openid.security.SecurityUtils.java

/**
 * Calculate signature for specified data using an Association.
 * /*  w w  w .  j a v a  2 s.  co  m*/
 * @param association association
 * @param data data to calculate signature for
 * @return calculated signature
 * @throws SecurityException if unable to calculate the signature
 */
public static String calculateSignature(Association association, String data) throws SecurityException {
    log.debug("calculating signature using association: {}", association.getHandle());
    log.debug("signature data = {}", data);

    try {
        Mac mac = Mac.getInstance(association.getMacKey().getAlgorithm());
        mac.init(association.getMacKey());

        byte[] rawHmac = mac.doFinal(data.getBytes());
        return new String(Base64.encodeBase64(rawHmac));
    } catch (InvalidKeyException e) {
        log.error("Unable to generate MAC - " + e.getMessage());
        throw new SecurityException("Unable to generate MAC", e);
    } catch (NoSuchAlgorithmException e) {
        log.error("Unable to generate MAC - " + e.getMessage());
        throw new SecurityException("Unable to generate MAC", e);
    }
}

From source file:com.sibvisions.rad.server.security.spring.SpringSecurityManager.java

/**
 * Creates and return the authentication meta data handler.
 * /*from   w ww.  j ava2s . c o m*/
 * @param pProperties properties for the authentication meta data handler
 * @param pSession the session
 * 
 * @return the authentication meta data handler
 */
protected ISpringMetaDataHandler getAuthenticationMetaDataHandler(Hashtable<String, Object> pProperties,
        ISession pSession) {
    Hashtable<String, Object> properties = pProperties;

    if (pProperties == null) {
        pProperties = new Hashtable<String, Object>();
    }

    // append additional configuration properties
    List<XmlNode> propertiesNode = pSession.getConfig()
            .getNodes("/application/securitymanager/preauhtentication/metadtahandler/properties/property");

    if (propertiesNode != null) {
        for (int i = 0, ic = propertiesNode.size(); i < ic; i++) {
            XmlNode property = propertiesNode.get(i);

            XmlNode propertyName = property.getNode("/name");
            XmlNode propertyValue = property.getNode("/value");

            if (propertyName != null && propertyValue != null) {
                properties.put(propertyName.getValue(), propertyValue.getValue());
            }
        }
    }

    // create metadata handler class instance
    String className = pSession.getConfig()
            .getProperty("/application/securitymanager/preauhtentication/metadtahandler/class");

    if (className == null) {
        return new DefaultAuthenticationMetaDataHandler(properties);
    } else {
        try {
            return (ISpringMetaDataHandler) Reflective.construct(ResourceUtil.getResourceClassLoader(this),
                    className, properties);
        } catch (Throwable thr) {
            throw new SecurityException("Access denied! Cannot create spring metadata handler.", thr);
        }
    }
}

From source file:com.facebook.react.modules.location.LocationModule.java

/**
 * Provides a clearer exception message than the default one.
 *///from   w  w w. jav a 2  s.c o  m
private static void throwLocationPermissionMissing(SecurityException e) {
    throw new SecurityException("Looks like the app doesn't have the permission to access location.\n"
            + "Add the following line to your app's AndroidManifest.xml:\n"
            + "<uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\" />", e);
}

From source file:org.openmainframe.ade.impl.PropertyAnnotation.java

@SuppressWarnings({ "unchecked" })
static private void setProps(Object obj, Map<String, ? extends Object> props, Pattern filter, boolean safe)
        throws MissingPropertyException, IllegalArgumentException {
    final Class<?> annotatedClass = obj.getClass();
    final Set<String> keyset = new TreeSet<String>(props.keySet());

    for (Field field : annotatedClass.getDeclaredFields()) {
        final Property annos = field.getAnnotation(Property.class);
        if (annos != null) {
            // skip missing and non-required properties
            final String key = annos.key();
            if (!props.containsKey(key)) {
                if (annos.required()) {
                    throw new MissingPropertyException("Missing property: " + key);
                } else {
                    // no value for non-required property
                    continue;
                }/* ww  w .  j a  v a  2  s.co m*/
            }

            final Class<? extends IPropertyFactory<?>> factoryClass = annos.factory();

            final Object rawVal = props.get(key);
            final Type fieldType = field.getGenericType();
            Object val = null;
            if (factoryClass != Property.NULL_PROPERTY_FACTORY.class) {
                // check if this factory is eligible for creating this property
                final Type factoryProductType = resolveActualTypeArgs(factoryClass, IPropertyFactory.class)[0];
                if (!TypeUtils.isAssignable(factoryProductType, fieldType)) {
                    throw new IllegalArgumentException("The factory provided for the field: " + field.getName()
                            + " is not compatible for creating object of type: " + fieldType);
                }

                Constructor<? extends IPropertyFactory<?>> constructor;
                try {
                    constructor = factoryClass.getConstructor();
                } catch (Exception e) {
                    throw new IllegalArgumentException(
                            "Missing empty constructor in: " + factoryClass.getName(), e);
                }

                IPropertyFactory<?> factory;
                try {
                    factory = constructor.newInstance();
                } catch (Exception e) {
                    throw new IllegalArgumentException("Failed instantiating: " + factoryClass.getName(), e);
                }

                try {
                    val = factory.create(rawVal);
                } catch (Exception e) {
                    throw new IllegalArgumentException("Failed extractring property value: " + key, e);
                }
            } else if (TypeUtils.isAssignable(rawVal.getClass(), fieldType)) {
                val = rawVal;
            } else if (rawVal.getClass().equals(String.class)) {
                final Class<?> fieldClass = field.getType();
                final String stringVal = (String) rawVal;
                if (fieldClass == Integer.class || fieldClass == int.class) {
                    try {
                        val = Integer.parseInt(stringVal);
                    } catch (Exception e) {
                        throw new IllegalArgumentException("Failed parsing integer value for property: " + key,
                                e);
                    }
                } else if (fieldClass == Double.class || fieldClass == double.class) {
                    try {
                        val = Double.parseDouble(stringVal);
                    } catch (Exception e) {
                        throw new IllegalArgumentException("Failed parsing double value for property: " + key,
                                e);
                    }
                } else if (fieldClass == Boolean.class || fieldClass == boolean.class) {
                    try {
                        val = Boolean.parseBoolean(stringVal);
                    } catch (Exception e) {
                        throw new IllegalArgumentException("Failed parsing boolean value for property: " + key,
                                e);
                    }
                } else if (fieldClass == String.class) {
                    // should never have reached here, since String is assignable from String
                    val = stringVal;
                } else if (fieldClass.isEnum()) {
                    Class<Enum> fieldEnum;
                    try {
                        fieldEnum = (Class<Enum>) fieldClass;
                    } catch (ClassCastException e) {
                        throw new IllegalArgumentException(
                                "Failed casting to Class<Enum> field class: " + fieldClass.getName(), e);
                    }
                    try {
                        val = Enum.valueOf(fieldEnum, stringVal);
                    } catch (Exception e) {
                        throw new IllegalArgumentException("Failed parsing enum value for property: " + key
                                + "\n\t possible values: " + Arrays.toString(fieldEnum.getEnumConstants()), e);
                    }
                } else {
                    // try to find String constructor for field, or else throw exception
                    Constructor<?> constructor;
                    try {
                        constructor = fieldClass.getConstructor(String.class);
                    } catch (Exception e) {
                        throw new IllegalArgumentException("Field: " + field.getName() + " of type "
                                + fieldClass
                                + " is not one of the known property type (Integer, Double, Boolean, String, Enum), does not have a String constructor and no custom factory is defined in the annotation!",
                                e);
                    }
                    try {
                        val = constructor.newInstance(stringVal);
                    } catch (Exception e) {
                        throw new IllegalArgumentException("Could not create a new instance for "
                                + field.getName() + " using the String constructor for type: " + fieldClass, e);
                    }
                }
            }

            if (val == null) {
                throw new IllegalArgumentException("For the key " + key
                        + ", we expect the value to be either assignable to " + fieldType + " or a String");
            }

            try {
                field.setAccessible(true);
                field.set(obj, val);
                keyset.remove(key);
            } catch (SecurityException e) {
                throw new SecurityException("Field " + field.getName()
                        + " is not accesible, and could not be set as accesible (probably due to PermissionManager)",
                        e);
            } catch (Exception e) {
                throw new IllegalArgumentException(
                        "Failed setting field: " + field.getName() + " with value: " + val, e);
            }
        }
    }
    if (safe && !keyset.isEmpty()) {
        throw new IllegalArgumentException("Unrecongnized arguments in the properties: " + keyset.toString());
    }
}

From source file:com.cws.esolutions.security.utils.PasswordUtils.java

/**
 * Provides two-way (reversible) encryption of a provided string. Can be used where reversibility
 * is required but encryption (obfuscation, technically) is required.
 *
 * @param value - The plain text data to encrypt
 * @param salt - The salt value to utilize for the request
 * @param secretInstance - The cryptographic instance to use for the SecretKeyFactory
 * @param iterations - The number of times to loop through the keyspec
 * @param keyBits - The size of the key, in bits
 * @param algorithm - The algorithm to encrypt the data with
 * @param cipherInstance - The cipher instance to utilize
 * @param encoding - The text encoding/*from  w w w.j av a2  s.c om*/
 * @return The encrypted string in a reversible format
 * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing
 */
public static final String decryptText(final String value, final String salt, final String secretInstance,
        final int iterations, final int keyBits, final String algorithm, final String cipherInstance,
        final String encoding) throws SecurityException {
    final String methodName = PasswordUtils.CNAME
            + "#encryptText(final String value, final String salt, final String secretInstance, final int iterations, final int keyBits, final String algorithm, final String cipherInstance, final String encoding) throws SecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", secretInstance);
        DEBUGGER.debug("Value: {}", iterations);
        DEBUGGER.debug("Value: {}", keyBits);
        DEBUGGER.debug("Value: {}", algorithm);
        DEBUGGER.debug("Value: {}", cipherInstance);
        DEBUGGER.debug("Value: {}", encoding);
    }

    String decPass = null;

    try {
        String decoded = new String(Base64.getDecoder().decode(value));
        String iv = decoded.split(":")[0];
        String property = decoded.split(":")[1];

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(secretInstance);
        PBEKeySpec keySpec = new PBEKeySpec(salt.toCharArray(), salt.getBytes(), iterations, keyBits);
        SecretKey keyTmp = keyFactory.generateSecret(keySpec);
        SecretKeySpec sks = new SecretKeySpec(keyTmp.getEncoded(), algorithm);

        Cipher pbeCipher = Cipher.getInstance(cipherInstance);
        pbeCipher.init(Cipher.DECRYPT_MODE, sks, new IvParameterSpec(Base64.getDecoder().decode(iv)));
        decPass = new String(pbeCipher.doFinal(Base64.getDecoder().decode(property)), encoding);
    } catch (InvalidKeyException ikx) {
        throw new SecurityException(ikx.getMessage(), ikx);
    } catch (NoSuchAlgorithmException nsx) {
        throw new SecurityException(nsx.getMessage(), nsx);
    } catch (NoSuchPaddingException npx) {
        throw new SecurityException(npx.getMessage(), npx);
    } catch (IllegalBlockSizeException ibx) {
        throw new SecurityException(ibx.getMessage(), ibx);
    } catch (BadPaddingException bpx) {
        throw new SecurityException(bpx.getMessage(), bpx);
    } catch (UnsupportedEncodingException uex) {
        throw new SecurityException(uex.getMessage(), uex);
    } catch (InvalidAlgorithmParameterException iapx) {
        throw new SecurityException(iapx.getMessage(), iapx);
    } catch (InvalidKeySpecException iksx) {
        throw new SecurityException(iksx.getMessage(), iksx);
    }

    return decPass;
}

From source file:info.magnolia.cms.security.SecurityUtil.java

public static String getPrivateKey() {
    String path = SystemProperty.getProperty(KEY_LOCATION_PROPERTY);
    checkPrivateKeyStoreExistence(path);
    try {//  w  w  w. j a  va2 s .  com
        Properties defaultProps = new Properties();
        FileInputStream in = new FileInputStream(path);
        defaultProps.load(in);
        in.close();
        return defaultProps.getProperty(PRIVATE_KEY);
    } catch (FileNotFoundException e) {
        throw new SecurityException(
                "Failed to retrieve private key. Please make sure the key is located in " + path, e);
    } catch (IOException e) {
        throw new SecurityException(
                "Failed to retrieve private key. Please make sure the key is located in " + path, e);
    }
}