Remove metadata from an image using jmagick - java

I have removed the metadata from an image using the below imagemagick command.
convert input.png -strip output.png
It almost reduces 20% of the size for the 2MB file.
I need to do the same using Jmagick java api.
Is there any api available in Jmagick to remove the metadata?

I can't read Java, but there seems to be a strip method in src/magick/magick_MagickImage.c:
/*
* Class: magick_MagickImage
* Method: strip
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL Java_magick_MagickImage_strip
(JNIEnv *env, jobject self) {
Image *image = NULL;
jboolean retVal;
image = (Image*) getHandle(env, self, "magickImageHandle", NULL);
if (image == NULL) {
throwMagickException(env, "Unable to retrieve image handle");
return JNI_FALSE;
}
retVal = StripImage(image);
return(retVal);
}

It depends on the version you are using!
JMagick up to version 6.7.7:
MagickImage has no method strip()
Current (Master) JMagick version:
MagickImage has a method named strip()

Related

Get a string from a c++ library with a java wrapper around it

Good Evening,
I have a c++ library file where I am trying to get a string value from but not by return.
This is for an Android Application build in Xamarin.
.cpp file
JNIEXPORT jint JNICALL Java_MyNamespace_ClassName_FunctionName
(JNIEnv *env, jclass obj, jstring returnString)
{
returnString = env->NewStringUTF("returnStringValue");
return 1;
}
In my Solution I have:
.cs File
namespace myNamespace
{
[DllImport("FolderName", EntryPoint = "Java_MyNamespace_ClassName_FunctionName")]
private static extern int FunctionName(IntPtr env, IntPtr thiz, IntPtr returnString);
void test_function()
{
IntPtr j = new IntPtr();
int status = FunctionName(JNIEnv.Handle, IntPtr.Zero, j);
string ss = j.ToString();
//Where I am expecting ss to be containing "returnStringValue".
}
}
Thanks #SushiHangover
We created a byte array
byte[] x = new byte[120];
Allocated that memory and copied it
System.Runtime.InteropServices.Marshal.AllocHGlobal()
System.Runtime.InteropServices.Marshal.Copy()
And then converted using:
System.Text.Encoding.UTF8.GetString()
Apparently this worked verry well.
Regards

NDK how to get the dvm point?

now I have a question to use "JNI_GetCreatedJavaVMs".
but I couldn't use JNI_OnLoad method because my native code is not provid for java .
void *pHandle = dlopen("/system/lib/libart.so", RTLD_NOW | RTLD_GLOBAL);
JavaVM* m_pJvm = NULL;
void * pFunAddr =dlsym(pHandle, "JNI_GetCreatedJavaVMs");
LOGD("pJNI_GetCreatedJavaVMs = %08X", pFunAddr);
pJNIGetCreatedJavaVMs = (int)pFunAddr - 1;
LOGD("call !!!!!!!");
pJNIGetCreatedJavaVMs(&m_pJvm, 0, &vm_count);
LOGD("pJNIGetCreatedJavaVMs result is %d", result);
when I call the JNI_GetCreatedJavaVMs, process was crashed.
I didn't found what happend in IDA.
who can help me !!!!!!!!!!!!!! THX
ps:JNI_GetCreatedJavaVMs method is found in the android source code.
and another method is use runtime(libart.so) or gdvm(libdvm.so).
Some code from my native app, it is build in the AOSP source tree.
I am not sure if it could work in NDK
#include <jni.h>
#include <android_runtime/AndroidRuntime.h>
...
JNIEnv *env;
jint res;
JavaVM *jvm = AndroidRuntime::getJavaVM();
assert(jvm != NULL);
res = jvm->AttachCurrentThread(&env, NULL);
assert(res >= 0);

JNI Call java method from c program

I need to call java method from c program. i have tried below code to call the java method through Java native interface but facing issues while compilation. i m new to C and have experience in java. so, i m not able to think myself what is happening while creating JVM.
Below is the code.
CTest.c
#include <stdio.h>
#include <jni.h>
JNIEnv* create_vm() {
JavaVM* jvm;
JNIEnv* env;
JavaVMInitArgs args;
JavaVMOption options[1];
args.version = JNI_VERSION_1_6;
args.nOptions = 1;
options[0].optionString = "-Djava.class.path=D:\\Ashish_Review\\JNI\\src";
args.options = options;
args.ignoreUnrecognized = JNI_FALSE;
JNI_CreateJavaVM(&jvm, (void **)&env, &args);
return env;
}
void invoke_class(JNIEnv* env) {
jclass helloWorldClass;
jmethodID mainMethod;
jobjectArray applicationArgs;
jstring applicationArg0;
helloWorldClass = (*env)->FindClass(env, "HelloWorld");
mainMethod = (*env)->GetStaticMethodID(env, helloWorldClass, "main", "([Ljava/lang/String;)V");
applicationArgs = (*env)->NewObjectArray(env, 1, (*env)->FindClass(env, "java/lang/String"), NULL);
applicationArg0 = (*env)->NewStringUTF(env, "From-C-program");
(*env)->SetObjectArrayElement(env, applicationArgs, 0, applicationArg0);
(*env)->CallStaticVoidMethod(env, helloWorldClass, mainMethod, applicationArgs);
}
int main(int argc, char **argv) {
JNIEnv* env = create_vm();
invoke_class( env );
}
C:\Users\Desktop\tcc>tcc C:\TurboC++\Disk\TurboC3\BIN\CTest.c -I "C:\Program Files\Java\jdk1.6.0_16\include" -I "C:\Program Files\Java\jdk1.6.0_16\include\win32" -shared -o CTest.dll
tcc: undefined symbol '_JNI_CreateJavaVM#12'
please help me out.
The error message is about the linking stage, not compilation - you have included the header file, but to create the executable you have to specify the .a (library files) also.
You have to link with JVM's library (add some reference to libjvm.a to the tcc's command line).
If you don't have a precompiled jvm.lib file for TurboC++, there is another option - link with the jvm.dll file and export all the methods from JVM manually. This uses the LoadLibrary/GetProcAddress functions.
For a short sample (sorry, couldn't find the entire export source code), look at this:
/* load library */
HMODULE dll = LoadLibraryA("jvm.dll");
/* declare a function pointer and initialize it with the "pointer" to dll's code */
JNI_CreateJavaVM_func JNI_CreateJavaVM_ptr = GetProcAddress(dll, "JNI_CreateJavaVM");
Later use the JNI_CreateJavaVM_ptr instead of JNI_CreateJavaVM. Also you'll have to declare the JNI_CreateJavaVM_func type - you might just copy the signature from "jni.h"

JNI UnsatisfiedLinkError on a native method

I'm running a basic Java wrapper for a C++ BSD socket client. I can compile the Java and generate a header file, but when I try to run it, it returns Exception in thread "main" java.lang.UnsatisfiedLinkError: JavaClient.socketComm()V
From what I've been able to find, it seems like this is indicative of a mismatch between method signatures, but I can't find anything wrong with mine.
Java Code
public class JavaClient
{
public native void socketComm();
public static void main(String[] args)
{
System.load("/home/cougar/workspace/ArbiterBSDSocketComms/JNIClient/JavaClient.so");
JavaClient client = new JavaClient();
client.socketComm();
System.out.println("Done");
}
}
C Implementation
#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#include <cstdlib>
#include <stdio.h>
#include <jni.h>
#include "JavaClient.h"
#define MAXHOSTNAME 256
JNIEXPORT void JNICALL Java_JavaClient_socketComm
(JNIEnv *env, jobject obj) {
struct sockaddr_in remoteSocketInfo;
struct hostent *hPtr;
int socketHandle;
char *remoteHost="localhost";
int portNumber = 8080;
memset(&remoteSocketInfo, 0, sizeof(struct sockaddr_in)); //Clear structure memory
if ((hPtr = gethostbyname(remoteHost)) == NULL) //Get sysinfo
{
printf("System DNS resolution misconfigured.");
printf("Error number: ", ECONNREFUSED);
exit(EXIT_FAILURE);
}
if((socketHandle = socket(AF_INET, SOCK_STREAM, 0)) < 0) //Create socket
{
close(socketHandle);
exit(EXIT_FAILURE);
}
memcpy((char *)&remoteSocketInfo.sin_addr,
hPtr->h_addr, hPtr->h_length); //Load sys info into sock data structures
remoteSocketInfo.sin_family = AF_INET;
remoteSocketInfo.sin_port = htons((u_short)portNumber); //Set port number
if(connect(socketHandle, (struct sockaddr *)&remoteSocketInfo, sizeof(struct sockaddr_in)) < 0)
{
close(socketHandle);
exit(EXIT_FAILURE);
}
int rc=0;
char buf[512];
strcpy(buf, "Sup server");
send(socketHandle, buf, strlen(buf)+1, 0);
}
void main(){}
Header File
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class JavaClient */
#ifndef _Included_JavaClient
#define _Included_JavaClient
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: JavaClient
* Method: socketComm
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_JavaClient_socketComm
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
Excuse some of the bad formatting, I haven't used stackoverflow much and the code formatting is a bit sketchy.
These files all reside in /JNIClient.
I'm running Ubuntu 12.04 x64, and I have both 32- and 64-bit JDKs installed. I tried generating the .so with the 32-bit verison first, which would have been ideal, but I got an ELF mismatch, so I just went with the 64-bit so I wouldn't have to deal with that. (Any insight on that is welcome as well.)
My process is:
$>javac JavaClient.java
$>javah JavaClient
$>cc -m64 -g -I/usr/lib/jvm/java-6-openjdk-amd64/include -I/usr/lib/jvm/java-6-openjdk-amd64/include/linux -shared JavaClient.c -o JavaClient.so
$>java JavaClient
The full error message is
Exception in thread "main" java.lang.UnsatisfiedLinkError: JavaClient.socketComm()V
at JavaClient.socketComm(Native Method)
at JavaClient.main(JavaClient.java:9)
$>nm JavaClient.so returns:
cougar#Wanda:~/workspace/ArbiterBSDSocketComms/JNIClient$ nm JavaClient.so
0000000000200e50 a _DYNAMIC
0000000000200fe8 a _GLOBAL_OFFSET_TABLE_
w _Jv_RegisterClasses
0000000000200e30 d __CTOR_END__
0000000000200e28 d __CTOR_LIST__
0000000000200e40 d __DTOR_END__
0000000000200e38 d __DTOR_LIST__
00000000000005e0 r __FRAME_END__
0000000000200e48 d __JCR_END__
0000000000200e48 d __JCR_LIST__
0000000000201010 A __bss_start
w __cxa_finalize##GLIBC_2.2.5
0000000000000540 t __do_global_ctors_aux
0000000000000490 t __do_global_dtors_aux
0000000000201008 d __dso_handle
w __gmon_start__
0000000000201010 A _edata
0000000000201020 A _end
0000000000000578 T _fini
0000000000000438 T _init
0000000000000470 t call_gmon_start
0000000000201010 b completed.6531
0000000000201018 b dtor_idx.6533
0000000000000510 t frame_dummy
Edit: I have a theory that the .so is being built improperly, as $>nm JavaClient.so doesn't show the method names in it. Any suggestions on what's wrong about that cc command?
Okay, SO: I kept at this because nothing seemed right. The method signatures were all matched, nothing should be wrong, eclipse file properties said it was editing the right file, etc etc. I finally catted the JavaClient.c, and it was blank. Apparently eclipse wasn't ACTUALLY editing the file it said it was. Fixed that up and now everything's fine.
I will give you a far better solution.
public void socketComm() throws IOException
{
Socket socket = new Socket("localhost", 8080);
try
{
socket.getOutputStream().write("Sup server\u0000".getBytes());
}
finally
{
socket.close(); // You forgot this
}
}
No JNI required at all. It also doesn't close an invalid handle if socket() returns < 0, unlike your code.
I kept at this because nothing seemed right. The method signatures were all matched, nothing should be wrong, eclipse file properties said it was editing the right file, etc etc. I finally catted the JavaClient.c, and it was blank. Apparently eclipse wasn't ACTUALLY editing the file it said it was. Fixed that up and now everything's fine.
Not sure why Eclipse claimed to be editing a blank file, I checked and rechecked and it wasn't referencing any links or anything, but if you're having the same problem as me check it out.

Issues with SHA1 hash implementation in Android

I have two small snippets for calculating SHA1.
One is very fast but it seems that it isn't correct and the other is very slow but correct.
I think the FileInputStream conversion to ByteArrayInputStream is the problem.
Fast version:
MessageDigest md = MessageDigest.getInstance("SHA1");
FileInputStream fis = new FileInputStream("path/to/file.exe");
ByteArrayInputStream byteArrayInputStream =
new ByteArrayInputStream(fis.toString().getBytes());
DigestInputStream dis = new DigestInputStream(byteArrayInputStream, md);
BufferedInputStream bis = new BufferedInputStream(fis);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int ch;
while ((ch = dis.read()) != -1) {
byteArrayOutputStream.write(ch);
}
byte[] newInput = byteArrayOutputStream.toByteArray();
System.out.println("in digest : " +
byteArray2Hex(dis.getMessageDigest().digest()));
byteArrayOutputStream = new ByteArrayOutputStream();
DigestOutputStream digestOutputStream =
new DigestOutputStream(byteArrayOutputStream, md);
digestOutputStream.write(newInput);
System.out.println("out digest: " +
byteArray2Hex(digestOutputStream.getMessageDigest().digest()));
System.out.println("length: " +
new String(
byteArray2Hex(digestOutputStream.getMessageDigest().digest())).length());
digestOutputStream.close();
byteArrayOutputStream.close();
dis.close();
Slow version:
MessageDigest algorithm = MessageDigest.getInstance("SHA1");
FileInputStream fis = new FileInputStream("path/to/file.exe");
BufferedInputStream bis = new BufferedInputStream(fis);
DigestInputStream dis = new DigestInputStream(bis, algorithm);
// read the file and update the hash calculation
while (dis.read() != -1);
// get the hash value as byte array
byte[] hash = algorithm.digest();
Conversion method:
private static String byteArray2Hex(byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash) {
formatter.format("%02x", b);
}
return formatter.toString();
}
I hope there is another possibility to get it running because I need the performance.
I used a high performance c++ implementation which I load with JNI.
For more details write a comment, please.
EDIT:
Requirements for JNI is the Android NDK. For Windows is needed in addition cygwin or something similar.
If you decided for cygwin, I give you some little instructions how to get it working with the NDK:
Download the setup.exe from cygwin and execute it.
Click on Next and choice Install from Internet confirm with Next.
The next two steps adjust the settings as desired and as always click Next.
Select your internet connection and the same procedure as in the final stages.
A download page will catch the eye select it or take just a download page, which is in your country. There is nothing more to say.
We need the packages make and gcc-g++. You can find them using the search in the left upper corner, click on the Skip til a version is displayed and the first field is selected. Do that what we have always done after a selection.
You will get the information, that there are dependencies, which must be resolved. It is usually not necessary to do it yourself and confirm it.
The download and installation started.
If you need you can create shortcuts otherwise click on exceptional Finish.
Download the zip file and extract the NDK to a non space containing path.
You can start now cygwin.
Navigate to the NDK. The path /cydrive gives you all available drives f.e. cd /cygdrive/d navigates to the drive with the letter D.
In the root folder of the NDK you can execute the file ndk-build with ./ndk-build. There should be an error occurs like Android NDK: Could not find application project directory !.
You have to navigate in an Android project to execute the command. So let's start with a project.
Before we can start with the project search for a C/C++ implementation of the hash algorithm. I took the code from this site CSHA1.
You should edit the source code for your requirements.
Now we can start with JNI.
You create a folder called jni in your Android project. It contains all native source files and the Android.mk (more about that file later), too.
Copy your downloaded (and edited) source files in that folder.
My java package is called de.dhbw.file.sha1, so I named my source files similar to find them easily.
Android.mk:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_LDLIBS := -llog
# How the lib is called?
LOCAL_MODULE := SHA1Calc
# Which is your main SOURCE(!) file?
LOCAL_SRC_FILES := de_dhbw_file_sha1_SHA1Calc.cpp
include $(BUILD_SHARED_LIBRARY)
Java code:
I used the AsyncTask with a ProgressDialog to give the user some feedback about the action.
package de.dhbw.file.sha1;
// TODO: Add imports
public class SHA1HashFileAsyncTask extends AsyncTask<String, Integer, String> {
// [...]
static {
// loads a native library
System.loadLibrary("SHA1Calc");
}
// [...]
// native is the indicator for native written methods
protected native void calcFileSha1(String filePath);
protected native int getProgress();
protected native void unlockMutex();
protected native String getHash();
// [...]
}
Native code (C++):
Remember accessing variables inside native code or other way around using threads needs synchronizing or you will get a segmentation fault soon!
For JNI usage you have to add #include <jni.h>.
For logging insert following include #include <android/log.h>.
Now you can log with __android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "Version [%s]", "19");.
The first argument is the type of message and the second the causing library.
You can see I had a version number in my code. It is very helpful because sometimes the apk builder doesn't use the new native libraries. Troubleshooting can be extremely shortened, if the wrong version is online.
The naming conventions in the native code are a little bit crasier: Java_[package name]_[class name]_[method name].
The first to arguments are always given, but depending on the application you should distinguish:
func(JNIEnv * env, jobject jobj) -> JNI call is an instance method
func(JNIEnv * env, jclass jclazz) -> JNI call is a static method
The header for the method calcFileSha1(...):
JNIEXPORT void JNICALL Java_de_dhbw_file_sha1_SHA1HashFileAsyncTask_calcFileSha1(JNIEnv * env, jobject jobj, jstring file)
The JDK delivers the binary javah.exe, which generates the header file for the native code. The usage is very simple, simply call it with the full qualified class:
javah de.dhbw.file.sha1.SHA1HashFileAsyncTask
In my case I have to give the bootclasspath additionally, because I use Android classes:
javah -bootclasspath <path_to_the_used_android_api> de.dhbw.file.sha1.SHA1HashFileAsyncTask
That would be the generated file:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class de_dhbw_file_sha1_SHA1HashFileAsyncTask */
#ifndef _Included_de_dhbw_file_sha1_SHA1HashFileAsyncTask
#define _Included_de_dhbw_file_sha1_SHA1HashFileAsyncTask
#ifdef __cplusplus
extern "C" {
#endif
#undef de_dhbw_file_sha1_SHA1HashFileAsyncTask_ERROR_CODE
#define de_dhbw_file_sha1_SHA1HashFileAsyncTask_ERROR_CODE -1L
#undef de_dhbw_file_sha1_SHA1HashFileAsyncTask_PROGRESS_CODE
#define de_dhbw_file_sha1_SHA1HashFileAsyncTask_PROGRESS_CODE 1L
/*
* Class: de_dhbw_file_sha1_SHA1HashFileAsyncTask
* Method: calcFileSha1
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_de_dhbw_file_sha1_SHA1HashFileAsyncTask_calcFileSha1
(JNIEnv *, jobject, jstring);
/*
* Class: de_dhbw_file_sha1_SHA1HashFileAsyncTask
* Method: getProgress
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_de_dhbw_file_sha1_SHA1HashFileAsyncTask_getProgress
(JNIEnv *, jobject);
/*
* Class: de_dhbw_file_sha1_SHA1HashFileAsyncTask
* Method: unlockMutex
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_de_dhbw_file_sha1_SHA1HashFileAsyncTask_unlockMutex
(JNIEnv *, jobject);
/*
* Class: de_dhbw_file_sha1_SHA1HashFileAsyncTask
* Method: getHash
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_de_dhbw_file_sha1_SHA1HashFileAsyncTask_getHash
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
You can change the file without further notice. But do not use javah again!
Class and methods
To get a class instance you can use jclass clz = callEnv->FindClass(CALL_CLASS);. In this case is CALL_CLASS the full qualified path to the class de/dhbw/file/sha1/SHA1HashFileAsyncTask.
To find a method you need the JNIEnv and an instance of the class:
jmethodID midSet = callEnv->GetMethodID(callClass, "setFileSize", "(J)V");
The first argument is the instance of the class, the second the name of the method and the third is the signature of the method.
The signature you can get with the from JDK given binary javap.exe. Simply call it with the full qualified path of the class f.e. javap -s de.dhbw.file.sha1.SHA1HashFileAsyncTask.
You will get an result like:
Compiled from "SHA1HashFileAsyncTask.java"
public class de.dhbw.file.sha1.SHA1HashFileAsyncTask extends android.os.AsyncTas
k<java.lang.String, java.lang.Integer, java.lang.String> {
[...]
static {};
Signature: ()V
public de.dhbw.file.sha1.SHA1HashFileAsyncTask(android.content.Context, de.dhb
w.file.sha1.SHA1HashFileAsyncTask$SHA1AsyncTaskListener);
Signature: (Landroid/content/Context;Lde/dhbw/file/sha1/SHA1HashFileAsyncTas
k$SHA1AsyncTaskListener;)V
protected native void calcFileSha1(java.lang.String);
Signature: (Ljava/lang/String;)V
protected native int getProgress();
Signature: ()I
protected native void unlockMutex();
Signature: ()V
protected native java.lang.String getHash();
Signature: ()Ljava/lang/String;
[...]
public void setFileSize(long);
Signature: (J)V
[...]
}
If the method is found the variable is not equal 0.
Calling the method is very easy:
callEnv->CallVoidMethod(callObj, midSet, size);
The first argument is the given jobject from the "main" method and I think the others are clear.
Remember that you can call from native code although private methods of the class, because the native code is part of it!
Strings
The given string would be converted with following code:
jboolean jbol;
const char *fileName = env->GetStringUTFChars(file, &jbol);
And the other way:
TCHAR* szReport = new TCHAR;
jstring result = callEnv->NewStringUTF(szReport);
It can be every char* variable.
Exceptions
Can be thrown with the JNIEnv:
callEnv->ThrowNew(callEnv->FindClass("java/lang/Exception"),
"Hash generation failed");
You can also check if there is an exception occurred also with JNIEnv:
if (callEnv->ExceptionOccurred()) {
callEnv->ExceptionDescribe();
callEnv->ExceptionClear();
}
Specifications
Java Native Interface Specifications
Build/Clean
Build
After we have created all files and filled them with content, we can build it.
Open cygwin, navigate to the project root and execute from there the ndk-build, which is in the NDK root.
This start the compile, if it is success you will get an output like that:
$ /cygdrive/d/android-ndk-r5c/ndk-build
Compile++ thumb : SHA1Calc <= SHA1Calc.cpp
SharedLibrary : libSHA1Calc.so
Install : libSHA1Calc.so => libs/armeabi/libSHA1Calc.so
If there is any error, you will get the typical output from the compiler.
Clean
Open cygwin, switch in your Android project and execute the command /cygdrive/d/android-ndk-r5c/ndk-build clean.
Build apk
After you have build the native libraries you can build your project. I've found clean, it is advantageous to use the eclipse feature clean project.
Debugging
Debugging of java code isn't different as before.
The debugging of c++ code will follow in the next time.
Do this:
MessageDigest md = MessageDigest.getInstance("SHA1");
InputStream in = new FileInputStream("hereyourinputfilename");
byte[] buf = new byte[8192];
for (;;) {
int len = in.read(buf);
if (len < 0)
break;
md.update(buf, 0, len);
}
in.close();
byte[] hash = md.digest();
Performance comes from handling data by blocks. An 8 kB buffer, as here, ought to be blocky enough. You do not have to use a BufferedInputStream since the 8 kB buffer also serves as I/O buffer.
The reason the fast one is fast and incorrect is (I think) that it is not hashing the file contents!
FileInputStream fis = new FileInputStream("C:/Users/Ich/Downloads/srware_iron.exe");
ByteArrayInputStream byteArrayInputStream =
new ByteArrayInputStream(fis.toString().getBytes());
The fis.toString() call does not read the contents of the file. Rather it gives you a string that (I suspect) looks something like this:
"java.io.FileInputStream#xxxxxxxx"
which you are then proceeding to calculate the SHA1 hash for. FileInputStream and its superclasses do not override Object::toString ...
The simple way to read the entire contents of an InputStream to a byte[] is to use an Apache Commons I/O helper method - IOUtils.toByteArray(InputStream).
public void computeSHAHash(String path)// path to your file
{
String SHAHash = null;
try
{
MessageDigest md = MessageDigest.getInstance("SHA1");
InputStream in = new FileInputStream(path);
byte[] buf = new byte[8192];
int len = -1;
while((len = in.read(buf)) > 0)
{
md.update(buf, 0, len);
}
in.close();
byte[] data = md.digest();
try
{
SHAHash = convertToHex(data);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeToast(getApplicationContext(),"Generated Hash ="+SHAHash,Toast.LENGTH_SHORT).show();
}
private static String convertToHex(byte[] data) throws java.io.IOException
{
StringBuffer sb = new StringBuffer();
String hex = null;
hex = Base64.encodeToString(data, 0, data.length, NO_OPTIONS);
sb.append(hex);
return sb.toString();
}

Categories

Resources