Esempio n. 1
0
func NewConnWithHash(conn *net.TCPConn) *hashedConn {
	return &hashedConn{
		Conn:  NewConn(conn, nullCipherKit),
		rHash: sha1.New(),
		wHash: sha1.New(),
	}
}
Esempio n. 2
0
func TestTable_SymmeticsHash(t *testing.T) {
	ft := NewTable()
	GenerateTestFlows(t, ft, 0xca55e77e, "probe")

	foundLayers := make(map[string]bool)

	for _, f := range ft.GetFlows() {
		hasher := sha1.New()
		for _, ep := range f.GetStatistics().GetEndpoints() {
			hasher.Write(ep.Hash)
		}
		layersH := hex.EncodeToString(hasher.Sum(nil))
		foundLayers[layersH] = true
	}

	ft2 := NewTable()
	GenerateTestFlowsSymmetric(t, ft2, 0xca55e77e, "probe")

	for _, f := range ft2.GetFlows() {
		hasher := sha1.New()
		for _, ep := range f.GetStatistics().GetEndpoints() {
			hasher.Write(ep.Hash)
		}
		layersH := hex.EncodeToString(hasher.Sum(nil))
		if _, found := foundLayers[layersH]; !found {
			t.Errorf("hash endpoint should be symmeticaly, not found : %s", layersH)
			t.Fail()
		}
	}
}
Esempio n. 3
0
func NewSessionHandler(handler http.Handler, key string, rs *RequestSessions) *SessionHandler {
	// sha1 sums are 20 bytes long.  we use the first 16 bytes as
	// the aes key.
	encHash := sha1.New()
	encHash.Write([]byte(key))
	encHash.Write([]byte("-encryption"))
	hmacHash := sha1.New()
	hmacHash.Write([]byte(key))
	hmacHash.Write([]byte("-hmac"))

	// if the user hasn't specified a session handler, use the
	// package's default one
	if rs == nil {
		rs = Session
	}

	return &SessionHandler{
		Handler:    handler,
		CookieName: "session",
		CookiePath: "/",
		RS:         rs,
		encKey:     encHash.Sum(nil)[:blockSize],
		hmacKey:    hmacHash.Sum(nil)[:blockSize],
	}
}
Esempio n. 4
0
func main() {
	TestString := "Hi,panda!"

	Md5Inst := md5.New()
	Md5Inst.Write([]byte(TestString))
	Result := Md5Inst.Sum([]byte(""))
	fmt.Printf("%x\n\n", Result)

	Sha1Inst := sha1.New()
	Sha1Inst.Write([]byte(TestString))
	Result = Sha1Inst.Sum([]byte(""))
	fmt.Printf("%x\n\n", Result)

	TestFile := "123.txt"
	infile, inerr := os.Open(TestFile)
	if inerr == nil {
		md5h := md5.New()
		io.Copy(md5h, infile)
		fmt.Printf("%x , %s \n", md5h.Sum([]byte("")), TestFile)

		sha1h := sha1.New()
		io.Copy(sha1h, infile)
		fmt.Printf("%x ,%s \n", sha1h.Sum([]byte("")), TestFile)
	} else {
		fmt.Println(inerr)
		os.Exit(1)
	}
}
Esempio n. 5
0
// TestWriteReadLargeStreams tests that a 5GB file may be written to the storage
// driver safely.
func (suite *DriverSuite) TestWriteReadLargeStreams(c *check.C) {
	if testing.Short() {
		c.Skip("Skipping test in short mode")
	}

	filename := randomPath(32)
	defer suite.deletePath(c, firstPart(filename))

	checksum := sha1.New()
	var fileSize int64 = 5 * 1024 * 1024 * 1024

	contents := newRandReader(fileSize)
	written, err := suite.StorageDriver.WriteStream(suite.ctx, filename, 0, io.TeeReader(contents, checksum))
	c.Assert(err, check.IsNil)
	c.Assert(written, check.Equals, fileSize)

	reader, err := suite.StorageDriver.ReadStream(suite.ctx, filename, 0)
	c.Assert(err, check.IsNil)
	defer reader.Close()

	writtenChecksum := sha1.New()
	io.Copy(writtenChecksum, reader)

	c.Assert(writtenChecksum.Sum(nil), check.DeepEquals, checksum.Sum(nil))
}
Esempio n. 6
0
func Filehash(path_or string, file_or *os.File) (string, error) {
	if (path_or != "" && file_or == nil) || (path_or == "" && file_or != nil) {
		if path_or != "" && file_or == nil {

			if file, err := os.Open(path_or); err != nil {
				return "", err
			} else {
				defer file.Close()
				h := sha1.New()

				if _, erro := io.Copy(h, file); erro != nil {
					return "", erro
				} else {
					result := hex.EncodeToString(h.Sum(nil))
					return result, nil
				}
			}
		} else {
			h := sha1.New()
			if _, erro := io.Copy(h, file_or); erro != nil {
				return "", erro
			} else {
				result := hex.EncodeToString(h.Sum(nil))
				return result, nil
			}
		}
	}
	return "", errors.New("没有参数无法生成hash,请输入文件路径 或 *os.File!")
}
Esempio n. 7
0
// Create a new handler dumping data chunks and index info to db for an
// object/file identified by label.
func New(tx *sql.Tx, label string) (h *Handler, err error) {
	// get next file/object id
	var maxfid sql.NullInt64
	row := tx.QueryRow(getMaxFidSql)
	if err := row.Scan(&maxfid); err != nil {
		return nil, err
	}

	// get next chunk rowid
	var maxrow sql.NullInt64
	row = tx.QueryRow(getMaxChunkRowSql)
	if err := row.Scan(&maxrow); err != nil {
		return nil, err
	}

	// config and return handler
	h = &Handler{}
	h.tx = tx
	h.nextChunkRow = int(maxrow.Int64) + 1
	h.label = label
	h.fid = int(maxfid.Int64) + 1
	h.fullH = sha1.New()
	h.chunkH = sha1.New()
	return h, nil
}
Esempio n. 8
0
func TestPad(t *testing.T) {
	private, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil || private == nil {
		t.Fatal("Can't gen private key %s\n", err)
	}
	public := &private.PublicKey
	var a [9]byte
	copy(a[0:8], "IDENTITY")

	seed := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
	encrypted_secret, err := rsa.EncryptOAEP(sha1.New(), rand.Reader,
		public, seed, a[0:9])
	if err != nil {
		t.Fatal("Can't encrypt ", err)
	}
	fmt.Printf("encrypted_secret: %x\n", encrypted_secret)
	decrypted_secret, err := rsa.DecryptOAEP(sha1.New(), rand.Reader,
		private, encrypted_secret, a[0:9])
	if err != nil {
		t.Fatal("Can't decrypt ", err)
	}
	fmt.Printf("decrypted_secret: %x\n", decrypted_secret)
	var N *big.Int
	var D *big.Int
	var x *big.Int
	var z *big.Int
	N = public.N
	D = private.D
	x = new(big.Int)
	z = new(big.Int)
	x.SetBytes(encrypted_secret)
	z = z.Exp(x, D, N)
	decrypted_pad := z.Bytes()
	fmt.Printf("decrypted_pad   : %x\n", decrypted_pad)
}
Esempio n. 9
0
func (c Combination) New() []byte {

	if len(c.Salt) == 0 {
		c.Salt = generateSalt(c.Secret, 16)
	}

	salt := c.Salt
	comb := c.Secret + string(salt)

	fn := c.Func

	var pwhash hash.Hash

	switch fn {
	case MD5:
		pwhash = md5.New()
	case SHA1:
		pwhash = sha1.New()
	case SHA256:
		pwhash = sha256.New()
	default:
		pwhash = sha1.New()
	}

	io.WriteString(pwhash, comb)

	return pwhash.Sum(nil)
}
func NewConnWithHash(conn *net.TCPConn) *hashedConn {
	return &hashedConn{
		Conn:  &Conn{Conn: conn, wlock: new(sync.Mutex)},
		rHash: sha1.New(),
		wHash: sha1.New(),
	}
}
Esempio n. 11
0
func newFinishedHash(version uint16, cipherSuite *cipherSuite) finishedHash {
	var ret finishedHash

	if version >= VersionTLS12 {
		ret.hash = cipherSuite.hash()

		ret.client = ret.hash.New()
		ret.server = ret.hash.New()

		if version == VersionTLS12 {
			ret.prf = prf12(ret.hash.New)
		}
	} else {
		ret.hash = crypto.MD5SHA1

		ret.client = sha1.New()
		ret.server = sha1.New()
		ret.clientMD5 = md5.New()
		ret.serverMD5 = md5.New()

		ret.prf = prf10
	}

	ret.buffer = []byte{}
	ret.version = version
	return ret
}
Esempio n. 12
0
// Sign generate sign for data with cert & private key
func Sign(data io.Reader, cert *x509.Certificate, priv *rsa.PrivateKey) ([]byte, error) {
	var hash = sha1.New()
	if _, err := io.Copy(hash, data); err != nil {
		return nil, err
	}
	var signedData = signedData{
		Version: 1,
		DigestAlgorithms: []algorithmIdentifier{{
			Algorithm:  oidSHA1,
			Parameters: asn1.RawValue{Tag: 5},
		}},
		ContentInfo: contentInfo{Type: oidPKCS7Data},
		Certificates: asn1.RawValue{
			Class: 2, Tag: 0, Bytes: append(wwdr, cert.Raw...), IsCompound: true,
		},
		SignerInfos: []signerInfo{{
			Version: 1,
			IssuerAndSerialNumber: issuerAndSerialNumber{
				Issuer:       asn1.RawValue{FullBytes: cert.RawIssuer},
				SerialNumber: cert.SerialNumber,
			},
			DigestAlgorithm: algorithmIdentifier{
				Algorithm:  oidSHA1,
				Parameters: asn1.RawValue{Tag: 5},
			},
			AuthenticatedAttributes: []attribute{
				newAttribute(oidPKCS9ContentType, oidPKCS7Data),
				newAttribute(oidPKCS9SigningTime, time.Now().UTC()),
				newAttribute(oidPKCS9MessageDigest, hash.Sum(nil)),
			},
			DigestEncryptionAlgorithm: algorithmIdentifier{
				Algorithm:  oidPKCS1RSAEncryption,
				Parameters: asn1.RawValue{Tag: 5},
			},
		}},
	}
	encodedAuthenticatedAttributes, err := asn1.Marshal(
		signedData.SignerInfos[0].AuthenticatedAttributes)
	if err != nil {
		return nil, err
	}
	// For the digest of the authenticated attributes, we need a
	// slightly different encoding.  Change the attributes from a
	// SEQUENCE to a SET.
	var originalFirstByte = encodedAuthenticatedAttributes[0]
	encodedAuthenticatedAttributes[0] = 0x31
	hash = sha1.New()
	hash.Write(encodedAuthenticatedAttributes)
	var attributesDigest = hash.Sum(nil)
	encodedAuthenticatedAttributes[0] = originalFirstByte
	encryptedDigest, err := rsa.SignPKCS1v15(rand.Reader, priv, crypto.SHA1, attributesDigest)
	if err != nil {
		return nil, err
	}
	signedData.SignerInfos[0].EncryptedDigest = encryptedDigest
	return asn1.Marshal(container{
		OID:        oidPKCS7SignedData,
		SignedData: signedData,
	})
}
Esempio n. 13
0
func TestSiteBuilderBuildFormatsSources(t *testing.T) {
	mkTestSite()
	if noCleanup {
		fmt.Println("tmpdir =", tmpdir)
	} else {
		defer rmTmpDir()
	}

	sb, err := newSiteBuilder(&SiteBuilderCfg{
		WwwRoot:       testWwwRoot,
		OutputGopath:  tmpdir,
		GenServerBind: ":9182",
		Format:        true,
		MkOutDir:      true,
		Compile:       false,
	})
	if err != nil {
		t.Error(err)
		return
	}

	err = sb.Build()
	if err != nil {
		t.Error(err)
		return
	}

	fileName := path.Join(aspenGoGenDir, "shill-SLASH-cans-DOT-txt.go")

	fileContent, err := ioutil.ReadFile(fileName)
	if err != nil {
		t.Error(err)
		return
	}

	firstHash := sha1.New()
	io.WriteString(firstHash, string(fileContent))
	firstSum := fmt.Sprintf("%x", firstHash.Sum(nil))

	err = formatAspenGoGen()
	if err != nil {
		t.Error(err)
		return
	}

	fileContent, err = ioutil.ReadFile(fileName)
	if err != nil {
		t.Error(err)
		return
	}

	secondHash := sha1.New()
	io.WriteString(secondHash, string(fileContent))
	secondSum := fmt.Sprintf("%x", secondHash.Sum(nil))

	if firstSum != secondSum {
		t.Errorf("Hash for %q changed!", fileName)
	}
}
Esempio n. 14
0
func getUserHash(salt []byte, user string, password string) *big.Int {
	hash1 := sha1.New()
	hash1.Write(bytes.NewBufferString(user + ":" + password).Bytes())
	hash2 := sha1.New()
	hash2.Write(salt)
	hash2.Write(hash1.Sum(nil))
	return bytesToBig(hash2.Sum(nil))
}
Esempio n. 15
0
// Close finishes writing the APK. This includes writing the manifest and
// signing the archive, and writing the ZIP central directory.
//
// It does not close the underlying writer.
func (w *Writer) Close() error {
	if err := w.clearCur(); err != nil {
		return fmt.Errorf("apk: %v", err)
	}

	manifest := new(bytes.Buffer)
	fmt.Fprint(manifest, manifestHeader)
	certBody := new(bytes.Buffer)

	for _, entry := range w.manifest {
		n := entry.name
		h := base64.StdEncoding.EncodeToString(entry.sha1.Sum(nil))
		fmt.Fprintf(manifest, "Name: %s\nSHA1-Digest: %s\n\n", n, h)
		cHash := sha1.New()
		fmt.Fprintf(cHash, "Name: %s\r\nSHA1-Digest: %s\r\n\r\n", n, h)
		ch := base64.StdEncoding.EncodeToString(cHash.Sum(nil))
		fmt.Fprintf(certBody, "Name: %s\nSHA1-Digest: %s\n\n", n, ch)
	}

	mHash := sha1.New()
	mHash.Write(manifest.Bytes())
	cert := new(bytes.Buffer)
	fmt.Fprint(cert, certHeader)
	fmt.Fprintf(cert, "SHA1-Digest-Manifest: %s\n\n", base64.StdEncoding.EncodeToString(mHash.Sum(nil)))
	cert.Write(certBody.Bytes())

	mw, err := w.Create("META-INF/MANIFEST.MF")
	if err != nil {
		return err
	}
	if _, err := mw.Write(manifest.Bytes()); err != nil {
		return fmt.Errorf("apk: %v", err)
	}

	cw, err := w.Create("META-INF/CERT.SF")
	if err != nil {
		return err
	}
	if _, err := cw.Write(cert.Bytes()); err != nil {
		return fmt.Errorf("apk: %v", err)
	}

	rsa, err := signPKCS7(rand.Reader, w.priv, cert.Bytes())
	if err != nil {
		return fmt.Errorf("apk: %v", err)
	}
	rw, err := w.Create("META-INF/CERT.RSA")
	if err != nil {
		return err
	}
	if _, err := rw.Write(rsa); err != nil {
		return fmt.Errorf("apk: %v", err)
	}

	return w.w.Close()
}
Esempio n. 16
0
func newHashedConn(conn net.Conn) (h *hashedConn, c *Conn) {
	c = NewConn(conn, nullCipherKit)
	h = &hashedConn{
		Conn:     c,
		rHash:    sha1.New(),
		wHash:    sha1.New(),
		hashSize: sha1.Size,
	}
	return
}
Esempio n. 17
0
// authenticate the marshalled result of a snmp version 3 packet
func (packet *SnmpPacket) authenticate(msg []byte, authParamStart uint32) ([]byte, error) {
	defer func() {
		if e := recover(); e != nil {
			fmt.Printf("recover: %v\n", e)
		}
	}()
	if packet.Version != Version3 {
		return msg, nil
	}
	if packet.MsgFlags&AuthNoPriv == 0 {
		return msg, nil
	}
	if packet.SecurityModel != UserSecurityModel {
		return nil, fmt.Errorf("Error authenticating message: Unknown security model.")
	}

	var secParams *UsmSecurityParameters
	secParams, ok := packet.SecurityParameters.(*UsmSecurityParameters)
	if !ok || secParams == nil {
		return nil, fmt.Errorf("Error authenticating message: Unable to extract UsmSecurityParameters")
	}
	var secretKey = genlocalkey(secParams.AuthenticationProtocol,
		secParams.AuthenticationPassphrase,
		secParams.AuthoritativeEngineID)

	var extkey [64]byte

	copy(extkey[:], secretKey)

	var k1, k2 [64]byte

	for i := 0; i < 64; i++ {
		k1[i] = extkey[i] ^ 0x36
		k2[i] = extkey[i] ^ 0x5c
	}

	var h, h2 hash.Hash

	switch secParams.AuthenticationProtocol {
	default:
		h = md5.New()
		h2 = md5.New()
	case SHA:
		h = sha1.New()
		h2 = sha1.New()
	}

	h.Write(k1[:])
	h.Write(msg)
	d1 := h.Sum(nil)
	h2.Write(k2[:])
	h2.Write(d1)
	copy(msg[authParamStart:authParamStart+12], h2.Sum(nil)[:12])
	return msg, nil
}
Esempio n. 18
0
File: user.go Progetto: hyber/go-web
func UserSettingsHandler(w http.ResponseWriter, r *http.Request, s *sessions.Session) {
	if r.Method == "GET" {
		UserIndexHandler(w, r, s)
		return
	}
	var v UserSettingsRequest
	err := ParseJSON(r, &v)
	if err != nil {
		httpError(w, 400, err)
		return
	}
	u, err := GetUserById(s.Values["Id"].(int))
	if err != nil {
		httpError(w, 503, err)
		return
	}
	changes := 0
	n := strings.Trim(v.FullName, "")
	nl := len(n)
	if nl > 0 && n != u.FullName.String {
		if nl > 80 {
			JSON(w, UserSettingsResponse{Error: "InvalidName"})
			return
		}
		u.FullName.String = n
		changes++
	}
	if v.NewPasswd != "" {
		if len(v.NewPasswd) < 4 {
			JSON(w, UserSettingsResponse{Error: "InvalidPasswd"})
			return
		}
		if v.NewPasswd != v.Confirm {
			JSON(w, UserSettingsResponse{Error: "PasswdMismatch"})
			return
		}
		h := sha1.New()
		io.WriteString(h, v.OldPasswd) // old pwd
		if hex.EncodeToString(h.Sum(nil)) != u.Passwd {
			JSON(w, UserSettingsResponse{Error: "InvalidOldPasswd"})
			return
		}
		newpw := sha1.New()
		io.WriteString(newpw, v.NewPasswd)
		u.Passwd = hex.EncodeToString(newpw.Sum(nil))
		changes++
	}
	if changes > 0 {
		if err := UpdateUser(u); err != nil {
			httpError(w, 503, err)
			return
		}
	}
	JSON(w, UserSettingsResponse{Ok: true, Changes: changes})
}
Esempio n. 19
0
func newFinishedHash(version uint16, cipherSuite *cipherSuite) finishedHash {
	if version >= VersionTLS12 {
		newHash := sha256.New
		if cipherSuite.flags&suiteSHA384 != 0 {
			newHash = sha512.New384
		}

		return finishedHash{newHash(), newHash(), nil, nil, []byte{}, version, prf12(newHash)}
	}
	return finishedHash{sha1.New(), sha1.New(), md5.New(), md5.New(), []byte{}, version, prf10}
}
Esempio n. 20
0
func TestDiskFSCreate(t *testing.T) {
	tmp, err := ioutil.TempDir("", "ent-diskfs-test")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(tmp)

	var (
		b        = ent.NewBucket("create", ent.Owner{})
		fs       = newDiskFS(tmp)
		h        = sha1.New()
		testFile = "./fixture/test.zip"
	)

	r, err := os.Open(testFile)
	if err != nil {
		t.Fatal(err)
	}
	defer r.Close()

	tr := io.TeeReader(r, h)

	_, err = fs.Create(b, filepath.Base(testFile), tr)
	if err != nil {
		t.Fatal(err)
	}

	destination := filepath.Join(tmp, b.Name, filepath.Base(testFile))
	_, err = os.Stat(destination)
	if err != nil {
		t.Fatal(err)
	}

	f, err := fs.Open(b, filepath.Base(testFile))
	if err != nil {
		t.Fatal(err)
	}

	s := sha1.New()

	_, err = io.Copy(s, f)
	if err != nil {
		t.Fatal(err)
	}

	var (
		expected = hex.EncodeToString(h.Sum(nil))
		got      = hex.EncodeToString(s.Sum(nil))
	)

	if got != expected {
		t.Errorf("hash miss-match: %s != %s", got, expected)
	}
}
Esempio n. 21
0
func (t *SignerTest) TestItsDangerousSignerCompatibility(c *C) {
	sha1Hash := sha1.New()
	sha1Hash.Write([]byte("itsdangerous.Signersignerfoo-bar"))
	key := sha1Hash.Sum(nil)
	h = hmac.New(func() hash.Hash {
		return sha1.New()
	}, key)

	s := signer.NewBase64Signer(h)
	msg := s.Sign([]byte("hello"))
	c.Assert(string(msg), Equals, "hello.z_6t_YXT-K_Lki8whMeb9uCpB7o")
}
Esempio n. 22
0
func TestEMSAPSS(t *testing.T) {
	// Test vector in file pss-int.txt from: ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip
	msg := []byte{
		0x85, 0x9e, 0xef, 0x2f, 0xd7, 0x8a, 0xca, 0x00, 0x30, 0x8b,
		0xdc, 0x47, 0x11, 0x93, 0xbf, 0x55, 0xbf, 0x9d, 0x78, 0xdb,
		0x8f, 0x8a, 0x67, 0x2b, 0x48, 0x46, 0x34, 0xf3, 0xc9, 0xc2,
		0x6e, 0x64, 0x78, 0xae, 0x10, 0x26, 0x0f, 0xe0, 0xdd, 0x8c,
		0x08, 0x2e, 0x53, 0xa5, 0x29, 0x3a, 0xf2, 0x17, 0x3c, 0xd5,
		0x0c, 0x6d, 0x5d, 0x35, 0x4f, 0xeb, 0xf7, 0x8b, 0x26, 0x02,
		0x1c, 0x25, 0xc0, 0x27, 0x12, 0xe7, 0x8c, 0xd4, 0x69, 0x4c,
		0x9f, 0x46, 0x97, 0x77, 0xe4, 0x51, 0xe7, 0xf8, 0xe9, 0xe0,
		0x4c, 0xd3, 0x73, 0x9c, 0x6b, 0xbf, 0xed, 0xae, 0x48, 0x7f,
		0xb5, 0x56, 0x44, 0xe9, 0xca, 0x74, 0xff, 0x77, 0xa5, 0x3c,
		0xb7, 0x29, 0x80, 0x2f, 0x6e, 0xd4, 0xa5, 0xff, 0xa8, 0xba,
		0x15, 0x98, 0x90, 0xfc,
	}
	salt := []byte{
		0xe3, 0xb5, 0xd5, 0xd0, 0x02, 0xc1, 0xbc, 0xe5, 0x0c, 0x2b,
		0x65, 0xef, 0x88, 0xa1, 0x88, 0xd8, 0x3b, 0xce, 0x7e, 0x61,
	}
	expected := []byte{
		0x66, 0xe4, 0x67, 0x2e, 0x83, 0x6a, 0xd1, 0x21, 0xba, 0x24,
		0x4b, 0xed, 0x65, 0x76, 0xb8, 0x67, 0xd9, 0xa4, 0x47, 0xc2,
		0x8a, 0x6e, 0x66, 0xa5, 0xb8, 0x7d, 0xee, 0x7f, 0xbc, 0x7e,
		0x65, 0xaf, 0x50, 0x57, 0xf8, 0x6f, 0xae, 0x89, 0x84, 0xd9,
		0xba, 0x7f, 0x96, 0x9a, 0xd6, 0xfe, 0x02, 0xa4, 0xd7, 0x5f,
		0x74, 0x45, 0xfe, 0xfd, 0xd8, 0x5b, 0x6d, 0x3a, 0x47, 0x7c,
		0x28, 0xd2, 0x4b, 0xa1, 0xe3, 0x75, 0x6f, 0x79, 0x2d, 0xd1,
		0xdc, 0xe8, 0xca, 0x94, 0x44, 0x0e, 0xcb, 0x52, 0x79, 0xec,
		0xd3, 0x18, 0x3a, 0x31, 0x1f, 0xc8, 0x96, 0xda, 0x1c, 0xb3,
		0x93, 0x11, 0xaf, 0x37, 0xea, 0x4a, 0x75, 0xe2, 0x4b, 0xdb,
		0xfd, 0x5c, 0x1d, 0xa0, 0xde, 0x7c, 0xec, 0xdf, 0x1a, 0x89,
		0x6f, 0x9d, 0x8b, 0xc8, 0x16, 0xd9, 0x7c, 0xd7, 0xa2, 0xc4,
		0x3b, 0xad, 0x54, 0x6f, 0xbe, 0x8c, 0xfe, 0xbc,
	}

	hash := sha1.New()
	hash.Write(msg)
	hashed := hash.Sum(nil)

	encoded, err := emsaPSSEncode(hashed, 1023, salt, sha1.New())
	if err != nil {
		t.Errorf("Error from emsaPSSEncode: %s\n", err)
	}
	if !bytes.Equal(encoded, expected) {
		t.Errorf("Bad encoding. got %x, want %x", encoded, expected)
	}

	if err = emsaPSSVerify(hashed, encoded, 1023, len(salt), sha1.New()); err != nil {
		t.Errorf("Bad verification: %s", err)
	}
}
Esempio n. 23
0
func TestIndex(t *testing.T) {
	f, err := os.Open("testdata/divina2.txt.gz")
	if err != nil {
		t.Fatal(err)
	}
	defer f.Close()

	gz, err := NewReader(f)
	if err != nil {
		t.Fatal(err)
	}

	type offsets struct {
		Off Offset
		Sum string
	}
	var pos []offsets

	seed := time.Now().UnixNano()
	t.Log("using seed:", seed)
	rand.Seed(seed)
	for {
		skip := rand.Int63n(10000) + 1
		_, err := io.CopyN(ioutil.Discard, gz, skip)
		if err == io.EOF {
			break
		}

		off := gz.Offset()
		hash := sha1.New()
		io.CopyN(hash, gz, 64)
		sum := hash.Sum([]byte{})

		pos = append(pos, offsets{Off: off, Sum: hex.EncodeToString(sum)})
	}

	if !gz.IsProbablyMultiGzip() {
		t.Error("file is not detected as multigzip")
	}

	perm := rand.Perm(len(pos))
	for _, idx := range perm {
		p := pos[idx]
		gz.Seek(p.Off)
		hash := sha1.New()
		io.CopyN(hash, gz, 64)
		sum := hash.Sum([]byte{})
		if hex.EncodeToString(sum) != p.Sum {
			t.Error("invalid checksum", p, hex.EncodeToString(sum))
		}
	}
}
Esempio n. 24
0
func newFinishedHash(version uint16, cipherSuite *cipherSuite) finishedHash {
	var buffer []byte
	if version == VersionSSL30 || version >= VersionTLS12 {
		buffer = []byte{}
	}

	prf, hash := prfAndHashForVersion(version, cipherSuite)
	if hash != 0 {
		return finishedHash{hash.New(), hash.New(), nil, nil, buffer, version, prf}
	}

	return finishedHash{sha1.New(), sha1.New(), md5.New(), md5.New(), buffer, version, prf}
}
Esempio n. 25
0
// PlainMatcher returns a PasswordMatcher that does a constant-time
// byte comparison against the password passw.
func PlainMatcher(passw string) PasswordMatcher {
	// compare hashes of equal length instead of actual password
	// to avoid leaking password length
	passwHash := sha1.New()
	passwHash.Write([]byte(passw))
	passwSum := passwHash.Sum(nil)
	return func(pw string) bool {
		pwHash := sha1.New()
		pwHash.Write([]byte(pw))
		pwSum := pwHash.Sum(nil)
		return subtle.ConstantTimeCompare([]byte(pwSum), []byte(passwSum)) == 1
	}
}
Esempio n. 26
0
func createKey() (encKey, hmacKey []byte) {
	encSha1 := sha1.New()
	encSha1.Write([]byte(time.Now().UTC().String()))
	encSha1.Write([]byte("-enc"))
	encKey = encSha1.Sum(nil)[:blockSize]

	hmacSha1 := sha1.New()
	hmacSha1.Write([]byte(time.Now().UTC().String()))
	hmacSha1.Write([]byte("-hmac"))
	hmacKey = hmacSha1.Sum(nil)[:blockSize]

	return
}
Esempio n. 27
0
// Return hash for a file, return a hex string uppercase
func hasher(filename string, method string) string {
	file, _ := ioutil.ReadFile(filename) // bytes
	var h hash.Hash
	switch method {
	case "sha1":
		h = sha1.New()
	case "md5":
		h = md5.New()
	default:
		h = sha1.New()
	}
	h.Write(file)
	return fmt.Sprintf("%X", h.Sum(nil)) // Return hex to upper
}
Esempio n. 28
0
// Returns the current stage in the "daemonization process", that's kept in
// an environment variable. The variable is instrumented with a digital
// signature, to avoid misbehavior if it was present in the user's
// environment. The original value is restored after the last stage, so that
// there's no final effect on the environment the application receives.
func getStage() (stage int, advanceStage func(), resetEnv func()) {
	var origValue string
	stage = 0

	daemonStage := os.Getenv(stageVar)
	stageTag := strings.SplitN(daemonStage, ":", 2)
	stageInfo := strings.SplitN(stageTag[0], "/", 3)

	if len(stageInfo) == 3 {
		stageStr, tm, check := stageInfo[0], stageInfo[1], stageInfo[2]

		hash := sha1.New()
		hash.Write([]byte(stageStr + "/" + tm + "/"))

		if check != hex.EncodeToString(hash.Sum([]byte{})) {
			// This whole chunk is original data
			origValue = daemonStage
		} else {
			stage, _ = strconv.Atoi(stageStr)

			if len(stageTag) == 2 {
				origValue = stageTag[1]
			}
		}
	} else {
		origValue = daemonStage
	}

	advanceStage = func() {
		base := fmt.Sprintf("%d/%09d/", stage+1, time.Now().Nanosecond())
		hash := sha1.New()
		hash.Write([]byte(base))

		tag := base + hex.EncodeToString(hash.Sum([]byte{}))

		if err := os.Setenv(stageVar, tag+":"+origValue); err != nil {
			fmt.Fprintf(os.Stderr, "can't set %s (stage %d)\n", stageVar, stage)
			os.Exit(1)
		}
	}

	resetEnv = func() {
		if err := os.Setenv(stageVar, origValue); err != nil {
			fmt.Fprintf(os.Stderr, "can't reset %s\n", stageVar)
			os.Exit(1)
		}
	}

	return stage, advanceStage, resetEnv
}
Esempio n. 29
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. 30
0
// determine whether a message is authentic
func (sp *UsmSecurityParameters) isAuthentic(packetBytes []byte, packet *SnmpPacket) (bool, error) {

	var packetSecParams *UsmSecurityParameters
	var err error

	if packetSecParams, err = castUsmSecParams(packet.SecurityParameters); err != nil {
		return false, err
	}

	var secretKey = genlocalkey(sp.AuthenticationProtocol,
		sp.AuthenticationPassphrase,
		sp.AuthoritativeEngineID)

	var extkey [64]byte

	copy(extkey[:], secretKey)

	var k1, k2 [64]byte

	for i := 0; i < 64; i++ {
		k1[i] = extkey[i] ^ 0x36
		k2[i] = extkey[i] ^ 0x5c
	}

	var h, h2 hash.Hash

	switch sp.AuthenticationProtocol {
	default:
		h = md5.New()
		h2 = md5.New()
	case SHA:
		h = sha1.New()
		h2 = sha1.New()
	}

	h.Write(k1[:])
	h.Write(packetBytes)
	d1 := h.Sum(nil)
	h2.Write(k2[:])
	h2.Write(d1)

	result := h2.Sum(nil)[:12]
	for k, v := range []byte(packetSecParams.AuthenticationParameters) {
		if result[k] != v {
			return false, nil
		}
	}
	return true, nil
}