Esempio n. 1
0
// Initialize manifest from BLOB
func (s *Manifest) ParseBlob(in io.Reader, chunkSize int64) (err error) {
	var chunkHasher hash.Hash
	var w io.Writer
	var chunk Chunk
	hasher := sha3.New256()
	var written int64

	for {
		chunk = Chunk{
			Offset: s.Size,
		}
		chunkHasher = sha3.New256()
		w = io.MultiWriter(hasher, chunkHasher)
		written, err = io.CopyN(w, in, chunkSize)
		s.Size += written
		chunk.Size = written
		chunk.ID = ID(hex.EncodeToString(chunkHasher.Sum(nil)))
		s.Chunks = append(s.Chunks, chunk)

		if err == io.EOF {
			err = nil
			break
		} else if err != nil {
			return
		}
	}
	s.ID = ID(hex.EncodeToString(hasher.Sum(nil)))
	return
}
Esempio n. 2
0
func Test_SHA3(t *testing.T) {

	hasher1 := sha3.New256()
	hasher1.Write([]byte("mama_myla_ramu"))

	hasher2 := sha3.New256()
	hasher2.Write([]byte("mama_"))
	hasher2.Write([]byte("myla_"))
	hasher2.Write([]byte("ramu"))

	assert.Equal(t, hasher1.Sum(nil), hasher2.Sum(nil))
}
Esempio n. 3
0
func (s *BlockStorage) getCAFile(name string) (w *contentaddressable.File, err error) {
	caOpts := contentaddressable.DefaultOptions()
	caOpts.Hasher = sha3.New256()

	w, err = contentaddressable.NewFileWithOptions(name, caOpts)
	return
}
Esempio n. 4
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
}
Esempio n. 5
0
func (u *U16x16) PutData3(data []byte, key string) (length int64, hash string, err error) {
	s := sha3.New256()
	s.Write(data)
	hash = hex.EncodeToString(s.Sum(nil))
	if hash != key {
		fmt.Printf("expected data to have key %s, but content key is %s",
			key, hash)
		err = errors.New("content/key mismatch")
		return
	}
	length = int64(len(data))
	topSubDir := hash[0:1]
	lowerDir := hash[1:2]
	targetDir := filepath.Join(u.path, topSubDir, lowerDir)
	found, err := xf.PathExists(targetDir)
	if err == nil && !found {
		err = os.MkdirAll(targetDir, 0775)
	}
	fullishPath := filepath.Join(targetDir, key[2:])
	found, err = xf.PathExists(fullishPath)
	if !found {
		var dest *os.File
		dest, err = os.Create(fullishPath)
		if err == nil {
			var count int
			defer dest.Close()
			count, err = dest.Write(data)
			if err == nil {
				length = int64(count)
			}
		}
	}
	return
}
Esempio n. 6
0
func (u *UFlat) PutData3(data []byte, key string) (length int64, hash string, err error) {
	s := sha3.New256()
	s.Write(data)
	hash = hex.EncodeToString(s.Sum(nil))
	if hash != key {
		fmt.Printf("expected data to have key %s, but content key is %s",
			key, hash)
		err = errors.New("content/key mismatch")
		return
	}
	length = int64(len(data))
	fullishPath := filepath.Join(u.path, key)
	found, err := xf.PathExists(fullishPath)
	if !found {
		var dest *os.File
		dest, err = os.Create(fullishPath)
		if err == nil {
			var count int
			defer dest.Close()
			count, err = dest.Write(data)
			if err == nil {
				length = int64(count)
			}
		}
	}
	return
}
Esempio n. 7
0
func Test_Assembler_StoreChunk(t *testing.T) {
	wd, _ := os.Getwd()
	wd = filepath.Join(wd, "testdata", "assembler-StoreChunk")
	m, err := model.New(wd, false, proto.CHUNK_SIZE, 128)
	assert.NoError(t, err)

	data := []byte("mama myla ramu")
	hasher := sha3.New256()
	_, err = hasher.Write([]byte(data))
	id := proto.ID(hex.EncodeToString(hasher.Sum(nil)))

	a, err := model.NewAssembler(m)
	assert.NoError(t, err)
	defer a.Close()

	err = a.StoreChunk(bytes.NewReader(data), id)
	assert.NoError(t, err)

	// check stored chunk
	f, err := os.Open(filepath.Join(a.Where, id.String()))
	assert.NoError(t, err)
	defer f.Close()
	defer os.Remove(filepath.Join(a.Where, id.String()))

	r2, err := ioutil.ReadAll(f)
	assert.NoError(t, err)

	assert.Equal(t, data, r2)
}
Esempio n. 8
0
func (s *XLSuite) verifyLeafSHA(c *C, rng *xr.PRNG,
	node MerkleNodeI, pathToFile string, whichSHA int) {

	c.Assert(node.IsLeaf(), Equals, true)
	found, err := xf.PathExists(pathToFile)
	c.Assert(err, IsNil)
	c.Assert(found, Equals, true)
	data, err := ioutil.ReadFile(pathToFile)
	c.Assert(err, IsNil)
	c.Assert(data, NotNil)

	var sha hash.Hash
	switch whichSHA {
	case xu.USING_SHA1:
		sha = sha1.New()
	case xu.USING_SHA2:
		sha = sha256.New()
	case xu.USING_SHA3:
		sha = sha3.New256()
		// XXX DEFAULT = ERROR
	}
	sha.Write(data)
	sum := sha.Sum(nil)
	c.Assert(node.GetHash(), DeepEquals, sum)
}
Esempio n. 9
0
// Store chunk in assemble
func (a *Assembler) StoreChunk(r io.Reader, id proto.ID) (err error) {
	lock, err := a.model.FdLocks.Take()
	if err != nil {
		return
	}
	defer lock.Release()

	caOpts := contentaddressable.DefaultOptions()
	caOpts.Hasher = sha3.New256()

	w, err := contentaddressable.NewFileWithOptions(
		filepath.Join(a.Where, id.String()), caOpts)
	if os.IsExist(err) {
		err = nil
		return
	}
	if err != nil {
		return
	}
	defer w.Close()

	if _, err = io.Copy(w, r); err != nil {
		return
	}
	err = w.Accept()
	return
}
Esempio n. 10
0
// Checks the signature against
// the message
func SchnorrVerify(suite abstract.Suite,
	kp SchnorrPublicKey,
	msg []byte, sig []byte) (bool, error) {

	buf := bytes.NewBuffer(sig)
	signature := SchnorrSignature{}
	err := abstract.Read(buf, &signature, suite)
	if err != nil {
		return false, err
	}

	s := signature.S
	e := signature.E

	var gs, ye, r abstract.Point
	gs = suite.Point().Mul(nil, s)  // g^s
	ye = suite.Point().Mul(kp.Y, e) // y^e
	r = suite.Point().Add(gs, ye)   // g^xy^e

	r_bin, _ := r.MarshalBinary()
	msg_and_r := append(msg, r_bin...)
	hasher := sha3.New256()
	hasher.Write(msg_and_r)
	h := hasher.Sum(nil)

	// again I'm hoping this just reads the state out
	// and doesn't  actually perform any ops
	lct := suite.Cipher(h)

	ev := suite.Secret().Pick(lct)
	return ev.Equal(e), nil
}
/* GenerateZ takes some random agreed information and creates
   Z the "public-only" key that is witness-independent as per
   the paper. We've probably broken that slightly in this implementation
   because I could not pick a point without generating it
   via a Secret, instead of directly via a Point - that is, even as a
   32-byte string, we cannot decode on C25519 (and this wouldn't work
   for abstract suites anyway).

   However, it demonstrates the idea.
*/
func GenerateZ(suite abstract.Suite, info []byte) (abstract.Point, error) {

	hasher := sha3.New256()
	hasher.Write(info)
	zraw := hasher.Sum(nil)

	//I think this might be cheating
	zrawCt := suite.Cipher(zraw)

	zfactor := suite.Secret().Pick(zrawCt)
	Z := suite.Point()
	Z.Mul(nil, zfactor)

	// every 32-bit integer exists on Curve25519 only if we have the fullgroup
	// this should work, but doesn't.

	/*var Z abstract.Point
	  zrawBuf := bytes.NewBuffer(zraw)
	  err := abstract.Read(zrawBuf, &Z, suite);
	  if err != nil {
	      return nil, err
	  }*/

	return Z, nil
}
Esempio n. 12
0
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)
	}
}
Esempio n. 13
0
func (d *XLSuite) TestXLatticePkt(c *C) {
	if VERBOSITY > 0 {
		fmt.Println("TEST_XLATTICE_PKT")
	}

	rng := xr.MakeSimpleRNG()

	myMsgN := uint64(rng.Int63())
	for myMsgN == 0 { // must not be zero
		myMsgN = uint64(rng.Int63())
	}

	id := make([]byte, 32) // sha3 length
	rng.NextBytes(id)      // random bytes

	seqBuf := new(bytes.Buffer)
	binary.Write(seqBuf, binary.LittleEndian, myMsgN)

	msgLen := 64 + rng.Intn(64)
	msg := make([]byte, msgLen)
	rng.NextBytes(msg) // fill with rubbish

	salt := make([]byte, 8)
	rng.NextBytes(salt) // still more rubbish

	digest := sha3.New256()
	digest.Write(id)
	digest.Write(seqBuf.Bytes())
	digest.Write(msg)
	digest.Write([]byte(salt))

	hash := digest.Sum(nil)

	// XXX This does not adhere to the rules: it has no Cmd field;
	// since it has a payload it must be a Put, and so the id is
	// also required and the Hash field should be a Sig instead, right?
	var pkt = XLatticeMsg{
		MsgN:    &myMsgN,
		Payload: msg,
		Salt:    salt,
		Hash:    hash,
	}

	// In each of these cases, the test proves that the field
	// was present; otherwise the 'empty' value (zero, nil, etc)
	// would have been returned.
	msgNOut := pkt.GetMsgN()
	c.Assert(msgNOut, Equals, myMsgN)

	msgOut := pkt.GetPayload()
	d.compareByteSlices(c, msgOut, msg)

	saltOut := pkt.GetSalt()
	d.compareByteSlices(c, saltOut, salt)

	hashOut := pkt.GetHash()
	d.compareByteSlices(c, hashOut, hash)
}
Esempio n. 14
0
func createKeyFromPassword(pwd string) ([]byte, error) {
	if len(pwd) < 8 {
		return nil, fmt.Errorf("Password has to be at least 8 characters")
	}

	h := sha3.New256()
	h.Write([]byte(pwd))

	return h.Sum(nil), nil
}
// (Either side) This function takes the aggregate public commitment
// r and returns sha3(m||r) for a given message.
func SchnorrMComputeCollectiveChallenge(suite abstract.Suite,
	msg []byte,
	pubCommit SchnorrMAggregateCommmitment) []byte {

	p_bin, _ := pubCommit.P.MarshalBinary()
	msg_and_p := append(msg, p_bin...)
	hasher := sha3.New256()
	hasher.Write(msg_and_p)
	h := hasher.Sum(nil)
	return h
}
/* This is the function that given the client's challenge and response from the server is able to
   compute the final blind signature. This is done on the user side (blindly to the signer). */
func ClientSignBlindly(suite abstract.Suite, clientParameters WISchnorrClientParamersList, responseMsg WISchnorrResponseMessage, pubKey SchnorrPublicKey, msg []byte) (WIBlindSignature, bool) {

	rho := suite.Secret()
	omega := suite.Secret()
	sigma := suite.Secret()
	delta := suite.Secret()

	rho.Add(responseMsg.R, clientParameters.T1)
	omega.Add(responseMsg.C, clientParameters.T2)
	sigma.Add(responseMsg.S, clientParameters.T3)
	delta.Add(responseMsg.D, clientParameters.T4)

	gp := suite.Point()
	gp.Mul(nil, rho)

	yw := suite.Point()
	yw.Mul(pubKey.Y, omega)
	gpyw := suite.Point()

	gpyw.Add(gp, yw)
	bGpyw, _ := gpyw.MarshalBinary()

	gs := suite.Point()
	gs.Mul(nil, sigma)
	zd := suite.Point()
	zd.Mul(clientParameters.Z, delta)
	gszd := suite.Point()
	gszd.Add(gs, zd)
	bGszd, _ := gszd.MarshalBinary()

	bZ, _ := clientParameters.Z.MarshalBinary()

	var combinedmsg []byte

	combinedmsg = append(combinedmsg, bGpyw...)
	combinedmsg = append(combinedmsg, bGszd...)
	combinedmsg = append(combinedmsg, bZ...)
	combinedmsg = append(combinedmsg, msg...)

	hasher := sha3.New256()
	hasher.Write(combinedmsg)
	bSig := hasher.Sum(nil)
	bSigCt := suite.Cipher(bSig)

	sig := suite.Secret().Pick(bSigCt)

	vsig := suite.Secret()
	vsig.Add(omega, delta)

	//fmt.Println(sig)
	//fmt.Println(vsig)

	return WIBlindSignature{rho, omega, sigma, delta}, sig.Equal(vsig)
}
Esempio n. 17
0
File: utils.go Progetto: unix4fun/ac
func HashSHA3Data(input []byte) (out []byte, err error) {
	//sha3hash := sha3.NewKeccak256()
	sha3hash := sha3.New256()
	_, err = sha3hash.Write(input)
	if err != nil {
		//return nil, acprotoError(-1, "HashSHA3Data().Write(): ", err)
		//return nil, &protoError{value: -1, msg: "HashSHA3Data().Write(): ", err: err}
		return nil, &AcError{Value: -1, Msg: "HashSHA3Data().Write(): ", Err: err}
	}
	out = sha3hash.Sum(nil)
	return
}
Esempio n. 18
0
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
}
Esempio n. 19
0
func Test_Proto_Spec1(t *testing.T) {
	m1, err := proto.NewFromManifest(fixtures.CleanInput(`BAR:MANIFEST

		id ac934d9a88b42aa3b40ef7c81a9dee1aad5a2cddccb00ae6abab9c38095fc15c
		size 1234


		id ac934d9a88b42aa3b40ef7c81a9dee1aad5a2cddccb00ae6abab9c38095fc15c
		size 1234
		offset 0
	`))
	assert.NoError(t, err)
	m2, err := proto.NewFromManifest(fixtures.CleanInput(`BAR:MANIFEST

		id ac934d9a88b42aa3b40ef7c81a9dee1aad5a2cddccb00ae6abab9c38095fc15c
		size 1234


		id ac934d9a88b42aa3b40ef7c81a9dee1aad5a2cddccb00ae6abab9c38095fc15c
		size 1234
		offset 0
	`))
	assert.NoError(t, err)

	spec, err := proto.NewSpec(time.Now().UnixNano(), map[string]proto.ID{
		"file/1": m1.ID,
		"file/2": m2.ID,
	}, []string{})

	// hand-made fixture
	var sorted sort.StringSlice
	sorted = append(sorted, "file/2")
	sorted = append(sorted, "file/1")
	sorted.Sort()

	hasher := sha3.New256()
	var id []byte

	err = m1.ID.Decode(id)
	assert.NoError(t, err)

	_, err = hasher.Write([]byte(sorted[0]))
	_, err = hasher.Write(id)

	_, err = hasher.Write([]byte(sorted[1]))
	_, err = hasher.Write(id)

	assert.Equal(t, spec.ID, proto.ID(hex.EncodeToString(hasher.Sum(nil))))
}
Esempio n. 20
0
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)
		}
	}

}
Esempio n. 21
0
func getHashSHA3(bitsize int) (hash.Hash, error) {
	switch bitsize {
	case 224:
		return sha3.New224(), nil
	case 256:
		return sha3.New256(), nil
	case 384:
		return sha3.New384(), nil
	case 512:
		return sha3.New512(), nil
	case 521:
		return sha3.New512(), nil
	default:
		return nil, fmt.Errorf("Invalid bitsize. It was [%d]. Expected [224, 256, 384, 512, 521]", bitsize)
	}
}
Esempio n. 22
0
func SHA3File(pathToFile string) (hash []byte, err error) {
	var data []byte
	found, err := xf.PathExists(pathToFile)
	if err == nil && !found {
		err = FileNotFound
	}
	if err == nil {
		data, err = ioutil.ReadFile(pathToFile)
		if err == nil {
			digest := sha3.New256()
			digest.Write(data)
			hash = digest.Sum(nil)
		}
	}
	return
}
Esempio n. 23
0
func (s *XLSuite) doTestSHA(c *C, rng *xr.PRNG, whichSHA int) {

	var hash, fHash []byte
	var sHash string

	// name guaranteed to be unique
	length, pathToFile := rng.NextDataFile("tmp", 1024, 256)
	data, err := ioutil.ReadFile(pathToFile)
	c.Assert(err, IsNil)
	c.Assert(len(data), Equals, length)
	parts := strings.Split(pathToFile, "/")
	c.Assert(len(parts), Equals, 2)
	fileName := parts[1]

	switch whichSHA {
	case xu.USING_SHA1:
		sha := sha1.New()
		sha.Write(data)
		hash = sha.Sum(nil)
		fHash, err = SHA1File(pathToFile)
	case xu.USING_SHA2:
		sha := sha256.New()
		sha.Write(data)
		hash = sha.Sum(nil)
		fHash, err = SHA2File(pathToFile)
	case xu.USING_SHA3:
		sha := sha3.New256()
		sha.Write(data)
		hash = sha.Sum(nil)
		fHash, err = SHA3File(pathToFile)
		// XXX DEFAULT = ERROR
	}
	c.Assert(err, IsNil)
	c.Assert(bytes.Equal(hash, fHash), Equals, true)

	ml, err := CreateMerkleLeafFromFileSystem(pathToFile, fileName, whichSHA)
	c.Assert(err, IsNil)
	c.Assert(ml.Name(), Equals, fileName)
	c.Assert(bytes.Equal(ml.GetHash(), hash), Equals, true)
	c.Assert(ml.WhichSHA(), Equals, whichSHA)

	// TODO: test ToString
	_ = sHash // TODO

}
Esempio n. 24
0
func TestSHA(t *testing.T) {

	for i := 0; i < 100; i++ {
		b, err := GetRandomBytes(i)
		if err != nil {
			t.Fatalf("Failed getting random bytes [%s]", err)
		}

		h1, err := currentBCCSP.Hash(b, &bccsp.SHAOpts{})
		if err != nil {
			t.Fatalf("Failed computing SHA [%s]", err)
		}

		var h hash.Hash
		switch currentTestConfig.hashFamily {
		case "SHA2":
			switch currentTestConfig.securityLevel {
			case 256:
				h = sha256.New()
			case 384:
				h = sha512.New384()
			default:
				t.Fatalf("Invalid security level [%d]", currentTestConfig.securityLevel)
			}
		case "SHA3":
			switch currentTestConfig.securityLevel {
			case 256:
				h = sha3.New256()
			case 384:
				h = sha3.New384()
			default:
				t.Fatalf("Invalid security level [%d]", currentTestConfig.securityLevel)
			}
		default:
			t.Fatalf("Invalid hash family [%s]", currentTestConfig.hashFamily)
		}

		h.Write(b)
		h2 := h.Sum(nil)
		if !bytes.Equal(h1, h2) {
			t.Fatalf("Discrempancy found in HASH result [%x], [%x]!=[%x]", b, h1, h2)
		}
	}
}
Esempio n. 25
0
File: u.go Progetto: jddixon/xlU_go
// returns the SHA3 hash of the contents of a file
func FileBinSHA3(path string) (binHash []byte, err error) {
	var data2 []byte

	binHash = xu.SHA3_BIN_NONE
	found, err := xf.PathExists(path)
	if err == nil && !found {
		err = errors.New("IllegalArgument: empty path or non-existent file")
	}

	if err == nil {
		data2, err = ioutil.ReadFile(path)
	}
	if err == nil {
		d2 := sha3.New256()
		d2.Write(data2)
		binHash = d2.Sum(nil)
	}
	return
}
Esempio n. 26
0
func NewSpec(timestamp int64, in map[string]ID, kill []string) (res Spec, err error) {
	hasher := sha3.New256()
	var idBuf []byte

	var names sort.StringSlice
	for n, _ := range in {
		names = append(names, n)
	}
	sort.Sort(names)

	kills := sort.StringSlice(kill)
	kills.Sort()

	drop := map[string]ID{}
	var removalsDrop []string

	for _, n := range names {
		if _, err = hasher.Write([]byte(filepath.ToSlash(n))); err != nil {
			return
		}
		if err = in[n].Decode(idBuf); err != nil {
			return
		}
		if _, err = hasher.Write(idBuf); err != nil {
			return
		}
		drop[filepath.ToSlash(n)] = in[n]
	}
	for _, n := range kills {
		if _, err = hasher.Write([]byte(filepath.ToSlash(n))); err != nil {
			return
		}
		removalsDrop = append(removalsDrop, filepath.ToSlash(n))
	}

	res = Spec{
		ID(hex.EncodeToString(hasher.Sum(nil))),
		timestamp,
		drop,
		removalsDrop}
	return
}
Esempio n. 27
0
func (s *XLSuite) verifyTreeSHA(c *C, rng *xr.PRNG,
	n MerkleNodeI, pathToNode string, whichSHA int) {

	c.Assert(n.IsLeaf(), Equals, false)
	node := n.(*MerkleTree)

	if node.nodes == nil {
		c.Assert(node.GetHash(), Equals, nil)
	} else {
		hashCount := 0
		var sha hash.Hash
		switch whichSHA {
		case xu.USING_SHA1:
			sha = sha1.New()
		case xu.USING_SHA2:
			sha = sha256.New()
		case xu.USING_SHA3:
			sha = sha3.New256()
			// XXX DEFAULT = ERROR
		}
		for i := 0; i < len(node.nodes); i++ {
			n := node.nodes[i]
			pathToFile := path.Join(pathToNode, n.Name())
			if n.IsLeaf() {
				s.verifyLeafSHA(c, rng, n, pathToFile, whichSHA)
			} else if !n.IsLeaf() {
				s.verifyTreeSHA(c, rng, n, pathToFile, whichSHA)
			} else {
				c.Error("unknown node type!")
			}
			if n.GetHash() != nil {
				hashCount += 1
				sha.Write(n.GetHash())
			}
		}
		if hashCount == 0 {
			c.Assert(node.GetHash(), IsNil)
		} else {
			c.Assert(node.GetHash(), DeepEquals, sha.Sum(nil))
		}
	}
}
Esempio n. 28
0
// GetHash returns and instance of hash.Hash using options opts.
// If opts is nil then the default hash function is returned.
func (csp *impl) GetHash(opts bccsp.HashOpts) (h hash.Hash, err error) {
	if opts == nil {
		return csp.conf.hashFunction(), nil
	}

	switch opts.(type) {
	case *bccsp.SHAOpts:
		return csp.conf.hashFunction(), nil
	case *bccsp.SHA256Opts:
		return sha256.New(), nil
	case *bccsp.SHA384Opts:
		return sha512.New384(), nil
	case *bccsp.SHA3_256Opts:
		return sha3.New256(), nil
	case *bccsp.SHA3_384Opts:
		return sha3.New384(), nil
	default:
		return nil, fmt.Errorf("Algorithm not recognized [%s]", opts.Algorithm())
	}
}
Esempio n. 29
0
func computeHash(msg []byte, bitsize int) ([]byte, error) {
	var hash hash.Hash

	switch bitsize {
	case 224:
		hash = sha3.New224()
	case 256:
		hash = sha3.New256()
	case 384:
		hash = sha3.New384()
	case 512:
		hash = sha3.New512()
	case 521:
		hash = sha3.New512()
	default:
		return nil, fmt.Errorf("Invalid bitsize. It was [%d]. Expected [224, 256, 384, 512, 521]", bitsize)
	}

	hash.Write(msg)
	return hash.Sum(nil), nil
}
Esempio n. 30
0
func (md *MerkleDoc) SetTree(tree *MerkleTree) (err error) {
	if tree == nil {
		err = NilTree
	} else {
		var digest hash.Hash
		switch md.whichSHA {
		case xu.USING_SHA1:
			digest = sha1.New()
		case xu.USING_SHA2:
			digest = sha256.New()
		case xu.USING_SHA3:
			digest = sha3.New256()
			// XXX DEFAULT = ERROR
		}
		digest.Write(tree.hash)
		digest.Write([]byte(md.path))
		md.tree = tree
		md.hash = digest.Sum(nil)
	}
	return
}