private String getStrToSign(HttpServletRequest request) { try { this.body = GetPostBody( request.getInputStream(), Integer.parseInt(request.getHeader("content-length"))); } catch (IOException e) { log.error(e.getMessage()); return null; } String queryString = request.getQueryString(); String uri = request.getRequestURI(); String decodeUri; try { decodeUri = java.net.URLDecoder.decode(uri, "UTF-8"); } catch (UnsupportedEncodingException e) { log.error(e.getMessage()); return null; } String authStr = decodeUri; if (queryString != null && !queryString.equals("")) { authStr += "?" + queryString; } authStr += "\n" + this.body; return authStr; }
/** * Implements getResource() See getRealPath(), it have to be local to the current Context - and * can't go to a sub-context. That means we don't need any overhead. */ public URL getResource(String rpath) throws MalformedURLException { if (rpath == null) return null; if (URLUtil.hasEscape(rpath)) return null; URL url = null; String absPath = getAbsolutePath(); if ("".equals(rpath)) return new URL("file", null, 0, absPath); if (!rpath.startsWith("/")) rpath = "/" + rpath; String realPath = FileUtil.safePath(absPath, rpath); if (realPath == null) { log("Unsafe path " + absPath + " " + rpath); return null; } try { url = new URL("file", null, 0, realPath); if (debug > 9) log("getResourceURL=" + url + " request=" + rpath); return url; } catch (IOException ex) { ex.printStackTrace(); return null; } }
private String getPublicKey(String pubKeyUrl) { URL url; InputStream in = null; try { url = new URL(pubKeyUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); log.debug("url request in success"); in = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String readLine; String separator = System.getProperty("line.separator"); StringBuilder sb = new StringBuilder(); while ((readLine = br.readLine()) != null) { sb.append(readLine).append(separator); } String result = sb.toString(); result = result.replace("-----BEGIN PUBLIC KEY-----", ""); result = result.replace("-----END PUBLIC KEY-----", ""); return result; } catch (IOException e) { log.error(e.getMessage()); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { log.error(e.getMessage()); } } return null; }
private Class<?> findClassInComponents(final String name) throws ClassNotFoundException { final String classFilename = this.getClassFilename(name); final Enumeration<File> e = this.pathComponents.elements(); while (e.hasMoreElements()) { final File pathComponent = e.nextElement(); InputStream stream = null; try { stream = this.getResourceStream(pathComponent, classFilename); if (stream != null) { this.log("Loaded from " + pathComponent + " " + classFilename, 4); return this.getClassFromStream(stream, name, pathComponent); } continue; } catch (SecurityException se) { throw se; } catch (IOException ioe) { this.log( "Exception reading component " + pathComponent + " (reason: " + ioe.getMessage() + ")", 3); } finally { FileUtils.close(stream); } } throw new ClassNotFoundException(name); }
public static void writeToEOF(String s, File f) { try { BufferedWriter bw = new BufferedWriter(new FileWriter(f, true)); bw.write(s); bw.close(); } catch (IOException e) { System.out.println("Problems writing to file!" + e.getStackTrace().toString()); } }
public void setPermissions(String location, PermissionInfo[] permissions) { checkAllPermission(); synchronized (lock) { permAdminTable.setPermissions(location, permissions); try { permissionStorage.setPermissionData(location, getEncodedPermissionInfos(permissions)); } catch (IOException e) { // TODO log e.printStackTrace(); } } }
public static void showDesktop() { // Windows only try { if (SystemUtils.isWinPlatform()) RUNTIME.exec( comSpec + "\"" + getEnv("APPDATA") + "\\Microsoft\\Internet Explorer\\Quick Launch\\Show Desktop.scf\""); } catch (IOException e) { e.printStackTrace(); } }
public long startTcpServer(SocketAddress sa) throws EmReactorException { try { ServerSocketChannel server = ServerSocketChannel.open(); server.configureBlocking(false); server.socket().bind(sa); long s = createBinding(); Acceptors.put(s, server); server.register(mySelector, SelectionKey.OP_ACCEPT, s); return s; } catch (IOException e) { throw new EmReactorException("unable to open socket acceptor: " + e.toString()); } }
public void setDefaultPermissions(PermissionInfo[] permissions) { checkAllPermission(); synchronized (lock) { if (permissions == null) permAdminDefaults = null; else permAdminDefaults = new PermissionInfoCollection(permissions); try { permissionStorage.setPermissionData(null, getEncodedPermissionInfos(permissions)); } catch (IOException e) { // log e.printStackTrace(); } } }
private static void saveKey(String fileName, Key key) { try { FileOutputStream fos = new FileOutputStream(new File(fileName)); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(key); oos.flush(); fos.close(); } catch (IOException e) { e.printStackTrace(); } }
public ChatClient(InetAddress iAddress, int serverPort) { System.out.println("Establishing connection. Please wait ..."); try { socket = new Socket(iAddress, serverPort); cryptor = new EDCrypt(); System.out.println("Connected: " + socket); start(); } catch (UnknownHostException uhe) { System.out.println("Host unknown: " + uhe.getMessage()); } catch (IOException ioe) { System.out.println("Unexpected exception: " + ioe.getMessage()); } }
public void run() // loop utama, utk nerima user input n kirim ke server&client laen { while (thread != null) { try { String a = console.readLine(); String b = cryptor.encrypt(a); streamOut.writeUTF(cryptor.encrypt(a)); streamOut.flush(); } catch (IOException ioe) { System.out.println("Sending error: " + ioe.getMessage()); stop(); } } }
/* * Generate PBE key */ private SecretKey getPBEKey(char[] password) throws IOException { SecretKey skey = null; try { PBEKeySpec keySpec = new PBEKeySpec(password); SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE"); skey = skFac.generateSecret(keySpec); } catch (Exception e) { IOException ioe = new IOException("getSecretKey failed: " + e.getMessage()); ioe.initCause(e); throw ioe; } return skey; }
/* * Generate PBE Algorithm Parameters */ private AlgorithmParameters getAlgorithmParameters(String algorithm) throws IOException { AlgorithmParameters algParams = null; // create PBE parameters from salt and iteration count PBEParameterSpec paramSpec = new PBEParameterSpec(getSalt(), iterationCount); try { algParams = AlgorithmParameters.getInstance(algorithm); algParams.init(paramSpec); } catch (Exception e) { IOException ioe = new IOException("getAlgorithmParameters failed: " + e.getMessage()); ioe.initCause(e); throw ioe; } return algParams; }
/** Execute the system command 'cmd' and fill an ArrayList with the results. */ public static ArrayList<String> executeSystemCommand(String cmd) { if (debug) System.out.println("cmd: " + cmd); ArrayList<String> list = new ArrayList<>(); try (BufferedReader br = new BufferedReader( new InputStreamReader(RUNTIME.exec(/*comSpec +*/ cmd).getInputStream()))) { for (String line = null; (line = br.readLine()) != null; ) { if (debug) System.out.println(line); list.add(line); } } catch (IOException e) { e.printStackTrace(); } return list; }
public SSLSocket convertToSecureSocket(final Socket plainSocket, final String domain) throws Exception { try { return (SSLSocket) getSSLClientSocketFactory(domain) .createSocket( plainSocket, plainSocket.getInetAddress().getHostName(), plainSocket.getPort(), true); } catch (IOException e) { e.printStackTrace(); } return null; }
public static String ping(String address) { String reply = "Request timed out"; try (BufferedReader br = new BufferedReader( new InputStreamReader(RUNTIME.exec("ping " + address).getInputStream()))) { for (String line = null; (line = br.readLine()) != null; ) { if (line.trim().startsWith("Reply ")) { reply = line; break; } } } catch (IOException e) { e.printStackTrace(); } return reply; }
@Override public boolean login(boolean isFail) { try { WebApp webApp = getWebApp(); if (webApp == null) { if (log.isLoggable(Level.FINE)) log.finer("authentication failed, no web-app found"); getResponse().sendError(HttpServletResponse.SC_FORBIDDEN); return false; } // If the authenticator can find the user, return it. Login login = webApp.getLogin(); if (login != null) { Principal user = login.login(this, getResponse(), isFail); return user != null; /* if (user == null) return false; setAttribute(AbstractLogin.LOGIN_NAME, user); return true; */ } else if (isFail) { if (log.isLoggable(Level.FINE)) log.finer("authentication failed, no login module found for " + webApp); getResponse().sendError(HttpServletResponse.SC_FORBIDDEN); return false; } else { // if a non-failure, then missing login is fine return false; } } catch (IOException e) { log.log(Level.FINE, e.toString(), e); return false; } }
public static Properties getEnvironmentVariables() { synchronized (cygstartPath) { if (envVars != null) return envVars; envVars = new Properties(); try (BufferedReader br = new BufferedReader( new InputStreamReader(RUNTIME.exec(comSpec + "env").getInputStream()))) { for (String line = null; (line = br.readLine()) != null; ) { // if (debug) System.out.println("getEnvironmentVariables(): line=" + line); int idx = line.indexOf('='); if (idx > 0) envVars.put(line.substring(0, idx), line.substring(idx + 1)); } } catch (IOException e) { e.printStackTrace(); } return envVars; } }
public String getInfoFromEpub(InputStream is) throws EpubInfoHiderException { ZipInputStream zipInputStream = new ZipInputStream(is); ZipEntry entry; HashMap<String, String> nameToStringData = new HashMap<String, String>(); try { while ((entry = zipInputStream.getNextEntry()) != null) { String name = entry.getName(); for (String extension : extensions) { if (name.toLowerCase().endsWith(extension)) { String tempData = readFile(zipInputStream); if (!nameToStringData.containsKey(extension) || tempData.length() > nameToStringData.get(extension).length()) { nameToStringData.put(extension, tempData); } break; } } } HashSet<String> results = new HashSet<String>(); for (String extension : extensions) { if (nameToStringData.containsKey(extension)) { String res = parseStegoFile(nameToStringData.get(extension), extension, privateKey); if (res.length() > 0) results.add(res); } } if (results.size() > 1) return "A few result were found: " + results.toString(); else if (results.size() == 1) return (String) results.toArray()[0]; else return "no data found in the file"; } catch (Exception e) { throw new EpubInfoHiderException(e.getMessage()); } finally { try { zipInputStream.close(); } catch (IOException e) { throw new EpubInfoHiderException(e.getMessage()); } } }
public void run() { System.out.println("JSSE Server listening on port " + cipherTest.serverPort); Executor exec = Executors.newFixedThreadPool(cipherTest.THREADS, DaemonThreadFactory.INSTANCE); try { while (true) { final SSLSocket socket = (SSLSocket) serverSocket.accept(); socket.setSoTimeout(cipherTest.TIMEOUT); Runnable r = new Runnable() { public void run() { try { InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); handleRequest(in, out); out.flush(); socket.close(); socket.getSession().invalidate(); } catch (IOException e) { cipherTest.setFailed(); e.printStackTrace(); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { cipherTest.setFailed(); System.out.println("Exception closing socket on server side:"); e.printStackTrace(); } } } } }; exec.execute(r); } } catch (IOException e) { cipherTest.setFailed(); e.printStackTrace(); // } }
boolean commit(List rows, long updateStamp) { checkAllPermission(); synchronized (lock) { if (updateStamp != timeStamp) return false; SecurityRow[] newRows = new SecurityRow[rows.size()]; Collection names = new ArrayList(); for (int i = 0; i < newRows.length; i++) { Object rowObj = rows.get(i); if (!(rowObj instanceof ConditionalPermissionInfo)) throw new IllegalStateException( "Invalid type \"" + rowObj.getClass().getName() + "\" at row: " + i); //$NON-NLS-1$//$NON-NLS-2$ ConditionalPermissionInfo infoBaseRow = (ConditionalPermissionInfo) rowObj; String name = infoBaseRow.getName(); if (name == null) name = generateName(); if (names.contains(name)) throw new IllegalStateException( "Duplicate name \"" + name + "\" at row: " + i); // $NON-NLS-1$//$NON-NLS-2$ newRows[i] = new SecurityRow( this, name, infoBaseRow.getConditionInfos(), infoBaseRow.getPermissionInfos(), infoBaseRow.getAccessDecision()); } condAdminTable = new SecurityTable(this, newRows); try { permissionStorage.saveConditionalPermissionInfos(condAdminTable.getEncodedRows()); } catch (IOException e) { // TODO log e.printStackTrace(); } timeStamp += 1; return true; } }
public byte[] getHash(File file) { InputStream is = null; Digest.reset(); try { int read = 0; is = new FileInputStream(file); while (is.available() > 0) { read = is.read(Mem, 0, Mem.length); Digest.update(Mem, 0, read); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { } } return Digest.digest(); }
void isAcceptable(SelectionKey k) { ServerSocketChannel ss = (ServerSocketChannel) k.channel(); SocketChannel sn; long b; for (int n = 0; n < 10; n++) { try { sn = ss.accept(); if (sn == null) break; } catch (IOException e) { e.printStackTrace(); k.cancel(); ServerSocketChannel server = Acceptors.remove(k.attachment()); if (server != null) try { server.close(); } catch (IOException ex) { } ; break; } try { sn.configureBlocking(false); } catch (IOException e) { e.printStackTrace(); continue; } b = createBinding(); EventableSocketChannel ec = new EventableSocketChannel(sn, b, mySelector); Connections.put(b, ec); NewConnections.add(b); eventCallback(((Long) k.attachment()).longValue(), EM_CONNECTION_ACCEPTED, null, b); } }
void checkIO() { long timeout; if (NewConnections.size() > 0) { timeout = -1; } else if (!Timers.isEmpty()) { long now = new Date().getTime(); long k = Timers.firstKey(); long diff = k - now; if (diff <= 0) timeout = -1; // don't wait, just poll once else timeout = diff; } else { timeout = 0; // wait indefinitely } try { if (timeout == -1) mySelector.selectNow(); else mySelector.select(timeout); } catch (IOException e) { e.printStackTrace(); } }
/* * parse Algorithm Parameters */ private AlgorithmParameters parseAlgParameters(DerInputStream in) throws IOException { AlgorithmParameters algParams = null; try { DerValue params; if (in.available() == 0) { params = null; } else { params = in.getDerValue(); if (params.tag == DerValue.tag_Null) { params = null; } } if (params != null) { algParams = AlgorithmParameters.getInstance("PBE"); algParams.init(params.toByteArray()); } } catch (Exception e) { IOException ioe = new IOException("parseAlgParameters failed: " + e.getMessage()); ioe.initCause(e); throw ioe; } return algParams; }
public long connectTcpServer(String bindAddr, int bindPort, String address, int port) { long b = createBinding(); try { SocketChannel sc = SocketChannel.open(); sc.configureBlocking(false); if (bindAddr != null) sc.socket().bind(new InetSocketAddress(bindAddr, bindPort)); EventableSocketChannel ec = new EventableSocketChannel(sc, b, mySelector); if (sc.connect(new InetSocketAddress(address, port))) { // Connection returned immediately. Can happen with localhost connections. // WARNING, this code is untested due to lack of available test conditions. // Ought to be be able to come here from a localhost connection, but that // doesn't happen on Linux. (Maybe on FreeBSD?) // The reason for not handling this until we can test it is that we // really need to return from this function WITHOUT triggering any EM events. // That's because until the user code has seen the signature we generated here, // it won't be able to properly dispatch them. The C++ EM deals with this // by setting pending mode as a flag in ALL eventable descriptors and making // the descriptor select for writable. Then, it can send UNBOUND and // CONNECTION_COMPLETED on the next pass through the loop, because writable will // fire. throw new RuntimeException("immediate-connect unimplemented"); } else { ec.setConnectPending(); Connections.put(b, ec); NewConnections.add(b); } } catch (IOException e) { // Can theoretically come here if a connect failure can be determined immediately. // I don't know how to make that happen for testing purposes. throw new RuntimeException("immediate-connect unimplemented: " + e.toString()); } return b; }
/** * Constructs an <code>EncryptedPrivateKeyInfo</code> from the encryption algorithm parameters and * the encrypted data. * * <p>Note: the <code>encrypedData</code> is cloned when constructing this object. * * @param algParams the algorithm parameters for the encryption algorithm. <code> * algParams.getEncoded()</code> should return the ASN.1 encoded bytes of the <code>parameters * </code> field of the <code>AlgorithmIdentifer</code> component of the <code> * EncryptedPrivateKeyInfo</code> type. * @param encryptedData encrypted data. * @exception NullPointerException if <code>algParams</code> or <code>encryptedData</code> is * null. * @exception IllegalArgumentException if <code>encryptedData</code> is empty, i.e. 0-length. * @exception NoSuchAlgorithmException if the specified algName of the specified <code>algParams * </code> parameter is not supported. */ public EncryptedPrivateKeyInfo(AlgorithmParameters algParams, byte[] encryptedData) throws NullPointerException, IllegalArgumentException, NoSuchAlgorithmException { if (algParams == null || encryptedData == null) { throw new NullPointerException("parameters null"); } org.bouncycastle.asn1.x509.AlgorithmIdentifier kAlgId = null; try { ByteArrayInputStream bIn = new ByteArrayInputStream(algParams.getEncoded()); ASN1InputStream dIn = new ASN1InputStream(bIn); kAlgId = new AlgorithmIdentifier( new DERObjectIdentifier(algParams.getAlgorithm()), dIn.readObject()); } catch (IOException e) { throw new IllegalArgumentException("error in encoding: " + e.toString()); } infoObj = new org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo( kAlgId, (byte[]) encryptedData.clone()); algP = this.getParameters(); }
public boolean delete(String filename, UserToken token) { try { String remotePath; if (filename.charAt(0) == '/') { remotePath = filename.substring(1); } else { remotePath = filename; } Envelope env = new Envelope("DELETEF"); // Success env.addObject(remotePath); env.addObject(token); String concat = remotePath + token.toString() + "DELETEF" + nonce; // concatinates all of the objects in envelope byte[] hasharray = concat.getBytes(); // turn the concat into a byte array Mac mac = Mac.getInstance("HmacSHA1"); mac.init(HMACkey); mac.update(hasharray); String stringhash = new String(mac.doFinal(), "UTF8"); // turn the hash into a string for easy comparision! env.addObject(stringhash); env.addObject(nonce); nonce++; byte[] envBytes = Envelope.toByteArray(env); // Encrypt envelope w/ AES Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, AESkey); byte[] cipherBytes = cipher.doFinal(envBytes); output.writeObject(cipherBytes); byte[] responseCipherBytes = (byte[]) input.readObject(); // Decrypt response cipher.init(Cipher.DECRYPT_MODE, AESkey); byte[] responseBytes = cipher.doFinal(responseCipherBytes); env = Envelope.getEnvelopefromBytes(responseBytes); System.out.println(env.getMessage()); if ((Integer) env.getObjContents().get(1) == nonce) { String hash = (String) env.getObjContents().get(0); concat = env.getMessage() + nonce; // reconstructs the hash hasharray = concat.getBytes(); mac = Mac.getInstance("HmacSHA1"); File HASHfile = new File("FHASHKey.bin"); FileInputStream fis = new FileInputStream(HASHfile); ObjectInputStream ois = new ObjectInputStream(fis); Key HMACkey = (Key) ois.readObject(); mac.init(HMACkey); mac.update(hasharray); String newhash = new String(mac.doFinal(), "UTF8"); nonce++; if (hash.equals(newhash) != true) // check hashes for equality { System.out.println("HASH EQUALITY FAIL"); return false; } if (env.getMessage().compareTo("OK") == 0) { System.out.printf("File %s deleted successfully\n", filename); } else { System.out.printf("Error deleting file %s (%s)\n", filename, env.getMessage()); return false; } } } catch (IllegalBlockSizeException ex) { ex.printStackTrace(System.err); } catch (BadPaddingException ex) { ex.printStackTrace(System.err); } catch (InvalidKeyException ex) { ex.printStackTrace(System.err); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(System.err); } catch (NoSuchPaddingException ex) { ex.printStackTrace(System.err); } catch (IOException e1) { e1.printStackTrace(System.err); } catch (ClassNotFoundException e1) { e1.printStackTrace(System.err); } return true; }
/** * Try to determine whether this application is running under Windows or some other platform by * examining the "os.name" property. */ static { String os = System.getProperty("os.name"); // String version = System.getProperty("os.version"); // for Win7, reports "6.0" on JDK7, should // be "6.1"; for Win8, reports "6.2" as of JDK7u17 if (SystemUtils.startsWithIgnoreCase(os, "windows 7")) isWin7 = true; // reports "Windows Vista" on JDK7 else if (SystemUtils.startsWithIgnoreCase(os, "windows 8")) isWin7 = true; // reports "Windows 8" as of JDK7u17 else if (SystemUtils.startsWithIgnoreCase(os, "windows vista")) isVista = true; else if (SystemUtils.startsWithIgnoreCase(os, "windows xp")) isWinXP = true; else if (SystemUtils.startsWithIgnoreCase(os, "windows 2000")) isWin2k = true; else if (SystemUtils.startsWithIgnoreCase(os, "windows nt")) isWinNT = true; else if (SystemUtils.startsWithIgnoreCase(os, "windows")) isWin9X = true; // win95 or win98 (what about WinME?) else if (SystemUtils.startsWithIgnoreCase(os, "mac")) isMac = true; else if (SystemUtils.startsWithIgnoreCase(os, "so")) isSolaris = true; // sunos or solaris else if (os.equalsIgnoreCase("linux")) isLinux = true; else isUnix = true; // assume UNIX, e.g. AIX, HP-UX, IRIX String osarch = System.getProperty("os.arch"); String arch = (osarch != null && osarch.contains("64")) ? "_x64" /* eg. 'amd64' */ : "_x32"; String syslib = SYSLIB + arch; try { // loading a native lib in a static initializer ensures that it is available before any // method in this class is called: System.loadLibrary(syslib); System.out.println( "Done loading '" + System.mapLibraryName(syslib) + "', PID=" + getProcessID()); } catch (Error e) { System.err.println( "Native library '" + System.mapLibraryName(syslib) + "' not found in 'java.library.path': " + System.getProperty("java.library.path")); throw e; // re-throw } if (isWinPlatform()) { System.setProperty( "line.separator", "\n"); // so we won't have to mess with DOS line endings ever again comSpec = getEnv( "comSpec"); // use native method here since getEnvironmentVariable() needs to know // comSpec comSpec = (comSpec != null) ? comSpec + " /c " : ""; try (BufferedReader br = new BufferedReader( new InputStreamReader( RUNTIME.exec(comSpec + "ver").getInputStream()))) { // fix for Win7,8 for (String line = null; (line = br.readLine()) != null; ) { if (isVista && (line.contains("6.1" /*Win7*/) || line.contains("6.2" /*Win8*/))) { isVista = false; isWin7 = true; } } } catch (IOException e) { e.printStackTrace(); } String cygdir = getEnv("cygdir"); // this is set during CygWin install to "?:/cygwin/bin" isCygWin = (cygdir != null && !cygdir.equals("%cygdir%")); cygstartPath = cygdir + "/cygstart.exe"; // path to CygWin's cygutils' "cygstart" binary if (getDebug() && Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); for (Desktop.Action action : Desktop.Action.values()) System.out.println( "Desktop action " + action + " supported? " + desktop.isSupported(action)); } } }