Issues with SHA1 hash implementation in Android

前端 未结 4 683
自闭症患者
自闭症患者 2020-12-13 11:33

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 F

4条回答
  •  暖寄归人
    2020-12-13 12:11

    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).

提交回复
热议问题