Exemplo n.º 1
2
func GetHash(a string) (hash.Hash, error) {
	var h hash.Hash
	switch a {
	case "adler32":
		h = adler32.New()
	case "crc32", "crc32ieee":
		h = crc32.New(crc32.MakeTable(crc32.IEEE))
	case "crc32castagnoli":
		h = crc32.New(crc32.MakeTable(crc32.Castagnoli))
	case "crc32koopman":
		h = crc32.New(crc32.MakeTable(crc32.Koopman))
	case "crc64", "crc64iso":
		h = crc64.New(crc64.MakeTable(crc64.ISO))
	case "crc64ecma":
		h = crc64.New(crc64.MakeTable(crc64.ECMA))
	case "fnv", "fnv32":
		h = fnv.New32()
	case "fnv32a":
		h = fnv.New32a()
	case "fnv64":
		h = fnv.New64()
	case "fnv64a":
		h = fnv.New64a()
	case "hmac", "hmacsha256":
		h = hmac.New(sha256.New, []byte(key))
	case "hmacmd5":
		h = hmac.New(md5.New, []byte(key))
	case "hmacsha1":
		h = hmac.New(sha1.New, []byte(key))
	case "hmacsha512":
		h = hmac.New(sha512.New, []byte(key))
	case "md4":
		h = md4.New()
	case "md5":
		h = md5.New()
	case "ripemd160":
		h = ripemd160.New()
	case "sha1":
		h = sha1.New()
	case "sha224":
		h = sha256.New224()
	case "sha256":
		h = sha256.New()
	case "sha384":
		h = sha512.New384()
	case "sha512":
		h = sha512.New()
	default:
		return nil, errors.New("Invalid algorithm")
	}
	return h, nil
}
Exemplo n.º 2
0
func (e *Engine) sha224() error {
	data, err := computeHash(sha256.New224(), e.stack.Pop())
	if err == nil {
		e.stack.Push(data)
	}
	return err
}
Exemplo n.º 3
0
func process_file(filename string, complete chan Sumlist) {
	sumlist := Sumlist{}
	sumlist.filename = filename

	// Open the file and bail if we fail
	infile, err := os.Open(filename)
	if err != nil {
		log.Printf("Unable to open %s: %s", filename, err)
		complete <- sumlist
		return
	}
	defer infile.Close()

	// Create the checksum objects
	if flag_crc32 {
		sumlist.sums = append(sumlist.sums, Checksum{"CRC32", crc32.New(crc32.IEEETable)})
	}
	if flag_crc64 {
		sumlist.sums = append(sumlist.sums, Checksum{"CRC64", crc64.New(crc64.MakeTable(crc64.ISO))})
	}
	if flag_sha224 {
		sumlist.sums = append(sumlist.sums, Checksum{"SHA224", sha256.New224()})
	}
	if flag_sha256 {
		sumlist.sums = append(sumlist.sums, Checksum{"SHA256", sha256.New()})
	}
	if flag_sha384 {
		sumlist.sums = append(sumlist.sums, Checksum{"SHA384", sha512.New384()})
	}
	if flag_sha512 {
		sumlist.sums = append(sumlist.sums, Checksum{"SHA512", sha512.New()})
	}

	// Create our file reader
	reader := bufio.NewReader(infile)

	// Start a buffer and loop to read the entire file
	buf := make([]byte, 4096)
	for {
		read_count, err := reader.Read(buf)
		// If we get an error that is not EOF, then we have a problem
		if err != nil && err != io.EOF {
			log.Printf("Unable to open %s: %s", filename, err)
			complete <- sumlist
			return
		}
		// If the returned size is zero, we're at the end of the file
		if read_count == 0 {
			break
		}

		// Add the buffer contents to the checksum calculation
		for _, sum := range sumlist.sums {
			sum.hashFunc.Write(buf[:read_count])
		}

	}

	complete <- sumlist
}
Exemplo n.º 4
0
// Encrypts a symmetric key to this identity
func (this *PublicIdentity) Encrypt(key *SymmetricKey) (ek *EncryptedKey) {
	out, err := rsa.EncryptOAEP(sha256.New224(), rand.Reader, this.key, key.key, nil)
	if err != nil {
		panic(err)
	}
	return &EncryptedKey{impl: out}
}
Exemplo n.º 5
0
// Checksum returns the checksum of some data, using a specified algorithm.
// It only returns an error when an invalid algorithm is used. The valid ones
// are MD5, SHA1, SHA224, SHA256, SHA384, SHA512, SHA3224, SHA3256, SHA3384,
// and SHA3512.
func Checksum(algorithm string, data []byte) (checksum string, err error) {
	// default
	var hasher hash.Hash
	switch strings.ToUpper(algorithm) {
	case "MD5":
		hasher = md5.New()
	case "SHA1":
		hasher = sha1.New()
	case "SHA224":
		hasher = sha256.New224()
	case "SHA256":
		hasher = sha256.New()
	case "SHA384":
		hasher = sha512.New384()
	case "SHA512":
		hasher = sha512.New()
	case "SHA3224":
		hasher = sha3.New224()
	case "SHA3256":
		hasher = sha3.New256()
	case "SHA3384":
		hasher = sha3.New384()
	case "SHA3512":
		hasher = sha3.New512()
	default:
		msg := "Invalid algorithm parameter passed go Checksum: %s"
		return checksum, fmt.Errorf(msg, algorithm)
	}
	hasher.Write(data)
	str := hex.EncodeToString(hasher.Sum(nil))
	return str, nil
}
Exemplo n.º 6
0
// Decrypts a symmetric key encrypted to this Identity
func (this *SecretIdentity) Decrypt(ek *EncryptedKey) (key *SymmetricKey) {
	out, err := rsa.DecryptOAEP(sha256.New224(), rand.Reader, this.key, ek.impl, nil)
	if err != nil {
		panic(err)
	}
	return &SymmetricKey{key: out}
}
Exemplo n.º 7
0
func main() {
	for _, h := range []hash.Hash{md4.New(), md5.New(), sha1.New(),
		sha256.New224(), sha256.New(), sha512.New384(), sha512.New(),
		ripemd160.New()} {
		fmt.Printf("%x\n\n", h.Sum())
	}
}
Exemplo n.º 8
0
// Sha224base64 performs a sha224 hash on a byte array and then perfroms a base64 encoding on the result.
func Sha224base64(item []byte) (string, []byte) {

	phash := sha256.New224()
	io.WriteString(phash, string(item))
	phashbytes := phash.Sum(nil)
	return base64.StdEncoding.EncodeToString(phashbytes), phashbytes
}
Exemplo n.º 9
0
func hash(pass string, salt_secret string, salt string, interation int64) (string, error) {
	var pass_salt string = salt_secret + pass + salt + salt_secret + pass + salt + pass + pass + salt
	var i int

	hash_pass := salt_local_secret
	hash_start := sha512.New()
	hash_center := sha256.New()
	hash_output := sha256.New224()

	i = 0
	for i <= stretching_password {
		i = i + 1
		hash_start.Write([]byte(pass_salt + hash_pass))
		hash_pass = hex.EncodeToString(hash_start.Sum(nil))
	}

	i = 0
	for int64(i) <= interation {
		i = i + 1
		hash_pass = hash_pass + hash_pass
	}

	i = 0
	for i <= stretching_password {
		i = i + 1
		hash_center.Write([]byte(hash_pass + salt_secret))
		hash_pass = hex.EncodeToString(hash_center.Sum(nil))
	}
	hash_output.Write([]byte(hash_pass + salt_local_secret))
	hash_pass = hex.EncodeToString(hash_output.Sum(nil))

	return hash_pass, nil
}
Exemplo n.º 10
0
/*
   read from os.File and return the whole file's checksum
*/
func calc_checksum(fp io.Reader, t string) string {
	var m hash.Hash
	switch t {
	case "md5":
		m = md5.New()
	case "sha1":
		m = sha1.New()
	case "sha512":
		m = sha512.New()
	case "sha256":
		m = sha256.New()
	case "sha224":
		m = sha256.New224()
	case "sha384":
		m = sha512.New384()
	default:
		output_e("unknown type: %s\n", t)
		return ""
	}

	/*  issue:
	    if fp is os.Stdin, there is no way to trigger EOF
	*/
	_, err := io.Copy(m, fp)

	if err != nil {
		output_e("%ssum: %s\n", t, err.Error())
		return ""
	}

	return fmt.Sprintf("%x", m.Sum(nil))
}
Exemplo n.º 11
0
func Sha224Sum(rdr io.Reader) (hash []byte, err error) {
	s224 := sha256.New224()
	if _, err = io.Copy(s224, rdr); err != nil {
		return
	}
	hash = make([]byte, 0, sha256.Size224)
	hash = s224.Sum(hash)
	return
}
Exemplo n.º 12
0
// Computes a cryptographic fingerprint of this identity
func (this *PublicIdentity) Fingerprint() (fingerprint *Digest) {
	hash := sha256.New224()
	data, err := x509.MarshalPKIXPublicKey(this.key)
	if err != nil {
		panic(err)
	}
	hash.Write(data)
	return &Digest{impl: hash.Sum(nil)}
}
Exemplo n.º 13
0
func TestSize(t *testing.T) {
	c := sha256.New()
	if got := c.Size(); got != Size {
		t.Errorf("Size = %d; want %d", got, sha256.Size)
	}
	c = sha256.New224()
	if got := c.Size(); got != Size224 {
		t.Errorf("New224.Size = %d; want %d", got, sha256.Size224)
	}
}
Exemplo n.º 14
0
func (b *backend) pathHashWrite(
	req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
	inputB64 := d.Get("input").(string)
	format := d.Get("format").(string)
	algorithm := d.Get("urlalgorithm").(string)
	if algorithm == "" {
		algorithm = d.Get("algorithm").(string)
	}

	input, err := base64.StdEncoding.DecodeString(inputB64)
	if err != nil {
		return logical.ErrorResponse(fmt.Sprintf("unable to decode input as base64: %s", err)), logical.ErrInvalidRequest
	}

	switch format {
	case "hex":
	case "base64":
	default:
		return logical.ErrorResponse(fmt.Sprintf("unsupported encoding format %s; must be \"hex\" or \"base64\"", format)), nil
	}

	var hf hash.Hash
	switch algorithm {
	case "sha2-224":
		hf = sha256.New224()
	case "sha2-256":
		hf = sha256.New()
	case "sha2-384":
		hf = sha512.New384()
	case "sha2-512":
		hf = sha512.New()
	default:
		return logical.ErrorResponse(fmt.Sprintf("unsupported algorithm %s", algorithm)), nil
	}
	hf.Write(input)
	retBytes := hf.Sum(nil)

	var retStr string
	switch format {
	case "hex":
		retStr = hex.EncodeToString(retBytes)
	case "base64":
		retStr = base64.StdEncoding.EncodeToString(retBytes)
	}

	// Generate the response
	resp := &logical.Response{
		Data: map[string]interface{}{
			"sum": retStr,
		},
	}
	return resp, nil
}
Exemplo n.º 15
0
func cryptoSHA2Example() {
	h224 := sha256.New224()
	io.WriteString(h224, "foo")
	h256 := sha256.New()
	io.WriteString(h256, "foo")

	h384 := sha512.New384()
	io.WriteString(h384, "foo")
	h512 := sha512.New()
	io.WriteString(h512, "foo")

	fmt.Printf("SHA224 %x\n", h224.Sum(nil))
	fmt.Printf("SHA256 %x\n", h256.Sum(nil))
	fmt.Printf("SHA384 %x\n", h384.Sum(nil))
	fmt.Printf("SHA512 %x\n", h512.Sum(nil))
}
Exemplo n.º 16
0
func getHashSHA2(bitsize int) (hash.Hash, error) {
	switch bitsize {
	case 224:
		return sha256.New224(), nil
	case 256:
		return sha256.New(), nil
	case 384:
		return sha512.New384(), nil
	case 512:
		return sha512.New(), nil
	case 521:
		return sha512.New(), nil
	default:
		return nil, fmt.Errorf("Invalid bitsize. It was [%d]. Expected [224, 256, 384, 512, 521]", bitsize)
	}
}
Exemplo n.º 17
0
func printHashes(input io.Reader) {
	var md5writer hash.Hash = nil
	if *printmd5hash == false {
		md5writer = md5.New()
	}
	var sha1writer hash.Hash = nil
	if *printsha1hash == false {
		sha1writer = sha1.New()
	}
	var sha224writer hash.Hash = nil
	if *printsha224hash == false {
		sha224writer = sha256.New224()
	}
	var sha256writer hash.Hash = nil
	if *printsha256hash == false {
		sha256writer = sha256.New()
	}
	var sha384writer hash.Hash = nil
	if *printsha384hash == false {
		sha384writer = sha512.New384()
	}
	var sha512writer hash.Hash = nil
	if *printsha512hash == false {
		sha512writer = sha512.New()
	}
	hashwriter := NilSafeMultiWriter(md5writer, sha1writer, sha224writer, sha256writer, sha384writer, sha512writer)
	io.Copy(hashwriter, input)
	if md5writer != nil {
		fmt.Printf(" -md5 %x", md5writer.Sum(nil))
	}
	if sha1writer != nil {
		fmt.Printf(" -sha1 %x", sha1writer.Sum(nil))
	}
	if sha224writer != nil {
		fmt.Printf(" -sha224 %x", sha224writer.Sum(nil))
	}
	if sha256writer != nil {
		fmt.Printf(" -sha256 %x", sha256writer.Sum(nil))
	}
	if sha384writer != nil {
		fmt.Printf(" -sha384 %x", sha384writer.Sum(nil))
	}
	if sha512writer != nil {
		fmt.Printf(" -sha512 %x", sha512writer.Sum(nil))
	}
	fmt.Print("\n")
}
Exemplo n.º 18
0
func GenerateChallenge(
	/* to verify */ A *rsa.PublicKey,
	/* ours*/ B *rsa.PublicKey) (Challenge, [32]byte, error) {

	// variables
	var challenge Challenge
	var r [32]byte
	var err error

	// encode b
	copy(challenge.PubKey[:], crypto.MarshalPKCS1PublicKey(B))
	if err != nil {
		log.Fatalln("Auth.GenerateChallenge: cannot marshall public key b, error: " + err.Error())
	}

	// generate r
	_, err = rand.Read(r[:])
	if err != nil {
		log.Fatalln("Auth.GenerateChallenge: cannot get secure random number, error: " + err.Error())
	}
	//fmt.Printf("r: %.x\n", r)

	// get h(r)
	challenge.HR = sha256.Sum256(r[:])

	{ // get P_A(r,B)
		buf := make([]byte, 64)
		copy(buf[0:32], r[:])
		hb := sha256.Sum256(challenge.PubKey[:])
		copy(buf[32:64], hb[:])

		// encrypt (r,h(B))
		enc, err := rsa.EncryptOAEP(
			sha256.New224(), /* hash function  */
			rand.Reader,     /* random source  */
			A,               /* encryption key */
			buf,             /* plaintext      */
			[]byte{})        /* label          */
		if err != nil {
			return challenge, r, errors.New("Auth.GenerateChallenge: Could not encrypt (r,B), due to " + err.Error())
		}
		challenge.Enc = enc
	}
	// fill challenge struct
	return challenge, r, nil
}
Exemplo n.º 19
0
func TestGolden(t *testing.T) {
	for i := 0; i < len(golden); i++ {
		g := golden[i]
		s := fmt.Sprintf("%x", sha256.Sum256([]byte(g.in)))
		if s != g.out {
			t.Fatalf("Sum256 function: sha256(%s) = %s want %s", g.in, s, g.out)
		}
		c := sha256.New()
		for j := 0; j < 3; j++ {
			if j < 2 {
				io.WriteString(c, g.in)
			} else {
				io.WriteString(c, g.in[0:len(g.in)/2])
				c.Sum(nil)
				io.WriteString(c, g.in[len(g.in)/2:])
			}
			s := fmt.Sprintf("%x", c.Sum(nil))
			if s != g.out {
				t.Fatalf("sha256[%d](%s) = %s want %s", j, g.in, s, g.out)
			}
			c.Reset()
		}
	}
	for i := 0; i < len(golden224); i++ {
		g := golden224[i]
		s := fmt.Sprintf("%x", sha256.Sum224([]byte(g.in)))
		if s != g.out {
			t.Fatalf("Sum224 function: sha224(%s) = %s want %s", g.in, s, g.out)
		}
		c := sha256.New224()
		for j := 0; j < 3; j++ {
			if j < 2 {
				io.WriteString(c, g.in)
			} else {
				io.WriteString(c, g.in[0:len(g.in)/2])
				c.Sum(nil)
				io.WriteString(c, g.in[len(g.in)/2:])
			}
			s := fmt.Sprintf("%x", c.Sum(nil))
			if s != g.out {
				t.Fatalf("sha224[%d](%s) = %s want %s", j, g.in, s, g.out)
			}
			c.Reset()
		}
	}
}
Exemplo n.º 20
0
func SaveThumbnailAndImage(imgr io.ReadSeeker, maxw, maxh int, tdir, dir, fname string) (tname, name string, err error) {
	var resized bool
	tname, resized, err = saveThumbnail(imgr, maxw, maxh, tdir, fname)
	if err != nil {
		return
	}

	var source io.Reader
	var file *os.File

	if resized {
		imgr.Seek(0, 0)
		var s224 = sha256.New224()
		if _, err = io.Copy(s224, imgr); err != nil {
			return
		}

		hash := make([]byte, 0, sha256.Size224)
		hash = s224.Sum(hash)
		name = fmt.Sprintf("%x%s", hash, path.Ext(tname))
		imgr.Seek(0, 0)

		if _, err = os.Stat(dir + name); err == nil {
			return
		} else if !os.IsNotExist(err) {
			return
		}
		source = imgr
	} else {
		var sourcefile *os.File
		if sourcefile, err = os.Open(util.AddDirTrailSlash(tdir) + tname); err != nil {
			return
		}
		defer sourcefile.Close()
		source = sourcefile
		name = tname
	}

	if file, err = os.Create(dir + name); err != nil {
		return
	}
	defer file.Close()

	_, err = io.Copy(file, source)
	return
}
Exemplo n.º 21
0
func getHash(t string) hash.Hash {
	var h hash.Hash
	switch t {
	case "md5":
		h = md5.New()
	case "sha1":
		h = sha1.New()
	case "sha224":
		h = sha256.New224()
	case "sha256":
		h = sha256.New()
	case "sha384":
		h = sha512.New384()
	case "sha512":
		h = sha512.New()
	}
	return h
}
Exemplo n.º 22
0
func GenerateResponse(Challenge Challenge, A_PrivK *rsa.PrivateKey, B_Onion string) (Response, error) {
	var response Response
	// variables
	var hb_ [32]byte // B'
	var r_ [32]byte  // R'

	// check that onion of B == the host which we connected to in the first place!
	challenge_b, err := crypto.UnmarshalPKCS1PublicKey(Challenge.PubKey[:])
	if err != nil {
		return Response{[32]byte{0}}, errors.New("invalid B given by remote!")
	}
	if B_Onion != crypto.GetOnionAddress(&challenge_b) {
		return Response{[32]byte{0}}, errors.New("wrong B given by remote!")
	}

	{ // decrypt (r,h(B))
		dec, err := rsa.DecryptOAEP(
			sha256.New224(), /* hash function  */
			rand.Reader,     /* random source  */
			A_PrivK,         /* decryption key */
			Challenge.Enc,   /* ciphertext     */
			[]byte{})        /* label          */
		if err != nil {
			return response, errors.New("Auth.GenerateResponse: Could not decrypt challenge: " + err.Error())
		}
		copy(r_[:], dec[0:32])
		copy(hb_[:], dec[32:64])
		if err != nil {
			return response, errors.New("Auth.GenerateResponse: Could not decode b_")
		}
	}
	// check that h(B) == h(B') => B == B'
	if sha256.Sum256(Challenge.PubKey[:]) != hb_ {
		return response, errors.New("B and B' differ!")
	}

	// check that h(r) == h(r_)
	if sha256.Sum256(r_[:]) != Challenge.HR {
		return response, errors.New("h(r) and h(r') differ!")
	}

	return Response{r_}, nil
}
Exemplo n.º 23
0
func (p HashAlgorithm) Hasher() (hasher hash.Hash) {
	switch p {
	case MD5:
		hasher = md5.New()
	case SHA1:
		hasher = sha1.New()
	case SHA224:
		hasher = sha256.New224()
	case SHA256:
		hasher = sha256.New()
	case SHA384:
		hasher = sha512.New384()
	case SHA512:
		hasher = sha512.New()
	default:
		hasher = sha512.New()
	}
	return
}
Exemplo n.º 24
0
// hashFuncFromType returns a hash.Hash which corresponds to the given hash
// type byte. See RFC 4880, section 9.4.
func hashFuncFromType(hashType byte) hash.Hash {
	switch hashType {
	case 1:
		return md5.New()
	case 2:
		return sha1.New()
	case 3:
		return ripemd160.New()
	case 8:
		return sha256.New()
	case 9:
		return sha512.New384()
	case 10:
		return sha512.New()
	case 11:
		return sha256.New224()
	}

	return nil
}
Exemplo n.º 25
0
func createHash(method crypto.Hash) (hash.Hash, error) {
	var h hash.Hash

	switch method {
	case crypto.MD5:
		h = md5.New()
	case crypto.SHA1:
		h = sha1.New()
	case crypto.SHA224:
		h = sha256.New224()
	case crypto.SHA256:
		h = sha256.New()
	case crypto.SHA384:
		h = sha512.New384()
	case crypto.SHA512:
		h = sha512.New()
	default:
		return h, errors.New("Unsupported hashing method")
	}
	return h, nil
}
Exemplo n.º 26
0
// checksum checks the hash of a given file using the given algorithm
func checksum(parameters []string) (exitCode int, exitMessage string) {
	// getChecksum returns the checksum of some data, using a specified
	// algorithm
	getChecksum := func(algorithm string, data []byte) (checksum string) {
		algorithm = strings.ToUpper(algorithm)
		// default
		hasher := md5.New()
		switch algorithm {
		case "SHA1":
			hasher = sha1.New()
		case "SHA224":
			hasher = sha256.New224()
		case "SHA256":
			hasher = sha256.New()
		case "SHA384":
			hasher = sha512.New384()
		case "SHA512":
			hasher = sha512.New()
		}
		hasher.Write(data)
		str := hex.EncodeToString(hasher.Sum(nil))
		return str

	}
	// getFileChecksum is self-explanatory
	getFileChecksum := func(algorithm string, path string) (checksum string) {
		return getChecksum(algorithm, wrkutils.FileToBytes(path))
	}

	algorithm := parameters[0]
	checkAgainst := parameters[1]
	path := parameters[2]
	chksum := getFileChecksum(algorithm, path)
	// TODO warn on unequal lengths
	if chksum == checkAgainst {
		return 0, ""
	}
	msg := "Checksums do not match for file: " + path
	return wrkutils.GenericError(msg, checkAgainst, []string{chksum})
}
Exemplo n.º 27
0
func main() {
	flag.Parse()

	//open file
	b, err := ioutil.ReadFile(*file)
	if err != nil {
		log.Println(err)
		os.Exit(1)
	}

	var h hash.Hash
	switch *algo {
	case "sha1":
		h = sha1.New()
	case "sha256":
		h = sha256.New()
	case "sha224":
		h = sha256.New224()
	case "sha512":
		h = sha512.New()
	case "sha384":
		h = sha512.New384()
	case "md5":
		h = md5.New()
	default:
		log.Println("unsported hash algorithm", *algo)
		os.Exit(3)
	}

	_, err = h.Write(b)
	if err != nil {
		log.Println(err)
		os.Exit(2)
	}

	s := h.Sum(nil)
	fmt.Printf("%x  %s\n", s, *file)

	os.Exit(0)
}
Exemplo n.º 28
0
func calculateDigest(files []string, algorithm string) {
	var hasher hash.Hash
	switch algorithm {
	case "md5":
		hasher = md5.New()
	case "sha1":
		hasher = sha1.New()
	case "sha224":
		hasher = sha256.New224()
	case "sha256":
		hasher = sha256.New()
	case "sha384":
		hasher = sha512.New384()
	case "sha512":
		hasher = sha512.New()
	case "sha512224":
		hasher = sha512.New512_224()
	case "sha512256":
		hasher = sha512.New512_256()
	case "ripemd160":
		hasher = ripemd160.New()
	default:
		fmt.Printf("Algorithm %s not implemented yet\n", algorithm)
		os.Exit(1)
	}
	for _, fn := range files {
		hasher.Reset()
		file, err := os.Open(fn)
		if err != nil {
			panic(err.Error())
		}
		if _, err := io.Copy(hasher, file); err != nil {
			panic(err.Error())
		}
		fmt.Printf("%x  %s\n", hasher.Sum(nil), fn)
		file.Close()
	}
}
Exemplo n.º 29
0
// Stolen from https://github.com/gosexy/checksum/blob/master/checksum.go
func hashLookup(method string) hash.Hash {
	var h hash.Hash

	switch method {
	case "MD5":
		h = md5.New()
	case "SHA1":
		h = sha1.New()
	case "SHA224":
		h = sha256.New224()
	case "SHA256":
		h = sha256.New()
	case "SHA384":
		h = sha512.New384()
	case "SHA512":
		h = sha512.New()
	default:
		// NOTE return err, nil ? panic ? ? warning and default to 256 ?
		panic("Unknown hashing method.")
	}

	return h
}
Exemplo n.º 30
0
func (s *Resource) sum(body []byte) (string, error) {
	var hasher hash.Hash

	switch s.HashType {
	case "md5":
		hasher = md5.New()
	case "sha1":
		hasher = sha1.New()
	case "sha256":
		hasher = sha256.New()
	case "sha224":
		hasher = sha256.New224()
	default:
		return "", ErrBadHashType
	}

	_, err := hasher.Write(body)
	if err != nil {
		return "", err
	}

	return hex.EncodeToString(hasher.Sum(nil)), nil
}