How to use the xxxx.md5 file or how to remove .md5 extension?

louxiu picture louxiu · Apr 13, 2011 · Viewed 23.2k times · Source

I get files like this below:

GT-I5500-CSC-SERJK1.tar.md5

This is what I want:

GT-I5500-CSC-SERJK1.tar 

How can I get it? Can I just remove the md5 file extension?

Answer

beltorak picture beltorak · Feb 13, 2012

From what I understand this is a simple means of adding a checksum onto a tar file. Since the tar standard states that the end of the tar file is two successive blank "entries" in a row, all data past that point is ignored by "tar -x". So the android dev community has apparently taken to simply concatting the output of md5 to the end of this file.

The following bash script can be used to validate a ".tar.md5" file:

#! /bin/bash

check_tar_md5 () {
    local file="${1:?Required: file to check}"
    [[ ! -f "$file" ]] && {
            echo "File not found: $file" >&2
            return 1
    }
    local filename="$(basename "$file")"
    if [ "${filename##*.}" = md5 ]; then filename="${filename%.*}"; fi;
    local md5_line_length=$(printf "%032d *%s\n" 0 "$filename" | wc -c)
    local embedded_md5=$(tail -c $md5_line_length "$file" | ( read md5 rest; echo $md5 ) )
    local actual_md5=$(head -c -$md5_line_length "$file" | md5sum | ( read md5 rest; echo $md5 ) )
    if [ $embedded_md5 = $actual_md5 ]; then
            echo "$file: OK"
    else
            echo "$file: FAILED"
            return 1
    fi
}

[[ ! -z "$1" ]] && check_tar_md5 "$1"

If you 'source' this script you will have a 'check_tar_md5' function in your current env; otherwise you can just execute it; in either case you provide the file as the only argument. Output is similar to the "md5sum --check" utility.

Making the script more robust (e.g.: in the event you provide a file that is not a .tar.md5) is left as an exercise to the reader.