logo
down
shadow

MD5 checksum from input stream


MD5 checksum from input stream

By : lehung1192
Date : November 17 2020, 04:28 AM
I hope this helps . The method digest() returns the hash as bytes. Then you tried to turn those bytes into a string directly.
What you wanted is to convert each of those bytes into two hexadecimal digits. Here is the code:
code :
byte[] hash = complete.digest();
StringBuilder sb = new StringBuilder();
for (byte b : hash)
  sb.append(String.format("%02x", b & 0xFF));
String hexHash = sb.toString();
System.out.println(hexHash);


Share : facebook icon twitter icon
Easy way to generate XOR checksum on a stream?

Easy way to generate XOR checksum on a stream?


By : Tammy Freeman
Date : March 29 2020, 07:55 AM
I hope this helps . In C# is there an easy way to generate an XOR checksum on a MemoryStream (binary) excluding the first, and last two, bytes? , You can use LINQ to get the answer:
code :
var checksum = memStream
    .GetBuffer() // Get the underlying byte array
    .Skip(1)     // Skip the first byte
    .Take(memStream.Length-3) // One for the beginning, two more for the end
    .Aggregate(0, (p,v) => p ^ v); // XOR the accumulated value and the next byte
preCalculate file stream checksum

preCalculate file stream checksum


By : ZENG g
Date : March 29 2020, 07:55 AM
With these it helps i'm trying to ensure an output File integrity in case of disk out of space , network problem ,or any anyException that might occur during the streaming to file process . is there a way to precalculate the FileStream checkSum before writing to disk then check if the file was written properly. it sounds a bit nonsensical for me , that a system validates the integrity of its own exported XML through checkSum , normaly it's the job of the other end to verify if the the consumed file lives up to the file produced by the other system . , try this :
code :
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.MessageDigest;


public class CheckSumFileTest 
{

    private File buildChecksumFile(File fileToCheck, String filePrefix, String checksumAlgorithm) throws Exception
    {
        String checksum = null;
        File checksumFile = null;
        String tempDir = System.getProperty("java.io.tmpdir");
        try {
            checksumFile = new File(tempDir, filePrefix+"."+ checksumAlgorithm.toLowerCase());
            checksumFile.createNewFile();
            checksumFile.deleteOnExit();
        } catch (Exception e1) {
            e1.printStackTrace();
            throw e1;
        }
        FileWriter fw = null;
        try {
            checksum = checkSum(fileToCheck,checksumAlgorithm);
            fw = new FileWriter(checksumFile);
            fw.write(checksum);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        finally
        {
            if(fw !=null)
                fw.close();
        }

        return checksumFile;
    }

    private static String checkSum(File file, String checksumAlgorithm) throws Exception
    {
        MessageDigest digest = MessageDigest.getInstance(checksumAlgorithm);

        InputStream input = null;
        StringBuffer sb = new StringBuffer();
        try{
            input = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            do {
                int read = input.read(buffer);
                if(read <= 0)
                    break;
                digest.update(buffer, 0, read);
            } while(true);
            byte[] sum = digest.digest();

            for (int i = 0; i < sum.length; i++) {
                sb.append(Integer.toString((sum[i] & 0xff) + 0x100, 16).substring(1));
            }

        }catch(IOException io)
        {

        }finally{
            if(input != null)
                input.close();
        }

        return sb.toString();
    }

    private static String checkSumInStream(InputStream stream, String checksumAlgorithm) throws Exception
    {
        MessageDigest digest = MessageDigest.getInstance(checksumAlgorithm);

        InputStream input = null;
        StringBuffer sb = new StringBuffer();
        try{
            input = stream;
            byte[] buffer = new byte[8192];
            do {
                int read = input.read(buffer);
                if(read <= 0)
                    break;
                digest.update(buffer, 0, read);
            } while(true);
            byte[] sum = digest.digest();

            for (int i = 0; i < sum.length; i++) {
                sb.append(Integer.toString((sum[i] & 0xff) + 0x100, 16).substring(1));
            }

        }catch(IOException io)
        {

        }finally{
            if(input != null)
                input.close();
        }

        return sb.toString();
    }

    private boolean checkIntegrity(String targetFileName, String checksumFileName, String checksumAlgorithm) throws Exception
    {
        FileInputStream stream = null;
        BufferedReader br = null;
        InputStreamReader ipsr = null;
        File checksumFile = null;
        String checksumString="";
        File targetFile = new File(targetFileName);
        try{
            checksumFile = new File(checksumFileName);
            stream = new FileInputStream(checksumFile);
            ipsr = new InputStreamReader(stream);
            br = new BufferedReader(ipsr);

            //In checksum file : only one line to read
            checksumString = br.readLine();

        }finally
        {
            if(br != null)
                br.close();
            if(ipsr != null)
                ipsr.close();
            if(stream != null)
                stream.close();
        }


        if(checksumString.equals(checkSum(targetFile,checksumAlgorithm)))
        {
            return true;
        }
        else
        {
            return false;
        }
    }



    /**
     * @param args
     */
    public static void main(String[] args) 
    {
        String str = "Amine";
        InputStream stream = new ByteArrayInputStream(str.getBytes());
        //step1
        try {
            System.out.println(checkSumInStream(stream,"MD5"));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //step2
        File file = new File("c:/test.txt");

        // if file doesnt exists, then create it
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        FileWriter fw;
        BufferedWriter bw;

        try {
            fw = new FileWriter(file.getAbsoluteFile());
            bw = new BufferedWriter(fw);
            bw.write(str);
            bw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            System.out.println(checkSum(file, "MD5"));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Done");
    }

}
ClassNotFoundException: stream class checksum mismatch

ClassNotFoundException: stream class checksum mismatch


By : user2005562
Date : March 29 2020, 07:55 AM
it fixes the issue Looks like you are trying (intentionally or not) to send java.io.FileDescriptor over the network. I cannot confirm this right now, but I believe this class may be platform-specific, thus the checksum mismatch.
On the other hand, deserialized file descriptor will not be valid on remote computer anyway because it contains operating system file descriptors/handles. I think the solution here is just to make sure that instances of java.io.FileDescriptor are not sent to remote nodes.
computing checksum for an input stream

computing checksum for an input stream


By : Saviour Nibir
Date : March 29 2020, 07:55 AM
This might help you You're using the same stream object for both calls - after you've called checkSum once, the stream will not have any more data to read, so the second call will be creating a hash of an empty stream. The simplest approach would be to create a new stream each time:
code :
String test = "Hello world";
byte[] bytes = test.getBytes(StandardCharsets.UTF_8);
System.out.println("MD5 checksum for file using Java : " 
    + checkSum(new ByteArrayInputStream(bytes)));
System.out.println("MD5 checksum for file using Java : " 
    + checkSum(new ByteArrayInputStream(bytes)));
Python: test response stream with md5 checksum

Python: test response stream with md5 checksum


By : Sara
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , By reading help(hashlib) I think you can iterate your response something like this:
code :
hs = hashlib.md5()
...
for i in rv.response:
  hs.update(i)

self.assertEqual(hs.hexdigest(), ...)
Related Posts Related Posts :
  • How to write generic Java API without method Overloading
  • Java Serialization / Deserialization of an ArrayList works only on first program execution
  • Conway's Game of Life's rules dont apply properly
  • call a java method when Click on a html button without using javascript
  • Why does SSLSocketFactory.createSocket returns a Socket instead of SSLSocket?
  • How to schedule a task in Tomcat
  • compare two pdf files (approach) using java
  • What is the use of allowCoreThreadTimeout( ) in ThreadPoolExecutor?
  • Describe the Strategy Design Pattern in Java?
  • MongoDB too many open connections
  • Issue with generate JAXB classes with value constructors
  • Moving from one frame to another in java swing
  • Get a thread by Id
  • how to open front camera and back camera at same time?
  • Messed up with Java Declaration
  • Extracting chart in EXcel as image using java
  • How to get latitude and longitude in Android phone?
  • Do GC pauses and kill -STOP produce the same behavior?
  • Android HTML.ImageGetter Images resized
  • The way to instantiate map<String, List<String>> in Java
  • Java Making objects move while buttons held
  • Androidx Navigation View - `setNavigationItemSelectedListener` Doesn't Work
  • after compiling code JFrame does not appear
  • Netbeans project, JFrames ran from the main JFrame close all JFrames in project
  • Square Retrofit Client: How to enable/disable followRedirects? How to intercept redirect URL?
  • Java Circular Reference - Can’t Compile
  • Mouse click on specific time JAVA
  • android 4 onCreateDialog return type incompatible when overriding
  • Java Implementation of Oracle's DBMS_UTILITY.GET_HASH_VALUE Function
  • javac cannot be run, and furthermore does not seem installed
  • Function to obtain a thread given its ID
  • Java File path to Executable has spaces
  • Minimum Oracle Java VM heap memory setting?
  • Elegant way to create one of a large number of classes
  • Java fx binding styles
  • Summing weights based on string in large file
  • Android ListView setOnItemClickListener not working
  • How is the Java Bootstrap Classloader loaded?
  • Check object is blank
  • Add image between text in JEditorPane
  • Java POI Excel creating new column and new rows
  • NullPointerException when managing bean with Spring+JSF(Primefaces)
  • Content autocomplete in spring tool suite 4
  • Super Noob Help ~ MouseEvent/Frame
  • Making one project with dependencies stand-alone in Eclipse (Java)
  • Jsoup- getting certain attributes from website
  • MongoDB, how to make a link between collections with JAVA code
  • Overriding an abstract method means class abstract class or not in java?
  • Bukkit teleport - nullPointerException
  • How to check if a Float variable is negative in java
  • Servlet: Cannot forward after response has been committed
  • sql query to select a specific cell in excel
  • How to make new picture when mouse dragged in java
  • Use Constants interface in GWT Project
  • Setting size of a JPanel in GroupLayout
  • Construct a map from two equal size arrays
  • Implementing Read-Write Locks with Double-Checked Locking
  • Disable NO_BUTTON from JOptionPane Java if a condition is true
  • UDP multiple socket
  • Android Threading: This Handler class should be static or leaks might occur
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org