Golang DecodeString示例

说明

golang decodestring示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: encoding/hex

示例#1
文件: main.go 项目: uwydoc/web-blog

// reads the configuration file from the path specified by
// the config command line flag.
func readConfig(configFile string) error {
	b, err := ioutil.ReadFile(configFile)
	if err != nil {
		return err
	}
	err = json.Unmarshal(b, &config)
	if err != nil {
		return err
	}
	cookieAuthKey, err = hex.DecodeString(*config.CookieAuthKeyHexStr)
	if err != nil {
		return err
	}
	cookieEncrKey, err = hex.DecodeString(*config.CookieEncrKeyHexStr)
	if err != nil {
		return err
	}
	secureCookie = securecookie.New(cookieAuthKey, cookieEncrKey)
	// verify auth/encr keys are correct
	val := map[string]string{
		"foo": "bar",
	}
	_, err = secureCookie.Encode(cookieName, val)
	if err != nil {
		// for convenience, if the auth/encr keys are not set,
		// generate valid, random value for them
		auth := securecookie.GenerateRandomKey(32)
		encr := securecookie.GenerateRandomKey(32)
		fmt.Printf("auth: %s\nencr: %s\n", hex.EncodeToString(auth), hex.EncodeToString(encr))
	}
	// TODO: somehow verify twitter creds
	return err
}

示例#2
文件: amqp_test.go 项目: ruflin/beats

func TestAmqp_GetEmptyMethod(t *testing.T) {
	if testing.Verbose() {
		logp.LogInit(logp.LOG_DEBUG, "", false, true, []string{"amqp", "amqpdetailed"})
	}

	amqp := amqpModForTests()
	amqp.sendRequest = true

	data, err := hex.DecodeString("01000100000013003c004600000b526f626269" +
		"654b65616e6501ce")
	assert.Nil(t, err)
	data2, err := hex.DecodeString("01000100000005003c004800ce")
	assert.Nil(t, err)

	tcptuple := testTCPTuple()

	req := protos.Packet{Payload: data}
	private := protos.ProtocolData(new(amqpPrivateData))
	private = amqp.Parse(&req, tcptuple, 0, private)
	req = protos.Packet{Payload: data2}
	amqp.Parse(&req, tcptuple, 1, private)

	trans := expectTransaction(t, amqp)
	assert.Equal(t, "basic.get-empty", trans["method"])
	assert.Equal(t, "basic.get RobbieKeane", trans["request"])
	assert.Equal(t, "amqp", trans["type"])
	assert.Equal(t, common.OK_STATUS, trans["status"])
}

示例#3
文件: amqp_test.go 项目: ruflin/beats

func TestAmqp_RecoverMethod(t *testing.T) {
	if testing.Verbose() {
		logp.LogInit(logp.LOG_DEBUG, "", false, true, []string{"amqp", "amqpdetailed"})
	}

	amqp := amqpModForTests()
	amqp.sendRequest = true

	data, err := hex.DecodeString("01000100000005003c006e01ce")
	assert.Nil(t, err)
	data2, err := hex.DecodeString("01000100000004003c006fce")
	assert.Nil(t, err)

	tcptuple := testTCPTuple()

	req := protos.Packet{Payload: data}
	private := protos.ProtocolData(new(amqpPrivateData))
	private = amqp.Parse(&req, tcptuple, 0, private)
	req = protos.Packet{Payload: data2}
	amqp.Parse(&req, tcptuple, 1, private)

	trans := expectTransaction(t, amqp)
	assert.Equal(t, "basic.recover", trans["method"])
	assert.Equal(t, "basic.recover", trans["request"])
	assert.Equal(t, "amqp", trans["type"])
	assert.Equal(t, common.OK_STATUS, trans["status"])
	assert.Equal(t, common.MapStr{"requeue": true}, trans["amqp"])
}

示例#4
文件: core.go 项目: GetLevvel/blockchain-digital-notary

func Bond(nodeAddr, pubkey, unbondAddr, amtS, nonceS string) (*types.BondTx, error) {
	pub, addrBytes, amt, nonce, err := checkCommon(nodeAddr, pubkey, "", amtS, nonceS)
	if err != nil {
		return nil, err
	}
	var pubKey account.PubKeyEd25519
	var unbondAddrBytes []byte

	if unbondAddr == "" {
		pkb, _ := hex.DecodeString(pubkey)
		copy(pubKey[:], pkb)
		unbondAddrBytes = pubKey.Address()
	} else {
		unbondAddrBytes, err = hex.DecodeString(unbondAddr)
		if err != nil {
			return nil, fmt.Errorf("unbondAddr is bad hex: %v", err)
		}

	}

	tx, err := types.NewBondTx(pub)
	if err != nil {
		return nil, err
	}
	_ = addrBytes
	tx.AddInputWithNonce(pub, amt, int(nonce))
	tx.AddOutput(unbondAddrBytes, amt)

	return tx, nil
}

示例#5
文件: amqp_test.go 项目: ruflin/beats

func TestAmqp_ConnectionCloseNoError(t *testing.T) {
	if testing.Verbose() {
		logp.LogInit(logp.LOG_DEBUG, "", false, true, []string{"amqp", "amqpdetailed"})
	}

	amqp := amqpModForTests()
	amqp.hideConnectionInformation = false

	data, err := hex.DecodeString("01000000000012000a003200c8076b74687862616900000000ce")
	assert.Nil(t, err)
	data2, err := hex.DecodeString("01000000000004000a0033ce")
	assert.Nil(t, err)

	tcptuple := testTCPTuple()

	req := protos.Packet{Payload: data}
	private := protos.ProtocolData(new(amqpPrivateData))
	private = amqp.Parse(&req, tcptuple, 0, private)
	req = protos.Packet{Payload: data2}
	amqp.Parse(&req, tcptuple, 1, private)

	trans := expectTransaction(t, amqp)
	assert.Equal(t, "connection.close", trans["method"])
	assert.Equal(t, "amqp", trans["type"])
	assert.Equal(t, common.OK_STATUS, trans["status"])
	assert.Nil(t, trans["notes"])

	fields, ok := trans["amqp"].(common.MapStr)
	assert.True(t, ok)
	code, ok := fields["reply-code"].(uint16)
	assert.True(t, ok)
	assert.Equal(t, uint16(200), code)
}

示例#6
文件: main.go 项目: patf/boulder

func addCerts(csvFilename string, dbMap *gorp.DbMap, stats metrics.Statter, statsRate float32) {
	file, err := os.Open(csvFilename)
	cmd.FailOnError(err, "Could not open the file for reading")
	csvReader := csv.NewReader(file)

	for {
		record, err := csvReader.Read()
		if err == io.EOF {
			break
		} else if err != nil {
			fmt.Println("Error:", err)
			return
		}

		notAfter, err := time.Parse(datestampFormat, record[3])
		spkiBytes, err := hex.DecodeString(record[4])
		certDER, err := hex.DecodeString(record[7])

		externalCert := core.ExternalCert{
			SHA1:     record[0],
			Issuer:   record[1],
			Subject:  record[2],
			NotAfter: notAfter,
			SPKI:     spkiBytes,
			Valid:    record[5] == "1",
			EV:       record[6] == "1",
			CertDER:  certDER,
		}

		importStart := time.Now()
		err = dbMap.Insert(&externalCert)
		stats.TimingDuration("ExistingCert.Certs.ImportLatency", time.Since(importStart), statsRate)
		stats.Inc("ExistingCert.Certs.Imported", 1, statsRate)
	}
}

示例#7
文件: key_wrap_test.go 项目: CometKim/platform

func TestAesKeyWrapInvalid(t *testing.T) {
	kek, _ := hex.DecodeString("000102030405060708090A0B0C0D0E0F")

	// Invalid unwrap input (bit flipped)
	input0, _ := hex.DecodeString("1EA68C1A8112B447AEF34BD8FB5A7B828D3E862371D2CFE5")

	block, _ := aes.NewCipher(kek)

	_, err := KeyUnwrap(block, input0)
	if err == nil {
		t.Error("key unwrap failed to detect invalid input")
	}

	// Invalid unwrap input (truncated)
	input1, _ := hex.DecodeString("1EA68C1A8112B447AEF34BD8FB5A7B828D3E862371D2CF")

	_, err = KeyUnwrap(block, input1)
	if err == nil {
		t.Error("key unwrap failed to detect truncated input")
	}

	// Invalid wrap input (not multiple of 8)
	input2, _ := hex.DecodeString("0123456789ABCD")

	_, err = KeyWrap(block, input2)
	if err == nil {
		t.Error("key wrap accepted invalid input")
	}

}

示例#8
文件: secp256k1_test.go 项目: decred/dcrd

func TestGeneralSecp256k1(t *testing.T) {
	// Sample expanded pubkey (Satoshi from Genesis block)
	samplePubkey, _ := hex.DecodeString("04" +
		"678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb6" +
		"49f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f")
	_, err := Secp256k1.ParsePubKey(samplePubkey)
	if err != nil {
		t.Errorf("failure parsing pubkey: %v", err)
	}

	// Sample compressed pubkey
	samplePubkey, _ = hex.DecodeString("02" +
		"4627032575180c2773b3eedd3a163dc2f3c6c84f9d0a1fc561a9578a15e6d0e3")
	_, err = Secp256k1.ParsePubKey(samplePubkey)
	if err != nil {
		t.Errorf("failure parsing pubkey: %v", err)
	}

	// Sample signature from https://en.bitcoin.it/wiki/Transaction
	sampleSig, _ := hex.DecodeString("30" +
		"45" +
		"02" +
		"20" +
		"6e21798a42fae0e854281abd38bacd1aeed3ee3738d9e1446618c4571d1090db" +
		"02" +
		"21" +
		"00e2ac980643b0b82c0e88ffdfec6b64e3e6ba35e7ba5fdd7d5d6cc8d25c6b2415")
	_, err = Secp256k1.ParseDERSignature(sampleSig)
	if err != nil {
		t.Errorf("failure parsing DER signature: %v", err)
	}
}

示例#9
文件: sipadll_test.go 项目: liudch/gocoin

func TestVerify(t *testing.T) {
	pkey, _ := hex.DecodeString("040eaebcd1df2df853d66ce0e1b0fda07f67d1cabefde98514aad795b86a6ea66dbeb26b67d7a00e2447baeccc8a4cef7cd3cad67376ac1c5785aeebb4f6441c16")
	hasz, _ := hex.DecodeString("3382219555ddbb5b00e0090f469e590ba1eae03c7f28ab937de330aa60294ed6")
	sign, _ := hex.DecodeString("3045022100fe00e013c244062847045ae7eb73b03fca583e9aa5dbd030a8fd1c6dfcf11b1002207d0d04fed8fa1e93007468d5a9e134b0a7023b6d31db4e50942d43a250f4d07c01")
	res := EC_Verify(pkey, sign, hasz)
	if res != 1 {
		t.Error("Verify failed")
	}
	hasz[0]++
	res = EC_Verify(pkey, sign, hasz)
	if res != 0 {
		t.Error("Verify not failed while it should")
	}
	res = EC_Verify(pkey[:1], sign, hasz)
	if res >= 0 {
		t.Error("Negative result expected", res)
	}
	res = EC_Verify(pkey, sign[:1], hasz)
	if res >= 0 {
		t.Error("Yet negative result expected", res)
	}
	res = EC_Verify(pkey, sign, hasz[:1])
	if res != 0 {
		t.Error("Zero expected", res)
	}
}

示例#10
文件: postgres.go 项目: eklementev/esp

func (repo *postgresRepository) listenDaemon() error {
	doneCh := registry.DoneChannel()
	pqNotificationCh := repo.listener.NotificationChannel()

	for {
		select {
		case <-doneCh:
			return nil
		case pqNotification, ok := <-pqNotificationCh:
			if !ok {
				return nil
			}

			decodedChannel, err := hex.DecodeString(pqNotification.Channel[1:]) // trim leading '_'
			if err != nil {
				return err
			}

			decodedPayload, err := hex.DecodeString(pqNotification.Extra)
			if err != nil {
				return err
			}

			repo.m.RLock()
			for ch := range repo.listenChannels[string(decodedChannel)] {
				ch <- string(decodedPayload)
			}
			repo.m.RUnlock()
		}
	}
}

示例#11
文件: im920.go 项目: tomoya0x00/go-im920

func parseReadHeaders(s string) (info ReadInfo, err error) {
	headers := strings.Split(s, ",")
	if len(headers) < 3 {
		err = fmt.Errorf("error: Split headers failed: %s", s)
		return
	}

	node, derr := hex.DecodeString(headers[0])
	if derr != nil {
		err = fmt.Errorf("error: Decode Node failed (%s): %s", headers[0], derr)
		return
	}
	info.FromNode = Node(node[0])

	id, derr := strToUint16(headers[1])
	if err != nil {
		err = fmt.Errorf("error: Decode FromId failed (%s): %s", headers[1], derr)
		return
	}
	info.FromId = Id(id)

	rssi, derr := hex.DecodeString(headers[2])
	if err != nil {
		err = fmt.Errorf("error: Decode Rssi failed (%s): %s", headers[2], derr)
		return
	}
	info.FromRssi = Rssi(rssi[0])

	return
}

示例#12
文件: ec_test.go 项目: Chao-Jia/skycoin

func TestVerify1(t *testing.T) {
	for i := range ta {
		pkey, _ := hex.DecodeString(ta[i][0])
		sign, _ := hex.DecodeString(ta[i][1])
		hasz, _ := hex.DecodeString(ta[i][2])

		res := ecdsa_verify(pkey, sign, hasz)
		if res != 1 {
			t.Fatal("Verify failed at", i)
		}

		hasz[0]++
		res = ecdsa_verify(pkey, sign, hasz)
		if res != 0 {
			t.Error("Verify not failed while it should", i)
		}
		res = ecdsa_verify(pkey[:1], sign, hasz)
		if res >= 0 {
			t.Error("Negative result expected", res, i)
		}
		res = ecdsa_verify(pkey, sign[:1], hasz)
		if res >= 0 {
			t.Error("Yet negative result expected", res, i)
		}
		res = ecdsa_verify(pkey, sign, hasz[:1])
		if res != 0 {
			t.Error("Zero expected", res, i)
		}
	}
}

示例#13
文件: key.go 项目: dumbunny/vitess

// ParseShardingSpec parses a string that describes a sharding
// specification. a-b-c-d will be parsed as a-b, b-c, c-d. The empty
// string may serve both as the start and end of the keyspace: -a-b-
// will be parsed as start-a, a-b, b-end.
func ParseShardingSpec(spec string) ([]*topodatapb.KeyRange, error) {
	parts := strings.Split(spec, "-")
	if len(parts) == 1 {
		return nil, fmt.Errorf("malformed spec: doesn't define a range: %q", spec)
	}
	old := parts[0]
	ranges := make([]*topodatapb.KeyRange, len(parts)-1)

	for i, p := range parts[1:] {
		if p == "" && i != (len(parts)-2) {
			return nil, fmt.Errorf("malformed spec: MinKey/MaxKey cannot be in the middle of the spec: %q", spec)
		}
		if p != "" && p <= old {
			return nil, fmt.Errorf("malformed spec: shard limits should be in order: %q", spec)
		}
		s, err := hex.DecodeString(old)
		if err != nil {
			return nil, err
		}
		if len(s) == 0 {
			s = nil
		}
		e, err := hex.DecodeString(p)
		if err != nil {
			return nil, err
		}
		if len(e) == 0 {
			e = nil
		}
		ranges[i] = &topodatapb.KeyRange{Start: s, End: e}
		old = p
	}
	return ranges, nil
}

示例#14
文件: utxo_test.go 项目: C0rWin/fabric

func TestParse_LibbitconTX(t *testing.T) {
	txData, err := hex.DecodeString(consensusScriptVerifyTx)
	if err != nil {
		t.Fatalf("Error decoding HEX tx from libbitcoin:  %s", err)
		return
	}

	prevTxScript, err := hex.DecodeString(consensusScriptVerifyPreviousOutputScript)
	if err != nil {
		t.Fatalf("Error decoding HEX tx from libbitcoin:  %s", err)
		return
	}

	t.Logf("TX data from libbitcoin: %v", txData)

	tx := ParseUTXOBytes(txData)

	// Call Verify_script
	txInputIndex := uint(0)
	result := consensus.Verify_script(&txData[0], int64(len(txData)), &prevTxScript[0], int64(len(prevTxScript)), txInputIndex, uint(consensus.Verify_flags_p2sh))
	if result != consensus.Verify_result_eval_true {
		t.Fatalf("Unexpected result from verify_script, expected %d, got %d", consensus.Verify_result_eval_true, result)
	}
	t.Log(result)
	t.Log(consensus.Verify_result_eval_true)
	t.Logf("TX from %v", tx)
}

示例#15
文件: smpp_test.go 项目: XmsCoders/smpp34

func handleConnection(n net.Conn) {
	l := make([]byte, 1024)
	_, err := n.Read(l)
	if err != nil {
		panic("server read error")
	}

	// Bind Resp
	d, _ := hex.DecodeString("000000158000000900000000000000016875676f00")
	n.Write(d)

	time.Sleep(100 * time.Millisecond)

	// Invalid CMD ID
	d, _ = hex.DecodeString("0000001090000015000000005222b523")
	n.Write(d)

	time.Sleep(100 * time.Millisecond)

	// PDU Len different than read bytes
	d, _ = hex.DecodeString("000000178000000900000000000000016875676f00")
	n.Write(d)

	time.Sleep(100 * time.Millisecond)

	// Max PDU Len err
	d, _ = hex.DecodeString("0000F01080000015000000005222b526")
	n.Write(d)
}

示例#16
文件: key.go 项目: j4ustin/go-ethereum

func (k *Key) UnmarshalJSON(j []byte) (err error) {
	keyJSON := new(plainKeyJSON)
	err = json.Unmarshal(j, &keyJSON)
	if err != nil {
		return err
	}

	u := new(uuid.UUID)
	*u = uuid.Parse(keyJSON.Id)
	k.Id = *u
	addr, err := hex.DecodeString(keyJSON.Address)
	if err != nil {
		return err
	}

	privkey, err := hex.DecodeString(keyJSON.PrivateKey)
	if err != nil {
		return err
	}

	k.Address = common.BytesToAddress(addr)
	k.PrivateKey = ToECDSA(privkey)

	return nil
}

示例#17
文件: vm_test.go 项目: jaekwon/GuppyCamp

// Tests the code for a subcurrency contract compiled by serpent
func TestSubcurrency(t *testing.T) {
	st := newAppState()
	// Create accounts
	account1 := &Account{
		Address: LeftPadWord256(makeBytes(20)),
	}
	account2 := &Account{
		Address: LeftPadWord256(makeBytes(20)),
	}
	st.accounts[account1.Address.String()] = account1
	st.accounts[account2.Address.String()] = account2

	ourVm := NewVM(st, newParams(), Zero256, nil)

	var gas uint64 = 1000
	code_parts := []string{"620f42403355",
		"7c0100000000000000000000000000000000000000000000000000000000",
		"600035046315cf268481141561004657",
		"6004356040526040515460605260206060f35b63693200ce81141561008757",
		"60043560805260243560a052335460c0523360e05260a05160c05112151561008657",
		"60a05160c0510360e0515560a0516080515401608051555b5b505b6000f3"}
	code, _ := hex.DecodeString(strings.Join(code_parts, ""))
	fmt.Printf("Code: %x\n", code)
	data, _ := hex.DecodeString("693200CE0000000000000000000000004B4363CDE27C2EB05E66357DB05BC5C88F850C1A0000000000000000000000000000000000000000000000000000000000000005")
	output, err := ourVm.Call(account1, account2, code, data, 0, &gas)
	fmt.Printf("Output: %v Error: %v\n", output, err)
	if err != nil {
		t.Fatal(err)
	}
}

示例#18
文件: metadisk.go 项目: utamaro/farming

func download(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	key, err := hex.DecodeString(r.Form["key"][0])
	if err != nil {
		logging.Println(err.Error())
		return
	}
	fhash := r.URL.Path[len("/MetaDisk/api/download/"):]
	filehash, err := hex.DecodeString(fhash)
	if err != nil {
		logging.Println(err.Error())
		return
	}
	logging.Print(key)
	logging.Print(filehash)

	//	f, err := os.Open("rand.dat")
	//	if err != nil {
	//		logging.Println(err.Error())
	//		return
	//	}
	//	fi, err := f.Stat()
	//	if err != nil {
	//		logging.Println(err.Error())
	//		return
	//	}
	//	rh := newRetrieveandler(b, fi.Size())
	//	telehash.OpenChannel(loc, "retrieving", rh)
}

示例#19
文件: key_store_passphrase.go 项目: codeaudit/shift

func decryptKeyV1(keyProtected *encryptedKeyJSONV1, auth string) (keyBytes []byte, keyId []byte, err error) {
	keyId = uuid.Parse(keyProtected.Id)
	mac, err := hex.DecodeString(keyProtected.Crypto.MAC)
	if err != nil {
		return nil, nil, err
	}

	iv, err := hex.DecodeString(keyProtected.Crypto.CipherParams.IV)
	if err != nil {
		return nil, nil, err
	}

	cipherText, err := hex.DecodeString(keyProtected.Crypto.CipherText)
	if err != nil {
		return nil, nil, err
	}

	derivedKey, err := getKDFKey(keyProtected.Crypto, auth)
	if err != nil {
		return nil, nil, err
	}

	calculatedMAC := Sha3(derivedKey[16:32], cipherText)
	if !bytes.Equal(calculatedMAC, mac) {
		return nil, nil, errors.New("Decryption failed: MAC mismatch")
	}

	plainText, err := aesCBCDecrypt(Sha3(derivedKey[:16])[:16], cipherText, iv)
	if err != nil {
		return nil, nil, err
	}
	return plainText, keyId, err
}

示例#20
文件: main.go 项目: kelur-hawkingrei/learning-golang

func ExampleNewGCMDecrypter() {
	// The key argument should be the AES key, either 16 or 32 bytes
	// to select AES-128 or AES-256.
	key := []byte("AES256Key-32Characters1234567890")
	ciphertext, _ := hex.DecodeString("f90fbef747e7212ad7410d0eee2d965de7e890471695cddd2a5bc0ef5da1d04ad8147b62141ad6e4914aee8c512f64fba9037603d41de0d50b718bd665f019cdcd")

	nonce, _ := hex.DecodeString("bb8ef84243d2ee95a41c6c57")

	block, err := aes.NewCipher(key)
	if err != nil {
		panic(err.Error())
	}

	aesgcm, err := cipher.NewGCM(block)
	if err != nil {
		panic(err.Error())
	}

	plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
	if err != nil {
		panic(err.Error())
	}

	fmt.Printf("%s\n", string(plaintext))
}

示例#21
文件: core.go 项目: GetLevvel/blockchain-digital-notary

func Call(nodeAddr, pubkey, addr, toAddr, amtS, nonceS, gasS, feeS, data string) (*types.CallTx, error) {
	pub, _, amt, nonce, err := checkCommon(nodeAddr, pubkey, addr, amtS, nonceS)
	if err != nil {
		return nil, err
	}

	toAddrBytes, err := hex.DecodeString(toAddr)
	if err != nil {
		return nil, fmt.Errorf("toAddr is bad hex: %v", err)
	}

	fee, err := strconv.ParseInt(feeS, 10, 64)
	if err != nil {
		return nil, fmt.Errorf("fee is misformatted: %v", err)
	}

	gas, err := strconv.ParseInt(gasS, 10, 64)
	if err != nil {
		return nil, fmt.Errorf("gas is misformatted: %v", err)
	}

	dataBytes, err := hex.DecodeString(data)
	if err != nil {
		return nil, fmt.Errorf("data is bad hex: %v", err)
	}

	tx := types.NewCallTxWithNonce(pub, toAddrBytes, dataBytes, amt, gas, fee, int(nonce))
	return tx, nil
}

示例#22
文件: commands.go 项目: lightningnetwork/lnd

func addInvoice(ctx *cli.Context) error {
	client := getClient(ctx)

	preimage, err := hex.DecodeString(ctx.String("preimage"))
	if err != nil {
		return fmt.Errorf("unable to parse preimage: %v", err)
	}

	receipt, err := hex.DecodeString(ctx.String("receipt"))
	if err != nil {
		return fmt.Errorf("unable to parse receipt: %v", err)
	}

	invoice := &lnrpc.Invoice{
		Memo:      ctx.String("memo"),
		Receipt:   receipt,
		RPreimage: preimage,
		Value:     int64(ctx.Int("value")),
	}

	resp, err := client.AddInvoice(context.Background(), invoice)
	if err != nil {
		return err
	}

	printRespJson(struct {
		RHash string `json:"r_hash"`
	}{
		RHash: hex.EncodeToString(resp.RHash),
	})

	return nil
}

示例#23
文件: amqp_test.go 项目: ruflin/beats

func TestAmqp_ChannelCloseErrorMethod(t *testing.T) {
	if testing.Verbose() {
		logp.LogInit(logp.LOG_DEBUG, "", false, true, []string{"amqp", "amqpdetailed"})
	}

	amqp := amqpModForTests()

	data, err := hex.DecodeString("0100010000009000140028019685505245434f4e444" +
		"954494f4e5f4641494c4544202d20696e6571756976616c656e74206172672027617574" +
		"6f5f64656c6574652720666f722065786368616e676520277465737445786368616e676" +
		"52720696e2076686f737420272f273a207265636569766564202774727565272062757" +
		"42063757272656e74206973202766616c7365270028000ace")
	assert.Nil(t, err)
	data2, err := hex.DecodeString("0100010000000400280033ce")
	assert.Nil(t, err)

	tcptuple := testTCPTuple()

	req := protos.Packet{Payload: data}
	private := protos.ProtocolData(new(amqpPrivateData))
	private = amqp.Parse(&req, tcptuple, 0, private)
	req = protos.Packet{Payload: data2}
	amqp.Parse(&req, tcptuple, 1, private)

	trans := expectTransaction(t, amqp)
	assert.Equal(t, "channel.close", trans["method"])
	assert.Equal(t, "amqp", trans["type"])
	assert.Equal(t, common.ERROR_STATUS, trans["status"])
	assert.Nil(t, trans["notes"])
}

示例#24
文件: rncryptor_test.go 项目: muquit/RNCryptor-go

func TestEncrypt(t *testing.T) {
	for _, c := range cases {
		enc, encErr := hex.DecodeString(c.enc)
		if encErr != nil {
			t.Errorf("Error decoding hex: %v, %v", c.enc, encErr)
		}
		plain, plainErr := hex.DecodeString(c.plain)
		if plainErr != nil {
			t.Errorf("Error decoding hex: %v, %v", c.plain, plainErr)
		}
		encSalt, encSaltErr := hex.DecodeString(c.encSalt)
		if encSaltErr != nil {
			t.Errorf("Error decoding hex: %v, %v", c.encSalt, encSaltErr)
		}
		hmacSalt, hmacSaltErr := hex.DecodeString(c.hmacSalt)
		if hmacSaltErr != nil {
			t.Errorf("Error decoding hex: %v, %v", c.hmacSalt, hmacSaltErr)
		}
		iv, ivErr := hex.DecodeString(c.iv)
		if ivErr != nil {
			t.Errorf("Error decoding hex: %v, %v", c.iv, ivErr)
		}

		testEnc, testEncError := EncryptWithOptions(c.password, plain, encSalt, hmacSalt, iv)
		if testEncError != nil {
			t.Errorf("Error encrypting: %v, %v", testEnc, testEncError)
		}

		if !bytes.Equal(testEnc, enc) {
			t.Errorf("FAILED (%v) -> expected %v, got %v", c.title, enc, testEnc)
		}
	}
}

示例#25
文件: amqp_test.go 项目: ruflin/beats

func TestAmqp_MultipleBodyFrames(t *testing.T) {
	if testing.Verbose() {
		logp.LogInit(logp.LOG_DEBUG, "", false, true, []string{"amqp", "amqpdetailed"})
	}

	amqp := amqpModForTests()
	amqp.sendRequest = true
	data, err := hex.DecodeString("0100010000000e003c00280000000568656c6c6f00ce" +
		"02000100000021003c0000000000000000002a80400a746578742f706c61696e00000000" +
		"56a22873ce030001000000202a2a2a68656c6c6f2049206c696b6520746f207075626c69" +
		"736820626967206dce")
	assert.Nil(t, err)
	data2, err := hex.DecodeString("0300010000000a657373616765732a2a2ace")
	assert.Nil(t, err)

	tcptuple := testTCPTuple()
	req := protos.Packet{Payload: data}
	private := protos.ProtocolData(new(amqpPrivateData))
	private = amqp.Parse(&req, tcptuple, 0, private)
	req = protos.Packet{Payload: data2}
	amqp.Parse(&req, tcptuple, 0, private)
	trans := expectTransaction(t, amqp)
	assert.Equal(t, "basic.publish", trans["method"])
	assert.Equal(t, "***hello I like to publish big messages***", trans["request"])
}

示例#26
文件: server_test.go 项目: mewbak/repbin

func TestGenPostHandler(t *testing.T) {
	pubKey, _ := hex.DecodeString("39d8913ab046428e409cf1fa7cee6f63c1f6bf701356a44a8c8c2559bdb2526f")
	privKey, _ := hex.DecodeString("20a2633e422090a4f4a102f8e3d112f2b4378dbd9957e8c892067fc09239d36c39d8913ab046428e409cf1fa7cee6f63c1f6bf701356a44a8c8c2559bdb2526f")

	log.SetMinLevel(log.LevelDebug)
	testDir := path.Join(os.TempDir(), "repbin")
	if err := os.MkdirAll(testDir, 0700); err != nil {
		t.Fatal(err)
	}
	ms, err := New(testDir+string(os.PathSeparator), pubKey, privKey)
	if err != nil {
		t.Fatalf("New: %s", err)
	}
	enforceTimeOuts = false
	debug = true
	ms.NotifyDuration = 0
	ms.FetchDuration = 0
	ms.LoadPeers()
	ms.NotifyPeers()
	ms.FetchPeers()
	http.HandleFunc("/id", ms.ServeID)
	http.HandleFunc("/keyindex", ms.GetKeyIndex)
	http.HandleFunc("/globalindex", ms.GetGlobalIndex)
	http.HandleFunc("/post", ms.GenPostHandler(false))
	http.HandleFunc("/local/post", ms.GenPostHandler(true))
	http.HandleFunc("/fetch", ms.Fetch)
	http.HandleFunc("/notify", ms.GetNotify)
	http.HandleFunc("/delete", ms.Delete)
	go http.ListenAndServe(":8080", nil)
	time.Sleep(time.Second / 100)
	if !testing.Short() {
		// only necessary for long test in getpost_test.go
		time.Sleep(time.Second * 10)
	}
}

示例#27
文件: amqp_test.go 项目: ruflin/beats

func TestAmqp_GetMethod(t *testing.T) {
	if testing.Verbose() {
		logp.LogInit(logp.LOG_DEBUG, "", false, true, []string{"amqp", "amqpdetailed"})
	}

	amqp := amqpModForTests()
	amqp.sendRequest = true
	amqp.sendResponse = true

	data, err := hex.DecodeString("0100010000000f003c0046000007546573744" +
		"7657401ce")
	assert.Nil(t, err)
	data2, err := hex.DecodeString("0100010000001a003c00470000000000000001" +
		"0000075465737447657400000001ce02000100000019003c000000000000000000" +
		"1280000a746578742f706c61696ece03000100000012476574206d6520696620796" +
		"f752064617265ce")
	assert.Nil(t, err)

	tcptuple := testTCPTuple()

	req := protos.Packet{Payload: data}
	private := protos.ProtocolData(new(amqpPrivateData))
	private = amqp.Parse(&req, tcptuple, 0, private)
	req = protos.Packet{Payload: data2}
	amqp.Parse(&req, tcptuple, 1, private)

	trans := expectTransaction(t, amqp)
	assert.Equal(t, "basic.get", trans["method"])
	assert.Equal(t, "basic.get TestGet", trans["request"])
	assert.Equal(t, "amqp", trans["type"])
	assert.Equal(t, common.OK_STATUS, trans["status"])
	assert.Equal(t, "Get me if you dare", trans["response"])
}

示例#28
文件: example_test.go 项目: CryptocurrencyCabal/htcd

// This example demonstrates decrypting a message using a private key that is
// first parsed from raw bytes.
func Example_decryptMessage() {
	// Decode the hex-encoded private key.
	pkBytes, err := hex.DecodeString("a11b0a4e1a132305652ee7a8eb7848f6ad" +
		"5ea381e3ce20a2c086a2e388230811")
	if err != nil {
		fmt.Println(err)
		return
	}

	privKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), pkBytes)

	ciphertext, err := hex.DecodeString("35f644fbfb208bc71e57684c3c8b437402ca" +
		"002047a2f1b38aa1a8f1d5121778378414f708fe13ebf7b4a7bb74407288c1958969" +
		"00207cf4ac6057406e40f79961c973309a892732ae7a74ee96cd89823913b8b8d650" +
		"a44166dc61ea1c419d47077b748a9c06b8d57af72deb2819d98a9d503efc59fc8307" +
		"d14174f8b83354fac3ff56075162")

	// Try decrypting the message.
	plaintext, err := btcec.Decrypt(privKey, ciphertext)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(string(plaintext))

	// Output:
	// test message
}

示例#29
文件: commitChain_test.go 项目: FactomProject/factomd

func newCommitChain() *CommitChainMsg {
	msg := new(CommitChainMsg)

	cc := entryCreditBlock.NewCommitChain()

	cc.Version = 0x11
	cc.MilliTime = (*primitives.ByteSlice6)(&[6]byte{1, 1, 1, 1, 1, 1})
	p, _ := hex.DecodeString("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
	cc.ChainIDHash.SetBytes(p)
	p, _ = hex.DecodeString("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
	cc.Weld.SetBytes(p)
	p, _ = hex.DecodeString("cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc")
	cc.EntryHash.SetBytes(p)
	cc.Credits = 11

	// make a key and sign the msg
	if pub, privkey, err := ed.GenerateKey(rand.Reader); err != nil {
		panic(err)
	} else {
		cc.ECPubKey = (*primitives.ByteSlice32)(pub)
		cc.Sig = (*primitives.ByteSlice64)(ed.Sign(privkey, cc.CommitMsg()))
	}

	msg.CommitChain = cc
	//msg.Timestamp = primitives.NewTimestampNow()

	return msg
}

示例#30
文件: fileblobwriter_test.go 项目: cinode/archive-golib

func blobValidation(t *testing.T, test blobTest, result blobFinalizer, m BlobStorage) {

	key := strings.Replace(test.key, " ", "", -1)
	bid := strings.Replace(test.bid, " ", "", -1)

	rbid, rkey, err := result.Finalize()
	if err != nil {
		t.Error(err)
	}

	if rbid != bid {
		t.Errorf("Invalid blob id generated, got: %v..., expected: %v...", rbid[:16], bid[:16])
	}

	if rkey != key {
		t.Errorf("Invalid key generated, got: %v..., expected: %v...", rkey[:16], key[:16])
	}

	reader, err := m.NewBlobReader(rbid)
	if err != nil {
		t.Errorf("Couldn't open the blob with id: %v... for reading: %v", rbid[:16], err)
	} else {

		readBytes, err := ioutil.ReadAll(reader)
		if err != nil {
			t.Errorf("Couldn't read the blob with id: %v..., error: %v", rbid[:16], err)
		} else {

			blobHex := strings.Replace(test.blobHex, " ", "", -1)
			splitPos := strings.Index(blobHex, "...")
			if splitPos >= 0 {
				dataBefore, _ := hex.DecodeString(blobHex[:splitPos])
				dataAfter, _ := hex.DecodeString(blobHex[splitPos+3:])

				if !bytes.Equal(readBytes[:len(dataBefore)], dataBefore) {
					t.Errorf("The blob with id: %v... has invalid content (starting bytes), got: %v, expected %v",
						rbid[:16],
						hexDump(readBytes),
						hexDump(dataBefore))
				}

				if !bytes.Equal(readBytes[len(readBytes)-len(dataAfter):], dataAfter) {
					t.Errorf("The blob with id: %v... has invalid content (ending bytes), got: %v, expected %v",
						rbid[:16],
						hexDump(readBytes[len(readBytes)-len(dataAfter):]),
						hexDump(dataAfter))
				}

			} else {
				blob, _ := hex.DecodeString(blobHex)
				if !bytes.Equal(readBytes, blob) {
					t.Errorf("The blob with id: %v... has invalid content, got: %v, expected %v",
						rbid[:16],
						hexDump(readBytes),
						hexDump(blob))
				}
			}
		}
	}
}

展开阅读全文