本文整理匯總了Golang中crypto/md5.Sum函數的典型用法代碼示例。如果您正苦於以下問題:Golang Sum函數的具體用法?Golang Sum怎麽用?Golang Sum使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Sum函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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)
}
}
示例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)
}
示例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
}
示例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
}
示例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)))
}
示例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
}
示例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
}
示例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())
}
}
示例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())
}
}
示例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, "*")
}
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}