Golang Sum示例

说明

golang sum示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: crypto/md5

示例#1
文件: hash1.go 项目: flueg/PrivateWorkSpace

func main() {
	var TestString string
	for {
		fmt.Scanln(&TestString)

		Result1 := md5.Sum([]byte(TestString))
		fmt.Printf("md5 1: %x\n", Result1)
		tmpMd5 := fmt.Sprintf("%x", Result1)
		Result := md5.Sum([]byte(tmpMd5))
		tmpMd52 := fmt.Sprintf("%x", Result)
		fmt.Printf("md5 2: %s\n", tmpMd52)
		// Second md5 value
		//Md5Inst1 := md5.New()
		//Md5Inst1.Write([]byte(tmpMd5))
		//Result = Md5Inst1.Sum([]byte(""))
		//fmt.Printf("md5 2: %x\n", Result)

		// Third: sha1 value
		//Sha1Inst := sha1.New()
		//Sha1Inst.Write([]byte(tmpMd52))
		//Result2 := Sha1Inst.Sum([]byte(""))
		Result2 := sha1.Sum([]byte(tmpMd52))
		fmt.Printf("sha1 after md5 2: %x\n", Result2)
	}
}

示例#2
文件: mpqfix.go 项目: mewrnd/blizzconv

func (fix Fix) Apply() error {
	path := filepath.Join(mpqpath, fix.path)
	buf, err := ioutil.ReadFile(path)
	if err != nil {
		return err
	}
	oldsum := md5.Sum(buf)
	if oldsum == fix.newsum {
		return fmt.Errorf("%q already patched.", fix.path)
	}
	if oldsum != fix.oldsum {
		return fmt.Errorf("MD5 checksum mismatch for unpatched version of %q.", fix.path)
	}
	err = ioutil.WriteFile(path+".orig", buf, 0644)
	if err != nil {
		return fmt.Errorf("failed to create backup for %q; %v", fix.path, err)
	}
	for pos, val := range fix.data {
		buf[pos] = val
	}
	newsum := md5.Sum(buf)
	if newsum != fix.newsum {
		return fmt.Errorf("MD5 checksum mismatch for patched version of %q.", fix.path)
	}
	return ioutil.WriteFile(path, buf, 0644)
}

示例#3
文件: vmessout.go 项目: xiatiansong/v2ray-core

func handleResponse(conn net.Conn, request *protocol.VMessRequest, output chan<- *alloc.Buffer, finish *sync.Mutex, isUDP bool) {
	defer finish.Unlock()
	defer close(output)
	responseKey := md5.Sum(request.RequestKey[:])
	responseIV := md5.Sum(request.RequestIV[:])

	decryptResponseReader, err := v2io.NewAesDecryptReader(responseKey[:], responseIV[:], conn)
	if err != nil {
		log.Error("VMessOut: Failed to create decrypt reader: %v", err)
		return
	}

	buffer, err := v2net.ReadFrom(decryptResponseReader, nil)
	if err != nil {
		log.Error("VMessOut: Failed to read VMess response (%d bytes): %v", buffer.Len(), err)
		return
	}
	if buffer.Len() < 4 || !bytes.Equal(buffer.Value[:4], request.ResponseHeader[:]) {
		log.Warning("VMessOut: unexepcted response header. The connection is probably hijacked.")
		return
	}
	log.Info("VMessOut received %d bytes from %s", buffer.Len()-4, conn.RemoteAddr().String())

	buffer.SliceFrom(4)
	output <- buffer

	if !isUDP {
		v2net.ReaderToChan(output, decryptResponseReader)
	}

	return
}

示例#4
文件: db.go 项目: fiorix/freegeoip

// Calculate geoipupdate URL
// The auto update URL for paid products has a fun scheme.
// Use this function to calculate that URL from various information
func GeoIPUpdateURL(hostName string, userID string, licenseKey string, productID string) (url string, err error) {
	// Get the file name from the product
	url = fmt.Sprintf("%s://%s/app/update_getfilename?product_id=%s", "https", hostName, productID)
	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	hexDigest := fmt.Sprintf("%x", md5.Sum(body))

	// Get our client IP address
	url = fmt.Sprintf("%s://%s/app/update_getipaddr", "https", hostName)
	resp, err = http.Get(url)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	challenge := []byte(fmt.Sprintf("%s%s", licenseKey, body))
	hexDigest2 := fmt.Sprintf("%x", md5.Sum(challenge))

	// Create the URL
	return fmt.Sprintf("%s://%s/app/update_secure?db_md5=%s&challenge_md5=%s&user_id=%s&edition_id=%s", "https", hostName, hexDigest, hexDigest2, userID, productID), nil
}

示例#5
文件: np.go 项目: aid414944/macheart

// 注销一个管道
func (s *Socket) UnregisterChannel(name string) {
	if s.isClose {
		return
	}
	s.netchans[md5.Sum([]byte(name))].Close(ChanClosedErr)
	delete(s.netchans, md5.Sum([]byte(name)))
}

示例#6
文件: vmessout.go 项目: nikedog/v2ray-core

func (handler *VMessOutboundHandler) startCommunicate(request *vmessio.VMessRequest, dest v2net.Address, ray core.OutboundRay) error {
	conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{dest.IP, int(dest.Port), ""})
	log.Debug("VMessOutbound dialing tcp: %s", dest.String())
	if err != nil {
		log.Error("Failed to open tcp (%s): %v", dest.String(), err)
		return err
	}
	defer conn.Close()

	input := ray.OutboundInput()
	output := ray.OutboundOutput()

	requestWriter := vmessio.NewVMessRequestWriter()
	err = requestWriter.Write(conn, request)
	if err != nil {
		log.Error("Failed to write VMess request: %v", err)
		close(output)
		return err
	}

	requestKey := request.RequestKey[:]
	requestIV := request.RequestIV[:]
	responseKey := md5.Sum(requestKey)
	responseIV := md5.Sum(requestIV)

	response := vmessio.VMessResponse{}
	nBytes, err := conn.Read(response[:])
	if err != nil {
		close(output)
		log.Error("Failed to read VMess response (%d bytes): %v", nBytes, err)
		return err
	}
	log.Debug("Got response %v", response)
	// TODO: check response

	encryptRequestWriter, err := v2io.NewAesEncryptWriter(requestKey, requestIV, conn)
	if err != nil {
		close(output)
		log.Error("Failed to create encrypt writer: %v", err)
		return err
	}
	decryptResponseReader, err := v2io.NewAesDecryptReader(responseKey[:], responseIV[:], conn)
	if err != nil {
		close(output)
		log.Error("Failed to create decrypt reader: %v", err)
		return err
	}

	readFinish := make(chan bool)
	writeFinish := make(chan bool)

	go handler.dumpInput(encryptRequestWriter, input, readFinish)
	go handler.dumpOutput(decryptResponseReader, output, writeFinish)

	<-readFinish
	conn.CloseWrite()
	log.Debug("VMessOut closing write")
	<-writeFinish
	return nil
}

示例#7
文件: keepclient_test.go 项目: WangZhenfei/arvados

func (s *StandaloneSuite) TestChecksum(c *C) {
	foohash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
	barhash := fmt.Sprintf("%x", md5.Sum([]byte("bar")))

	st := BarHandler{make(chan string, 1)}

	ks := RunFakeKeepServer(st)
	defer ks.listener.Close()

	arv, err := arvadosclient.MakeArvadosClient()
	kc, _ := MakeKeepClient(&arv)
	arv.ApiToken = "abc123"
	kc.SetServiceRoots(map[string]string{"x": ks.url}, map[string]string{ks.url: ""}, nil)

	r, n, _, err := kc.Get(barhash)
	_, err = ioutil.ReadAll(r)
	c.Check(n, Equals, int64(3))
	c.Check(err, Equals, nil)

	<-st.handled

	r, n, _, err = kc.Get(foohash)
	_, err = ioutil.ReadAll(r)
	c.Check(n, Equals, int64(3))
	c.Check(err, Equals, BadChecksum)

	<-st.handled
}

示例#8
文件: vmessin_udp.go 项目: vtroop/v2ray-core

func (handler *VMessInboundHandler) handlePacket(conn *net.UDPConn, request *protocol.VMessRequest, packet v2net.Packet, clientAddr *net.UDPAddr) {
	ray := handler.vPoint.DispatchToOutbound(packet)
	close(ray.InboundInput())

	responseKey := md5.Sum(request.RequestKey)
	responseIV := md5.Sum(request.RequestIV)

	buffer := alloc.NewBuffer().Clear()
	defer buffer.Release()

	responseWriter, err := v2io.NewAesEncryptWriter(responseKey[:], responseIV[:], buffer)
	if err != nil {
		log.Error("VMessIn: Failed to create encrypt writer: %v", err)
		return
	}
	responseWriter.Write(request.ResponseHeader)

	hasData := false

	if data, ok := <-ray.InboundOutput(); ok {
		hasData = true
		responseWriter.Write(data.Value)
		data.Release()
	}

	if hasData {
		conn.WriteToUDP(buffer.Value, clientAddr)
		log.Info("VMessIn sending %d bytes to %s", buffer.Len(), clientAddr.String())
	}
}

示例#9
文件: vmessin_udp.go 项目: TonyShield/v2ray-core

func (handler *VMessInboundHandler) handlePacket(conn *net.UDPConn, request *protocol.VMessRequest, packet v2net.Packet, clientAddr *net.UDPAddr) {
	ray := handler.vPoint.DispatchToOutbound(packet)
	close(ray.InboundInput())

	responseKey := md5.Sum(request.RequestKey[:])
	responseIV := md5.Sum(request.RequestIV[:])

	buffer := bytes.NewBuffer(make([]byte, 0, bufferSize))

	response := protocol.NewVMessResponse(request)
	responseWriter, err := v2io.NewAesEncryptWriter(responseKey[:], responseIV[:], buffer)
	if err != nil {
		log.Error("VMessIn: Failed to create encrypt writer: %v", err)
		return
	}
	responseWriter.Write(response[:])

	hasData := false

	if data, ok := <-ray.InboundOutput(); ok {
		hasData = true
		responseWriter.Write(data)
	}

	if hasData {
		conn.WriteToUDP(buffer.Bytes(), clientAddr)
		log.Info("VMessIn sending %d bytes to %s", len(buffer.Bytes()), clientAddr.String())
	}
}

示例#10
文件: keepproxy_test.go 项目: Kunde21/arvados

func (s *ServerRequiredSuite) TestCorsHeaders(c *C) {
	runProxy(c, nil, false)
	defer closeListener()

	{
		client := http.Client{}
		req, err := http.NewRequest("OPTIONS",
			fmt.Sprintf("http://%s/%x+3", listener.Addr().String(), md5.Sum([]byte("foo"))),
			nil)
		req.Header.Add("Access-Control-Request-Method", "PUT")
		req.Header.Add("Access-Control-Request-Headers", "Authorization, X-Keep-Desired-Replicas")
		resp, err := client.Do(req)
		c.Check(err, Equals, nil)
		c.Check(resp.StatusCode, Equals, 200)
		body, err := ioutil.ReadAll(resp.Body)
		c.Check(string(body), Equals, "")
		c.Check(resp.Header.Get("Access-Control-Allow-Methods"), Equals, "GET, HEAD, POST, PUT, OPTIONS")
		c.Check(resp.Header.Get("Access-Control-Allow-Origin"), Equals, "*")
	}

	{
		resp, err := http.Get(
			fmt.Sprintf("http://%s/%x+3", listener.Addr().String(), md5.Sum([]byte("foo"))))
		c.Check(err, Equals, nil)
		c.Check(resp.Header.Get("Access-Control-Allow-Headers"), Equals, "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
		c.Check(resp.Header.Get("Access-Control-Allow-Origin"), Equals, "*")
	}
}

示例#11
文件: redis.go 项目: nanopack/portal

// SetCert tells all members to add the cert to their database.
// rolls back on failure
func (r Redis) SetCert(cert core.CertBundle) error {
	conn := pool.Get()
	defer conn.Close()

	// publishJson to others
	err := r.publishJson(conn, "set-cert", cert)
	if err != nil {
		// nothing to rollback yet (nobody received)
		return err
	}

	actionHash := fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprintf("set-cert %s", cert))))

	// ensure all members applied action
	err = r.waitForMembers(conn, actionHash)
	if err != nil {
		uActionHash := fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprintf("delete-cert %s", cert))))
		// cleanup rollback cruft. clear actionHash ensures no mistakes on re-submit
		defer conn.Do("DEL", uActionHash, actionHash)
		// attempt rollback - no need to waitForMembers here
		uerr := r.publishJson(conn, "delete-cert", cert)
		if uerr != nil {
			err = fmt.Errorf("%v - %v", err, uerr)
		}
		return err
	}

	if database.CentralStore {
		return database.SetCert(cert)
	}

	return nil
}

示例#12
文件: vmessout.go 项目: nenew/v2ray-core

func handleResponse(conn net.Conn, request *protocol.VMessRequest, output chan<- []byte, finish *sync.Mutex, isUDP bool) {
	defer finish.Unlock()
	defer close(output)
	responseKey := md5.Sum(request.RequestKey[:])
	responseIV := md5.Sum(request.RequestIV[:])

	decryptResponseReader, err := v2io.NewAesDecryptReader(responseKey[:], responseIV[:], conn)
	if err != nil {
		log.Error("VMessOut: Failed to create decrypt reader: %v", err)
		return
	}

	buffer := make([]byte, 2*1024)

	nBytes, err := decryptResponseReader.Read(buffer)
	if err != nil {
		//log.Error("VMessOut: Failed to read VMess response (%d bytes): %v", nBytes, err)
		return
	}
	if !bytes.Equal(buffer[:4], request.ResponseHeader[:]) {
		log.Warning("VMessOut: unexepcted response header. The connection is probably hijacked.")
		return
	}

	output <- buffer[4:nBytes]

	if !isUDP {
		v2net.ReaderToChan(output, decryptResponseReader)
	}

	return
}

示例#13
文件: redis.go 项目: nanopack/portal

// SetServer tells all members to add the server to their database.
// rolls back on failure
func (r *Redis) SetServer(svcId string, server *core.Server) error {
	conn := pool.Get()
	defer conn.Close()

	// publishStringJson to others
	err := r.publishStringJson(conn, "set-server", svcId, server)
	if err != nil {
		return err
	}

	actionHash := fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprintf("set-server %s %s", *server, svcId))))

	// ensure all members applied action
	err = r.waitForMembers(conn, actionHash)
	if err != nil {
		uActionHash := fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprintf("delete-server %s %s", server.Id, svcId))))
		// cleanup rollback cruft. clear actionHash ensures no mistakes on re-submit
		defer conn.Do("DEL", uActionHash, actionHash)
		// attempt rollback - no need to waitForMembers here
		uerr := r.publishStringJson(conn, "delete-server", server.Id, svcId)
		if uerr != nil {
			err = fmt.Errorf("%v - %v", err, uerr)
		}
		return err
	}

	if database.CentralStore {
		return database.SetServer(svcId, server)
	}

	return nil
}

示例#14
文件: auth_config.go 项目: pweil-/origin

func getSessionSecrets(filename string) ([]string, error) {
	// Build secrets list
	secrets := []string{}

	if len(filename) != 0 {
		sessionSecrets, err := latest.ReadSessionSecrets(filename)
		if err != nil {
			return nil, fmt.Errorf("error reading sessionSecretsFile %s: %v", filename, err)
		}

		if len(sessionSecrets.Secrets) == 0 {
			return nil, fmt.Errorf("sessionSecretsFile %s contained no secrets", filename)
		}

		for _, s := range sessionSecrets.Secrets {
			secrets = append(secrets, s.Authentication)
			secrets = append(secrets, s.Encryption)
		}
	} else {
		// Generate random signing and encryption secrets if none are specified in config
		secrets = append(secrets, fmt.Sprintf("%x", md5.Sum([]byte(uuid.NewRandom().String()))))
		secrets = append(secrets, fmt.Sprintf("%x", md5.Sum([]byte(uuid.NewRandom().String()))))
	}

	return secrets, nil
}

示例#15
文件: authguard.go 项目: zafhiel/gelada

// get visitor
func (ag *AuthGuard) visitorGet(username string, req *http.Request) (*visitor, bool) {
	ag.mu.Lock()
	defer ag.mu.Unlock()

	ag.data.mu.Lock()
	defer ag.data.mu.Unlock()

	var id [16]byte

	switch ag.options.BindMethod {
	case BindToIP:
		id = md5.Sum([]byte(ag.getHost(req)))
	case BindToUsernameAndIP:
		id = md5.Sum([]byte(username + ag.getHost(req)))
	}

	v := ag.data.Pool[string(id[:])]
	if v == nil {
		return nil, false
	}

	ag.visitorDataActualize(v)

	return v, true
}

示例#16
文件: vmessout.go 项目: starsw001/v2ray-core

func handleResponse(conn *net.TCPConn, request *protocol.VMessRequest, output chan<- []byte, finish *sync.Mutex) {
	defer finish.Unlock()
	defer close(output)
	responseKey := md5.Sum(request.RequestKey[:])
	responseIV := md5.Sum(request.RequestIV[:])

	decryptResponseReader, err := v2io.NewAesDecryptReader(responseKey[:], responseIV[:], conn)
	if err != nil {
		log.Error("VMessOut: Failed to create decrypt reader: %v", err)
		return
	}

	response := protocol.VMessResponse{}
	nBytes, err := decryptResponseReader.Read(response[:])
	if err != nil {
		log.Error("VMessOut: Failed to read VMess response (%d bytes): %v", nBytes, err)
		log.Error(InfoTimeNotSync)
		return
	}
	if !bytes.Equal(response[:], request.ResponseHeader[:]) {
		log.Warning("VMessOut: unexepcted response header. The connection is probably hijacked.")
		return
	}

	v2net.ReaderToChan(output, decryptResponseReader)
	return
}

示例#17
文件: auth.go 项目: v2ray/v2ray-core

// GenerateChacha20Poly1305Key generates a 32-byte key from a given 16-byte array.
func GenerateChacha20Poly1305Key(b []byte) []byte {
	key := make([]byte, 32)
	t := md5.Sum(b)
	copy(key, t[:])
	t = md5.Sum(key[:16])
	copy(key[16:], t[:])
	return key
}

示例#18
文件: inbound.go 项目: ducktsmt/v2ray-core

func (this *VMessInboundHandler) HandleConnection(connection *net.TCPConn) error {
	defer connection.Close()

	connReader := v2net.NewTimeOutReader(16, connection)
	requestReader := protocol.NewVMessRequestReader(this.clients)

	request, err := requestReader.Read(connReader)
	if err != nil {
		log.Access(connection.RemoteAddr().String(), "", log.AccessRejected, err.Error())
		log.Warning("VMessIn: Invalid request from (%s): %v", connection.RemoteAddr().String(), err)
		return err
	}
	log.Access(connection.RemoteAddr().String(), request.Address.String(), log.AccessAccepted, "")
	log.Debug("VMessIn: Received request for %s", request.Address.String())

	ray := this.space.PacketDispatcher().DispatchToOutbound(v2net.NewPacket(request.Destination(), nil, true))
	input := ray.InboundInput()
	output := ray.InboundOutput()
	var readFinish, writeFinish sync.Mutex
	readFinish.Lock()
	writeFinish.Lock()

	userSettings := vmess.GetUserSettings(request.User.Level)
	connReader.SetTimeOut(userSettings.PayloadReadTimeout)
	go handleInput(request, connReader, input, &readFinish)

	responseKey := md5.Sum(request.RequestKey)
	responseIV := md5.Sum(request.RequestIV)

	aesStream, err := v2crypto.NewAesEncryptionStream(responseKey[:], responseIV[:])
	if err != nil {
		log.Error("VMessIn: Failed to create AES decryption stream: %v", err)
		close(input)
		return err
	}

	responseWriter := v2crypto.NewCryptionWriter(aesStream, connection)

	// Optimize for small response packet
	buffer := alloc.NewLargeBuffer().Clear()
	defer buffer.Release()
	buffer.AppendBytes(request.ResponseHeader[0] ^ request.ResponseHeader[1])
	buffer.AppendBytes(request.ResponseHeader[2] ^ request.ResponseHeader[3])
	buffer.AppendBytes(byte(0), byte(0))

	if data, open := <-output; open {
		buffer.Append(data.Value)
		data.Release()
		responseWriter.Write(buffer.Value)
		go handleOutput(request, responseWriter, output, &writeFinish)
		writeFinish.Lock()
	}

	connection.CloseWrite()
	readFinish.Lock()

	return nil
}

示例#19
文件: release.go 项目: hako/afto

// AddPackageSignature appends an MD5 Signature of Packages & Packages.bz2 in the Release file.
// It should be in the form of:
// MD5Sum:
//  <hash> <size in bytes> Packages
//  <hash> <size in bytes> Packages.bz2
func (r *Release) AddPackageSignature(pkgs []byte, pkgbz2 []byte) {
	pkgsum := fmt.Sprintf("%x", md5.Sum(pkgs))
	pkgbz2sum := fmt.Sprintf("%x", md5.Sum(pkgbz2))

	pkgsig := MD5Signature{pkgsum, len(pkgs), "Packages"}
	pkgbz2sig := MD5Signature{pkgbz2sum, len(pkgbz2), "Packages.bz2"}

	r.signatures = []MD5Signature{pkgsig, pkgbz2sig}
}

示例#20
文件: crypt.go 项目: qqzj/gotest

func main() {
	data := []byte("admin")
	fmt.Println(md5.Sum(data))
	fmt.Printf("%T\n", md5.Sum(data))
	fmt.Printf("%v\n", md5.Sum(data))
	fmt.Printf("%x\n", md5.Sum(data))
	fmt.Printf("%X\n", md5.Sum(data))
	fmt.Printf("%v\n", rand.Intn(50))
}

示例#21
文件: md5.go 项目: zonesan/golang

func main() {
	data := []byte("These pretzels are making me thirsty.")
	fmt.Printf("%x\n", md5.Sum(data))
	data = []byte("88888888")
	fmt.Printf("%x\n", md5.Sum(data))
	data = []byte("BDXLDPdatahub")
	fmt.Printf("BDXLDPdatahub: %x\n", md5.Sum(data))
	data = []byte("shuyian5511")
	fmt.Printf("shuyian5511: %x\n", md5.Sum(data))
}

示例#22
文件: event.go 项目: ashwinds/ics-golang

//  generates an unique id for the event
func (e *Event) GenerateEventId() string {
	if e.GetImportedID() != "" {
		toBeHashed := fmt.Sprintf("%s%s%s%s", e.GetStart(), e.GetEnd(), e.GetImportedID())
		return fmt.Sprintf("%x", md5.Sum(stringToByte(toBeHashed)))
	} else {
		toBeHashed := fmt.Sprintf("%s%s%s%s", e.GetStart(), e.GetEnd(), e.GetSummary(), e.GetDescription())
		return fmt.Sprintf("%x", md5.Sum(stringToByte(toBeHashed)))
	}

}

示例#23
文件: vmessin.go 项目: Jamalmo/v2ray-core

func (handler *VMessInboundHandler) HandleConnection(connection net.Conn) error {
	defer connection.Close()

	reader := vmessio.NewVMessRequestReader(handler.clients)

	request, err := reader.Read(connection)
	if err != nil {
		log.Debug("Failed to parse VMess request: %v", err)
		return err
	}
	log.Debug("Received request for %s", request.Address.String())

	ray := handler.vPoint.NewInboundConnectionAccepted(request.Address)
	input := ray.InboundInput()
	output := ray.InboundOutput()

	readFinish := make(chan bool)
	writeFinish := make(chan bool)

	go handleInput(request, connection, input, readFinish)

	responseKey := md5.Sum(request.RequestKey[:])
	responseIV := md5.Sum(request.RequestIV[:])

	response := vmessio.NewVMessResponse(request)
	responseWriter, err := v2io.NewAesEncryptWriter(responseKey[:], responseIV[:], connection)
	if err != nil {
		return log.Error("Failed to create encrypt writer: %v", err)
	}
	//responseWriter.Write(response[:])

	// Optimize for small response packet
	buffer := make([]byte, 0, 1024)
	buffer = append(buffer, response[:]...)
	data, open := <-output
	if open {
		buffer = append(buffer, data...)
	}
	responseWriter.Write(buffer)

	if open {
		go handleOutput(request, responseWriter, output, writeFinish)
	} else {
		close(writeFinish)
	}

	<-writeFinish
	if tcpConn, ok := connection.(*net.TCPConn); ok {
		log.Debug("VMessIn closing write")
		tcpConn.CloseWrite()
	}
	<-readFinish

	return nil
}

示例#24
文件: login.go 项目: hinike/gowebQQ

func (s *LoginRet) gen() (vcl string, vcs string) {
	lg.Trace("generating vcl and vcs")

	sum1 := md5.Sum([]byte(s.pass))
	sum2 := md5.Sum([]byte(append(sum1[:], s.p2...)))
	sum3 := md5.Sum([]byte(fmt.Sprintf("%X", sum2) + strings.ToUpper(s.p1)))

	vcl = fmt.Sprintf("%X", sum3)
	vcs = strings.ToUpper(s.p1)
	return
}

示例#25
文件: request.go 项目: gofmt/go-leancloud

func (cloud *Client) makeSign() string {
	timestamp := strconv.Itoa(int(time.Now().Unix()))
	sign := ""
	if cloud.Cfg.UsingMaster {
		sign = fmt.Sprintf("%x", md5.Sum([]byte(timestamp+cloud.Cfg.MasterKey)))
		return fmt.Sprintf("%s,%s,%s", sign, timestamp, "master")
	} else {
		sign = fmt.Sprintf("%x", md5.Sum([]byte(timestamp+cloud.Cfg.AppKey)))
		return fmt.Sprintf("%s,%s", sign, timestamp)
	}
}

示例#26
文件: replica_test.go 项目: th3architect/longhorn

func md5Equals(c *C, expected, obtained []byte) {
	c.Assert(len(expected), Equals, len(obtained))

	expectedMd5 := md5.Sum(expected)
	obtainedMd5 := md5.Sum(obtained)
	for i := range expectedMd5 {
		l := fmt.Sprintf("%d=%x", i, expectedMd5[i])
		r := fmt.Sprintf("%d=%x", i, obtainedMd5[i])
		c.Assert(r, Equals, l)
	}
}

示例#27
文件: vmessin.go 项目: neverisland/v2ray-core

func (handler *VMessInboundHandler) HandleConnection(connection net.Conn) error {
	defer connection.Close()

	reader := vmessio.NewVMessRequestReader(handler.clients)

	request, err := reader.Read(connection)
	if err != nil {
		log.Debug("Failed to parse VMess request: %v", err)
		return err
	}
	log.Debug("Received request for %s", request.Address.String())

	response := vmessio.NewVMessResponse(request)
	nBytes, err := connection.Write(response[:])
	if err != nil {
		return log.Error("Failed to write VMess response (%d bytes): %v", nBytes, err)
	}

	requestKey := request.RequestKey[:]
	requestIV := request.RequestIV[:]
	responseKey := md5.Sum(requestKey)
	responseIV := md5.Sum(requestIV)

	requestReader, err := v2io.NewAesDecryptReader(requestKey, requestIV, connection)
	if err != nil {
		return log.Error("Failed to create decrypt reader: %v", err)
	}

	responseWriter, err := v2io.NewAesEncryptWriter(responseKey[:], responseIV[:], connection)
	if err != nil {
		return log.Error("Failed to create encrypt writer: %v", err)
	}

	ray := handler.vPoint.NewInboundConnectionAccepted(request.Address)
	input := ray.InboundInput()
	output := ray.InboundOutput()

	readFinish := make(chan bool)
	writeFinish := make(chan bool)

	go handler.dumpInput(requestReader, input, readFinish)
	go handler.dumpOutput(responseWriter, output, writeFinish)

	<-writeFinish
	if tcpConn, ok := connection.(*net.TCPConn); ok {
		log.Debug("VMessIn closing write")
		tcpConn.CloseWrite()
	}
	<-readFinish

	return nil
}

示例#28
文件: as.go 项目: cfstras/cfmedias

func (a *AS) LoginAS(ctx core.CommandContext) core.Result {
	var err error
	args := ctx.Args
	handshakeS, err := util.GetArg(args, "hs", true, err)
	handshake, err := util.CastBool(handshakeS, err)
	pVer, err := util.GetArg(args, "p", true, err)
	_, err = util.GetArg(args, "c", true, err)
	_, err = util.GetArg(args, "v", true, err)
	userS, err := util.GetArg(args, "u", true, err)
	timestampS, err := util.GetArg(args, "t", true, err)
	timestamp, err := util.CastInt64(timestampS, err)
	authMsg, err := util.GetArg(args, "a", true, err)

	if err != nil {
		return errorAS(StatusFailed, err)
	}
	if !*handshake {
		return errorAS(StatusFailed, errrs.New("this URL is only for handshake"+
			" requests, hs must be true"))
	}
	if *pVer != "1.2.1" {
		return errorAS(StatusFailed, errrs.New("Protocol version must be 1.2.1"))
	}

	//TODO maybe check audioscrobbler client id and version

	// check timestamp
	timestampReal := time.Now().Unix()
	if util.Abs(timestampReal-*timestamp) > 120 {
		return errorAS(StatusBadTime, nil)
	}

	// get user
	user, err := a.db.GetUserByName(*userS)
	if user == nil {
		logger.Log.Println("incorrect auth from unknown user ", *userS)
		return errorAS(StatusBadAuth, nil)
	}
	// check auth
	// md5(md5(auth_token) + timestamp)
	md5Token := fmt.Sprintf("%x", md5.Sum([]byte(user.AuthToken)))
	correctStr := fmt.Sprintf("%s%d", md5Token, *timestamp)
	correctAuthMsg := fmt.Sprintf("%x", md5.Sum([]byte(correctStr)))
	if correctAuthMsg != *authMsg {
		logger.Log.Println("incorrect auth from", user.Name, "with", *authMsg,
			"instead of", correctAuthMsg)
		return errorAS(StatusBadAuth, nil)
	}

	return core.Result{StatusOK, []interface{}{user.AuthToken, a.nowPlayingURL,
		a.submissionURL}, nil, true}
}

示例#29
文件: vmessin.go 项目: Botrix/v2ray-core

func (handler *VMessInboundHandler) HandleConnection(connection net.Conn) error {
	defer connection.Close()

	reader := protocol.NewVMessRequestReader(handler.clients)

	// Timeout 4 seconds to prevent DoS attack
	connection.SetReadDeadline(time.Now().Add(requestReadTimeOut))
	request, err := reader.Read(connection)
	if err != nil {
		log.Warning("VMessIn: Invalid request from (%s): %v", connection.RemoteAddr().String(), err)
		return err
	}
	log.Debug("VMessIn: Received request for %s", request.Address.String())
	// Clear read timeout
	connection.SetReadDeadline(zeroTime)

	ray := handler.vPoint.NewInboundConnectionAccepted(request.Destination())
	input := ray.InboundInput()
	output := ray.InboundOutput()

	readFinish := make(chan bool)
	writeFinish := make(chan bool)

	go handleInput(request, connection, input, readFinish)

	responseKey := md5.Sum(request.RequestKey[:])
	responseIV := md5.Sum(request.RequestIV[:])

	response := protocol.NewVMessResponse(request)
	responseWriter, err := v2io.NewAesEncryptWriter(responseKey[:], responseIV[:], connection)
	if err != nil {
		return log.Error("VMessIn: Failed to create encrypt writer: %v", err)
	}

	// Optimize for small response packet
	buffer := make([]byte, 0, 1024)
	buffer = append(buffer, response[:]...)

	if data, open := <-output; open {
		buffer = append(buffer, data...)
		responseWriter.Write(buffer)
		go handleOutput(request, responseWriter, output, writeFinish)
		<-writeFinish
	}

	if tcpConn, ok := connection.(*net.TCPConn); ok {
		tcpConn.CloseWrite()
	}
	<-readFinish

	return nil
}

示例#30
文件: vmessin.go 项目: amazted/v2ray-core

func (handler *VMessInboundHandler) HandleConnection(connection *net.TCPConn) error {
	defer connection.Close()

	connReader := v2net.NewTimeOutReader(16, connection)
	requestReader := protocol.NewVMessRequestReader(handler.clients)

	request, err := requestReader.Read(connReader)
	if err != nil {
		log.Access(connection.RemoteAddr().String(), "", log.AccessRejected, err.Error())
		log.Warning("VMessIn: Invalid request from (%s): %v", connection.RemoteAddr().String(), err)
		return err
	}
	log.Access(connection.RemoteAddr().String(), request.Address.String(), log.AccessAccepted, "")
	log.Debug("VMessIn: Received request for %s", request.Address.String())

	ray := handler.dispatcher.DispatchToOutbound(v2net.NewPacket(request.Destination(), nil, true))
	input := ray.InboundInput()
	output := ray.InboundOutput()
	var readFinish, writeFinish sync.Mutex
	readFinish.Lock()
	writeFinish.Lock()

	connReader.SetTimeOut(120)
	go handleInput(request, connReader, input, &readFinish)

	responseKey := md5.Sum(request.RequestKey)
	responseIV := md5.Sum(request.RequestIV)

	responseWriter, err := v2io.NewAesEncryptWriter(responseKey[:], responseIV[:], connection)
	if err != nil {
		log.Error("VMessIn: Failed to create encrypt writer: %v", err)
		return err
	}

	// Optimize for small response packet
	buffer := alloc.NewLargeBuffer().Clear()
	buffer.Append(request.ResponseHeader)

	if data, open := <-output; open {
		buffer.Append(data.Value)
		data.Release()
		responseWriter.Write(buffer.Value)
		buffer.Release()
		go handleOutput(request, responseWriter, output, &writeFinish)
		writeFinish.Lock()
	}

	connection.CloseWrite()
	readFinish.Lock()

	return nil
}

展开阅读全文