List of usage examples for java.lang SecurityException SecurityException
public SecurityException(Throwable cause)
From source file:be.fedict.eid.dss.protocol.simple.client.SignatureResponseProcessor.java
private void verifyServiceSignature(String serviceSigned, String target, String signatureRequest, String signatureRequestId, String signatureResponse, String signatureResponseId, String encodedSignatureCertificate, byte[] serviceSignatureValue, List<X509Certificate> serviceCertificateChain) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { LOG.debug("verifying service signature"); X509Certificate serviceCertificate = serviceCertificateChain.get(0); LOG.debug("service identity: " + serviceCertificate.getSubjectX500Principal()); Signature serviceSignature = Signature.getInstance("SHA1withRSA"); serviceSignature.initVerify(serviceCertificate); StringTokenizer serviceSignedStringTokenizer = new StringTokenizer(serviceSigned, ","); while (serviceSignedStringTokenizer.hasMoreTokens()) { String serviceSignedElement = serviceSignedStringTokenizer.nextToken(); LOG.debug("service signed: " + serviceSignedElement); byte[] data; if ("target".equals(serviceSignedElement)) { data = target.getBytes();/*from w w w. j av a 2 s . c o m*/ } else if ("SignatureRequest".equals(serviceSignedElement)) { data = signatureRequest.getBytes(); } else if ("SignatureRequestId".equals(serviceSignedElement)) { data = signatureRequestId.getBytes(); } else if ("SignatureResponse".equals(serviceSignedElement)) { data = signatureResponse.getBytes(); } else if ("SignatureResponseId".equals(serviceSignedElement)) { data = signatureResponseId.getBytes(); } else if ("SignatureCertificate".equals(serviceSignedElement)) { data = encodedSignatureCertificate.getBytes(); } else { throw new SecurityException("service signed unknown element: " + serviceSignedElement); } serviceSignature.update(data); } boolean valid = serviceSignature.verify(serviceSignatureValue); if (!valid) { throw new SecurityException("service signature not valid"); } if (null != this.serviceFingerprint) { LOG.debug("checking service fingerprint"); byte[] actualServiceFingerprint = DigestUtils.sha(serviceCertificate.getEncoded()); if (!Arrays.equals(this.serviceFingerprint, actualServiceFingerprint)) { throw new SecurityException("service certificate fingerprint mismatch"); } } }
From source file:it.greenvulcano.gvesb.iam.service.internal.GVUsersManager.java
@Override public void revokeRole(String username, String role) throws UserNotFoundException { try {/*from www . j av a 2 s . co m*/ User user = userRepository.get(username) .orElseThrow(() -> new SecurityException(new UserNotFoundException(username))); user.removeRole(role); userRepository.add(user); } catch (SecurityException e) { if (e.getCause() instanceof UserNotFoundException) { throw (UserNotFoundException) e.getCause(); } else { throw e; } } }
From source file:com.glaf.core.security.SecurityUtils.java
/** * ???/*ww w . j a v a 2 s .c o m*/ * * @param ctx * * @param source * * @param signed * ??? * @param pubKey * * @return boolean */ public static boolean verify(SecurityContext ctx, byte[] source, byte[] signed, PublicKey publicKey) { try { boolean verify = false; Signature sign = Signature.getInstance(ctx.getSignatureAlgorithm(), ctx.getJceProvider()); sign.initVerify(publicKey); sign.update(source); verify = sign.verify(signed); return verify; } catch (Exception ex) { throw new SecurityException(ex); } }
From source file:calliope.db.CouchConnection.java
/** * Save a file to the file system//from ww w .ja v a 2 s . co m * @param docID the docID of the file * @param data the data of the file * @throws AeseException */ @Override public void putImageToDb(String db, String docID, byte[] data) throws AeseException { try { docID = deconvertDocID(docID); docIDCheck(db, docID); File wd = new File(CouchConnection.webRoot); File child = new File(wd, db + "/" + docID); if (!child.getParentFile().exists()) if (!child.getParentFile().mkdirs()) throw new SecurityException("couldn't create " + docID); if (child.exists()) child.delete(); child.createNewFile(); FileOutputStream fos = new FileOutputStream(child); fos.write(data); fos.close(); } catch (Exception e) { throw new AeseException(e); } }
From source file:de.raptor2101.GalDroid.WebGallery.Gallery3.Gallery3Imp.java
public String getSecurityToken(String user, String password) throws SecurityException { try {/*www.j ava 2 s .com*/ HttpPost httpRequest = new HttpPost(LinkRest_LoadSecurityToken); httpRequest.addHeader("X-Gallery-Request-Method", "post"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart("user", new StringBody(user)); mpEntity.addPart("password", new StringBody(password)); httpRequest.setEntity(mpEntity); HttpResponse response; response = mHttpClient.execute(httpRequest); InputStream inputStream = response.getEntity().getContent(); InputStreamReader streamReader = new InputStreamReader(inputStream); BufferedReader reader = new BufferedReader(streamReader); String content = reader.readLine(); inputStream.close(); if (content.length() == 0 || content.startsWith("[]")) { throw new SecurityException("Couldn't verify user-credentials"); } return content.trim().replace("\"", ""); } catch (Exception e) { throw new SecurityException("Couldn't verify user-credentials", e); } }
From source file:org.kawanfw.file.api.client.RemoteSession.java
/** * Creates an Awake FILE session with a proxy and protocol parameters. * //from w ww . ja v a 2 s . c o m * @param url * the URL of the path to the {@code ServerFileManager} Servlet * @param username * the username for authentication on the Awake Server (may be * null for <code>call()</code> * @param password * the user password for authentication on the Awake Server (may * be null) * @param proxy * the proxy to use, may be null for direct access * @param passwordAuthentication * the proxy credentials, null if no proxy or if the proxy does * not require authentication * @param sessionParameters * the session parameters to use (may be null) * * @throws MalformedURLException * if the url is malformed * @throws UnknownHostException * if host URL (http://www.acme.org) does not exists or no * Internet Connection. * @throws ConnectException * if the Host is correct but the {@code ServerFileManager} * Servlet is not reachable * (http://www.acme.org/ServerFileManager) and access failed * with a status != OK (200). (If the host is incorrect, or is * impossible to connect to - Tomcat down - the * {@code ConnectException} will be the sub exception * {@code HttpHostConnectException}.) * @throws SocketException * if network failure during transmission * @throws InvalidLoginException * the username or password is invalid * @throws SecurityException * Scheme is required to be https (SSL/TLS) * @throws RemoteException * an exception has been thrown on the server side. This traps * an Awake product failure and should not happen. * @throws IOException * for all other IO / Network / System Error */ public RemoteSession(String url, String username, char[] password, Proxy proxy, PasswordAuthentication passwordAuthentication, SessionParameters sessionParameters) throws MalformedURLException, UnknownHostException, ConnectException, SocketException, InvalidLoginException, RemoteException, SecurityException, IOException { if (url == null) { throw new MalformedURLException("url is null!"); } @SuppressWarnings("unused") URL asUrl = new URL(url); // Try to raise a MalformedURLException; this.username = username; this.url = url; this.proxy = proxy; this.passwordAuthentication = passwordAuthentication; this.sessionParameters = sessionParameters; // username & password may be null: for call() if (username == null) { return; } // Launch the Servlet httpTransfer = HttpTransferUtil.HttpTransferFactory(url, proxy, passwordAuthentication, sessionParameters); // TestReload if SSL required by host if (this.url.toLowerCase().startsWith("http://") && isForceHttps()) { throw new SecurityException( Tag.PRODUCT_SECURITY + " Remote Host requires a SSL url that starts with \"https\" scheme"); } String passwordStr = new String(password); // Prepare the request parameters List<SimpleNameValuePair> requestParams = new Vector<SimpleNameValuePair>(); requestParams.add(new SimpleNameValuePair(Parameter.TEST_CRYPTO, Parameter.TEST_CRYPTO)); requestParams.add(new SimpleNameValuePair(Parameter.ACTION, Action.LOGIN_ACTION)); requestParams.add(new SimpleNameValuePair(Parameter.USERNAME, username)); requestParams.add(new SimpleNameValuePair(Parameter.PASSWORD, passwordStr)); httpTransfer.send(requestParams); // If everything is OK, we have in our protocol a response that // 1) starts with "OK". 2) Is followed by the Authentication Token // else: response starts with "INVALID_LOGIN_OR_PASSWORD". String receive = httpTransfer.recv(); debug("receive: " + receive); if (receive.startsWith(ReturnCode.INVALID_LOGIN_OR_PASSWORD)) { throw new InvalidLoginException("Invalid username or password."); } else if (receive.startsWith(ReturnCode.OK)) { // OK! We are logged in & and correctly authenticated // Keep in static memory the Authentication Token for next api // commands (First 20 chars) String theToken = receive.substring(ReturnCode.OK.length() + 1); authenticationToken = StringUtils.left(theToken, Parameter.TOKEN_LEFT_SIZE); } else { this.username = null; // Should never happen throw new InvalidLoginException(Tag.PRODUCT_PRODUCT_FAIL + " Please contact support."); } }
From source file:com.owncloud.android.utils.EncryptionUtils.java
/** * @param file encrypted file * @param encryptionKeyBytes key from metadata * @param iv initialization vector from metadata * @param authenticationTag authenticationTag from metadata * @return decrypted byte[]/*from w ww.ja va 2 s .com*/ */ @RequiresApi(api = Build.VERSION_CODES.KITKAT) public static byte[] decryptFile(File file, byte[] encryptionKeyBytes, byte[] iv, byte[] authenticationTag) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException { Cipher cipher = Cipher.getInstance(AES_CIPHER); Key key = new SecretKeySpec(encryptionKeyBytes, AES); GCMParameterSpec spec = new GCMParameterSpec(128, iv); cipher.init(Cipher.DECRYPT_MODE, key, spec); RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); byte[] fileBytes = new byte[(int) randomAccessFile.length()]; randomAccessFile.readFully(fileBytes); // check authentication tag byte[] extractedAuthenticationTag = Arrays.copyOfRange(fileBytes, fileBytes.length - (128 / 8), fileBytes.length); if (!Arrays.equals(extractedAuthenticationTag, authenticationTag)) { throw new SecurityException("Tag not correct"); } return cipher.doFinal(fileBytes); }
From source file:de.zib.gndms.kit.monitor.GroovyMonitor.java
synchronized void verifyPrincipal(@NotNull Principal thePrincipal) { if (!getPrincipal().equals(thePrincipal)) throw new SecurityException("Principal mismatch"); }
From source file:org.kawanfw.sql.servlet.DatabaseMetaDataExecutor.java
/** * // ww w . j a v a 2s . com * Calls a remote metadata method from the PC <br> * * @throws IOException * all network, etc. errors * @throws ClassNotFoundException * @throws IllegalAccessException * @throws InstantiationException * @throws NoSuchMethodException * @throws SecurityException * @throws InvocationTargetException * @throws IllegalArgumentException */ private void callMetaDataFunction(HttpServletRequest request, OutputStream out, Connection connection) throws SQLException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException { // The method name String methodName = request.getParameter(Parameter.METHOD_NAME); // methodName = HtmlConverter.fromHtml(methodName); // The parms name String paramsTypes = request.getParameter(Parameter.PARAMS_TYPES); String paramsValues = request.getParameter(Parameter.PARAMS_VALUES); // Make sure all values are not null and trimed methodName = this.getTrimValue(methodName); paramsTypes = this.getTrimValue(paramsTypes); paramsValues = this.getTrimValue(paramsValues); debug("actionInvokeRemoteMethod:methodName : " + methodName); // paramsTypes = HtmlConverter.fromHtml(paramsTypes); // paramsValues = HtmlConverter.fromHtml(paramsValues); List<String> listParamsTypes = ListOfStringTransport.fromJson(paramsTypes); List<String> listParamsValues = ListOfStringTransport.fromJson(paramsValues); debug("actionInvokeRemoteMethod:listParamsTypes : " + listParamsTypes); debug("actionInvokeRemoteMethod:listParamsValues : " + listParamsValues); DatabaseMetaData databaseMetaData = connection.getMetaData(); // Trap DatabaseMetaData.getTables() & DatabaseMetaData.getUDTs() // that have special array String[] or int[] parameters if (methodName.equals("getTables") || methodName.equals("getUDTs") || methodName.equals("getPrimaryKeys")) { DatabaseMetaDataSpecial databaseMetaDataSpecial = new DatabaseMetaDataSpecial(databaseMetaData, methodName, listParamsValues); ResultSet rs = databaseMetaDataSpecial.execute(); dumpResultSetOnServletOutStream(rs); return; } @SuppressWarnings("rawtypes") Class[] argTypes = new Class[listParamsTypes.size()]; Object[] values = new Object[listParamsValues.size()]; for (int i = 0; i < listParamsTypes.size(); i++) { String value = listParamsValues.get(i); String javaType = listParamsTypes.get(i); JavaValueBuilder javaValueBuilder = new JavaValueBuilder(javaType, value); argTypes[i] = javaValueBuilder.getClassOfValue(); values[i] = javaValueBuilder.getValue(); // Trap NULL values if (values[i].equals("NULL")) { values[i] = null; } debug("argTypes[i]: " + argTypes[i]); debug("values[i] : " + values[i]); } Class<?> c = Class.forName("java.sql.DatabaseMetaData"); Object theObject = databaseMetaData; // Invoke the method Method main = null; Object resultObj = null; // Get the Drvier Info String database = ""; String productVersion = ""; String DriverName = ""; String DriverVersion = ""; String driverInfo = Tag.PRODUCT; // try { // database = databaseMetaData.getDatabaseProductName(); // productVersion = databaseMetaData.getDatabaseProductVersion(); // DriverName = databaseMetaData.getDriverName(); // DriverVersion= databaseMetaData.getDriverVersion(); // driverInfo += database + " " + productVersion + " " + DriverName + // " " + DriverVersion; // } catch (Exception e1) { // ServerLogger.getLogger().log(Level.WARNING, Tag.PRODUCT + // "Impossible to get User Driver info."); // } database = databaseMetaData.getDatabaseProductName(); productVersion = databaseMetaData.getDatabaseProductVersion(); DriverName = databaseMetaData.getDriverName(); DriverVersion = databaseMetaData.getDriverVersion(); driverInfo += database + " " + productVersion + " " + DriverName + " " + DriverVersion; String methodParams = getMethodParams(values); try { main = c.getDeclaredMethod(methodName, argTypes); } catch (SecurityException e) { throw new SecurityException(driverInfo + " - Security - Impossible to get declared DatabaseMetaData." + methodName + "(" + methodParams + ")"); } catch (NoSuchMethodException e) { throw new NoSuchMethodException( driverInfo + " - No Such Method - Impossible get declared DatabaseMetaData." + methodName + "(" + methodParams + ")"); } try { resultObj = main.invoke(theObject, values); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( driverInfo + " - Impossible to call DatabaseMetaData." + methodName + "(" + methodParams + ")"); } catch (IllegalAccessException e) { throw new IllegalAccessException(driverInfo + " - Impossible to access DatabaseMetaData method." + methodName + "(" + methodParams + ")"); } catch (InvocationTargetException e) { throw new InvocationTargetException(e, driverInfo + " - Impossible to invoke DatabaseMetaData method." + methodName + "(" + methodParams + ")"); } if (resultObj instanceof ResultSet) { ResultSet rs = (ResultSet) resultObj; dumpResultSetOnServletOutStream(rs); } else { // All other formats are handled in String String result = null; if (resultObj != null) result = resultObj.toString(); debug("actionInvokeRemoteMethod:result: " + result); result = HtmlConverter.toHtml(result); //out.println(TransferStatus.SEND_OK); //out.println(result); ServerSqlManager.writeLine(out, TransferStatus.SEND_OK); ServerSqlManager.writeLine(out, result); } }
From source file:org.javascool.polyfilewriter.Gateway.java
/** * Perform a security assertion./* www. ja v a 2 s.c o m*/ * If the applet is locked, this function will interrupt the current thread. * * @throws SecurityException */ private void assertSafeUsage() { if (appletLocked) { if (showMessage) { JOptionPane.showMessageDialog(this, "This website (" + getCodeBase().getHost() + ") tried to hack" + " your computer by accessing to the local file system (Attack stopped)", "Error", JOptionPane.ERROR_MESSAGE); showMessage = false; } throw new SecurityException("This website is not authorized to use this applet"); } else { } }