2

how one can run following Java functionality using shell script only? Shouldn't openssl do the trick? For some reason values are not same.

Shell:

$ cat test.txt 
test
$ openssl sha1 test.txt
SHA1(test.txt)= fde773a18bb29f5ed65e6f0a7aa717fd1fa485d4

Java code (play framework origin):

import org.apache.commons.codec.binary.Hex;

public static String hexSHA1() {
    value = "test";
    try {
        MessageDigest md;
        md = MessageDigest.getInstance("SHA-1");
        md.update(value.getBytes("utf-8"));
        byte[] digest = md.digest();

        return byteToHexString(digest);
    } catch (Exception ex) {
        return null;
    }
}


public static String byteToHexString(byte[] bytes) {
    // a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
    return String.valueOf(Hex.encodeHex(bytes));
}

fde773a18bb29f5ed65e6f0a7aa717fd1fa485d4 != a94a8fe5ccb19ba61c4c0873d391e987982fbbd3

Markku
  • 555
  • 1
  • 8
  • 15
  • Next time, just read the binary data of `test.txt` into Java and see if the digest matches. If it does, check the if the *binary* input of the digest matches the one in the file. To see how to read a binary file, use this Q: http://stackoverflow.com/questions/858980/file-to-byte-in-java (check out the Java 7 way, should be a one liner). – Maarten Bodewes Jan 14 '13 at 22:14

2 Answers2

7

You have a carriage return and line feed at the end of test.txt. These are apparently not in your Java string.

$ echo -n test > test.txt
$ openssl sha1 test.txt
SHA1(test.txt)= a94a8fe5ccb19ba61c4c0873d391e987982fbbd3

$ echo -ne 'test\r\n' > test2.txt
$ openssl sha1 test2.txt
SHA1(test2.txt)= fde773a18bb29f5ed65e6f0a7aa717fd1fa485d4
PleaseStand
  • 31,641
  • 6
  • 68
  • 95
0

Values are not the same as in the first case you're calulating SHA1 for test.txt file, in next case you're calculating the same for test string.

If you're going to call openssl from inside java app use this code snippets:

Runtime.getRuntime().exec('openssl', 'sha1', 'test.txt')

Archer
  • 5,073
  • 8
  • 50
  • 96