Ejemplo n.º 1
0
func TestSlice(t *testing.T) {
	a := []string{"abc", "def"}
	h := md5.New()
	io.WriteString(h, a[0])
	io.WriteString(h, a[1])
	expected := h.Sum(nil)
	check(t, expected, a)

	b := []int{1, 2, 3}
	h = md5.New()
	binary.Write(h, binary.BigEndian, b[0])
	binary.Write(h, binary.BigEndian, b[1])
	binary.Write(h, binary.BigEndian, b[2])
	expected = h.Sum(nil)
	check(t, expected, b)

	p := []*int{}
	x, y, z := int(1), int(2), int(3)
	p = append(p, &x, &y, &z, nil)
	h = md5.New()
	binary.Write(h, binary.BigEndian, x)
	binary.Write(h, binary.BigEndian, y)
	binary.Write(h, binary.BigEndian, z)
	h.Write([]byte{0})
	expected = h.Sum(nil)
	check(t, expected, p)
}
Ejemplo n.º 2
0
func (socket *mongoSocket) loginClassic(cred Credential) error {
	// Note that this only works properly because this function is
	// synchronous, which means the nonce won't get reset while we're
	// using it and any other login requests will block waiting for a
	// new nonce provided in the defer call below.
	nonce, err := socket.getNonce()
	if err != nil {
		return err
	}
	defer socket.resetNonce()

	psum := md5.New()
	psum.Write([]byte(cred.Username + ":mongo:" + cred.Password))

	ksum := md5.New()
	ksum.Write([]byte(nonce + cred.Username))
	ksum.Write([]byte(hex.EncodeToString(psum.Sum(nil))))

	key := hex.EncodeToString(ksum.Sum(nil))

	cmd := authCmd{Authenticate: 1, User: cred.Username, Nonce: nonce, Key: key}
	res := authResult{}
	return socket.loginRun(cred.Source, &cmd, &res, func() error {
		if !res.Ok {
			return errors.New(res.ErrMsg)
		}
		socket.Lock()
		socket.dropAuth(cred.Source)
		socket.creds = append(socket.creds, cred)
		socket.Unlock()
		return nil
	})
}
Ejemplo n.º 3
0
func main() {
	fmt.Printf("Login......\n")
	unixTime := getUnixTime()

	//*******************token process begin************************
	var orignalToken = getToken(unixTime)
	//fmt.Printf("%s \n",orignalToken)
	vm.Set("token", orignalToken)
	token, error := vm.Run(encyptFunctions)
	if error != nil {
		//handler error
	}
	md5_t := md5.New()
	s_token, error := token.ToString()
	if error != nil {
		//handler error
	}
	md5_t.Write([]byte(s_token))
	true_token := hex.EncodeToString(md5_t.Sum(nil))
	//*******************token process end************************

	time.Sleep(1 * time.Second)
	email := "" //your email
	pwd := ""   //your password
	md5_p := md5.New()
	md5_p.Write([]byte(pwd))
	passwd := hex.EncodeToString(md5_p.Sum(nil))

	result := login(true_token, unixTime, email, passwd)
	fmt.Printf("%s\n", result)
}
Ejemplo n.º 4
0
func testMultipartObjectCreation(c *check.C, create func() Driver) {
	drivers := create()
	err := drivers.CreateBucket("bucket", "")
	c.Assert(err, check.IsNil)
	uploadID, err := drivers.NewMultipartUpload("bucket", "key", "")
	c.Assert(err, check.IsNil)

	parts := make(map[int]string)
	finalHasher := md5.New()
	for i := 1; i <= 10; i++ {
		randomPerm := rand.Perm(10)
		randomString := ""
		for _, num := range randomPerm {
			randomString = randomString + strconv.Itoa(num)
		}

		hasher := md5.New()
		finalHasher.Write([]byte(randomString))
		hasher.Write([]byte(randomString))
		expectedmd5Sum := base64.StdEncoding.EncodeToString(hasher.Sum(nil))
		expectedmd5Sumhex := hex.EncodeToString(hasher.Sum(nil))

		calculatedmd5sum, err := drivers.CreateObjectPart("bucket", "key", uploadID, i, "", expectedmd5Sum, int64(len(randomString)),
			bytes.NewBufferString(randomString))
		c.Assert(err, check.IsNil)
		c.Assert(calculatedmd5sum, check.Equals, expectedmd5Sumhex)
		parts[i] = calculatedmd5sum
	}
	finalExpectedmd5SumHex := hex.EncodeToString(finalHasher.Sum(nil))
	calculatedFinalmd5Sum, err := drivers.CompleteMultipartUpload("bucket", "key", uploadID, parts)
	c.Assert(err, check.IsNil)
	c.Assert(calculatedFinalmd5Sum, check.Equals, finalExpectedmd5SumHex)
}
Ejemplo n.º 5
0
func main() {
	/*
		bytes1 := []byte{53, 54, 52, 50, 51, 50, 54, 212, 29, 140, 217, 143, 0, 178, 4, 233, 128, 9, 152, 236, 248, 66, 126}
		fmt.Println(bytes1)
		fmt.Println(string(bytes1))

		bytes2 := []byte{25, 27, 244, 217, 128, 26, 104, 209, 142, 206, 225, 61, 224, 35, 194, 25, 34, 163, 48, 192, 204, 109, 175, 139, 249, 236, 223, 153, 231, 28, 80, 164}
		fmt.Println(bytes2)
		fmt.Sprintf("%s", bytes2)
	*/

	h := md5.New()
	c := h.Sum([]byte("test"))
	fmt.Sprintf("%x", []byte("test"))
	fmt.Println([]byte("test"))
	fmt.Println(string([]byte("test")))
	fmt.Println(fmt.Sprintf("%x", c))
	fmt.Println(c)
	fmt.Println(string(c))

	h1 := md5.New()
	io.WriteString(h1, "test")
	c2 := h1.Sum(nil)
	fmt.Sprintf("%x", c2)
	// fmt.Println(string(c2))

	bytes := []byte{53, 53, 53, 53}
	c1 := h.Sum(bytes)
	fmt.Sprintf("%x", c1)
	// fmt.Println(c1)

	// writeResult(c)
}
Ejemplo n.º 6
0
func (s *S) TestSendMessageWithAttributes(c *C) {
	testServer.PrepareResponse(200, nil, TestSendMessageXmlOK)

	q := &Queue{s.sqs, testServer.URL + "/123456789012/testQueue/"}
	attrs := map[string]string{
		"test_attribute_name_1": "test_attribute_value_1",
	}
	resp, err := q.SendMessageWithAttributes("This is a test message", attrs)
	req := testServer.WaitRequest()

	c.Assert(req.Method, Equals, "GET")
	c.Assert(req.URL.Path, Equals, "/123456789012/testQueue/")
	c.Assert(req.Header["Date"], Not(Equals), "")

	var attrsHash = md5.New()
	attrsHash.Write(encodeMessageAttribute("test_attribute_name_1"))
	attrsHash.Write(encodeMessageAttribute("String"))
	attrsHash.Write([]byte{1})
	attrsHash.Write(encodeMessageAttribute("test_attribute_value_1"))
	c.Assert(resp.MD5OfMessageAttributes, Equals, fmt.Sprintf("%x", attrsHash.Sum(nil)))

	msg := "This is a test message"
	var h hash.Hash = md5.New()
	h.Write([]byte(msg))
	c.Assert(resp.MD5, Equals, fmt.Sprintf("%x", h.Sum(nil)))
	c.Assert(resp.Id, Equals, "5fea7756-0ea4-451a-a703-a558b933e274")
	c.Assert(err, IsNil)
}
Ejemplo n.º 7
0
func (s *CollectionReaderUnit) TestCollectionReaderManyBlocks(c *check.C) {
	h := md5.New()
	buf := make([]byte, 4096)
	locs := make([]string, len(buf))
	filesize := 0
	for i := 0; i < len(locs); i++ {
		_, err := io.ReadFull(rand.Reader, buf[:i])
		c.Assert(err, check.IsNil)
		h.Write(buf[:i])
		locs[i], _, err = s.kc.PutB(buf[:i])
		c.Assert(err, check.IsNil)
		filesize += i
	}
	manifest := "./random " + strings.Join(locs, " ") + " 0:" + strconv.Itoa(filesize) + ":bytes.bin\n"
	dataMD5 := h.Sum(nil)

	checkMD5 := md5.New()
	rdr, err := s.kc.CollectionFileReader(map[string]interface{}{"manifest_text": manifest}, "random/bytes.bin")
	c.Check(err, check.IsNil)
	_, err = io.Copy(checkMD5, rdr)
	c.Check(err, check.IsNil)
	_, err = rdr.Read(make([]byte, 1))
	c.Check(err, check.Equals, io.EOF)
	c.Check(checkMD5.Sum(nil), check.DeepEquals, dataMD5)
}
Ejemplo n.º 8
0
func (h *HashcheckSuiteSuite) TestRead(c *C) {
	hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))

	{
		r, w := io.Pipe()
		hcr := HashCheckingReader{r, md5.New(), hash}
		go func() {
			w.Write([]byte("foo"))
			w.Close()
		}()
		p, err := ioutil.ReadAll(hcr)
		c.Check(len(p), Equals, 3)
		c.Check(err, Equals, nil)
	}

	{
		r, w := io.Pipe()
		hcr := HashCheckingReader{r, md5.New(), hash}
		go func() {
			w.Write([]byte("bar"))
			w.Close()
		}()
		p, err := ioutil.ReadAll(hcr)
		c.Check(len(p), Equals, 3)
		c.Check(err, Equals, BadChecksum)
	}
}
Ejemplo n.º 9
0
func login(w http.ResponseWriter, r *http.Request) {
	r.ParseForm() //解析参数
	Println("method:", r.Method)
	h := md5.New()
	test := md5.New()
	// str := "hebihui"
	// test.Write([]byte(str))
	haha := Sprintf("%x", test.Sum(nil))
	Println("my:", haha)
	if r.Method == "GET" {
		crutime := time.Now().Unix()
		io.WriteString(h, strconv.FormatInt(crutime, 10))
		token := Sprintf("%x", h.Sum(nil))
		t, _ := template.ParseFiles("login.gtpl")
		t.Execute(w, token)
	} else {
		token := r.Form.Get("token")
		if token != "" {
			if isValidation(token) {
				table[token] = 1
				Fprintf(w, "OK.")
			} else {
				Fprintf(w, "fail.")
			}
		} else {
			Fprintf(w, "null") //不合法
		}
		Println("username:"******"username"])
		Println("password:"******"password"])
	}
}
Ejemplo n.º 10
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)
	}
}
Ejemplo n.º 11
0
/* 插入用户 */
func (this *Member) Insert() string {
	if this.Id == "" { //id没有设置则初始化新的
		this.Id = bson.NewObjectId()
	}
	this.LastTime = bson.Now()
	this.StopTime = bson.Now()
	this.SalayTime = bson.Now()
	this.Token = strconv.Itoa(int(rand.New(rand.NewSource(time.Now().UnixNano())).Uint32()))
	this.ErrorChance = 6
	//如果没有头像,随机设置一个头像
	if this.Image == "" {
		this.Image = strconv.Itoa(rand.Intn(9))
	}
	//密码md5加盐+用户ID+md5加密
	m := md5.New()
	m.Write([]byte(this.Password))
	n := md5.New()
	n.Write([]byte(hex.EncodeToString(m.Sum(nil)) + beego.AppConfig.String("md5salt") + bson.ObjectId.Hex(this.Id)))
	this.Password = hex.EncodeToString(n.Sum(nil))
	err := memberC.Insert(this)
	if err != nil {
		panic(err)
	}
	return bson.ObjectId.Hex(this.Id)
}
Ejemplo n.º 12
0
/* 校验密码是否正确 支持类型:邮箱 */
func (this *Member) CheckPass(account string, password string) (string, int) {
	err := memberC.Find(bson.M{"e": account}).One(&this)
	if err != nil {
		return "", -2 //账号不存在
	}

	if bson.Now().Before(this.StopTime) { //锁定时间还没过
		long := this.StopTime.Sub(bson.Now())
		return strconv.FormatFloat(long.Seconds(), 'f', 0, 64) + " 秒", -3
	}
	//密码加密
	m := md5.New()
	m.Write([]byte(password))
	n := md5.New()
	n.Write([]byte(hex.EncodeToString(m.Sum(nil)) + beego.AppConfig.String("md5salt") + bson.ObjectId.Hex(this.Id)))
	//对比
	if hex.EncodeToString(n.Sum(nil)) != this.Password { //验证出错
		if this.ErrorChance <= 1 { //用尽验证机会,账号锁定10分钟
			this.ErrorChance = 6
			minute := time.Duration(10) * time.Minute
			this.StopTime = bson.Now().Add(minute)
			this.Update(bson.M{"$set": bson.M{"er": this.ErrorChance, "st": this.StopTime}})
			return "", -4 //进入锁定
		} else { //验证机会-1
			this.ErrorChance--
			this.Update(bson.M{"$set": bson.M{"er": this.ErrorChance}})
			return strconv.Itoa(int(this.ErrorChance)), -1 //密码不匹配
		}
	} else { //通过验证,重置机会次数
		this.ErrorChance = 6
		this.Update(bson.M{"$set": bson.M{"er": this.ErrorChance}})
		return this.Id.Hex(), 1
	}
}
Ejemplo n.º 13
0
// Sends an S3 multipart upload initiation request.
// See http://docs.amazonwebservices.com/AmazonS3/latest/dev/mpuoverview.html.
// The initial request returns an UploadId that we use to identify
// subsequent PUT requests.
func newPutter(url url.URL, h http.Header, c *Config, b *Bucket) (p *putter, err error) {
	p = new(putter)
	p.url = url
	p.c, p.b = new(Config), new(Bucket)
	*p.c, *p.b = *c, *b
	p.c.Concurrency = max(c.Concurrency, 1)
	p.c.NTry = max(c.NTry, 1)
	p.bufsz = max64(minPartSize, c.PartSize)
	resp, err := p.retryRequest("POST", url.String()+"?uploads", nil, h)
	if err != nil {
		return nil, err
	}
	defer checkClose(resp.Body, err)
	if resp.StatusCode != 200 {
		return nil, newRespError(resp)
	}
	err = xml.NewDecoder(resp.Body).Decode(p)
	if err != nil {
		return nil, err
	}
	p.ch = make(chan *part)
	for i := 0; i < p.c.Concurrency; i++ {
		go p.worker()
	}
	p.md5OfParts = md5.New()
	p.md5 = md5.New()

	p.sp = bufferPool(p.bufsz)

	return p, nil
}
Ejemplo n.º 14
0
func main() {
	// md5
	h := md5.New()
	h.Write([]byte("404 Pages"))
	//fmt.Printf("%x \n", h.Sum(nil))
	s := "0B2441996dc4ebeb1a356ebfe1b3e9a5"

	fmt.Println(fmt.Sprintf("%x", h.Sum(nil)))

	if strings.EqualFold(s, fmt.Sprintf("%x", h.Sum(nil))) {
		fmt.Println("They are equals! EqualFold")
	}

	if s == fmt.Sprintf("%x", h.Sum(nil)) {
		fmt.Println("They are equals!")
	}

	// sha-1
	h = sha1.New()
	h.Write([]byte("404 Pages"))
	fmt.Printf("%x \n", h.Sum(nil))

	// 文件hash
	f := md5.New()
	file := "F:\\cmdlet.txt"
	r, err := os.Open(file)
	if err != nil {
		return
	}
	defer r.Close()
	b, _ := ioutil.ReadAll(r)
	f.Write(b)
	fmt.Printf("File MD5: %x \n", f.Sum(nil))
}
Ejemplo n.º 15
0
func TestInt(t *testing.T) {
	i := int(123456789)
	h := md5.New()
	binary.Write(h, binary.BigEndian, i)
	expected := h.Sum(nil)
	check(t, expected, i)

	i8 := int8(123)
	h = md5.New()
	binary.Write(h, binary.BigEndian, i8)
	expected = h.Sum(nil)
	check(t, expected, i8)

	// byte is an alias for uint8
	b := byte('Q')
	h = md5.New()
	binary.Write(h, binary.BigEndian, b)
	expected = h.Sum(nil)
	check(t, expected, b)

	// rune is an alias for int32
	r := rune('龍')
	h = md5.New()
	binary.Write(h, binary.BigEndian, r)
	expected = h.Sum(nil)
	check(t, expected, r)

	ui64 := uint64(123456789123456789)
	h = md5.New()
	binary.Write(h, binary.BigEndian, ui64)
	expected = h.Sum(nil)
	check(t, expected, ui64)
}
Ejemplo n.º 16
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
}
Ejemplo n.º 17
0
//
// BuildAuthResponseHeader - return the body for auth header in response
func BuildAuthResponseHeader(username string, password string, hparams map[string]string) string {
	// https://en.wikipedia.org/wiki/Digest_access_authentication
	// HA1
	h := md5.New()
	A1 := fmt.Sprintf("%s:%s:%s", username, hparams["realm"], password)
	io.WriteString(h, A1)
	HA1 := fmt.Sprintf("%x", h.Sum(nil))

	// HA2
	h = md5.New()
	A2 := fmt.Sprintf("%s:%s", hparams["method"], hparams["uri"])
	io.WriteString(h, A2)
	HA2 := fmt.Sprintf("%x", h.Sum(nil))

	AuthHeader := ""
	if _, ok := hparams["qop"]; !ok {
		// build digest response
		response := HMD5(strings.Join([]string{HA1, hparams["nonce"], HA2}, ":"))
		// build header body
		AuthHeader = fmt.Sprintf(`Digest username="******", realm="%s", nonce="%s", uri="%s", algorithm=MD5, response="%s"`,
			username, hparams["realm"], hparams["nonce"], hparams["uri"], response)
	} else {
		// build digest response
		cnonce := RandomKey()
		response := HMD5(strings.Join([]string{HA1, hparams["nonce"], "00000001", cnonce, hparams["qop"], HA2}, ":"))
		// build header body
		AuthHeader = fmt.Sprintf(`Digest username="******", realm="%s", nonce="%s", uri="%s", cnonce="%s", nc=00000001, qop=%s, opaque="%s", algorithm=MD5, response="%s"`,
			username, hparams["realm"], hparams["nonce"], hparams["uri"], cnonce, hparams["qop"], hparams["opaque"], response)
	}
	return AuthHeader
}
Ejemplo n.º 18
0
func testObjectOverwriteWorks(c *check.C, create func() Filesystem) {
	fs := create()
	err := fs.MakeBucket("bucket", "")
	c.Assert(err, check.IsNil)

	hasher1 := md5.New()
	hasher1.Write([]byte("one"))
	md5Sum1 := base64.StdEncoding.EncodeToString(hasher1.Sum(nil))
	md5Sum1hex := hex.EncodeToString(hasher1.Sum(nil))
	objectMetadata, err := fs.CreateObject("bucket", "object", md5Sum1, int64(len("one")), bytes.NewBufferString("one"), nil)
	c.Assert(err, check.IsNil)
	c.Assert(md5Sum1hex, check.Equals, objectMetadata.MD5)

	hasher2 := md5.New()
	hasher2.Write([]byte("three"))
	md5Sum2 := base64.StdEncoding.EncodeToString(hasher2.Sum(nil))
	_, err = fs.CreateObject("bucket", "object", md5Sum2, int64(len("three")), bytes.NewBufferString("three"), nil)
	c.Assert(err, check.IsNil)

	var bytesBuffer bytes.Buffer
	length, err := fs.GetObject(&bytesBuffer, "bucket", "object", 0, 0)
	c.Assert(err, check.IsNil)
	c.Assert(length, check.Equals, int64(len("three")))
	c.Assert(string(bytesBuffer.Bytes()), check.Equals, "three")
}
Ejemplo n.º 19
0
func LoginHttpHandler(w http.ResponseWriter, req *http.Request) {
	var passWord string = "test md5 encrypto"
	var strMd5 string
	//1
	md5Ctx := md5.New()
	md5Ctx.Write([]byte(passWord))
	cipherStr := md5Ctx.Sum(nil)
	strMd5 = hex.EncodeToString(cipherStr)
	//2
	md5Ctx = md5.New()
	md5Ctx.Write([]byte(strMd5))
	cipherStr = md5Ctx.Sum(nil)
	strMd5 = hex.EncodeToString(cipherStr)

	_, err := w.Write([]byte(strMd5))
	if nil != err {
		fmt.Println("######LoginHttpHandler...err:", err)
	}

	time.Sleep(10 * time.Second)

	fmt.Println(strMd5)
	// 发送给login 服务器
	//异步返回给客户端,要么客户端主动请求服务器(ajax);要么采用WebSocket连接服务器
}
Ejemplo n.º 20
0
func (d *DigestHeaders) digestChecksum() {
	switch d.Algorithm {
	case "MD5":
		// A1
		h := md5.New()
		A1 := fmt.Sprintf("%s:%s:%s", d.Username, d.Realm, d.Password)
		io.WriteString(h, A1)
		d.HA1 = fmt.Sprintf("%x", h.Sum(nil))

		// A2
		h = md5.New()
		A2 := fmt.Sprintf("%s:%s", d.Method, d.Path)
		io.WriteString(h, A2)
		d.HA2 = fmt.Sprintf("%x", h.Sum(nil))
	case "MD5-sess":
		// A1
		h := md5.New()
		A1 := fmt.Sprintf("%s:%s:%s", d.Username, d.Realm, d.Password)
		io.WriteString(h, A1)
		haPre := fmt.Sprintf("%x", h.Sum(nil))
		h = md5.New()
		A1 = fmt.Sprintf("%s:%s:%s", haPre, d.Nonce, d.Cnonce)
		io.WriteString(h, A1)
		d.HA1 = fmt.Sprintf("%x", h.Sum(nil))

		// A2
		h = md5.New()
		A2 := fmt.Sprintf("%s:%s", d.Method, d.Path)
		io.WriteString(h, A2)
		d.HA2 = fmt.Sprintf("%x", h.Sum(nil))
	default:
		//token
	}
}
Ejemplo n.º 21
0
func (socket *mongoSocket) Login(cred Credential) error {
	nonce, err := socket.getNonce()
	if err != nil {
		return err
	}

	psum := md5.New()
	psum.Write([]byte(cred.Username + ":mongo:" + cred.Password))

	ksum := md5.New()
	ksum.Write([]byte(nonce + cred.Username))
	ksum.Write([]byte(hex.EncodeToString(psum.Sum(nil))))

	key := hex.EncodeToString(ksum.Sum(nil))

	cmd := authCmd{Authenticate: 1, User: cred.Username, Nonce: nonce, Key: key}
	fmt.Printf("Trying to login with nonce:%s \n", nonce)
	res := authResult{}
	op := queryOp{}
	op.query = &cmd
	op.collection = cred.Source + ".$cmd"
	op.limit = -1
	op.replyFunc = func(err error, reply *replyOp, docNum int, docData []byte) {
		err = bson.Unmarshal(docData, &res)
		if err != nil {
			return
		}
	}
	err = socket.Query(&op)
	if err != nil {
		return err
	}
	return err
}
Ejemplo n.º 22
0
func (d *Digest) computeAuthorization(username, password, method, uri, cnonce string) string {
	nc := fmt.Sprintf("%08x", d.NonceCount)
	ha1 := d.createHa1(username, password, cnonce, md5.New())
	ha2 := d.createHa2(method, uri, md5.New())
	response := d.createResponse(ha1, ha2, nc, cnonce, md5.New())

	sl := []string{fmt.Sprintf(`username="******"`, username)}
	sl = append(sl, fmt.Sprintf(`realm="%s"`, d.Realm))
	sl = append(sl, fmt.Sprintf(`nonce="%s"`, d.Nonce))
	sl = append(sl, fmt.Sprintf(`uri="%s"`, uri))
	sl = append(sl, fmt.Sprintf(`response="%s"`, response))
	if d.Qop != "" {
		sl = append(sl, fmt.Sprintf("qop=%s", d.Qop))
		sl = append(sl, fmt.Sprintf("nc=%s", nc))
		sl = append(sl, fmt.Sprintf(`cnonce="%s"`, cnonce))
	}
	if d.Algorithm != "" {
		sl = append(sl, fmt.Sprintf(`algorithm="%s"`, d.Algorithm))
	}
	if d.Opaque != "" {
		sl = append(sl, fmt.Sprintf(`opaque="%s"`, d.Opaque))
	}

	d.NonceCount++
	return fmt.Sprintf("Digest %s", strings.Join(sl, ", "))
}
Ejemplo n.º 23
0
func (s FastCGIServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) {

	req.ParseMultipartForm(100000000)

	stat := "PASSED"
	fmt.Fprintln(resp, "-")
	fileNum := 0
	{
		length := 0
		for k0, v0 := range req.Form {
			h := md5.New()
			io.WriteString(h, v0[0])
			md5 := fmt.Sprintf("%x", h.Sum(nil))

			length += len(k0)
			length += len(v0[0])

			// echo error when key != md5(val)
			if md5 != k0 {
				fmt.Fprintln(resp, "server:err ", md5, k0)
				stat = "FAILED"
			}
		}
		if req.MultipartForm != nil {
			fileNum = len(req.MultipartForm.File)
			for kn, fns := range req.MultipartForm.File {
				//fmt.Fprintln(resp, "server:filekey ", kn )
				length += len(kn)
				for _, f := range fns {
					fd, err := f.Open()
					if err != nil {
						log.Println("server:", err)
						return
					}
					h := md5.New()
					l0, err := io.Copy(h, fd)
					if err != nil {
						log.Println(err)
						return
					}
					length += int(l0)
					defer fd.Close()
					md5 := fmt.Sprintf("%x", h.Sum(nil))
					//fmt.Fprintln(resp, "server:filemd5 ", md5 )

					if kn != md5 {
						fmt.Fprintln(resp, "server:err ", md5, kn)
						stat = "FAILED"
					}
					//fmt.Fprintln(resp, "server:filename ", f.Filename )
				}
			}
		}

		fmt.Fprintln(resp, "server:got data length", length)
	}
	fmt.Fprintln(resp, "-"+stat+"-POST(", len(req.Form), ")-FILE(", fileNum, ")--")
}
Ejemplo n.º 24
0
func (c *Client) generateAuthToken() string {
	pH := md5.New()
	io.WriteString(pH, c.Password)
	tH := md5.New()
	io.WriteString(tH, c.Username)
	io.WriteString(tH, fmt.Sprintf("%x", pH.Sum(nil)))

	return fmt.Sprintf("%x", tH.Sum(nil))
}
Ejemplo n.º 25
0
func (pm *PrinterManager) syncPrinters(ignorePrivet bool) error {
	glog.Info("Synchronizing printers, stand by")

	// Get current snapshot of CUPS printers.
	cupsPrinters, err := pm.cups.GetPrinters()
	if err != nil {
		return fmt.Errorf("Sync failed while calling GetPrinters(): %s", err)
	}
	if pm.ignoreRawPrinters {
		cupsPrinters, _ = lib.FilterRawPrinters(cupsPrinters)
	}

	// Augment CUPS printers with extra information from SNMP.
	if pm.snmp != nil {
		err = pm.snmp.AugmentPrinters(cupsPrinters)
		if err != nil {
			glog.Warningf("Failed to augment printers with SNMP data: %s", err)
		}
	}

	// Set CapsHash on all printers.
	for i := range cupsPrinters {
		h := md5.New()
		lib.DeepHash(cupsPrinters[i].Tags, h)
		cupsPrinters[i].Tags["tagshash"] = fmt.Sprintf("%x", h.Sum(nil))

		h = md5.New()
		lib.DeepHash(cupsPrinters[i].Description, h)
		cupsPrinters[i].CapsHash = fmt.Sprintf("%x", h.Sum(nil))
	}

	// Compare the snapshot to what we know currently.
	diffs := lib.DiffPrinters(cupsPrinters, pm.printers.GetAll())
	if diffs == nil {
		glog.Infof("Printers are already in sync; there are %d", len(cupsPrinters))
		return nil
	}

	// Update GCP.
	ch := make(chan lib.Printer, len(diffs))
	for i := range diffs {
		go pm.applyDiff(&diffs[i], ch, ignorePrivet)
	}
	currentPrinters := make([]lib.Printer, 0, len(diffs))
	for _ = range diffs {
		p := <-ch
		if p.Name != "" {
			currentPrinters = append(currentPrinters, p)
		}
	}

	// Update what we know.
	pm.printers.Refresh(currentPrinters)
	glog.Infof("Finished synchronizing %d printers", len(currentPrinters))

	return nil
}
Ejemplo n.º 26
0
func (s *descbc) Sign(algo, usage int, data ...[]byte) ([]byte, error) {
	var h hash.Hash

	switch algo {
	case signGssDes:
		sz := 0
		for _, d := range data {
			sz += len(d)
		}
		sz = (sz + 7) &^ 7
		u := make([]byte, sz)
		v := u[:0]
		for _, d := range data {
			v = append(v, d...)
		}

		iv := [8]byte{}
		b, _ := des.NewCipher(s.key)
		c := cipher.NewCBCEncrypter(b, iv[:])
		c.CryptBlocks(u, u)
		return u[len(u)-8:], nil

	case signGssMd5Des:
		h = md5.New()
		for _, d := range data {
			h.Write(d)
		}
		return s.Sign(signGssDes, usage, h.Sum(nil))

	case signMd5Des:
		h = md5.New()
	case signMd4Des:
		h = md4.New()
	default:
		return unkeyedSign(algo, usage, data...)
	}

	var key [8]byte
	for i := 0; i < 8; i++ {
		key[i] = s.key[i] ^ 0xF0
	}

	chk := make([]byte, 24)
	io.ReadFull(rand.Reader, chk[:8])

	h.Write(chk[:8])
	for _, d := range data {
		h.Write(d)
	}
	h.Sum(chk[8:])

	iv := [8]byte{}
	b, _ := des.NewCipher(s.key)
	c := cipher.NewCBCEncrypter(b, iv[:])
	c.CryptBlocks(chk, chk)
	return chk, nil
}
Ejemplo n.º 27
0
func CheckUUID(uid string, account string) bool {
	h1 := md5.New()
	io.WriteString(h1, account)
	io.WriteString(h1, UUIDkey)
	h2 := md5.New()
	io.WriteString(h2, account)
	io.WriteString(h2, MD5key)
	return uid == fmt.Sprintf("%x%x", h1.Sum(nil), h2.Sum(nil))
}
Ejemplo n.º 28
0
// UUID() provides unique identifier strings.
func GenUUID(account string) string {
	h1 := md5.New()
	io.WriteString(h1, account)
	io.WriteString(h1, UUIDkey)
	h2 := md5.New()
	io.WriteString(h2, account)
	io.WriteString(h2, MD5key)
	return fmt.Sprintf("%x%x", h1.Sum(nil), h2.Sum(nil))
}
Ejemplo n.º 29
0
// 进行签名验证以及DES加密验证
func (this *Request) InitDES() error {

	params := ""
	this.Json = new(Js)
	params = this.PostParam("params").GetString()

	//如果是开启了 DES加密 需要验证是否加密,然后需要验证签名,和加密内容
	if Config.GetBool("system.OpenDES") == true {
		if params == "" {
			return errors.New("No params")
		}
	}

	if params != "" {

		sign := this.PostParam("sign").GetString()
		timeStamp := this.PostParam("timeStamp").GetString()
		randomNum := this.PostParam("randomNum").GetString()
		isEncrypted := this.PostParam("isEncrypted").GetString()
		if sign == "" || timeStamp == "" || randomNum == "" {
			return errors.New("No Md5 Parameter")
		}

		keymd5 := md5.New()
		keymd5.Write([]byte(Config.GetString("system.MD5key")))
		md5key := hex.EncodeToString(keymd5.Sum(nil))

		signmd5 := md5.New()
		signmd5.Write([]byte(params + isEncrypted + timeStamp + randomNum + md5key))
		sign2 := hex.EncodeToString(signmd5.Sum(nil))

		if sign != sign2 {
			return errors.New("No Md5 Failure")
		}

		//如果是加密的params那么进行解密操作
		if isEncrypted == "1" {

			base64params, err := base64.StdEncoding.DecodeString(params)
			if err != nil {
				return err
			}

			origData, err := this.Des.DesDecrypt(base64params, Config.GetString("system.DESkey"), Config.GetString("system.DESiv"))
			if err != nil {
				return err
			}
			params = string(origData)
		}
		this.Json = Json(params)
		this.Encryption = true
	} else {
		this.Encryption = false
	}

	return nil
}
Ejemplo n.º 30
0
func main() {
	cli := &http.Client{}
	resp, err := cli.Get(upmp)

	// orderTime = "20140523150727";

	val := url.Values{}
	val.Add("version", version)
	val.Add("charset", charset)
	val.Add("transType", transType)
	val.Add("merId", merId)
	val.Add("orderTime", orderTime)
	val.Add("orderNumber", orderNumber)
	//val.Add("merReserved", merReserved);
	//val.Add("sysReserved", sysReserved);

	keymd5 := md5.New()
	keymd5.Write([]byte(security_key))
	strkey := hex.EncodeToString(keymd5.Sum(nil))

	md := md5.New()
	str := mkstr(strkey)
	md.Write([]byte(str))

	log.Println("sign: ", str)

	val.Add("signMethod", signMethod)
	val.Add("signature", hex.EncodeToString(md.Sum(nil)))

	postDataBytes := []byte(val.Encode())
	postBytesReader := bytes.NewReader(postDataBytes)

	req, err := http.NewRequest("POST", upmp, postBytesReader)
	req.Header.Set("Content-Type", "application/octet-stream")

	log.Println("url: ", upmp)
	log.Println("data: ", val.Encode())
	resp, err = cli.Do(req)

	if err != nil {
		log.Println("handle error")
	}

	body, err := ioutil.ReadAll(resp.Body)

	log.Println("res: ", string(body))

	res, err := url.ParseQuery(string(body))
	if err != nil {
		log.Println("err: ", err)
	}

	log.Println("Msg: ", res.Get("respMsg"))
	log.Println("Stat: ", res.Get("transStatus"))
}