Skip to content

Commit

Permalink
Created command: md5sum
Browse files Browse the repository at this point in the history
  • Loading branch information
jdparent committed Dec 21, 2010
1 parent 08c4eda commit aeb3a4f
Show file tree
Hide file tree
Showing 4 changed files with 107 additions and 0 deletions.
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ SUBDIRS = basename\
cal\
cat\
echo\
md5sum\
mkdir\
pbd\
sleep
Expand Down
9 changes: 9 additions & 0 deletions md5sum/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# md5sum - calculate RFC1321 hash of files

TARG = md5sum

include ../std.mk

pre-uninstall:

post-install:
13 changes: 13 additions & 0 deletions md5sum/md5sum.1
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
.TH MD5SUM 1
.SH NAME
md5sum \- compute and check MD5 message digest
.SH SYNOPSIS
.B md5sum
[
.I file ...
]
.SH DESCRIPTION
Md5sum computes the 32 hex digit RSA Data Security, Inc. MD5
Message-Digest Algorithm described in RFC1321. If no files are
givem, the standard input is summed.

84 changes: 84 additions & 0 deletions md5sum/md5sum.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package main

import (
"os"
"fmt"
"flag"
"crypto/md5"
"io/ioutil"
)

func usage() {
fmt.Fprintf(os.Stderr, "usage: md5sum [file ...]\n")
os.Exit(1)
}

func main() {
flag.Parse()

if flag.NArg() == 0 { // Stdin
f := os.Stdin
h := md5.New()
var buf [64]byte

for {
switch nr, _ := f.Read(buf[:]); true {
case nr > 0:
_, e := h.Write(buf[0:nr])

if e != nil {
fmt.Fprintf(os.Stderr, "md5sum: error generating hash\n")
os.Exit(1)
}
case nr == 0:
s := h.Sum()

for j := 0; j < len(s); j++ {
if s[j] < 0x10 {
fmt.Fprintf(os.Stdout, "0%0x", s[j])
} else {
fmt.Fprintf(os.Stdout, "%0x", s[j])
}
}
fmt.Fprintf(os.Stdout, " -\n")
return
case nr < 0:
fmt.Fprintf(os.Stderr, "md5sum: error generating hash\n")
os.Exit(1)
}
}
} else {
h := md5.New()

for i := 0; i < flag.NArg(); i++ {
d, e := ioutil.ReadFile(flag.Arg(i))

if e != nil {
fmt.Fprintf(os.Stderr, "md5sum: cant read file %s\n", flag.Arg(i))
os.Exit(1)
}

_, e = h.Write(d)

if e != nil {
fmt.Fprintf(os.Stderr, "md5sum: error generating hash\n")
os.Exit(1)
}

s := h.Sum()

for j := 0; j < len(s); j++ {
if s[j] < 0x10 {
fmt.Fprintf(os.Stdout, "0%0x", s[j])
} else {
fmt.Fprintf(os.Stdout, "%0x", s[j])
}
}

fmt.Fprintf(os.Stdout, " %s\n", flag.Arg(i))

h.Reset() // Reset has for next file
}
}
}

0 comments on commit aeb3a4f

Please sign in to comment.