• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang sha1.New函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中crypto/sha1.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了New函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: NewConnWithHash

func NewConnWithHash(conn *net.TCPConn) *hashedConn {
	return &hashedConn{
		Conn:  NewConn(conn, nullCipherKit),
		rHash: sha1.New(),
		wHash: sha1.New(),
	}
}
开发者ID:carvenli,项目名称:deblocus,代码行数:7,代码来源:conn.go


示例2: TestTable_SymmeticsHash

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()
		}
	}
}
开发者ID:fdebonneval,项目名称:skydive,代码行数:30,代码来源:table_test.go


示例3: NewSessionHandler

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],
	}
}
开发者ID:beatgammit,项目名称:seshcookie,代码行数:25,代码来源:seshcookie.go


示例4: main

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)
	}
}
开发者ID:smilefish1987,项目名称:funshion,代码行数:28,代码来源:hashFunc.go


示例5: TestWriteReadLargeStreams

// 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))
}
开发者ID:burnzoire,项目名称:distribution,代码行数:27,代码来源:testsuites.go


示例6: Filehash

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!")
}
开发者ID:wcreate,项目名称:lawoto,代码行数:29,代码来源:file.go


示例7: New

// 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
}
开发者ID:rwcarlsen,项目名称:gobup,代码行数:27,代码来源:handler.go


示例8: TestPad

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)
}
开发者ID:tmroeder,项目名称:cloudproxy,代码行数:35,代码来源:support_test.go


示例9: New

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)
}
开发者ID:jochasinga,项目名称:hog,代码行数:28,代码来源:hog.go


示例10: NewConnWithHash

func NewConnWithHash(conn *net.TCPConn) *hashedConn {
	return &hashedConn{
		Conn:  &Conn{Conn: conn, wlock: new(sync.Mutex)},
		rHash: sha1.New(),
		wHash: sha1.New(),
	}
}
开发者ID:4DD8A19D69F5324F9D49D17EF78BBBCC,项目名称:deblocus,代码行数:7,代码来源:conn.go


示例11: newFinishedHash

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
}
开发者ID:onedata,项目名称:helpers,代码行数:27,代码来源:prf.go


示例12: Sign

// 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,
	})
}
开发者ID:mdigger,项目名称:pkcs7sign,代码行数:61,代码来源:pkcs7.go


示例13: TestSiteBuilderBuildFormatsSources

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)
	}
}
开发者ID:AspenWeb,项目名称:aspen.go,代码行数:59,代码来源:aspen_test.go


示例14: getUserHash

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))
}
开发者ID:kleopatra999,项目名称:firebirdsql,代码行数:8,代码来源:srp.go


示例15: Close

// 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()
}
开发者ID:Kralica52281,项目名称:apk,代码行数:60,代码来源:writer.go


示例16: newHashedConn

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
}
开发者ID:angle1895,项目名称:deblocus,代码行数:10,代码来源:conn.go


示例17: authenticate

// 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
}
开发者ID:irumiha,项目名称:gosnmp,代码行数:56,代码来源:security.go


示例18: UserSettingsHandler

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})
}
开发者ID:hyber,项目名称:go-web,代码行数:55,代码来源:user.go


示例19: newFinishedHash

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}
}
开发者ID:endlessm,项目名称:chromium-browser,代码行数:11,代码来源:prf.go


示例20: TestDiskFSCreate

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)
	}
}
开发者ID:umsatz,项目名称:ent,代码行数:54,代码来源:fs_test.go



注:本文中的crypto/sha1.New函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang sha1.Sum函数代码示例发布时间:2022-05-24
下一篇:
Golang rsa.PublicKey类代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap