I'm trying to implement SHA-1 on Android with the following code
String name = "potato";
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(name.getBytes("iso-8859-1"), 0 , name.getBytes( "iso-8859-1").length );
Bytes[] sha1hash = md.digest();
textview.setText(sha1hash.toString());
but when i run this code twice, it gives me different hash codes to "potato". As far as i know they should give me the same answer every time i run the program, anyone have any idea what problem could it be?
You can use this Code for getting SHA-1 value.
public class sha1Calculate {
public static void main(String[] args)throws Exception
{
File file = new File("D:\\Android Links.txt");
String outputTxt= "";
String hashcode = null;
try {
FileInputStream input = new FileInputStream(file);
ByteArrayOutputStream output = new ByteArrayOutputStream ();
byte [] buffer = new byte [65536];
int l;
while ((l = input.read (buffer)) > 0)
output.write (buffer, 0, l);
input.close ();
output.close ();
byte [] data = output.toByteArray ();
MessageDigest digest = MessageDigest.getInstance( "SHA-1" );
byte[] bytes = data;
digest.update(bytes, 0, bytes.length);
bytes = digest.digest();
StringBuilder sb = new StringBuilder();
for( byte b : bytes )
{
sb.append( String.format("%02X", b) );
}
System.out.println("Digest(in hex format):: " + sb.toString());
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try this Link for any Help.
http://www.mkyong.com/java/how-to-generate-a-file-checksum-value-in-java/
Related
public class helloWorldClient {
public static void main(String[] args) {
helloWorldClient crunchifyClient = new helloWorldClient();
crunchifyClient.getResponse();
}
private void getResponse() {
try {
Client client = Client.create();
WebResource webResource2 = client.resource("http://localhost:8080/Downloader/webapi/folder/zipFile");
ClientResponse response2 = webResource2.accept("application/zip").get(ClientResponse.class);
if (response2.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response2.getStatus());
}
String output2 = response2.getEntity(String.class);
System.out.println("\n============RESPONSE============");
System.out.println(output2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This program returning an unreadable output. but when I hit that URL "http://localhost:8080/Downloader/webapi/folder/zipFile" in browser "server.zip" file is getting downloaded.
My question is how can I read that response and write to some folder through java client program?
You can get the InputStream instead of String. Then just do your basic IO.
InputStream output2 = response2.getEntity(InputStream.class);
FileOutputStream out = new FileOutputStream(file);
// do io writing
// close streams
InputStream output2 = response2.getEntity(InputStream.class);
OutputStream out = new FileOutputStream(new File("/home/mpasala/Downloads/demo.zip"));
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = output2.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
output2.close();
out.close();
System.out.println("Done!");
Thanks to https://stackoverflow.com/users/2587435/peeskillet .
I try to create an asynctask that runs permanently (all the time my app is running). Thay task read every second a file on a server (status.xml).
My problem is that when I execute the app, I have an java.io.IOException: closed exception the second time I do :
reader.read(buffer); // HERE I HAVE AN IOException closed
(first loop is ok, then I have error each loop)
Thanks if someone can help me. I undesrtand the reason of the error, but I cannot find a solution...
Here is my code :
class StatusnAsync extends AsyncTask<Void, Void, Void> {
InputStream in = null;
int responseCode;
void Sleep(int ms) {
try {
Thread.sleep(ms);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
// inits for doInBackground thread
try {
URL url = new URL(address + "/status.xml");
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000 /* milliseconds */);
conn.setConnectTimeout(80000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected Void doInBackground(Void... arg0) {
while (not_end) {
try {
readStatus();
// Sleep 1 sec
Sleep(1000);
} catch (IOException e) {
e.printStackTrace ();
}
}
return null;
}
private void readStatus() throws IOException {
try {
conn.connect();
responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
in = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(in, 340);
// close the inputstream
in.close();
}
} catch (IOException e) {
e.printStackTrace ();
} finally {
if (in != null) in.close();
}
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer); // HERE I HAVE AN IOException closed
return new String(buffer);
}
}
Thank you.
Sorry for my question, I found my error, a stupid error.
Of course I need to openConnection for each GET.
I give the corrected code if it can help someone :
class StatusnAsync extends AsyncTask<Void, Void, Void> {
InputStream in = null;
int responseCode;
URL url;
void Sleep(int ms) {
try {
Thread.sleep(ms);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
// inits for doInBackground thread
try {
url = new URL(address + "/file.xml");
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
#Override
protected Void doInBackground(Void... arg0) {
while (not_end) {
try {
readStatus();
// Sleep 1 sec
Sleep(1000);
} catch (IOException e) {
e.printStackTrace ();
}
}
return null;
}
private void readStatus() throws IOException {
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000 /* milliseconds */);
conn.setConnectTimeout(80000 /* milliseconds */);
conn.connect();
responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
in = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(in, 340);
// close the inputstream
in.close();
}
} catch (IOException e) {
e.printStackTrace ();
} finally {
if (in != null) in.close();
}
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
}
I have a problem w my applet: shortly speaking, I want to "take" the variable curreny which is taken from xml and print it when I click on the button OK. The error I get is: error: cannot find symbol curreny. The problem is not importing variable from xml, because I checked separately if it works.
Sorry for the messy code, I'm new to java. All the neccessary packages are imported in the original source, but i didnt put it here just to make the code shorter. EDIT: I deleted part of the code consisting GUI to make it shorter, as you suggested.
public class App2 extends Applet implements ActionListener {
TextField T1 = new TextField();
Label L1 = new Label();
/* GUI code here */
public void actionPerformed(ActionEvent ae)
{
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document xmlDocument = db.parse(new URL("http://www.nbp.pl/kursy/xml/LastA.xml").openStream());
xmlDocument.getDocumentElement().normalize();
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/tabela_kursow/pozycja[3]/kurs_sredni";
// System.out.println(expression);
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
// System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
String kurs_dolara = nodeList.item(i).getFirstChild().getNodeValue();
double d_kurs_dolara = Double.parseDouble(kurs_dolara.replace(',', '.'));
System.out.println(d_kurs_dolara*6);
}
expression = "/tabela_kursow/pozycja[8]/kurs_sredni";
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
String kurs_euro = nodeList.item(i).getFirstChild().getNodeValue();
double d_kurs_euro = Double.parseDouble(kurs_euro.replace(',', '.'));
System.out.println(d_kurs_euro*6);
}
expression = "/tabela_kursow/pozycja[11]/kurs_sredni";
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
String kurs_funta = nodeList.item(i).getFirstChild().getNodeValue();
double d_kurs_funta = Double.parseDouble(kurs_funta.replace(',', '.'));
System.out.println(d_kurs_funta*6);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
}
String wynik = String.valueOf(d_kurs_euro);
L1.setText(wynik);
repaint();
}}
I have a method which loads file from sdcard (Android) and then reads it with StringBuilder. The text which im reading is written with my native language characters such as ą ś ć ź ż...
StringBuilder (or FileInputStream) can't read them properly unfortunately. How I can set proper encoding ?
here is the code :
File file = new File(filePath);
FileInputStream fis = null;
StringBuilder builder = new StringBuilder();
try {
fis = new FileInputStream(file);
int content;
while ((content = fis.read()) != -1) {
builder.append((char) content);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
System.out.println("File Contents = " + builder.toString());
contactService.updateContacts(builder.toString());
for example you could try an InputStreamReader combinded with a BufferedReader, that should do the trick:
InputStreamReader inputStreamReader = new InputStreamReader((InputStream)fis, "UTF-8");
BufferedReader br = new BufferedReader(inputStreamReader);
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
So long,
Tom
I'm trying to write some data into DataOutputStream from FileConnection.
FileConnection con = (FileConnection)Connector.open("file:///C:/file.txt");
if (!con.exists())
con.create();
DataOutputStream out = con.openDataOutputStream();
out.writeUTF("some text");
out.close();
con.close();
But rather than the text I've typed, I receive some garbage in the file - like there are some problems with encoding.
Ok, from what I can see it adds null and 0xFF sign at the start of a file.
What can be the cause?
Please Look at my method for writing Files in Java ME
I think you are missing Connector.READ_WRITE in your code,
private void writeTextFile(String fileName, String text)
{
DataOutputStream os = null;
FileConnection fconn = null;
try
{
fconn = (FileConnection) Connector.open(fileName, Connector.READ_WRITE);
if (!fconn.exists())
fconn.create();
os = fconn.openDataOutputStream();
os.write(text.getBytes());
} catch (IOException e) {
System.out.println(e.getMessage());
} finally
{
try
{
if (null != os)
os.close();
if (null != fconn)
fconn.close();
} catch (IOException e)
{
System.out.println(e.getMessage());
}
}
}