Ejemplo n.º 1
0
// Sign the given hex-endcoded hash checksum and return a Signature
// @@TODO Remove this -- undeeded
func (pk PrivateKey) SignSHA256(hexbytes []byte) (Signature, error) {
	if hex.DecodedLen(len(hexbytes)) != sha256.Size {
		return nil, ErrPrivateKeySHA256
	}

	// Decode hex bytes into raw bytes
	decodedBytes := make([]byte, hex.DecodedLen(len(hexbytes)))
	_, err := hex.Decode(decodedBytes, hexbytes)
	if err != nil {
		return nil, errors.Wrap(err, ErrPrivateKeySHA256)
	}

	// Get the rsa cryptokey for signing
	cryptoKey, err := pk.GetCryptoKey()
	if err != nil {
		return nil, errors.Wrap(err, ErrPrivatKeySign)
	}

	// Compute the signature and return the results
	rawSignature, err := rsa.SignPKCS1v15(rand.Reader, cryptoKey, crypto.SHA256, decodedBytes)
	if err != nil {
		return nil, errors.Wrap(err, ErrPrivatKeySign)
	}
	return Signature(rawSignature), nil
}
Ejemplo n.º 2
0
func ConvertHexString(line []byte) (result []byte, err error) {
	buf := &bytes.Buffer{}
	for i, count := 0, len(line); i < count; i++ {
		b := line[i]
		if b == '\\' {
			if i+1 < count && line[i+1] == 'x' {
				if i+2+2 >= count {
					err = errors.New("invalid character \\x")
					return
				}
				b34hex := line[i+2 : i+2+2]
				b34 := make([]byte, hex.DecodedLen(len(b34hex)))
				_, err = hex.Decode(b34, b34hex)
				if err != nil {
					return
				}
				buf.Write(b34)
				i += 3 // skip \xff
			} else {
				buf.WriteByte('\\')
			}
		} else {
			buf.WriteByte(b)
		}
	}
	result = buf.Bytes()
	return
}
Ejemplo n.º 3
0
func main() {
	flag.StringVar(&Settings.src, "src", "src", "name for traffic src")
	flag.StringVar(&Settings.dst, "dst", "dst", "name for traffic dst")
	flag.StringVar(&Settings.graphite, "graphite", "", "name for traffic dst")
	flag.StringVar(&Settings.prefix, "prefix", "", "prefix for reported timings")
	flag.Parse()

	if Settings.graphite == "" || Settings.prefix == "" {
		log.Fatal("must supply graphite server and prefix")
	}

	report.NewRecorder().
		ReportTo(Settings.graphite, Settings.prefix).
		LogToConsole().
		SetAsDefault()

	scanner := bufio.NewScanner(os.Stdin)

	for scanner.Scan() {
		encoded := scanner.Bytes()

		buf := make([]byte, hex.DecodedLen(len(encoded)))
		hex.Decode(buf, encoded)

		kind := buf[0]
		if kind == RequestFlag {
			os.Stdout.Write(encoded)
		}
		go handle(kind, buf)
	}
}
Ejemplo n.º 4
0
func getShaFor(url string) ([]byte, error) {
	res, err := http.Get(url + ".sha1")
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	if res.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("HTTP Status: %d", res.StatusCode)
	}

	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}

	b = bytes.TrimSpace(b)

	b = b[:40]

	s := make([]byte, hex.DecodedLen(len(b)))

	if _, err := hex.Decode(s, b); err != nil {
		return nil, err
	}

	return s, nil
}
Ejemplo n.º 5
0
Archivo: hash.go Proyecto: decred/dcrd
// Decode decodes the byte-reversed hexadecimal string encoding of a Hash to a
// destination.
func Decode(dst *Hash, src string) error {
	// Return error if hash string is too long.
	if len(src) > MaxHashStringSize {
		return ErrHashStrSize
	}

	// Hex decoder expects the hash to be a multiple of two.  When not, pad
	// with a leading zero.
	var srcBytes []byte
	if len(src)%2 == 0 {
		srcBytes = []byte(src)
	} else {
		srcBytes = make([]byte, 1+len(src))
		srcBytes[0] = '0'
		copy(srcBytes[1:], src)
	}

	// Hex decode the source bytes to a temporary destination.
	var reversedHash Hash
	_, err := hex.Decode(reversedHash[HashSize-hex.DecodedLen(len(srcBytes)):], srcBytes)
	if err != nil {
		return err
	}

	// Reverse copy from the temporary hash to destination.  Because the
	// temporary was zeroed, the written result will be correctly padded.
	for i, b := range reversedHash[:HashSize/2] {
		dst[i], dst[HashSize-1-i] = reversedHash[HashSize-1-i], b
	}

	return nil
}
Ejemplo n.º 6
0
// Scan implements database/sql Scanner interface.
// It expectes EWKB with SRID 4326 (WGS 84).
func (p *PostGISPoint) Scan(value interface{}) error {
	if value == nil {
		*p = PostGISPoint{}
		return nil
	}

	v, ok := value.([]byte)
	if !ok {
		return fmt.Errorf("pq_types: expected []byte, got %T (%v)", value, value)
	}

	ewkb := make([]byte, hex.DecodedLen(len(v)))
	n, err := hex.Decode(ewkb, v)
	if err != nil {
		return err
	}

	var ewkbP ewkbPoint
	err = binary.Read(bytes.NewReader(ewkb[:n]), binary.LittleEndian, &ewkbP)
	if err != nil {
		return err
	}

	if ewkbP.ByteOrder != 1 || ewkbP.WkbType != 0x20000001 || ewkbP.SRID != 4326 {
		return fmt.Errorf("pq_types: unexpected ewkb %#v", ewkbP)
	}
	*p = ewkbP.Point
	return nil
}
Ejemplo n.º 7
0
// Decode extracts PDU from ASCII frame and verify LRC.
func (mb *asciiPackager) Decode(adu []byte) (pdu *ProtocolDataUnit, err error) {
	pdu = &ProtocolDataUnit{}
	// Slave address
	address, err := readHex(adu[1:])
	if err != nil {
		return
	}
	// Function code
	if pdu.FunctionCode, err = readHex(adu[3:]); err != nil {
		return
	}
	// Data
	dataEnd := len(adu) - 4
	data := adu[5:dataEnd]
	pdu.Data = make([]byte, hex.DecodedLen(len(data)))
	if _, err = hex.Decode(pdu.Data, data); err != nil {
		return
	}
	// LRC
	lrcVal, err := readHex(adu[dataEnd:])
	if err != nil {
		return
	}
	// Calculate checksum
	var lrc lrc
	lrc.reset()
	lrc.pushByte(address).pushByte(pdu.FunctionCode).pushBytes(pdu.Data)
	if lrcVal != lrc.value() {
		err = fmt.Errorf("modbus: response lrc '%v' does not match expected '%v'", lrcVal, lrc.value())
		return
	}
	return
}
Ejemplo n.º 8
0
func copyBinary(sourceName, targetName, sourceDir, targetDir string) error {
	source := filepath.Join(sourceDir, sourceName)
	dest := filepath.Join(targetDir, targetName)
	if _, err := os.Stat(source); err != nil {
		if os.IsNotExist(err) {
			return fmt.Errorf("missing file %s", source)
		}
		return err
	}
	if err := CopyFile(source, dest, 0755); err != nil {
		return err
	}
	if b, err := ioutil.ReadFile(source + ".sha256"); err == nil {
		if i := bytes.IndexRune(b, ' '); i > 0 {
			b = b[:i]
		}
		expectedHash := make([]byte, hex.DecodedLen(len(b)))
		if _, err := hex.Decode(expectedHash, b); err != nil {
			return err
		}
		if err := hashCheck(dest, expectedHash, sha256.New()); err != nil {
			return err
		}
	}

	return nil
}
Ejemplo n.º 9
0
// WireMsgToComposedMsg translates a multipart ZMQ messages received from a socket into
// a ComposedMsg struct and a slice of return identities. This includes verifying the
// message signature.
func WireMsgToComposedMsg(msgparts [][]byte, signkey []byte) (msg ComposedMsg,
	identities [][]byte, err error) {
	i := 0
	for string(msgparts[i]) != "<IDS|MSG>" {
		i++
	}
	identities = msgparts[:i]
	// msgparts[i] is the delimiter

	// Validate signature
	if len(signkey) != 0 {
		mac := hmac.New(sha256.New, signkey)
		for _, msgpart := range msgparts[i+2 : i+6] {
			mac.Write(msgpart)
		}
		signature := make([]byte, hex.DecodedLen(len(msgparts[i+1])))
		hex.Decode(signature, msgparts[i+1])
		if !hmac.Equal(mac.Sum(nil), signature) {
			return msg, nil, &InvalidSignatureError{}
		}
	}
	json.Unmarshal(msgparts[i+2], &msg.Header)
	json.Unmarshal(msgparts[i+3], &msg.Parent_header)
	json.Unmarshal(msgparts[i+4], &msg.Metadata)
	json.Unmarshal(msgparts[i+5], &msg.Content)
	return
}
Ejemplo n.º 10
0
// RandomIdentifierOfLength returns a string
// composed of random integers (from `crypto/rand`)
// with exactly len characters.
func randomIdentifierOfLength(len int) string {
	buflen := en.DecodedLen(len)
	buffer := make([]byte, buflen)
	rand.Read(buffer)

	return en.EncodeToString(buffer)
}
Ejemplo n.º 11
0
Archivo: entity.go Proyecto: siim-/siil
func createRandomKey(length int) (string, error) {
	var buffer []byte = make([]byte, hex.DecodedLen(length))
	if _, err := rand.Read(buffer); err != nil {
		return "", err
	} else {
		return hex.EncodeToString(buffer), nil
	}
}
Ejemplo n.º 12
0
Archivo: entity.go Proyecto: siim-/siil
func createRandomToken() (string, error) {
	var buffer []byte = make([]byte, hex.DecodedLen(TOKEN_LENGTH))
	if _, err := rand.Read(buffer); err != nil {
		return "", err
	} else {
		return hex.EncodeToString(buffer), nil
	}
}
Ejemplo n.º 13
0
// Unhex bytes
func (c *SCrypto) Unhex(src []byte, maxLen int) []byte {
	dst := make([]byte, hex.DecodedLen(len(src)))
	hex.Decode(dst, src)
	if len(dst) > maxLen {
		// avoid extraneous padding
		dst = dst[:maxLen]
	}
	return dst
}
Ejemplo n.º 14
0
func parseShortString(s string) (u UUID, e error) {
	b := []byte(s)
	if hex.DecodedLen(len(s)) != UUIDLen {
		e = fmt.Errorf("uuid: wrong string length for decode")
		return
	}
	_, e = hex.Decode(u[:], b)
	return
}
Ejemplo n.º 15
0
func (p *PublicKey) Set(value string) error {
	if hex.DecodedLen(len(value)) != ed25519.PublicKeySize {
		return fmt.Errorf("not a valid public key: wrong size")
	}
	if _, err := hex.Decode(p[:], []byte(value)); err != nil {
		return fmt.Errorf("not a valid public key: %v", err)
	}
	return nil
}
Ejemplo n.º 16
0
func (e *Engine) unhex() error {
	b := e.stack.Pop()
	dec := make([]byte, hex.DecodedLen(len(b)))
	n, err := hex.Decode(dec, b)
	if err == nil {
		e.stack.Push(dec[0:n])
	}
	return err
}
Ejemplo n.º 17
0
func (k *VolumeID) Set(value string) error {
	if hex.DecodedLen(len(value)) != VolumeIDLen {
		return fmt.Errorf("not a valid public key: wrong size")
	}
	if _, err := hex.Decode(k[:], []byte(value)); err != nil {
		return fmt.Errorf("not a valid public key: %v", err)
	}
	return nil
}
Ejemplo n.º 18
0
func (myCrypto *MyCrypto) hexDecode(srcStr string) ([]byte, error) {
	src := []byte(srcStr)
	dst := make([]byte, hex.DecodedLen(len(src)))
	_, err := hex.Decode(dst, src)
	if err != nil {
		return nil, err
	}
	return dst, nil
}
Ejemplo n.º 19
0
Archivo: decode.go Proyecto: koheeba/pg
func decodeBytes(f []byte) ([]byte, error) {
	f = f[2:] // Trim off "\\x".
	b := make([]byte, hex.DecodedLen(len(f)))
	_, err := hex.Decode(b, f)
	if err != nil {
		return nil, err
	}
	return b, nil
}
Ejemplo n.º 20
0
func decodeHex(hexBytes []byte) ([]byte, error) {
	cipher := make([]byte, hex.DecodedLen(len(hexBytes)))
	_, err := hex.Decode(cipher, hexBytes)

	if err != nil {
		return nil, err
	}

	return cipher, nil
}
Ejemplo n.º 21
0
func HexDecode(src []byte) ([]byte, error) {
	l := len(src)
	dst := make([]byte, hex.DecodedLen(l))
	l, err := hex.Decode(dst, src)
	if err != nil {
		return nil, err
	}

	return dst[:l], nil
}
Ejemplo n.º 22
0
func decodeBytes(b []byte) ([]byte, error) {
	if len(b) < 2 {
		return nil, fmt.Errorf("pg: can't parse bytes: %q", b)
	}

	b = b[2:] // Trim off "\\x".
	tmp := make([]byte, hex.DecodedLen(len(b)))
	_, err := hex.Decode(tmp, b)
	return tmp, err
}
Ejemplo n.º 23
0
func TestHash(t *testing.T) {
	for i, test := range hashTests {
		lastHash := make([]byte, hex.DecodedLen(len(test.lastHash)))
		hex.Decode(lastHash, test.lastHash)
		calcHash := createHash(uint8(test.version), test.seq, test.sessionId, test.key, lastHash)
		expectedHash, _ := hex.DecodeString(test.expected)
		if !bytes.Equal(calcHash, expectedHash) {
			t.Errorf("%d %s: expected '%x', got '%x'", i, test.name, expectedHash, calcHash)
		}
	}
}
Ejemplo n.º 24
0
func TestCrypt(t *testing.T) {
	for _, test := range cryptTests {
		calc := test.uncryptedData[:]
		crypt(calc, test.key, uint8(test.version), test.seq, test.sessionId)
		expected := make([]byte, hex.DecodedLen(len(test.cryptedData)))
		hex.Decode(expected, test.cryptedData)
		if !bytes.Equal(calc, expected) {
			t.Errorf("expected '%s' got '%s'", expected, calc)
		}
	}
}
Ejemplo n.º 25
0
func readHex(r *bufio.Reader) (s []byte, err error) {
	raw, err := r.ReadBytes('#')
	acc := make([]byte, 0, len(raw)-1)
	for _, c := range raw[:len(raw)-1] {
		if bytes.IndexByte(whitespaceChar, c) == -1 {
			acc = append(acc, c)
		}
	}
	s = make([]byte, hex.DecodedLen(len(acc)))
	n, err := hex.Decode(s, acc)
	return s[:n], err
}
Ejemplo n.º 26
0
Archivo: uuid.go Proyecto: agext/uuid
// NewFromString creates a UUID from a dash-separated hex string
func NewFromString(s string) (UUID, error) {
	digits := strings.Replace(s, "-", "", -1)
	if hex.DecodedLen(len(digits)) != 16 {
		return nil, fmt.Errorf("uuid.NewFromString: %s is not a valid UUID", s)
	}
	uuid, err := hex.DecodeString(digits)
	if err != nil {
		return nil, fmt.Errorf("uuid.NewFromString: %v", err)
	}

	return UUID(uuid), nil
}
Ejemplo n.º 27
0
func ConvertHexToBase64(input []byte) ([]byte, error) {
	data := make([]byte, hex.DecodedLen(len(input)))
	_, err := hex.Decode(data, input)
	if err != nil {
		return nil, errors.New("Can't convert hex input to raw data")
	}
	b := &bytes.Buffer{}
	e := base64.NewEncoder(base64.StdEncoding, b)
	e.Write(data)
	e.Close()
	return b.Bytes(), nil
}
Ejemplo n.º 28
0
// UnmarshalJSON allows the representation in JSON of hexbytes
func (b *HexBytes) UnmarshalJSON(data []byte) error {
	if len(data) < 2 || len(data)%2 != 0 || data[0] != '"' || data[len(data)-1] != '"' {
		return errors.New("tuf: invalid JSON hex bytes")
	}
	res := make([]byte, hex.DecodedLen(len(data)-2))
	_, err := hex.Decode(res, data[1:len(data)-1])
	if err != nil {
		return err
	}
	*b = res
	return nil
}
Ejemplo n.º 29
0
func gitHubVerifyRequest(secret []byte, req *http.Request, payload []byte) bool {
	const signaturePrefix = "sha1="
	const signatureLength = 45 // len(SignaturePrefix) + len(hex(sha1))

	signature := req.Header.Get("X-Hub-Signature")
	if len(signature) != signatureLength || !strings.HasPrefix(signature, signaturePrefix) {
		return false
	}
	actual := make([]byte, hex.DecodedLen(len(signature[5:])))
	hex.Decode(actual, []byte(signature[5:]))
	return hmac.Equal(hmacSum(secret, payload), actual)
}
Ejemplo n.º 30
0
// determine input type and decode accordingly
func decode(encoded []byte) (dst []byte, err error) {
	var b64NotHex = []byte("GHIJKLMNOPQRSTUVWXYZghijklmnopqrstuvwxyz+/-_")
	if bytes.IndexAny(b64NotHex, string(encoded)) < 0 {
		dst = make([]byte, hex.DecodedLen(len(encoded)))
		n, err := hex.Decode(dst, encoded)
		return dst[:n], err
	}

	enc := base64.StdEncoding
	dst = make([]byte, enc.DecodedLen(len(encoded)))
	n, err := enc.Decode(dst, encoded)
	return dst[:n], err
}