I need a little question.How can I repair that code so I can use it in android too.I need just to load a file from assets folder in android projet, decrypt it and to show the size of the file and how long it takes to the application to decrypt it.
Code :
package decryption;
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class Decryption {
public static void main(String args[]) throws Exception {
File file = new File("ecryption.pdf");
System.out.println(file.getAbsolutePath());
System.out.println("user.dir is: " + System.getProperty("user.dir"));
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec("01234567890abcde".getBytes(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec("fedcba9876543210".getBytes());
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
FileInputStream fis = new FileInputStream(new File("ecrypted.pdf"));
long start = System.currentTimeMillis();
System.out.print(start+" ");
CipherInputStream cis = new CipherInputStream(fis, cipher);
FileOutputStream fos = new FileOutputStream(new File("decrypted.pdf"));
long end = System.currentTimeMillis();
System.out.print(end);
byte[] b = new byte[8];
int i;
while ((i = cis.read(b)) != -1) {
fos.write(b, 0, i);
}
fos.flush(); fos.close();
cis.close(); fis.close();
}
}
// File file = new File("ecryption.pdf");
// System.out.println(file.getAbsolutePath());
// System.out.println("user.dir is: " + System.getProperty("user.dir"));
// FileInputStream fis = new FileInputStream(new File("ecrypted.pdf"));
InputStream fis = getAssets().open("ecryption.pdf");
// FileOutputStream fos = new FileOutputStream(new File("decrypted.pdf"));
FileOutputStream fos = new FileOutputStream(
new File(Environment.getExternalStorageDirectory(), "decrypted.pdf"));
Then you need to compile and adjust the rest.
this will copy one file at a time... start from there..
public void copyAssets() {
try {
in = getAssets().open("aabbccdd.mp3");
File outFolder = new File(root.getAbsolutePath() + "/testfolder182");
outFolder.mkdir();
File outFile = new File(outFolder, "ooooooooohhhigetit.mp3");
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: ", e);
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
Related
I am very new to java and coming from a js background. I am attempting to loop through a folder full of files and zipping it. Currently, I have done the zipping part successfully, but doing by statically adding the files. The answer is obviously a loop from a programming perspective. I am having trouble looping a list and making it equal to the zipping method below. Online Resources are not making sense much sense to me due to my beginner skill.
package zipFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFiles {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("atest.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
String file1Name = "src/resources/text1";
String file2Name = "src/resources/text2";
String file3Name = "src/resources/text3";
String file4Name = "src/resources/text4";
String file5Name = "src/resources/text5";
String file6Name = "src/resources/text6";
addToZipFile(file1Name, zos);
addToZipFile(file2Name, zos);
addToZipFile(file3Name, zos);
addToZipFile(file4Name, zos);
addToZipFile(file5Name, zos);
addToZipFile(file6Name, zos);
zos.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void addToZipFile(String fileName, ZipOutputStream zos) throws FileNotFoundException, IOException {
System.out.println("Writing '" + fileName + "' to zip file");
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(fileName);
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
fis.close();
}
}
The answer is in this article: http://www.baeldung.com/java-compress-and-uncompress
This code zips multiple files (Very similar to your code but slightly changed):
public class ZipMultipleFiles {
public static void main(String[] args) throws IOException {
List<String> srcFiles = Arrays.asList("test1.txt", "test2.txt");
FileOutputStream fos = new FileOutputStream("multiCompressed.zip");
ZipOutputStream zipOut = new ZipOutputStream(fos);
for (String srcFile : srcFiles) {
File fileToZip = new File(srcFile);
FileInputStream fis = new FileInputStream(fileToZip);
ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
}
zipOut.close();
fos.close();
}
}
EDIT:
This line in the code creates an array that is easy to go through in a while loop:
List<String> srcFiles = Arrays.asList("test1.txt", "test2.txt");
basically used finding children of a folder method thanks to Elliotk link. I am making the string equal to the path of the parent folder - >checking if whether if its a directory - > list its files -> get the names and while loop to write all of them to a zipped folder
here is my whole code
package zipfolder2;
import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class zipfolders2 {
public static void main(String[] args) {
try {
String sourceFile = "src/resources";
FileOutputStream fos = new FileOutputStream("zippedfiles.zip");
ZipOutputStream zipOut = new ZipOutputStream(fos);
File fileToZip = new File(sourceFile);
zipFile(fileToZip, fileToZip.getName(), zipOut);
zipOut.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException {
if (fileToZip.isHidden()) {
return;
}
if (fileToZip.isDirectory()) {
File[] children = fileToZip.listFiles();
for (File childFile : children) {
zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
}
return;
}
FileInputStream fis = new FileInputStream(fileToZip);
ZipEntry zipEntry = new ZipEntry(fileName);
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
}
}
I am trying to upload a file from a client to the server using sockets in JAVA. It is partially working, however, the file that gets created on the server is an empty text file. Can anyone offer any suggestions as to where I may have an issue. Thanks:
Server:
private void handleFileUpload(String fileSizeInBytes, String fileName) throws IOException{
String fullyQualifiedFileName = rootDirectory+System.getProperty("file.separator")+fileName;
File fileToWrite = new File(fullyQualifiedFileName);
if(fileToWrite.exists()){
fileToWrite.delete();
}
int bytesRead = 0;
byte[] aByte = new byte[1];
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
BufferedOutputStream bufferedOutputStream = null;
ByteArrayOutputStream baos = null;
try {
inputStream = socket.getInputStream();
fileOutputStream = new FileOutputStream(fullyQualifiedFileName);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
bytesRead = inputStream.read(aByte, 0, aByte.length);
baos = new ByteArrayOutputStream();
do {
baos.write(aByte);
bytesRead = inputStream.read(aByte);
} while (bytesRead != -1);
bufferedOutputStream.write(baos.toByteArray());
bufferedOutputStream.flush();
bufferedOutputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Client:
private void uploadFile(Socket socket, File fileToUpload){
byte[] mybytearray = new byte[(int) fileToUpload.length()];
try {
FileInputStream fis = new FileInputStream(fileToUpload);
BufferedOutputStream toServer = new BufferedOutputStream(socket.getOutputStream());
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
toServer.write(mybytearray, 0, mybytearray.length);
toServer.flush();
toServer.close();
return;
} catch (IOException ex) {
handleServerError("upload file", ex);
System.exit(0);
}
Change your handleFileUpload method as following
private void handleFileUpload(String fileSizeInBytes, String fileName) throws IOException{
String fullyQualifiedFileName = rootDirectory+System.getProperty("file.separator")+fileName;
File fileToWrite = new File(fullyQualifiedFileName);
if(fileToWrite.exists()){
fileToWrite.delete();
}
int bytesRead = 0;
byte[] aByte = new byte[1024];
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
BufferedOutputStream bufferedOutputStream = null;
ByteArrayOutputStream baos = null;
try {
inputStream = socket.getInputStream();
fileOutputStream = new FileOutputStream(fullyQualifiedFileName);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
bytesRead = inputStream.read(aByte, 0, aByte.length);
while (bytesRead != -1) {
bufferedOutputStream.write(aByte, 0, bytesRead);
bytesRead = inputStream.read(aByte, 0, aByte.length);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Please i Have a problem with the following code
public String encrypt(String fileToEncrypt) throws Exception{
_cipher.init(Cipher.ENCRYPT_MODE, _keyPair.getPublic());
File inputfile = new File(fileToEncrypt);
File outputfile = new File("C:/SECUREFILE".concat("/").concat(FilenameUtils.getName(fileToEncrypt)));
FileInputStream inputstream = new FileInputStream(inputfile);
FileOutputStream outputStream = new FileOutputStream(outputfile, false);
CipherOutputStream cos = new CipherOutputStream(outputStream, _cipher);
IOUtils.copy(inputstream, cos);
IOUtils.closeQuietly(inputstream);
IOUtils.closeQuietly(cos);
return outputfile.getPath();
}
The problem is that the resulting file written to disk is always 0kb. Please what am i doing wrong
Use IOUtils.closeQuietly(inputstream), and IOUtils.closeQuietly(cos); to close the streams, it should work
The following piece of code works for me
public static void main(String[] args) throws Exception {
encrypt(new Scanner(System.in).next());
}
public static String encrypt(String fileToEncrypt) throws Exception{
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey _keyPair = kgen.generateKey();
Cipher _cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
_cipher.init(Cipher.ENCRYPT_MODE, _keyPair);
File inputfile = new File(fileToEncrypt);
File outputfile = new File("D:/SECUREFILE".concat("/").concat(FilenameUtils.getName(fileToEncrypt)));
FileInputStream inputstream = new FileInputStream(inputfile);
FileOutputStream outputStream = new FileOutputStream(outputfile, false);
CipherOutputStream cos = new CipherOutputStream(outputStream, _cipher);
IOUtils.copy(inputstream, cos);
IOUtils.closeQuietly(inputstream);
IOUtils.closeQuietly(cos);
return outputfile.getPath();
}
input file content : dfsdafdsfasdfsadfs
output file content : –X‰8q'4ÆZ€’®!‡tÈérë/ű¤®v´rË
I'm trying to create a folder in internal storage called "unzip" and then unzip a file into the internal storage "unzip folder". Not sure what i'm doing wrong? If you could please explain what's wrong it'd be great! Thanks
Edit: The issues is that I don't think the folder is being created and the file is also not being unzipped.
public void send(View view) {
try {
File mydir = this.getDir("unzip", Context.MODE_PRIVATE);//create folder in internal storage
unzip(getFilesDir().getAbsolutePath(), job_no, getFilesDir() + "/unzip/");
} catch (IOException e) {
}
}
public void unzip(String filepath, String filename, String unzip_path) throws IOException {
InputStream is = new FileInputStream(filepath + filename);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
try {
ZipEntry ze;
while ((ze = zis.getNextEntry()) != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
String filename_temp = ze.getName();
File fmd = new File(filepath + filename_temp);
if (!fmd.getParentFile().exists()) {
fmd.getParentFile().mkdirs();
}
FileOutputStream fout = new FileOutputStream(unzip_path + filename_temp);
while ((count = zis.read(buffer)) != -1) {
baos.write(buffer, 0, count);
byte[] bytes = baos.toByteArray();
fout.write(bytes);
baos.reset();
}
fout.close();
//}
}
} finally {
zis.close();
}
}
This will get absolute storage device.
final static String MEDIA_PATH = Environment.getExternalStorageDirectory().getPath() + "/";
I'm using CipherInputStream and CipherOutputStream to encrypt files using AES.
encrypt(...) seems to be working fine, but my decrypt(...) function only decrypt the first 16 bytes of my files.
Here is my class :
public class AESFiles {
private byte[] getKeyBytes(final byte[] key) throws Exception {
byte[] keyBytes = new byte[16];
System.arraycopy(key, 0, keyBytes, 0, Math.min(key.length, keyBytes.length));
return keyBytes;
}
public Cipher getCipherEncrypt(final byte[] key) throws Exception {
byte[] keyBytes = getKeyBytes(key);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(keyBytes);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
return cipher;
}
public Cipher getCipherDecrypt(byte[] key) throws Exception {
byte[] keyBytes = getKeyBytes(key);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(keyBytes);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
return cipher;
}
public void encrypt(File inputFile, File outputFile, byte[] key) throws Exception {
Cipher cipher = getCipherEncrypt(key);
FileOutputStream fos = null;
CipherOutputStream cos = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(inputFile);
fos = new FileOutputStream(outputFile);
cos = new CipherOutputStream(fos, cipher);
byte[] data = new byte[1024];
int read = fis.read(data);
while (read != -1) {
cos.write(data, 0, read);
read = fis.read(data);
System.out.println(new String(data, "UTF-8").trim());
}
cos.flush();
} finally {
fos.close();
cos.close();
fis.close();
}
}
public void decrypt(File inputFile, File outputFile, byte[] key) throws Exception {
Cipher cipher = getCipherDecrypt(key);
FileOutputStream fos = null;
CipherInputStream cis = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(inputFile);
cis = new CipherInputStream(fis, cipher);
fos = new FileOutputStream(outputFile);
byte[] data = new byte[1024];
int read = cis.read(data);
while (read != -1) {
fos.write(data, 0, read);
read = cis.read(data);
System.out.println(new String(data, "UTF-8").trim());
}
} finally {
fos.close();
cis.close();
fis.close();
}
}
public static void main(String args[]) throws Exception {
byte[] key = "mykey".getBytes("UTF-8");
new AESFiles().encrypt(new File("C:\\Tests\\secure.txt"), new File("C:\\Tests\\secure.txt.aes"), key);
new AESFiles().decrypt(new File("C:\\Tests\\secure.txt.aes"), new File("C:\\Tests\\secure.txt.1"), key);
}
}
So my question is, why the decrypt function only read the first 16 bytes ?
This is very subtle. Your problem is that you are closing your fos before your cos. In your encrypt(...) method you are doing:
} finally {
fos.close();
cos.close();
fis.close();
}
That closes the FileOutputStream out from under the CipherOutputStream so the final padded block of encrypted output never gets written to the output file. If you close the fos after the cos then your code should work fine.
Really, you should consider doing something like:
FileOutputStream fos = null;
CipherOutputStream cos = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(inputFile);
fos = new FileOutputStream(outputFile);
cos = new CipherOutputStream(fos, cipher);
// once cos wraps the fos, you should set it to null
fos = null;
...
} finally {
if (cos != null) {
cos.close();
}
if (fos != null) {
fos.close();
}
if (fis != null) {
fis.close();
}
}
FYI: org.apache.commons.io.IOUtils has a great closeQuietly(...) method which handles null checks and catches the exceptions for you.