本文整理汇总了Golang中encoding/hex.EncodeToString函数的典型用法代码示例。如果您正苦于以下问题:Golang EncodeToString函数的具体用法?Golang EncodeToString怎么用?Golang EncodeToString使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了EncodeToString函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
}
示例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
}
示例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
})
}
示例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
}
示例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
}
示例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)
}
}
}
示例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])
}
示例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[:])
}
}
示例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)
}
}
示例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)))
}
}
示例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
}
示例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))
}
}
示例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))
}
}
示例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)))
}
}
示例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]))
}