コード例 #1
2
ファイル: picugen.go プロジェクト: patrickmn/picugen
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
}
コード例 #2
0
ファイル: backup_set.go プロジェクト: eadmund/cypherback
func (b *BackupSet) EndBackup() error {
	if b.records == nil {
		return fmt.Errorf("Cannot end unstarted backup run")
	}
	start, ok := b.records[b.lastStartIndex].(startRecord)
	if !ok {
		return fmt.Errorf("Corrupted backup set: purported last start record is not a start record")
	}
	start.length = 0
	digester := sha512.New384()
	for i := b.lastStartIndex; i < len(b.records); i++ {
		start.length += b.records[i].Len()
		recordType, data := b.records[i].Record()
		err := binary.Write(digester, binary.BigEndian, uint8(0))
		if err != nil {
			return err
		}
		err = binary.Write(digester, binary.BigEndian, recordType)
		if err != nil {
			return err
		}
		digester.Write(data)
	}
	end := endRecord{digester.Sum(nil)}
	start.length += end.Len()
	b.records[b.lastStartIndex] = start
	b.records = append(b.records, end)
	return nil
}
コード例 #3
0
ファイル: qhash.go プロジェクト: joerocklin/qhash
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
}
コード例 #4
0
ファイル: stoutbox.go プロジェクト: postfix/gocryptobox
// Sign is used to certify a message with the key pair passed in. It returns a
// boolean indicating success; on success, the signature value returned will
// contain the signature.
func Sign(message []byte, key PrivateKey, pub PublicKey) (signature []byte, ok bool) {
	if message == nil {
		return nil, false
	} else if !KeyIsSuitable(key, pub) {
		return nil, false
	}
	h := sha512.New384()
	h.Write(message)
	hash := h.Sum(nil)

	skey, ok := ecdsa_private(key, pub)
	if !ok {
		return
	}
	r, s, err := ecdsa.Sign(PRNG, skey, hash)
	if err != nil {
		ok = false
	} else {
		signature = marshalSignature(r, s)
		if signature == nil {
			ok = false
		}
	}
	return
}
コード例 #5
0
ファイル: csclient_test.go プロジェクト: jrwren/charmrepo
func (s *suite) checkGetArchive(c *gc.C) string {
	ch := charmRepo.CharmArchive(c.MkDir(), "wordpress")

	// Open the archive and calculate its hash and size.
	r, expectHash, expectSize := archiveHashAndSize(c, ch.Path)
	r.Close()

	url := charm.MustParseReference("~charmers/utopic/wordpress-42")
	err := s.client.UploadCharmWithRevision(url, ch, 42)
	c.Assert(err, gc.IsNil)

	rb, id, hash, size, err := s.client.GetArchive(url)
	c.Assert(err, gc.IsNil)
	defer rb.Close()
	c.Assert(id, jc.DeepEquals, url)
	c.Assert(hash, gc.Equals, expectHash)
	c.Assert(size, gc.Equals, expectSize)

	h := sha512.New384()
	size, err = io.Copy(h, rb)
	c.Assert(err, gc.IsNil)
	c.Assert(size, gc.Equals, expectSize)
	c.Assert(fmt.Sprintf("%x", h.Sum(nil)), gc.Equals, expectHash)

	// Return the stats key for the archive download.
	keys := []string{params.StatsArchiveDownload, "utopic", "wordpress", "charmers", "42"}
	return strings.Join(keys, ":")
}
コード例 #6
0
ファイル: main.go プロジェクト: cmars/shadowfax
func calcHash(pass, salt []byte) []byte {
	h := sha512.New384()
	h.Write(hashVersion)
	h.Write(salt)
	h.Write(pass)
	return h.Sum(nil)
}
コード例 #7
0
ファイル: fsstatus.go プロジェクト: allenbhuiyan/distributive
// 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
}
コード例 #8
0
ファイル: hash.go プロジェクト: sbhackerspace/sbhx-snippets
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())
	}
}
コード例 #9
0
ファイル: hash.go プロジェクト: ancientlore/hashsrv
func (e *Engine) sha384() error {
	data, err := computeHash(sha512.New384(), e.stack.Pop())
	if err == nil {
		e.stack.Push(data)
	}
	return err
}
コード例 #10
0
ファイル: calc_sum.go プロジェクト: patrickToca/go-coreutils
/*
   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))
}
コード例 #11
0
ファイル: impl_test.go プロジェクト: hyperledger/fabric
func TestHashOpts(t *testing.T) {
	msg := []byte("abcd")

	// SHA256
	digest1, err := currentBCCSP.Hash(msg, &bccsp.SHA256Opts{})
	if err != nil {
		t.Fatalf("Failed computing SHA256 [%s]", err)
	}

	h := sha256.New()
	h.Write(msg)
	digest2 := h.Sum(nil)

	if !bytes.Equal(digest1, digest2) {
		t.Fatalf("Different SHA256 computed. [%x][%x]", digest1, digest2)
	}

	// SHA384
	digest1, err = currentBCCSP.Hash(msg, &bccsp.SHA384Opts{})
	if err != nil {
		t.Fatalf("Failed computing SHA384 [%s]", err)
	}

	h = sha512.New384()
	h.Write(msg)
	digest2 = h.Sum(nil)

	if !bytes.Equal(digest1, digest2) {
		t.Fatalf("Different SHA384 computed. [%x][%x]", digest1, digest2)
	}

	// SHA3_256O
	digest1, err = currentBCCSP.Hash(msg, &bccsp.SHA3_256Opts{})
	if err != nil {
		t.Fatalf("Failed computing SHA3_256 [%s]", err)
	}

	h = sha3.New256()
	h.Write(msg)
	digest2 = h.Sum(nil)

	if !bytes.Equal(digest1, digest2) {
		t.Fatalf("Different SHA3_256 computed. [%x][%x]", digest1, digest2)
	}

	// SHA3_384
	digest1, err = currentBCCSP.Hash(msg, &bccsp.SHA3_384Opts{})
	if err != nil {
		t.Fatalf("Failed computing SHA3_384 [%s]", err)
	}

	h = sha3.New384()
	h.Write(msg)
	digest2 = h.Sum(nil)

	if !bytes.Equal(digest1, digest2) {
		t.Fatalf("Different SHA3_384 computed. [%x][%x]", digest1, digest2)
	}
}
コード例 #12
0
ファイル: dnssec.go プロジェクト: wallrat/dns
// ToDS converts a DNSKEY record to a DS record.
func (k *RR_DNSKEY) ToDS(h int) *RR_DS {
	if k == nil {
		return nil
	}
	ds := new(RR_DS)
	ds.Hdr.Name = k.Hdr.Name
	ds.Hdr.Class = k.Hdr.Class
	ds.Hdr.Rrtype = TypeDS
	ds.Hdr.Ttl = k.Hdr.Ttl
	ds.Algorithm = k.Algorithm
	ds.DigestType = uint8(h)
	ds.KeyTag = k.KeyTag()

	keywire := new(dnskeyWireFmt)
	keywire.Flags = k.Flags
	keywire.Protocol = k.Protocol
	keywire.Algorithm = k.Algorithm
	keywire.PublicKey = k.PublicKey
	wire := make([]byte, DefaultMsgSize)
	n, ok := PackStruct(keywire, wire, 0)
	if !ok {
		return nil
	}
	wire = wire[:n]

	owner := make([]byte, 255)
	off, ok1 := PackDomainName(k.Hdr.Name, owner, 0, nil, false)
	if !ok1 {
		return nil
	}
	owner = owner[:off]
	// RFC4034:
	// digest = digest_algorithm( DNSKEY owner name | DNSKEY RDATA);
	// "|" denotes concatenation
	// DNSKEY RDATA = Flags | Protocol | Algorithm | Public Key.

	// digest buffer
	digest := append(owner, wire...) // another copy

	switch h {
	case SHA1:
		s := sha1.New()
		io.WriteString(s, string(digest))
		ds.Digest = hex.EncodeToString(s.Sum(nil))
	case SHA256:
		s := sha256.New()
		io.WriteString(s, string(digest))
		ds.Digest = hex.EncodeToString(s.Sum(nil))
	case SHA384:
		s := sha512.New384()
		io.WriteString(s, string(digest))
		ds.Digest = hex.EncodeToString(s.Sum(nil))
	case GOST94:
		/* I have no clue */
	default:
		return nil
	}
	return ds
}
コード例 #13
0
ファイル: managedstorage_test.go プロジェクト: juju/blobstore
func calculateCheckSum(c *gc.C, start, length int64, blob []byte) (sha384HashHex string) {
	data := blob[start : start+length]
	sha384Hash := sha512.New384()
	_, err := sha384Hash.Write(data)
	c.Assert(err, gc.IsNil)
	sha384HashHex = fmt.Sprintf("%x", sha384Hash.Sum(nil))
	return sha384HashHex
}
コード例 #14
0
ファイル: fingerprint_test.go プロジェクト: juju/utils
func newFingerprint(c *gc.C, data string) ([]byte, string) {
	hash := sha512.New384()
	_, err := hash.Write([]byte(data))
	c.Assert(err, jc.ErrorIsNil)
	sum := hash.Sum(nil)

	hexStr := hex.EncodeToString(sum)
	return sum, hexStr
}
コード例 #15
0
ファイル: sha.go プロジェクト: szank/jose2go
func hashAlg(keySizeBits int) hash.Hash {
	switch keySizeBits {
	case 256:
		return sha256.New()
	case 384:
		return sha512.New384()
	default:
		return sha512.New()
	}
}
コード例 #16
0
ファイル: dedup.go プロジェクト: jwatt/kythe
func (d *Deduper) hash(data []byte, rest ...[]byte) (hash [HashSize]byte) {
	h := sha512.New384()
	h.Write(data)
	for _, d := range rest {
		h.Write(d)
	}
	s := h.Sum(nil)
	copy(hash[:], s[:HashSize])
	return
}
コード例 #17
0
ファイル: pbse2_hmac_aeskw.go プロジェクト: useidel/notary
func (alg *Pbse2HmacAesKW) prf() hash.Hash {
	switch alg.keySizeBits {
	case 128:
		return sha256.New()
	case 192:
		return sha512.New384()
	default:
		return sha512.New()
	}
}
コード例 #18
0
ファイル: csclient_test.go プロジェクト: jrwren/charmrepo
func archiveHashAndSize(c *gc.C, path string) (r csclient.ReadSeekCloser, hash string, size int64) {
	f, err := os.Open(path)
	c.Assert(err, gc.IsNil)
	h := sha512.New384()
	size, err = io.Copy(h, f)
	c.Assert(err, gc.IsNil)
	_, err = f.Seek(0, 0)
	c.Assert(err, gc.IsNil)
	return f, fmt.Sprintf("%x", h.Sum(nil)), size
}
コード例 #19
0
ファイル: cipher_suites.go プロジェクト: randombit/hacrypto
func macSHA384(version uint16, key []byte) macFunction {
	if version == VersionSSL30 {
		mac := ssl30MAC{
			h:   sha512.New384(),
			key: make([]byte, len(key)),
		}
		copy(mac.key, key)
		return mac
	}
	return tls10MAC{hmac.New(sha512.New384, key)}
}
コード例 #20
0
ファイル: archive.go プロジェクト: jrwren/charmrepo
// readerHashAndSize returns the SHA384 and size of the data included in the
// given reader.
func readerHashAndSize(r io.ReadSeeker) (hash string, size int64, err error) {
	h := sha512.New384()
	size, err = io.Copy(h, r)
	if err != nil {
		return "", 0, errgo.Notef(err, "cannot calculate hash")
	}
	if _, err := r.Seek(0, 0); err != nil {
		return "", 0, errgo.Notef(err, "cannot seek")
	}
	return fmt.Sprintf("%x", h.Sum(nil)), size, nil
}
コード例 #21
0
ファイル: vault.go プロジェクト: hdonnay/vaultd
func getPassphrase(prompt string) []byte {
	var h hash.Hash = sha512.New384()
	fmt.Fprintf(os.Stdout, prompt)
	phrase, err := terminal.ReadPassword(int(os.Stdin.Fd()))
	fmt.Fprintf(os.Stdout, "\n")
	if err != nil {
		log.Fatal(err)
	}
	io.Copy(h, bytes.NewReader(phrase))
	return h.Sum(nil)
}
コード例 #22
0
ファイル: path_hash.go プロジェクト: quixoten/vault
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
}
コード例 #23
0
ファイル: secrets.go プロジェクト: eadmund/cypherback
func (secrets *Secrets) Id() []byte {
	digester := sha512.New384()
	// no errors are possible from hash.Write, per the docs
	digester.Write([]byte("cypherback\x00"))
	digester.Write(secrets.metadataMaster)
	digester.Write(secrets.metadataAuthentication)
	digester.Write(secrets.metadataStorage)
	digester.Write(secrets.chunkMaster)
	digester.Write(secrets.chunkAuthentication)
	digester.Write(secrets.chunkStorage)
	return digester.Sum(nil)
}
コード例 #24
0
ファイル: charmstore.go プロジェクト: jrwren/charmrepo
// Get implements Interface.Get.
func (s *CharmStore) Get(curl *charm.URL) (charm.Charm, error) {
	// The cache location must have been previously set.
	if CacheDir == "" {
		panic("charm cache directory path is empty")
	}
	if curl.Series == "bundle" {
		return nil, errgo.Newf("expected a charm URL, got bundle URL %q", curl)
	}

	// Prepare the cache directory and retrieve the charm.
	if err := os.MkdirAll(CacheDir, 0755); err != nil {
		return nil, errgo.Notef(err, "cannot create the cache directory")
	}
	r, id, expectHash, expectSize, err := s.client.GetArchive(curl.Reference())
	if err != nil {
		if errgo.Cause(err) == params.ErrNotFound {
			// Make a prettier error message for the user.
			return nil, errgo.WithCausef(nil, params.ErrNotFound, "cannot retrieve charm %q: charm not found", curl)
		}
		return nil, errgo.NoteMask(err, fmt.Sprintf("cannot retrieve charm %q", curl), errgo.Any)
	}
	defer r.Close()

	// Check if the archive already exists in the cache.
	path := filepath.Join(CacheDir, charm.Quote(id.String())+".charm")
	if verifyHash384AndSize(path, expectHash, expectSize) == nil {
		return charm.ReadCharmArchive(path)
	}

	// Verify and save the new archive.
	f, err := ioutil.TempFile(CacheDir, "charm-download")
	if err != nil {
		return nil, errgo.Notef(err, "cannot make temporary file")
	}
	defer f.Close()
	hash := sha512.New384()
	size, err := io.Copy(io.MultiWriter(hash, f), r)
	if err != nil {
		return nil, errgo.Notef(err, "cannot read charm archive")
	}
	if size != expectSize {
		return nil, errgo.Newf("size mismatch; network corruption?")
	}
	if fmt.Sprintf("%x", hash.Sum(nil)) != expectHash {
		return nil, errgo.Newf("hash mismatch; network corruption?")
	}

	// Move the archive to the expected place, and return the charm.
	if err := utils.ReplaceFile(f.Name(), path); err != nil {
		return nil, errgo.Notef(err, "cannot move the charm archive")
	}
	return charm.ReadCharmArchive(path)
}
コード例 #25
0
ファイル: verifiers.go プロジェクト: devick/flynn
func newHash(name string) hash.Hash {
	switch name {
	case "sha256":
		return sha256.New()
	case "sha384":
		return sha512.New384()
	case "sha512":
		return sha512.New()
	default:
		panic("unsupport algorithm: " + name)
	}
}
コード例 #26
0
ファイル: checksum.go プロジェクト: qeedquan/misc_utilities
func makeHash(name string) hash.Hash {
	switch strings.ToLower(name) {
	case "ripemd160":
		return ripemd160.New()
	case "md4":
		return md4.New()
	case "md5":
		return md5.New()
	case "sha1":
		return sha1.New()
	case "sha256":
		return sha256.New()
	case "sha384":
		return sha512.New384()
	case "sha3-224":
		return sha3.New224()
	case "sha3-256":
		return sha3.New256()
	case "sha3-384":
		return sha3.New384()
	case "sha3-512":
		return sha3.New512()
	case "sha512":
		return sha512.New()
	case "sha512-224":
		return sha512.New512_224()
	case "sha512-256":
		return sha512.New512_256()
	case "crc32-ieee":
		return crc32.NewIEEE()
	case "crc64-iso":
		return crc64.New(crc64.MakeTable(crc64.ISO))
	case "crc64-ecma":
		return crc64.New(crc64.MakeTable(crc64.ECMA))
	case "adler32":
		return adler32.New()
	case "fnv32":
		return fnv.New32()
	case "fnv32a":
		return fnv.New32a()
	case "fnv64":
		return fnv.New64()
	case "fnv64a":
		return fnv.New64a()
	case "xor8":
		return new(xor8)
	case "fletch16":
		return &fletch16{}
	}
	return nil
}
コード例 #27
0
ファイル: hashsum.go プロジェクト: Nelson69/hashsum
func main() {
	flag.Parse()

	hashAlgorithm := sha1.New()
	if *sha1Flag {
		hashAlgorithm = sha1.New()
	}
	if *md5Flag {
		hashAlgorithm = md5.New()
	}
	if *sha256Flag {
		hashAlgorithm = sha256.New()
	}
	if *sha384Flag {
		hashAlgorithm = sha512.New384()
	}
	if *sha3256Flag {
		hashAlgorithm = sha3.New256()
	}
	if *sha3384Flag {
		hashAlgorithm = sha3.New384()
	}
	if *sha3512Flag {
		hashAlgorithm = sha3.New512()
	}
	if *whirlpoolFlag {
		hashAlgorithm = whirlpool.New()
	}
	if *blakeFlag {
		hashAlgorithm = blake2.NewBlake2B()
	}
	if *ripemd160Flag {
		hashAlgorithm = ripemd160.New()
	}

	for _, fileName := range flag.Args() {
		f, _ := os.Open(fileName)
		defer f.Close()
		hashAlgorithm.Reset()
		output := genericHashFile(f, hashAlgorithm)
		if *b64Flag {
			r64Output := base64.StdEncoding.EncodeToString(output)
			fmt.Printf("%s %s\n", r64Output, fileName)
		} else {
			fmt.Printf("%x %s\n", output, fileName)
		}
	}

}
コード例 #28
0
ファイル: filechecker.go プロジェクト: netantho/mig
// getHash calculates the hash of a file.
// It reads a file block by block, and updates a hashsum with each block.
// Reading by blocks consume very little memory, which is needed for large files.
// parameters:
//      - fd is an open file descriptor that points to the file to inspect
//      - hashType is an integer that define the type of hash
// return:
//      - hexhash, the hex encoded hash of the file found at fp
func getHash(fd *os.File, hashType float64) (hexhash string, err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("getHash() -> %v", e)
		}
	}()
	if debug {
		fmt.Printf("getHash: computing hash for '%s'\n", fd.Name())
	}
	var h hash.Hash
	switch hashType {
	case checkMD5:
		h = md5.New()
	case checkSHA1:
		h = sha1.New()
	case checkSHA256:
		h = sha256.New()
	case checkSHA384:
		h = sha512.New384()
	case checkSHA512:
		h = sha512.New()
	case checkSHA3_224:
		h = sha3.New224()
	case checkSHA3_256:
		h = sha3.New256()
	case checkSHA3_384:
		h = sha3.New384()
	case checkSHA3_512:
		h = sha3.New512()
	default:
		err := fmt.Sprintf("getHash: Unkown hash type %d", hashType)
		panic(err)
	}
	buf := make([]byte, 4096)
	var offset int64 = 0
	for {
		block, err := fd.ReadAt(buf, offset)
		if err != nil && err != io.EOF {
			panic(err)
		}
		if block == 0 {
			break
		}
		h.Write(buf[:block])
		offset += int64(block)
	}
	hexhash = fmt.Sprintf("%X", h.Sum(nil))
	return
}
コード例 #29
0
ファイル: crypto.go プロジェクト: kyokomi-sandbox/sandbox
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))
}
コード例 #30
0
ファイル: hash.go プロジェクト: C0rWin/fabric
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)
	}
}