本文整理汇总了Golang中crypto/md5.Sum函数的典型用法代码示例。如果您正苦于以下问题:Golang Sum函数的具体用法?Golang Sum怎么用?Golang Sum使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Sum函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: main
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)
}
}
开发者ID:flueg,项目名称:PrivateWorkSpace,代码行数:25,代码来源:hash1.go
示例2: Apply
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)
}
开发者ID:mewrnd,项目名称:blizzconv,代码行数:26,代码来源:mpqfix.go
示例3: handleResponse
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
}
开发者ID:xiatiansong,项目名称:v2ray-core,代码行数:32,代码来源:vmessout.go
示例4: GeoIPUpdateURL
// 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
}
开发者ID:fiorix,项目名称:freegeoip,代码行数:34,代码来源:db.go
示例5: UnregisterChannel
// 注销一个管道
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)))
}
开发者ID:aid414944,项目名称:macheart,代码行数:8,代码来源:np.go
示例6: startCommunicate
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
}
开发者ID:nikedog,项目名称:v2ray-core,代码行数:60,代码来源:vmessout.go
示例7: TestChecksum
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
}
开发者ID:WangZhenfei,项目名称:arvados,代码行数:28,代码来源:keepclient_test.go
示例8: handlePacket
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())
}
}
开发者ID:vtroop,项目名称:v2ray-core,代码行数:30,代码来源:vmessin_udp.go
示例9: handlePacket
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())
}
}
开发者ID:TonyShield,项目名称:v2ray-core,代码行数:29,代码来源:vmessin_udp.go
示例10: TestCorsHeaders
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, "*")
}
}
开发者ID:Kunde21,项目名称:arvados,代码行数:28,代码来源:keepproxy_test.go
示例11: SetCert
// 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
}
开发者ID:nanopack,项目名称:portal,代码行数:35,代码来源:redis.go
示例12: handleResponse
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
}
开发者ID:nenew,项目名称:v2ray-core,代码行数:32,代码来源:vmessout.go
示例13: SetServer
// 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
}
开发者ID:nanopack,项目名称:portal,代码行数:34,代码来源:redis.go
示例14: getSessionSecrets
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
}
开发者ID:pweil-,项目名称:origin,代码行数:26,代码来源:auth_config.go
示例15: visitorGet
// 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
}
开发者ID:zafhiel,项目名称:gelada,代码行数:26,代码来源:authguard.go
示例16: handleResponse
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
}
开发者ID:starsw001,项目名称:v2ray-core,代码行数:27,代码来源:vmessout.go
示例17: GenerateChacha20Poly1305Key
// 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
}
开发者ID:v2ray,项目名称:v2ray-core,代码行数:9,代码来源:auth.go
示例18: HandleConnection
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
}
开发者ID:ducktsmt,项目名称:v2ray-core,代码行数:58,代码来源:inbound.go
示例19: AddPackageSignature
// 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}
}
开发者ID:hako,项目名称:afto,代码行数:14,代码来源:release.go
示例20: main
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))
}
开发者ID:qqzj,项目名称:gotest,代码行数:9,代码来源:crypt.go
注:本文中的crypto/md5.Sum函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论