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(Throwable cause) 

Source Link

Document

Creates a SecurityException with the specified cause and a detail message of (cause==null ?

Usage

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

public static String encrypt(String message, String encodedKey) {
    try {/*www  . j a v  a2 s .com*/

        // read private key
        if (StringUtils.isBlank(encodedKey)) {
            throw new SecurityException(
                    "Activation key was not found. Please make sure your instance is correctly configured.");
        }
        byte[] binaryKey = hexToByteArray(encodedKey);

        // create RSA public key cipher
        Cipher pkCipher = Cipher.getInstance(ALGORITHM, "BC");
        try {
            // create private key
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(binaryKey);
            KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC");
            PrivateKey pk = kf.generatePrivate(privateKeySpec);

            pkCipher.init(Cipher.ENCRYPT_MODE, pk);
        } catch (InvalidKeySpecException e) {
            // encrypting with public key?
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(binaryKey);
            KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC");
            PublicKey pk = kf.generatePublic(publicKeySpec);

            pkCipher.init(Cipher.ENCRYPT_MODE, pk);
        }

        // encrypt
        byte[] bytes = message.getBytes("UTF-8");
        // split bit message in chunks
        int start = 0;
        StringBuilder chaos = new StringBuilder();
        while (start < bytes.length) {
            byte[] tmp = new byte[Math.min(bytes.length - start, binaryKey.length / 8)];
            System.arraycopy(bytes, start, tmp, 0, tmp.length);
            start += tmp.length;
            byte[] encrypted = pkCipher.doFinal(tmp);
            chaos.append(byteArrayToHex(encrypted));
            chaos.append(";");
        }
        chaos.setLength(chaos.length() - 1);

        return chaos.toString();

    } catch (IOException e) {
        throw new SecurityException(
                "Failed to create authentication string. Please use Java version with cryptography support.",
                e);
    } catch (NoSuchAlgorithmException e) {
        throw new SecurityException(
                "Failed to create authentication string. Please use Java version with cryptography support.",
                e);
    } catch (NoSuchPaddingException e) {
        throw new SecurityException(
                "Failed to create authentication string. Please use Java version with cryptography support.",
                e);
    } catch (InvalidKeySpecException e) {
        throw new SecurityException(
                "Failed to create authentication string. Please use Java version with cryptography support.",
                e);
    } catch (InvalidKeyException e) {
        throw new SecurityException(
                "Failed to create authentication string. Please use Java version with cryptography support.",
                e);
    } catch (NoSuchProviderException e) {
        throw new SecurityException(
                "Failed to find encryption provider. Please use Java version with cryptography support.", e);
    } catch (IllegalBlockSizeException e) {
        throw new SecurityException(
                "Failed to encrypt string. Please use Java version with cryptography support.", e);
    } catch (BadPaddingException e) {
        throw new SecurityException(
                "Failed to encrypt string. Please use Java version with cryptography support.", e);
    }
}

From source file:com.bilibili.boxing.AbsBoxingViewFragment.java

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults) {
    if (REQUEST_CODE_PERMISSION == requestCode) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            onRequestPermissionSuc(requestCode, permissions, grantResults);
        } else {//from   ww w .j  a v a 2 s  .c  om
            onRequestPermissionError(permissions,
                    new SecurityException("request " + permissions[0] + " error."));
        }
    }
}

From source file:com.p2p.peercds.client.SharedTorrent.java

/**
 * Create a new shared torrent from meta-info binary data.
 *
 * @param torrent The meta-info byte data.
 * @param parent The parent directory or location the torrent files.
 * @param seeder Whether we're a seeder for this torrent or not (disables
 * validation).//from   www.j  av  a  2  s . co m
 * @throws FileNotFoundException If the torrent file location or
 * destination directory does not exist and can't be created.
 * @throws IOException If the torrent file cannot be read or decoded.
 */
public SharedTorrent(byte[] torrent, File parent, boolean seeder) throws FileNotFoundException, IOException {
    super(torrent, seeder);

    if (parent == null || !parent.isDirectory()) {
        throw new IllegalArgumentException("Invalid parent directory!");
    }

    String parentPath = parent.getCanonicalPath();

    try {
        this.pieceLength = this.decoded_info.get("piece length").getInt();
        this.piecesHashes = ByteBuffer.wrap(this.decoded_info.get("pieces").getBytes());

        if (this.piecesHashes.capacity() / PIECE_HASH_SIZE * (long) this.pieceLength < this.getSize()) {
            throw new IllegalArgumentException(
                    "Torrent size does not " + "match the number of pieces and the piece size!");
        }
    } catch (InvalidBEncodingException ibee) {
        throw new IllegalArgumentException("Error reading torrent meta-info fields!");
    }

    List<FileStorage> files = new LinkedList<FileStorage>();
    long offset = 0L;
    for (Torrent.TorrentFile file : this.files) {
        File actual = new File(parent, file.file.getPath());

        if (!actual.getCanonicalPath().startsWith(parentPath)) {
            throw new SecurityException("Torrent file path attempted " + "to break directory jail!");
        }

        actual.getParentFile().mkdirs();
        files.add(new FileStorage(actual, offset, file.size));
        offset += file.size;
    }
    this.bucket = new FileCollectionStorage(files, this.getSize());

    this.random = new Random(System.currentTimeMillis());
    this.stop = false;

    this.uploaded = 0;
    this.downloaded = 0;
    this.numBytesFetchedFromCloud = 0;
    this.lastCloudFetchTime = 0;
    this.left = this.getSize();

    this.initialized = false;
    this.pieces = new Piece[0];
    this.rarest = Collections.synchronizedSortedSet(new TreeSet<Piece>());
    this.completedPieces = new BitSet();
    this.requestedPieces = new BitSet();
}

From source file:org.jcommon.com.util.jmx.RmiAdptor.java

public void setCserver(MBeanServer server) throws MalformedURLException, IOException {
    if (port == 0 || name == null || addr == null) {
        throw new NullPointerException("data not be ready");
    }/*from   w  w w .  j  ava2 s.c o m*/
    try {
        registry = LocateRegistry.createRegistry(port);
    } catch (RemoteException e) {

    }
    HashMap<String, Object> prop = new HashMap<String, Object>();
    if (CREDENTIALS != null) {
        authenticator = new JMXAuthenticator() {

            public Subject authenticate(Object credentials) {
                logger.info(credentials.getClass().getName() + " is trying connect...");
                if (credentials instanceof String) {
                    if (credentials.equals(CREDENTIALS)) {
                        return new Subject();
                    }
                } else if (credentials instanceof String[]) {
                    String[] copy = (String[]) credentials;
                    String username = copy.length > 0 ? copy[0] : null;
                    String passwd = copy.length > 1 ? copy[1] : null;
                    logger.info(username + " is trying connect...");
                    if (passwd.equals(CREDENTIALS) && username.equals(user)) {
                        return new Subject();
                    }
                }
                throw new SecurityException("not authicated");
            }
        };

        prop.put(JMXConnectorServer.AUTHENTICATOR, authenticator);
    }
    String url = "service:jmx:rmi:///jndi/rmi://" + addr + ":" + port + "/" + name;
    this.cserver = JMXConnectorServerFactory.newJMXConnectorServer(new JMXServiceURL(url), prop, server);
}

From source file:it.eng.spagobi.commons.filters.ProfileFilter.java

private void authenticate(UsernamePasswordCredentials credentials) throws Throwable {
    logger.debug("IN: userId = " + credentials.getUserName());
    try {//  w  ww . ja va 2  s.  c  o m
        ISecurityServiceSupplier supplier = SecurityServiceSupplierFactory.createISecurityServiceSupplier();
        SpagoBIUserProfile profile = supplier.checkAuthentication(credentials.getUserName(),
                credentials.getPassword());
        if (profile == null) {
            logger.error("Authentication failed for user " + credentials.getUserName());
            throw new SecurityException("Authentication failed");
        }
    } catch (Throwable t) {
        logger.error("Error while authenticating userId = " + credentials.getUserName(), t);
        throw t;
    } finally {
        logger.debug("OUT");
    }

}

From source file:org.geosdi.geoplatform.services.GPPublisherBasicServiceImpl.java

private String manageGeoportalDir(String geoportalDir) {
    File geoportalDirFile;/*from ww w. j a  v  a  2 s. c om*/
    if (geoportalDir != null) {
        geoportalDirFile = new File(geoportalDir);
        if (!geoportalDirFile.exists()) {
            boolean result = false;
            try {
                result = geoportalDirFile.mkdir();
            } catch (Exception e) {
                logger.error("Impossible to create the defined dir, " + "trying to create one in user dir");
            }
            if (!result) {
                geoportalDirFile = PublishUtility.generateGeoPortalDirInUserHome();
            }
        }
    } else {
        geoportalDirFile = PublishUtility.generateGeoPortalDirInUserHome();
    }
    if (!geoportalDirFile.exists()) {
        logger.error("@@@@@@@@@@@ Impossible to create GeoPortalDir @@@@@@@@@@@@@@@@");
        throw new SecurityException("Can't Create " + geoportalDir);
    }
    String pathGeoPortalDir = geoportalDirFile.getAbsolutePath();
    if (!pathGeoPortalDir.endsWith(System.getProperty("file.separator"))) {
        pathGeoPortalDir = pathGeoPortalDir + System.getProperty("file.separator");
    }
    return pathGeoPortalDir;
}

From source file:org.echocat.nodoodle.classloading.FileClassLoader.java

private Class<?> defineClass(String name, Resource resource) throws IOException {
    final int i = name.lastIndexOf('.');
    final URL packageUrl = resource.getPackageUrl();
    if (i != -1) {
        final String packageName = name.substring(0, i);
        // Check if package already loaded.
        final Package pkg = getPackage(packageName);
        final Manifest man = resource.getManifest();
        if (pkg != null) {
            // Package found, so check package sealing.
            if (pkg.isSealed()) {
                // Verify that code source URL is the same.
                if (!pkg.isSealed(packageUrl)) {
                    throw new SecurityException("sealing violation: package " + packageName + " is sealed");
                }//from www.  j a  v  a  2 s  .  c  o  m
            } else {
                // Make sure we are not attempting to seal the package
                // at this code source URL.
                if ((man != null) && isSealed(packageName, man)) {
                    throw new SecurityException(
                            "sealing violation: can't seal package " + packageName + ": already loaded");
                }
            }
        } else {
            if (man != null) {
                definePackage(packageName, man, packageUrl);
            } else {
                definePackage(packageName, null, null, null, null, null, null, null);
            }
        }
    }
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final InputStream inputStream = resource.openStream();
    try {
        IOUtils.copy(inputStream, baos);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
    final byte[] bytes = baos.toByteArray();
    final CodeSigner[] signers = resource.getCodeSigners();
    final CodeSource cs = new CodeSource(packageUrl, signers);
    return defineClass(name, bytes, 0, bytes.length, new ProtectionDomain(cs, new Permissions()));
}

From source file:org.apache.camel.component.linkedin.api.LinkedInOAuthRequestFilter.java

@SuppressWarnings("deprecation")
private String getRefreshToken() {
    // authorize application on user's behalf
    webClient.getOptions().setRedirectEnabled(true);

    try {//  w  w w . ja  v  a2 s.co m
        final String csrfId = String.valueOf(new SecureRandom().nextLong());

        final String encodedRedirectUri = URLEncoder.encode(oAuthParams.getRedirectUri(), "UTF-8");
        final OAuthScope[] scopes = oAuthParams.getScopes();

        final String url;
        if (scopes == null || scopes.length == 0) {
            url = String.format(AUTHORIZATION_URL, oAuthParams.getClientId(), csrfId, encodedRedirectUri);
        } else {
            final int nScopes = scopes.length;
            final StringBuilder builder = new StringBuilder();
            int i = 0;
            for (OAuthScope scope : scopes) {
                builder.append(scope.getValue());
                if (++i < nScopes) {
                    builder.append("%20");
                }
            }
            url = String.format(AUTHORIZATION_URL_WITH_SCOPE, oAuthParams.getClientId(), csrfId,
                    builder.toString(), encodedRedirectUri);
        }
        final HtmlPage authPage = webClient.getPage(url);

        // submit login credentials
        final HtmlForm loginForm = authPage.getFormByName("oauth2SAuthorizeForm");
        final HtmlTextInput login = loginForm.getInputByName("session_key");
        login.setText(oAuthParams.getUserName());
        final HtmlPasswordInput password = loginForm.getInputByName("session_password");
        password.setText(oAuthParams.getUserPassword());
        final HtmlSubmitInput submitInput = loginForm.getInputByName("authorize");

        // disable redirect to avoid loading redirect URL
        webClient.getOptions().setRedirectEnabled(false);

        // validate CSRF and get authorization code
        String redirectQuery;
        try {
            final Page redirectPage = submitInput.click();
            redirectQuery = redirectPage.getUrl().getQuery();
        } catch (FailingHttpStatusCodeException e) {
            // escalate non redirect errors
            if (e.getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) {
                throw e;
            }
            final String location = e.getResponse().getResponseHeaderValue("Location");
            redirectQuery = location.substring(location.indexOf('?') + 1);
        }
        final Map<String, String> params = new HashMap<String, String>();
        final Matcher matcher = QUERY_PARAM_PATTERN.matcher(redirectQuery);
        while (matcher.find()) {
            params.put(matcher.group(1), matcher.group(2));
        }
        final String state = params.get("state");
        if (!csrfId.equals(state)) {
            throw new SecurityException("Invalid CSRF code!");
        } else {
            // return authorization code
            // TODO check results??
            return params.get("code");
        }

    } catch (IOException e) {
        throw new IllegalArgumentException("Error authorizing application: " + e.getMessage(), e);
    }
}

From source file:com.infosupport.ellison.core.archive.ApplicationArchive.java

/**
 * Finds all files in a directory matching a specific pattern.
 * <p/>/* w  ww  .ja  v a 2 s .co  m*/
 * For a definition of what kinds of patterns are supported, see {@link WildcardFileFilter}.
 *
 * @param basePath
 *     the name of the base directory to search in. May be null if looking for files from the root directory.
 * @param wildcardPattern
 *     files matching this pattern will be in the returned collection. See {@link WildcardFileFilter} for the
 *     pattern format
 * @param doRecursively
 *     whether to search for files matching {@code wildcardPattern} recursively or not.
 *
 * @return a list of all files matching {@code wildcardPattern} in directory {@code basePath} within this
 *         application archive.
 *
 * @throws FileNotFoundException
 *     if {@code basePath != null} and {@code basePath} does not point to an existing file in the application
 *     archive
 */
public Collection<URI> findFilesByGlobPattern(String basePath, String wildcardPattern, boolean doRecursively)
        throws FileNotFoundException {
    IOFileFilter fileFilter = new WildcardFileFilter(wildcardPattern);
    File baseDir = null;
    IOFileFilter dirFilter = null;

    if (basePath == null) {
        baseDir = unpackedPath;
    } else {
        if (!isPathRelative(basePath)) {
            throw new SecurityException(
                    "It is not permitted to supply base paths containing references to parent directories ('..').");
        }
        baseDir = new File(unpackedPath, basePath);
    }

    if (doRecursively) {
        dirFilter = TrueFileFilter.INSTANCE;
    } else {
        dirFilter = FalseFileFilter.INSTANCE;
    }

    if (!baseDir.exists()) {
        throw new FileNotFoundException(String.format("Basepath '%s' does not exist within archive '%s'",
                basePath, getApplicationFile().getAbsolutePath()));
    }

    if (!baseDir.isDirectory()) {
        throw new IllegalArgumentException(
                String.format("Basepath '%s' is not a directory within the archive", basePath));
    }

    return Collections2.transform(FileUtils.listFiles(baseDir, fileFilter, dirFilter),
            new Function<File, URI>() {
                @Override
                public URI apply(File input) {
                    return relativizePath(input.toURI());
                }
            });
}

From source file:org.key2gym.business.services.AttendancesServiceBean.java

@Override
public List<AttendanceDTO> findAttendancesByDate(DateMidnight date) throws SecurityViolationException {

    /*//w  ww .j  av  a2 s. com
     * Arguments validation.
     */
    if (date == null) {
        throw new NullPointerException("The date is null."); //NOI18N
    }

    if (!date.equals(DateMidnight.now()) && !callerHasRole(SecurityRoles.MANAGER)) {
        throw new SecurityException(getString("Security.Access.Denied"));
    }

    List<Attendance> attendances = getEntityManager()
            .createNamedQuery("Attendance.findByDatetimeBeginRangeOrderByDateTimeBeginDesc") //NOI18N
            .setParameter("low", date.toDate()) //NOI18N
            .setParameter("high", date.plusDays(1).toDate()) //NOI18N
            .getResultList();
    List<AttendanceDTO> result = new LinkedList<AttendanceDTO>();

    for (Attendance attendance : attendances) {
        result.add(wrapAttendance(attendance));
    }

    return result;
}