// Decode reads keystore representation from r then decrypts and check signature using password
// It is strongly recommended to fill password slice with zero after usage
19968
func Decode(r io.Reader, password []byte) (KeyStore, error) {
	ksd := keyStoreDecoder{
		r:  r,
		md: sha1.New(),
	}
	passwordBytes := passwordBytes(password)
	defer zeroing(passwordBytes)
	_, err := ksd.md.Write(passwordBytes)
	if err != nil {
		return nil, err
	}
	_, err = ksd.md.Write(whitenerMessage)
	if err != nil {
		return nil, err
	}

	readMagic, err := ksd.readUint32()
	if err != nil {
		return nil, err
	}
	if readMagic != magic {
		return nil, ErrIncorrectMagic
	}
	version, err := ksd.readUint32()
	if err != nil {
		return nil, err
	}
	count, err := ksd.readUint32()
	if err != nil {
		return nil, err
	}
	keyStore := KeyStore{}
	for entitiesCount := count; entitiesCount > 0; entitiesCount-- {
		alias, entry, err := ksd.readEntry(version, password)
		if err != nil {
			return nil, err
		}
		keyStore[alias] = entry
	}

	computedDigest := ksd.md.Sum(nil)
	actualDigest, err := ksd.readBytes(uint32(ksd.md.Size()))
	for i := 0; i < len(actualDigest); i++ {
		if actualDigest[i] != computedDigest[i] {
			return nil, ErrInvalidDigest
		}
	}

	return keyStore, nil
}
1199830
func (ks *KeyStore) Parse(r io.Reader, password []byte) error {
	var md hash.Hash
	if password != nil {
		md = getPreKeyedHash(password)
		r = io.TeeReader(r, md)
	}

	version, err := parseHeader(r)
	if err != nil {
		return err
	}
	if version != jceksVersion {
		return fmt.Errorf("unexpected version: %d != %d", version, jceksVersion)
	}

	count, err := readInt32(r)
	if err != nil {
		return err
	}
	for i := 0; i < int(count); i++ {
		tag, err := readInt32(r)
		if err != nil {
			return err
		}
		switch tag {
		case 1:
			// Private-key entry
			err := ks.parsePrivateKey(r)
			if err != nil {
				return err
			}
		case 2:
			// Trusted-cert entry
			err := ks.parseTrustedCert(r)
			if err != nil {
				return err
			}
		case 3:
			// Secret-key entry
			return fmt.Errorf("unimplemented: Secret-key")
		default:
			return fmt.Errorf("unimplemented tag: %d", tag)
		}
	}

	if md != nil {
		computed := md.Sum([]byte{})
		actual := make([]byte, len(computed))
		_, err := io.ReadFull(r, actual)
		if err != nil {
			return err
		}
		if subtle.ConstantTimeCompare(computed, actual) != 1 {
			return fmt.Errorf("keystore was tampered with or password was incorrect")
		}
	}

	return nil
}
776935
func decode(buf []byte, out interface{}) error {
	r := bytes.NewReader(buf)
	hd := codec.MsgpackHandle{}
	dec := codec.NewDecoder(r, &hd)
	return dec.Decode(out)
}
758870
func (c *ReplyChannelRange) Decode(r io.Reader, pver uint32) error {
	err := c.QueryChannelRange.Decode(r, pver)
	if err != nil {
		return err
	}

	if err := ReadElements(r, &c.Complete); err != nil {
		return err
	}

	c.EncodingType, c.ShortChanIDs, err = decodeShortChanIDs(r)

	return err
}
1180650
func (p *WaitingProof) Decode(r io.Reader) error {
	if err := binary.Read(r, byteOrder, &p.isRemote); err != nil {
		return err
	}

	msg := &lnwire.AnnounceSignatures{}
	if err := msg.Decode(r, 0); err != nil {
		return err
	}

	(*p).AnnounceSignatures = msg
	return nil
}
1174000
func (c *Circuit) Decode(r io.Reader) error {
	var keyLength [1]byte
	if _, err := r.Read(keyLength[:]); err != nil {
		return err
	}

	sessionKeyData := make([]byte, uint8(keyLength[0]))
	if _, err := r.Read(sessionKeyData[:]); err != nil {
		return err
	}

	c.SessionKey, _ = btcec.PrivKeyFromBytes(btcec.S256(), sessionKeyData)
	var pathLength [1]byte
	if _, err := r.Read(pathLength[:]); err != nil {
		return err
	}
	c.PaymentPath = make([]*btcec.PublicKey, uint8(pathLength[0]))

	for i := 0; i < len(c.PaymentPath); i++ {
		var pubKeyData [btcec.PubKeyBytesLenCompressed]byte
		if _, err := r.Read(pubKeyData[:]); err != nil {
			return err
		}

		pubKey, err := btcec.ParsePubKey(pubKeyData[:], btcec.S256())
		if err != nil {
			return err
		}
		c.PaymentPath[i] = pubKey
	}

	return nil
}
251202
func Decode(in string) ([]byte, error) {
	out, err := Client().Decode(in)
	Trace("Decode", err, logrus.Fields{"in": in, "out": out})
	return out, err
}
163919
func (s *EDStore) Decrypt(dst []byte, cipherText []byte) ([]byte, error) {
	var gcm cipher.AEAD
	if len(cipherText) > 0 {
		switch cipherText[0] {
		case CryptoCodeAES:
			gcm = s.aesgcm
		case CryptoCodeChaCha:
			gcm = s.chachagcm
		default:
			// Anything else, assume no algo or something we don't know how to decrypt.
			return cipherText, nil
		}
	}
	if len(cipherText) <= 1+s.nonceSize {
		return nil, fmt.Errorf("trying to decrypt data that is not (len=%v)", len(cipherText))
	}
	dd, err := gcm.Open(dst, cipherText[1:1+s.nonceSize], cipherText[1+s.nonceSize:], nil)
	if err != nil {
		return nil, err
	}
	return dd, nil
}
835975
func (s *SphinxErrorEncrypter) Decode(r io.Reader) error {
	var ephemeral [33]byte
	if _, err := io.ReadFull(r, ephemeral[:]); err != nil {
		return err
	}

	var err error
	s.EphemeralKey, err = btcec.ParsePubKey(ephemeral[:], btcec.S256())
	if err != nil {
		return err
	}

	return nil
}
1296655
func Decode(r io.Reader, v interface{}, order binary.ByteOrder) error {
	b, err := Read(r, order)
	if err != nil {
		return err
	}
	err = json.Unmarshal(b, v)
	if err != nil {
		return errors.New(err.Error() + string(b))
	}
	return nil
}
433866
func Decode(input interface{}, output interface{}) error {
	config := &DecoderConfig{
		Metadata: nil,
		Result:   output,
	}

	decoder, err := NewDecoder(config)
	if err != nil {
		return err
	}

	return decoder.Decode(input)
}
1360234
func (k *KMS) Decrypt(ciphertext string) (string, error) {
	ciphertextBlob, err := b64.Decode(ciphertext)
	if err != nil {
		return "", err
	}
	input := &kms.DecryptInput{
		CiphertextBlob: []byte(ciphertextBlob),
	}
	output, err := k.Client.Decrypt(input)
	if err != nil {
		return "", err
	}
	return string(output.Plaintext), nil
}
824841
func (enc *Encoding) decode(dst, src []byte) (n int, end bool, err error) {
	si := 0

	// skip over newlines
	for si < len(src) && (src[si] == '\n' || src[si] == '\r') {
		si++
	}

	for si < len(src) && !end {
		// Decode quantum using the base64 alphabet
		var dbuf [4]byte
		dinc, dlen := 3, 4

		for j := range dbuf {
			if len(src) == si {
				if enc.padChar != NoPadding || j < 2 {
					return n, false, CorruptInputError(si - j)
				}
				dinc, dlen, end = j-1, j, true
				break
			}
			in := src[si]

			si++
			// skip over newlines
			for si < len(src) && (src[si] == '\n' || src[si] == '\r') {
				si++
			}

			if rune(in) == enc.padChar {
				// We've reached the end and there's padding
				switch j {
				case 0, 1:
					// incorrect padding
					return n, false, CorruptInputError(si - 1)
				case 2:
					// "==" is expected, the first "=" is already consumed.
					if si == len(src) {
						// not enough padding
						return n, false, CorruptInputError(len(src))
					}
					if rune(src[si]) != enc.padChar {
						// incorrect padding
						return n, false, CorruptInputError(si - 1)
					}

					si++
					// skip over newlines
					for si < len(src) && (src[si] == '\n' || src[si] == '\r') {
						si++
					}
				}
				if si < len(src) {
					// trailing garbage
					err = CorruptInputError(si)
				}
				dinc, dlen, end = 3, j, true
				break
			}
			dbuf[j] = enc.decodeMap[in]
			if dbuf[j] == 0xFF {
				return n, false, CorruptInputError(si - 1)
			}
		}

		// Convert 4x 6bit source bytes into 3 bytes
		val := uint(dbuf[0])<<18 | uint(dbuf[1])<<12 | uint(dbuf[2])<<6 | uint(dbuf[3])
		switch dlen {
		case 4:
			dst[2] = byte(val >> 0)
			fallthrough
		case 3:
			dst[1] = byte(val >> 8)
			fallthrough
		case 2:
			dst[0] = byte(val >> 16)
		}
		dst = dst[dinc:]
		n += dlen - 1
	}

	return n, end, err
}
1353587
func (d Decoder) Decode() (interface{}, error) {
	data, err := d.read()
	if err != nil {
		return nil, err
	}

	return d.decode(data)
}
493437
func (s *Session) Decode(data []byte) error {
	if len(data) == 0 {
		return nil
	}

	box := make([]byte, base64.RawStdEncoding.DecodedLen(len(data)))
	if _, err := base64.RawStdEncoding.Decode(box, data); err != nil {
		return errors.Wrapf(err, "failed decoding session data")
	}

	var nonce [24]byte
	var msg []byte
	var key [32]byte
	var ok bool
	copy(nonce[:], box[:24])

	for _, k := range s.keys {
		copy(key[:], k)
		msg, ok = secretbox.Open(nil, box[24:], &nonce, &key)
		if ok {
			if err := msgpack.Unmarshal(msg, &s.data); err != nil {
				return errors.Wrapf(err, "failed decoding session data")
			}
			return nil
		}
	}

	return errors.New("failed decrypting session data")
}
412910
func (g *Gzip) Decode(r io.Reader, w io.Writer) error {
	gzr, err := gzip.NewReader(r)
	if err != nil {
		return err
	}
	defer gzr.Close()
	_, err = io.Copy(w, gzr)
	return err
}
230261
func (pk *PrivateKey) Decrypt(passphrase []byte) error {
	if !pk.Encrypted {
		return nil
	}

	key := make([]byte, pk.cipher.KeySize())
	pk.s2k(key, passphrase)
	block := pk.cipher.new(key)
	cfb := cipher.NewCFBDecrypter(block, pk.iv)

	data := make([]byte, len(pk.encryptedData))
	cfb.XORKeyStream(data, pk.encryptedData)

	if pk.sha1Checksum {
		if len(data) < sha1.Size {
			return errors.StructuralError("truncated private key data")
		}
		h := sha1.New()
		h.Write(data[:len(data)-sha1.Size])
		sum := h.Sum(nil)
		if !bytes.Equal(sum, data[len(data)-sha1.Size:]) {
			return errors.StructuralError("private key checksum failure")
		}
		data = data[:len(data)-sha1.Size]
	} else {
		if len(data) < 2 {
			return errors.StructuralError("truncated private key data")
		}
		var sum uint16
		for i := 0; i < len(data)-2; i++ {
			sum += uint16(data[i])
		}
		if data[len(data)-2] != uint8(sum>>8) ||
			data[len(data)-1] != uint8(sum) {
			return errors.StructuralError("private key checksum failure")
		}
		data = data[:len(data)-2]
	}

	return pk.parsePrivateKey(data)
}