Java hash checking - java

For some reason i can't figure out why it downloads the new applet every time even though i have the newest application on my computer already (that's what this downloader/checker does, to check the hash, and if its outdated, it re-downloads the newer version which is uploaded to web host)
My downloader class
public class Downloader {
private static final String HASH_URL = "/current";
private static final String DOWNLOAD_URL = ".jar";
private LoadingFrame loadingFrame;
public Downloader(LoadingFrame loadingFrame) {
this.loadingFrame = loadingFrame;
}
private String getLatestHash() {
loadingFrame.setLoadingText("Checking if client is up to date...");
try (InputStream in = new URL(HASH_URL).openStream()) {
return new String(IOUtils.toByteArray(in)).trim();
} catch (IOException e) {
loadingFrame.setLoadingText("Error loading client [ErrorCode: 7A]");
throw new RuntimeException("Error loading client");
}
}
public File downloadLatestPack() {
try {
File dir = new File(System.getProperty("user.home") + File.separator + "Project" + File.separator + "client");
if (!dir.exists()) {
dir.mkdirs();
}
loadingFrame.setLoadingText("Checking if client is up to date...");
String latestHash = getLatestHash();
File latest = new File(dir.getPath() + File.separator + latestHash + ".jar");
if (!latest.exists() || !com.google.common.io.Files.hash(latest, Hashing.sha1()).toString().equals(latestHash)) {
loadingFrame.setLoadingText("Doing some house keeping...");
for (File f : dir.listFiles()) {
if (f.getName().endsWith(".jar") && !f.getName().equals(latest.getName())) {
f.delete();
}
}
loadingFrame.setLoadingText("Downloading latest client...");
latest.createNewFile();
try (InputStream in = new URL(DOWNLOAD_URL).openStream()) {
Files.copy(in, latest.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
} else {
loadingFrame.setLoadingText("Client is up to date!");
}
return latest;
} catch (IOException e) {
loadingFrame.setLoadingText("Error loading client [ErrorCode: 6B]");
throw new RuntimeException("Error loading client");
}
}
}

Related

Apache Commons Compress as solution to Zip Bomb

Java Code is implemented to uncompress zip file using java.util.zip library. Sonarqube reports Security Hotspots vulnerability as prone to "Zip Bomb" security issue with message "Make sure that expanding this archive file is safe here" in the line "ZipEntry entry = zipIn.getNextEntry();".
As a solution, trying to use Apache Commons Compress version 1.21 library which handles Zip Bomb starting from version 1.17. For testing, downloaded a Zip Bomb Vulnerable zip file from here .
But this zip file gets uncompressed without any error/exception. What is wrong with this code mentioned under heading "Implementation using Apache Commons Compress Library"?
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.21</version>
</dependency>
Zip Bomb Vulnerable code
private void unzipNormal(String zipFilePath, String destDirectory) {
try {
File destDir = new File(destDirectory);
if(!destDir.exists()) {
destDir.mkdir();
}
try(ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath))) {
ZipEntry entry = zipIn.getNextEntry();
while(entry != null) {
String filePath = destDirectory + File.separator + entry.getName();
if(!entry.isDirectory()) {
extractFile(zipIn, filePath);
} else {
File dir = new File(filePath);
dir.mkdir();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath))) {
byte[] bytesIn = new byte[4096];
int read = 0;
while((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
} catch (Exception ex) {
ex.printStackTrace();
throw ex;
}
}
Implementation using Apache Commons Compress Library
private void unzip(String srcZipFile, String destFolder) throws IOException {
Path filePath = Paths.get(srcZipFile);
try(InputStream inputStream = Files.newInputStream(filePath);
ZipArchiveInputStream i = new ZipArchiveInputStream(inputStream)
) {
System.out.println("Begin..");
ArchiveEntry entry = null;
while((entry = i.getNextEntry()) != null) {
if(!i.canReadEntryData(entry)) {
System.out.println("Continue..");
continue;
}
Path path = Paths.get(destFolder, entry.getName());
File f = path.toFile();
if(entry.isDirectory()) {
if (!f.isDirectory() && !f.mkdirs()) {
throw new IOException("failed to create directory " + f);
}
} else {
File parent = f.getParentFile();
if(!parent.isDirectory() && !parent.mkdirs()) {
throw new IOException("failed to create directory " + parent);
}
try (OutputStream o = Files.newOutputStream(f.toPath())) {
IOUtils.copy(i, o);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
Able to frame the solution with answer from here. Solution uses the Apache POI utility class and hence updated Maven pom.xml with Apache POI dependency.
Maven pom.xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
Solution
public static void main(String[] args) throws IOException {
Main main = new Main();
String srcZipFile = "/Users/user1/Documents/ZipBomb/zbsm.zip";
String destFolder = "/Users/user1/Documents/ZipBomb/unzipApacheLARGE/";
main.handle(srcZipFile, destFolder);
}
private void handle(String srcZipFile, String destFolder) throws IOException {
ZipSecureFile zipSecureFile = new ZipSecureFile(srcZipFile);
Enumeration<? extends ZipArchiveEntry> entries = zipSecureFile.getEntries();
while (entries.hasMoreElements()) {
ZipArchiveEntry entry = entries.nextElement();
String name = entry.getName();
try {
System.out.println("current file: " + name);
try (InputStream in = zipSecureFile.getInputStream(entry)) {
Path path = Paths.get(destFolder, entry.getName());
File f = path.toFile();
if(entry.isDirectory()) {
if (!f.isDirectory() && !f.mkdirs()) {
throw new IOException("failed to create directory " + f);
}
} else {
File parent = f.getParentFile();
if(!parent.isDirectory() && !parent.mkdirs()) {
throw new IOException("failed to create directory " + parent);
}
try (OutputStream out = Files.newOutputStream(f.toPath())) {
org.apache.poi.util.IOUtils.copy(in, out);
}
}
}
} catch (Exception e) {
throw new IOException("While handling entry " + name, e);
}
System.out.print("Completed Successfully!!");
}
}

How to restore file from GDrive?

I am making an app which stores its SQLite Database backup on GDrive. I succeeded in signing in and uploading the file in the drive but failed to restore it. Following is the code.
I use SQLiteDatabase to store the fileID so that when it is required while updating and restoring, it can be used. I am looking for a method which will make use of FileID to restore.
Error occurs at file.getDownloadUrl() and file.getContent().
class DriveClassHelper
{
private final Executor mExecutor = Executors.newSingleThreadExecutor();
private static Drive mDriveService;
private String FileID = null;
private static String filePath = "/data/data/com.example.gdrivebackup/databases/Data.db";
DriveClassHelper(Drive mDriveService)
{
DriveClassHelper.mDriveService = mDriveService;
}
// ---------------------------------- TO BackUp on Drive -------------------------------------------
public Task<String> createFile()
{
return Tasks.call(mExecutor, () ->
{
File fileMetaData = new File();
fileMetaData.setName("Backup");
java.io.File file = new java.io.File(filePath);
String mimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType("application/x-sqlite-3");
FileContent mediaContent = new FileContent(mimeType, file);
File myFile = null;
FileID = getFileIDFromDatabase();
try {
if (FileID != null) {
Log.i("CALLED : ", FileID);
//mDriveService.files().delete().execute();
myFile = mDriveService.files().update(FileID, fileMetaData, mediaContent).execute();
} else {
myFile = mDriveService.files().create(fileMetaData, mediaContent).execute();
MainActivity.demoSQLite.insertData(myFile.getId());
}
} catch (Exception e) {
e.printStackTrace();
}
if (myFile == null) {
throw new IOException("Null Result when requesting file creation");
}
Log.i("ID:", myFile.getId());
return myFile.getId();
}
);
}
// -------------------------------------------------------------------------------------------------
// ---------------------------------- TO get File ID -------------------------------------------
private static String getFileIDFromDatabase()
{
String FileIDFromMethod = null;
Cursor result = MainActivity.demoSQLite.getData();
if (result.getCount() == 0) {
Log.i("CURSOR :", "NO ENTRY");
return null;
} else {
while (result.moveToNext()) {
FileIDFromMethod = result.getString(0);
}
return FileIDFromMethod;
}
}
// -------------------------------------------------------------------------------------------------
// ---------------------------------- TO Restore -------------------------------------------
public static class Restore extends AsyncTask<Void, Void, String>
{
#Override
protected String doInBackground(Void... params) {
String fileId = null;
try
{
fileId = getFileIDFromDatabase();
if (fileId != null)
{
File file = mDriveService.files().get(fileId).execute();
downloadFile(file);
}
else
{
return null;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return fileId;
}
private void downloadFile(File file)
{
InputStream mInput = null;
FileOutputStream mOutput = null;
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) //Error occurs at file.getDownloadUrl()
{
try
{
HttpResponse resp = mDriveService.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute();
mInput = resp.getContent();
String outFileName = "file://" + Environment.getDataDirectory().getPath() + filePath;
// Log.e("com.example.myapp", "getDatabasePath="+ getDatabasePath(""));
//Log.e("com.example.myapp", "outFileName="+outFileName);
// String outFileName = "../databases/" + "Quickpay.db";
mOutput = new FileOutputStream(outFileName);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer)) > 0)
{
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
}
catch (IOException e)
{
// An error occurred.
e.printStackTrace();
// return null;
}
finally
{
try
{
//Close the streams
if (mOutput != null)
{
mOutput.close();
}
if (mInput != null)
{
mInput.close();
}
}
catch (IOException e)
{
Log.e("com.example.myapp", "failed to close databases");
}
}
}
else
{
// The file doesn't have any content stored on Drive.
// return null;
Log.e("com.example.myapp", "No content on Drive");
}
}
}
}
The Gradle file is like
implementation 'com.google.android.gms:play-services-auth:16.0.1'
implementation('com.google.apis:google-api-services-drive:v3-rev136-1.25.0')
{
exclude group: 'org.apache.httpcomponents'
}
implementation('com.google.api-client:google-api-client-android:1.26.0')
{
exclude group: 'org.apache.httpcomponents'
}
implementation 'com.google.http-client:google-http-client-gson:1.26.0'
As far as i know Download URL is only avalibale in Google drive api v2 and not in V3.
Short lived download URL for the file. This field is only populated for files with content stored in Google Drive; it is not populated for Google Docs or shortcut files.
It was not very stable in my opinion as not all file types would return a download url.
Using Google Drive v3 you should download the file using a stream.
String fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().get(fileId)
.executeMediaAndDownloadTo(outputStream);
This should work with the restore. Let me know if it doesnt and i will have a look its been a while since i have tried restore.

Application freezes when running method

I have an application which copies files from one directory to another. But every time I call the method to copy the files the UI (window) freezes until they´re done being copied. Do you have any idea why? It doesn't matter how many files that are in the directory as it always freezes.
This is my code:
public void startProcess(File orgDir, File destDir) {
Screen1Controller sf = new Screen1Controller();
int y = 1;
try {
File[] files = orgDir.listFiles();
for (File file : files) {
if (file.isDirectory() == false) {
File destinationPath = new File(destDir.getCanonicalPath() + "\\");
destDir = new File(destinationPath + "\\" + "");
destDir.mkdir();
System.out.println("file:" + file.getCanonicalPath());
try {
String fileNameWithOutExt = file.getName().replaceFirst("[.][^.]+$", "");
File destFile = new File(destDir.getPath() + "\\" + file.getName());
if (Files.exists(Paths.get(destFile.getPath()))) {
System.out.println("There is a duplicate.");
File[] destFiles = destDir.listFiles();
for (File destinationFile : destFiles) {
if (destinationFile.getName().startsWith(fileNameWithOutExt)) {
y++;
}
}
File newFile = new File(orgDir.getPath() + "\\" + fileNameWithOutExt + "." + y);
file.renameTo(newFile);
File destPath = new File(destDir.getPath() + "\\" + newFile.getName());
System.out.println(newFile.getCanonicalPath());
Files.copy(Paths.get(newFile.getCanonicalPath()), Paths.get(destPath.getPath()));
newFile.renameTo(new File(orgDir.getPath() + "\\" + fileNameWithOutExt));
} else {
Files.copy(Paths.get(file.getPath()), Paths.get(destFile.getPath()));
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
startProcess(file, destDir);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
You have to create a new Thread to handle the copying in a new thread and not the UI thread
new Thread(new Runnable() {
#Override
public void run() {
}
}).start();
put your method inside that, the one that is copying the files.
so it would look something like
new Thread(() -> {
startProcess(... , ...);
}).start();

how to import pictures into app from backup of db

I took the backup of my sqlite db and even i took backup of my pics which i captured through app and those images are stored in root directory..Now i imported my db but i don't know how to import pics ..Please help me to import pics in my app ..I have stored images in the name CAT_IMG.Here zipped when exported and unzipped when i import..i unzipped the images..Help me to import
public void backup() throws IOException {
File direct = new File(getFilesDir() + "/CAT_IMG");
System.out.println("LLLLLLLLLLLLLLLL"+direct);
File backupDirect = new File(root + "/instinctcoder"+"/zipunzip"+"/data");
System.out.println("PPPPPPPP"+backupDirect);
for(File srcFile : direct.listFiles()) {
if (srcFile.isFile() && srcFile.getName().endsWith(".JPG")) {
String targetFile = backupDirect.getAbsolutePath() + "/" + srcFile.getName();
copyFile(srcFile, targetFile);
}
}
}
private void copyFile(File src, String dest) throws IOException {
FileChannel sourceChannel = null;
FileChannel destChannel = null;
try {
sourceChannel = new FileInputStream(src).getChannel();
destChannel = new FileOutputStream(dest).getChannel();
destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
sourceChannel.close();
destChannel.close();
}
}

Extracting files in .iso using jSevenZip

I'm trying to extract the files in an .iso file I have. There are no errors and the console prints out all the files inside. However, none of the files get extracted. Any help is greatly appreciated!
I was able to find this link but I can't seem to integrate it in to my project.
Link to code example
class DownloadWorker extends SwingWorker<String, Object> {
private String flocation;
private JLabel out;
public DownloadWorker(String location, JLabel fout)
{
this.flocation = location;
this.out = fout;
}
#Override
public String doInBackground() {
//download here
out.setText("Beginning download. This may take a few minutes.");
try {
//ProgressBar/Install
System.out.println("FILELOCATION:\n----------");
System.out.println(flocation);
String URL_LOCATION = "http://www.futureretrogaming.tk/gamefiles/ProfessorPhys.iso";
String LOCAL_FILE = (flocation + "\\ProfessorPhys\\");
File localfile = new File(LOCAL_FILE);
if (localfile.exists()) {
System.out.println("Directory exists!");
}
else {
System.out.println("Directory doesn't exist! Creating...");
localfile.mkdir();
if (localfile.exists())
System.out.println("Directory created!");
}
System.out.println("LOCALFILE:\n-------");
System.out.println(LOCAL_FILE);
URL website = new URL(URL_LOCATION);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(LOCAL_FILE+"\\ProfessorPhys.iso\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
try {
randomAccessFile = new RandomAccessFile(localfile +"\\ProfessorPhys.iso\\", "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));
// Getting simple interface of the archive inArchive
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
System.out.println(" Hash | Size | Filename");
System.out.println("----------+------------+---------");
for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[] { 0 };
if (!item.isFolder()) {
ExtractOperationResult result;
final long[] sizeArray = new long[1];
result = item.extractSlow(new ISequentialOutStream() {
public int write(byte[] data) throws SevenZipException {
hash[0] ^= Arrays.hashCode(data); // Consume data
sizeArray[0] += data.length;
return data.length; // Return amount of consumed data
}
});
if (result == ExtractOperationResult.OK) {
System.out.println(String.format("%9X | %10s | %s", //
hash[0], sizeArray[0], item.getPath()));
} else {
System.err.println("Error extracting item: " + result);
}
}
}
} catch (Exception e) {
System.err.println("Error occurs: " + e);
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}
} catch (Exception e) {
System.out.println(e);
}
return "done";
}
#Override
protected void done() {
//done
out.setText(out.getText() + "\n Operation Done");
}
}
Code I'm trying to implement:
public class ExtractorUtil {
private static Logger logger = Logger.getLogger(ExtractorUtil.class.getCanonicalName());
public static void extract(File file, String extractPath) throws Exception {
ISevenZipInArchive inArchive = null;
RandomAccessFile randomAccessFile = null;
randomAccessFile = new RandomAccessFile(file, "r");
inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));
inArchive.extract(null, false, new MyExtractCallback(inArchive, extractPath));
if (inArchive != null) {
inArchive.close();
}
if (randomAccessFile != null) {
randomAccessFile.close();
}
}
public static class MyExtractCallback implements IArchiveExtractCallback {
private final ISevenZipInArchive inArchive;
private final String extractPath;
public MyExtractCallback(ISevenZipInArchive inArchive, String extractPath) {
this.inArchive = inArchive;
this.extractPath = extractPath;
}
#Override
public ISequentialOutStream getStream(final int index, ExtractAskMode extractAskMode) throws SevenZipException {
return new ISequentialOutStream() {
#Override
public int write(byte[] data) throws SevenZipException {
String filePath = inArchive.getStringProperty(index, PropID.PATH);
FileOutputStream fos = null;
try {
File dir = new File(extractPath);
File path = new File(extractPath + filePath);
if (!dir.exists()) {
dir.mkdirs();
}
if (!path.exists()) {
path.createNewFile();
}
fos = new FileOutputStream(path, true);
fos.write(data);
} catch (IOException e) {
logger.severe(e.getLocalizedMessage());
} finally {
try {
if (fos != null) {
fos.flush();
fos.close();
}
} catch (IOException e) {
logger.severe(e.getLocalizedMessage());
}
}
return data.length;
}
};
}

Categories

Resources