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

Golang hex.EncodeToString函数代码示例

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

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



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

示例1: pubkeyFromSeckey

//intenal, may fail
//may return nil
func pubkeyFromSeckey(seckey []byte) []byte {
	if len(seckey) != 32 {
		log.Panic("seckey length invalid")
	}

	if secp.SeckeyIsValid(seckey) != 1 {
		log.Panic("always ensure seckey is valid")
		return nil
	}

	var pubkey []byte = secp.GeneratePublicKey(seckey) //always returns true
	if pubkey == nil {
		log.Panic("ERROR: impossible, secp.BaseMultiply always returns true")
		return nil
	}
	if len(pubkey) != 33 {
		log.Panic("ERROR: impossible, invalid pubkey length")
	}

	if ret := secp.PubkeyIsValid(pubkey); ret != 1 {
		log.Panic("ERROR: pubkey invald, ret=%s", ret)
		return nil
	}

	if ret := VerifyPubkey(pubkey); ret != 1 {

		log.Printf("seckey= %s", hex.EncodeToString(seckey))
		log.Printf("pubkey= %s", hex.EncodeToString(pubkey))
		log.Panic("ERROR: pubkey verification failed, for deterministic. ret=%d", ret)
		return nil
	}

	return pubkey
}
开发者ID:keepwalking1234,项目名称:skycoin,代码行数:36,代码来源:secp256k1.go


示例2: hashFile

// Generate a human readable sha1 hash of the given file path
func hashFile(path string) (hashes FileInfo, err error) {
	f, err := os.Open(path)
	if err != nil {
		return
	}
	defer f.Close()

	reader := bufio.NewReader(f)

	if GetConfig().Hashes.SHA1 {
		sha1Hash := sha1.New()
		_, err = io.Copy(sha1Hash, reader)
		if err == nil {
			hashes.Sha1 = hex.EncodeToString(sha1Hash.Sum(nil))
		}
	}
	if GetConfig().Hashes.SHA256 {
		sha256Hash := sha256.New()
		_, err = io.Copy(sha256Hash, reader)
		if err == nil {
			hashes.Sha256 = hex.EncodeToString(sha256Hash.Sum(nil))
		}
	}
	if GetConfig().Hashes.MD5 {
		md5Hash := md5.New()
		_, err = io.Copy(md5Hash, reader)
		if err == nil {
			hashes.Md5 = hex.EncodeToString(md5Hash.Sum(nil))
		}
	}
	return
}
开发者ID:ninetian,项目名称:mirrorbits,代码行数:33,代码来源:utils.go


示例3: loginClassic

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


示例4: introduceVia

func (mod *module) introduceVia(router *e3x.Exchange, to hashname.H) error {
	localIdent, err := mod.e.LocalIdentity()
	if err != nil {
		return err
	}

	keys := localIdent.Keys()
	parts := hashname.PartsFromKeys(keys)

	for csid, key := range keys {
		inner := lob.New(key.Public())
		for partCSID, part := range parts {
			if partCSID == csid {
				inner.Header().SetBool(hex.EncodeToString([]byte{partCSID}), true)
			} else {
				inner.Header().SetString(hex.EncodeToString([]byte{partCSID}), part)
			}
		}

		body, err := lob.Encode(inner)
		if err != nil {
			return err
		}

		err = mod.peerVia(router, to, body)
		if err != nil {
			return err
		}
	}

	return nil
}
开发者ID:utamaro,项目名称:gogotelehash,代码行数:32,代码来源:channel_peer.go


示例5: Response

// Response is called by the HTTP server to handle a new OCSP request.
func (src *DBSource) Response(req *ocsp.Request) (response []byte, present bool) {
	log := blog.GetAuditLogger()

	// Check that this request is for the proper CA
	if bytes.Compare(req.IssuerKeyHash, src.caKeyHash) != 0 {
		log.Debug(fmt.Sprintf("Request intended for CA Cert ID: %s", hex.EncodeToString(req.IssuerKeyHash)))
		present = false
		return
	}

	serialString := core.SerialToString(req.SerialNumber)
	log.Debug(fmt.Sprintf("Searching for OCSP issued by us for serial %s", serialString))

	var ocspResponse core.OCSPResponse
	// Note: we order by id rather than createdAt, because otherwise we sometimes
	// get the wrong result if a certificate is revoked in the same second as its
	// last update (e.g. client issues and instant revokes).
	err := src.dbMap.SelectOne(&ocspResponse, "SELECT * from ocspResponses WHERE serial = :serial ORDER BY id DESC LIMIT 1;",
		map[string]interface{}{"serial": serialString})
	if err != nil {
		present = false
		return
	}

	log.Info(fmt.Sprintf("OCSP Response sent for CA=%s, Serial=%s", hex.EncodeToString(src.caKeyHash), serialString))

	response = ocspResponse.Response
	present = true
	return
}
开发者ID:sjas,项目名称:boulder,代码行数:31,代码来源:main.go


示例6: Test_Abnormal_Keys

func Test_Abnormal_Keys(t *testing.T) {

	for i := 0; i < 32*1024; i++ {

		seed := RandByte(32)

		pubkey1, seckey1 := generateDeterministicKeyPair(seed)

		if seckey1 == nil {
			t.Fail()
		}

		if pubkey1 == nil {
			t.Fail()
		}

		if VerifyPubkey(pubkey1) != 1 {
			seed_hex := hex.EncodeToString(seed)
			seckey_hex := hex.EncodeToString(seckey1)
			log.Printf("seed= %s", seed_hex)
			log.Printf("seckey= %s", seckey_hex)
			t.Errorf("GenerateKeyPair, generates key that fails validation, run=%i", i)
		}
	}
}
开发者ID:keepwalking1234,项目名称:skycoin,代码行数:25,代码来源:secp256_test.go


示例7: String

// The timestamp in hex encoded form.
func (me UUID) String() string {
	return hex.EncodeToString(me[0:4]) + "-" +
		hex.EncodeToString(me[4:6]) + "-" +
		hex.EncodeToString(me[6:8]) + "-" +
		hex.EncodeToString(me[8:10]) + "-" +
		hex.EncodeToString(me[10:16])
}
开发者ID:qingshao,项目名称:simpleuuid,代码行数:8,代码来源:uuid.go


示例8: String

// Convert a hash into a string with hex encoding
func (h *Hash) String() string {
	if h == nil {
		return hex.EncodeToString(nil)
	} else {
		return hex.EncodeToString(h[:])
	}
}
开发者ID:FactomProject,项目名称:factomd,代码行数:8,代码来源:hash.go


示例9: hashSections

func (d *Deb) hashSections() (string, error) {
	h1 := sha1.New()
	h5 := md5.New()
	w := io.MultiWriter(h1, h5)

	_, err := d.f.Seek(0, 0)
	if err != nil {
		return "", &InvalidDeb{d, err}
	}

	s := ""

	rd := ar.NewReader(d.f)
	for {
		h1.Reset()
		h5.Reset()

		hdr, err := rd.Next()
		if err == io.EOF {
			return s, nil
		} else if err != nil {
			return "", &InvalidDeb{d, err}
		}

		_, err = io.Copy(w, rd)
		if err != nil {
			return "", &InvalidDeb{d, err}
		}

		h1x := hex.EncodeToString(h1.Sum(nil))
		h5x := hex.EncodeToString(h5.Sum(nil))
		s += fmt.Sprintf("\t%s %s %d %s\n", h5x, h1x, hdr.Size, hdr.Name)
	}
}
开发者ID:qur,项目名称:repo_server,代码行数:34,代码来源:deb.go


示例10: TestJWKSymmetricKey

func TestJWKSymmetricKey(t *testing.T) {
	sample1 := `{"kty":"oct","alg":"A128KW","k":"GawgguFyGrWKav7AX4VKUg"}`
	sample2 := `{"kty":"oct","k":"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow","kid":"HMAC key used in JWS spec Appendix A.1 example"}`

	var jwk1 JsonWebKey
	json.Unmarshal([]byte(sample1), &jwk1)

	if jwk1.Algorithm != "A128KW" {
		t.Errorf("expected Algorithm to be A128KW, but was '%s'", jwk1.Algorithm)
	}
	expected1 := fromHexBytes("19ac2082e1721ab58a6afec05f854a52")
	if !bytes.Equal(jwk1.Key.([]byte), expected1) {
		t.Errorf("expected Key to be '%s', but was '%s'", hex.EncodeToString(expected1), hex.EncodeToString(jwk1.Key.([]byte)))
	}

	var jwk2 JsonWebKey
	json.Unmarshal([]byte(sample2), &jwk2)

	if jwk2.KeyID != "HMAC key used in JWS spec Appendix A.1 example" {
		t.Errorf("expected KeyID to be 'HMAC key used in JWS spec Appendix A.1 example', but was '%s'", jwk2.KeyID)
	}
	expected2 := fromHexBytes(`
    0323354b2b0fa5bc837e0665777ba68f5ab328e6f054c928a90f84b2d2502ebf
    d3fb5a92d20647ef968ab4c377623d223d2e2172052e4f08c0cd9af567d080a3`)
	if !bytes.Equal(jwk2.Key.([]byte), expected2) {
		t.Errorf("expected Key to be '%s', but was '%s'", hex.EncodeToString(expected2), hex.EncodeToString(jwk2.Key.([]byte)))
	}
}
开发者ID:CometKim,项目名称:platform,代码行数:28,代码来源:jwk_test.go


示例11: Post

func (s *SignupJoinEngine) Post(arg SignupJoinEngineRunArg) (err error) {
	var res *libkb.APIRes
	var ppGenTmp int
	res, err = s.G().API.Post(libkb.APIArg{
		Endpoint: "signup",
		Args: libkb.HTTPArgs{
			"salt":          libkb.S{Val: hex.EncodeToString(arg.PWSalt)},
			"pwh":           libkb.S{Val: hex.EncodeToString(arg.PWHash)},
			"username":      libkb.S{Val: arg.Username},
			"email":         libkb.S{Val: arg.Email},
			"invitation_id": libkb.S{Val: arg.InviteCode},
			"pwh_version":   libkb.I{Val: int(triplesec.Version)},
			"skip_mail":     libkb.B{Val: arg.SkipMail},
		}})
	if err == nil {
		s.username = libkb.NewNormalizedUsername(arg.Username)
		libkb.GetUIDVoid(res.Body.AtKey("uid"), &s.uid, &err)
		res.Body.AtKey("session").GetStringVoid(&s.session, &err)
		res.Body.AtKey("csrf_token").GetStringVoid(&s.csrf, &err)
		res.Body.AtPath("me.basics.passphrase_generation").GetIntVoid(&ppGenTmp, &err)
	}
	if err == nil {
		err = libkb.CheckUIDAgainstUsername(s.uid, arg.Username)
		s.ppGen = libkb.PassphraseGeneration(ppGenTmp)
	}
	return
}
开发者ID:mark-adams,项目名称:client,代码行数:27,代码来源:signup_join.go


示例12: TestConversion

// Tested functions:
//   EncodedBytesToBigInt
//   BigIntToFieldElement
//   FieldElementToEncodedBytes
//   BigIntToEncodedBytes
//   FieldElementToBigInt
//   EncodedBytesToFieldElement
func TestConversion(t *testing.T) {
	for _, vector := range testConversionVectors() {
		// Test encoding to FE --> bytes.
		feFB := EncodedBytesToFieldElement(vector.bIn)
		feTB := FieldElementToEncodedBytes(feFB)
		assert.Equal(t, vector.bIn, feTB)

		// Test encoding to big int --> FE --> bytes.
		big := EncodedBytesToBigInt(vector.bIn)
		fe := BigIntToFieldElement(big)
		b := FieldElementToEncodedBytes(fe)
		assert.Equal(t, vector.bIn, b)

		// Test encoding to big int --> bytes.
		b = BigIntToEncodedBytes(big)
		assert.Equal(t, vector.bIn, b)

		// Test encoding FE --> big int --> bytes.
		feBig := FieldElementToBigInt(fe)
		b = BigIntToEncodedBytes(feBig)
		assert.Equal(t, vector.bIn, b)

		// Test python lib bytes --> int vs our results.
		args := []string{"testdata/decodeint.py", hex.EncodeToString(vector.bIn[:])}
		pyNumStr, _ := exec.Command("python", args...).Output()
		stripped := strings.TrimSpace(string(pyNumStr))
		assert.Equal(t, stripped, big.String())

		// Test python lib int --> bytes versus our results.
		args = []string{"testdata/encodeint.py", big.String()}
		pyHexStr, _ := exec.Command("python", args...).Output()
		stripped = strings.TrimSpace(string(pyHexStr))
		assert.Equal(t, hex.EncodeToString(vector.bIn[:]), string(stripped))
	}
}
开发者ID:ironbits,项目名称:dcrd,代码行数:42,代码来源:primitives_test.go


示例13: TestPointConversion

// Tested functions:
//   BigIntPointToEncodedBytes
//   extendedToBigAffine
//   EncodedBytesToBigIntPoint
func TestPointConversion(t *testing.T) {
	curve := new(TwistedEdwardsCurve)
	curve.InitParam25519()

	for _, vector := range testPointConversionVectors() {
		x, y, err := curve.EncodedBytesToBigIntPoint(vector.bIn)
		// The random point wasn't on the curve.
		if err != nil {
			continue
		}

		yB := BigIntPointToEncodedBytes(x, y)
		assert.Equal(t, vector.bIn, yB)

		// Test python lib bytes --> point vs our results.
		args := []string{"testdata/decodepoint.py", hex.EncodeToString(vector.bIn[:])}
		pyNumStr, _ := exec.Command("python", args...).Output()
		stripped := strings.TrimSpace(string(pyNumStr))
		var buffer bytes.Buffer
		buffer.WriteString(x.String())
		buffer.WriteString(",")
		buffer.WriteString(y.String())
		localStr := buffer.String()
		assert.Equal(t, localStr, stripped)

		// Test python lib point --> bytes versus our results.
		args = []string{"testdata/encodepoint.py", x.String(), y.String()}
		pyHexStr, _ := exec.Command("python", args...).Output()
		stripped = strings.TrimSpace(string(pyHexStr))
		assert.Equal(t, hex.EncodeToString(vector.bIn[:]), string(stripped))
	}
}
开发者ID:ironbits,项目名称:dcrd,代码行数:36,代码来源:primitives_test.go


示例14: validate

func (o arc4Verifier) validate(count string, offset uint64, key, plaintext, expectedCiphertext []byte) {
	if offset%16 != 0 || len(plaintext) != 16 || len(expectedCiphertext) != 16 {
		panic(fmt.Errorf("Unexpected input value encountered: offset=%v; len(plaintext)=%v; len(expectedCiphertext)=%v",
			offset,
			len(plaintext),
			len(expectedCiphertext)))
	}
	stream, err := rc4.NewCipher(key)
	if err != nil {
		panic(err)
	}

	var currentOffset uint64 = 0
	ciphertext := make([]byte, len(plaintext))
	for currentOffset <= offset {
		stream.XORKeyStream(ciphertext, plaintext)
		currentOffset += uint64(len(plaintext))
	}
	if !bytes.Equal(ciphertext, expectedCiphertext) {
		panic(fmt.Errorf("vector mismatch @ COUNT = %s:\n  %s != %s\n",
			count,
			hex.EncodeToString(expectedCiphertext),
			hex.EncodeToString(ciphertext)))
	}
}
开发者ID:CHENSHUFANG,项目名称:cryptography,代码行数:25,代码来源:verify_arc4.go


示例15: Print

// Print outputs a formatted dump of the RTP packet.
func (rp *DataPacket) Print(label string) {
	fmt.Printf("RTP Packet at: %s\n", label)
	fmt.Printf("  fixed header dump:   %s\n", hex.EncodeToString(rp.buffer[0:rtpHeaderLength]))
	fmt.Printf("    Version:           %d\n", (rp.buffer[0]&0xc0)>>6)
	fmt.Printf("    Padding:           %t\n", rp.Padding())
	fmt.Printf("    Extension:         %t\n", rp.ExtensionBit())
	fmt.Printf("    Contributing SRCs: %d\n", rp.CsrcCount())
	fmt.Printf("    Marker:            %t\n", rp.Marker())
	fmt.Printf("    Payload type:      %d (0x%x)\n", rp.PayloadType(), rp.PayloadType())
	fmt.Printf("    Sequence number:   %d (0x%x)\n", rp.Sequence(), rp.Sequence())
	fmt.Printf("    Timestamp:         %d (0x%x)\n", rp.Timestamp(), rp.Timestamp())
	fmt.Printf("    SSRC:              %d (0x%x)\n", rp.Ssrc(), rp.Ssrc())

	if rp.CsrcCount() > 0 {
		cscr := rp.CsrcList()
		fmt.Printf("  CSRC list:\n")
		for i, v := range cscr {
			fmt.Printf("      %d: %d (0x%x)\n", i, v, v)
		}
	}
	if rp.ExtensionBit() {
		extLen := rp.ExtensionLength()
		fmt.Printf("  Extentsion length: %d\n", extLen)
		offsetExt := rtpHeaderLength + int(rp.CsrcCount()*4)
		fmt.Printf("    extension: %s\n", hex.EncodeToString(rp.buffer[offsetExt:offsetExt+extLen]))
	}
	payOffset := rtpHeaderLength + int(rp.CsrcCount()*4) + rp.ExtensionLength()
	fmt.Printf("  payload: %s\n", hex.EncodeToString(rp.buffer[payOffset:rp.inUse]))
}
开发者ID:thomasberger,项目名称:gortp,代码行数:30,代码来源:packets.go


示例16: TestParseTextAttachment

func (s *ParseMessageTestSuite) TestParseTextAttachment() {
	loop := 1
	for i := 0; i < loop; i++ {
		fileHandler, err := os.Open("fixtures/text_attachment.eml")
		assert.Nil(s.T(), err)

		reader := bufio.NewReader(fileHandler)
		parse := NewParse(reader)
		assert.Equal(s.T(), parse.To(), "Team R&D <[email protected]>")
		hasher := md5.New()

		text, _ := parse.Text()
		hasher.Write([]byte(text))
		hashString := hex.EncodeToString(hasher.Sum(nil))
		assert.Equal(s.T(), hashString, "b5b94cd495174ab6e4443fa81847b6ce")
		hasher.Reset()

		html, _ := parse.Html()
		hasher.Write([]byte(html))
		hashString = hex.EncodeToString(hasher.Sum(nil))
		assert.Equal(s.T(), hashString, "d41d8cd98f00b204e9800998ecf8427e")
		hasher.Reset()

		attachments := parse.Attachment()
		for key, value := range attachments {
			assert.Equal(s.T(), key, "content-type-sorted-distilled.txt")

			hasher.Write(value)
			hashString = hex.EncodeToString(hasher.Sum(nil))
			assert.Equal(s.T(), hashString, "bcd2881b9b06f24960d4998567be37bd")
			hasher.Reset()
		}
		fileHandler.Close()
	}
}
开发者ID:partkyle,项目名称:go-gmime,代码行数:35,代码来源:parse_test.go


示例17: Response

// Response is called by the HTTP server to handle a new OCSP request.
func (src *DBSource) Response(req *ocsp.Request) ([]byte, bool) {
	// Check that this request is for the proper CA
	if bytes.Compare(req.IssuerKeyHash, src.caKeyHash) != 0 {
		src.log.Debug(fmt.Sprintf("Request intended for CA Cert ID: %s", hex.EncodeToString(req.IssuerKeyHash)))
		return nil, false
	}

	serialString := core.SerialToString(req.SerialNumber)
	src.log.Debug(fmt.Sprintf("Searching for OCSP issued by us for serial %s", serialString))

	var response []byte
	defer func() {
		if len(response) != 0 {
			src.log.Info(fmt.Sprintf("OCSP Response sent for CA=%s, Serial=%s", hex.EncodeToString(src.caKeyHash), serialString))
		}
	}()
	err := src.dbMap.SelectOne(
		&response,
		"SELECT ocspResponse FROM certificateStatus WHERE serial = :serial",
		map[string]interface{}{"serial": serialString},
	)
	if err != nil && err != sql.ErrNoRows {
		src.log.Err(fmt.Sprintf("Failed to retrieve response from certificateStatus table: %s", err))
	}
	if err != nil {
		return nil, false
	}

	return response, true
}
开发者ID:ricardopadilha,项目名称:boulder,代码行数:31,代码来源:main.go


示例18: main

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


示例19: make_p2sh

// add P2SH pre-signing data into a raw tx
func make_p2sh() {
	tx := raw_tx_from_file(*rawtx)
	if tx == nil {
		fmt.Println("ERROR: Cannot decode the raw transaction")
		return
	}

	d, er := hex.DecodeString(*p2sh)
	if er != nil {
		println("P2SH hex data:", er.Error())
		return
	}

	ms, er := btc.NewMultiSigFromP2SH(d)
	if er != nil {
		println("Decode P2SH:", er.Error())
		return
	}

	fmt.Println("The P2SH data points to address", ms.BtcAddr(testnet).String())

	sd := ms.Bytes()

	for i := range tx.TxIn {
		tx.TxIn[i].ScriptSig = sd
		fmt.Println("Input number", i, " - hash to sign:", hex.EncodeToString(tx.SignatureHash(d, i, btc.SIGHASH_ALL)))
	}
	ioutil.WriteFile(MultiToSignOut, []byte(hex.EncodeToString(tx.Serialize())), 0666)
	fmt.Println("Transaction with", len(tx.TxIn), "inputs ready for multi-signing, stored in", MultiToSignOut)
}
开发者ID:wchh,项目名称:gocoin,代码行数:31,代码来源:multisig.go


示例20: TestAddPoliciesWithQualifiers

func TestAddPoliciesWithQualifiers(t *testing.T) {
	var cert x509.Certificate
	addPolicies(&cert, []config.CertificatePolicy{
		config.CertificatePolicy{
			ID: config.OID{1, 2, 3, 4},
			Qualifiers: []config.CertificatePolicyQualifier{
				config.CertificatePolicyQualifier{
					Type:  "id-qt-cps",
					Value: "http://example.com/cps",
				},
				config.CertificatePolicyQualifier{
					Type:  "id-qt-unotice",
					Value: "Do What Thou Wilt",
				},
			},
		},
	})

	if len(cert.ExtraExtensions) != 1 {
		t.Fatal("No extension added")
	}
	ext := cert.ExtraExtensions[0]
	if !reflect.DeepEqual(ext.Id, asn1.ObjectIdentifier{2, 5, 29, 32}) {
		t.Fatal(fmt.Sprintf("Wrong OID for policy qualifier %v", ext.Id))
	}
	if ext.Critical {
		t.Fatal("Policy qualifier marked critical")
	}
	expectedBytes, _ := hex.DecodeString("304e304c06032a03043045302206082b060105050702011616687474703a2f2f6578616d706c652e636f6d2f637073301f06082b0601050507020230130c11446f20576861742054686f752057696c74")
	if !bytes.Equal(ext.Value, expectedBytes) {
		t.Fatal(fmt.Sprintf("Value didn't match expected bytes: %s vs %s",
			hex.EncodeToString(ext.Value), hex.EncodeToString(expectedBytes)))
	}
}
开发者ID:JoeHorn,项目名称:boulder,代码行数:34,代码来源:signer_test.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang hex.EncodedLen函数代码示例发布时间:2022-05-24
下一篇:
Golang hex.Encode函数代码示例发布时间: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