// Unbox decrypts the given ciphertext with the given nonce, for the given generation of the
// given team. Can return an error. Will return a non-nil plaintext on success.
359146
func (c *Crypto) Unbox(ctx context.Context, teamSpec keybase1.TeamIDWithVisibility, metadata *keybase1.EncryptedGitMetadata) (plaintext []byte, err error) {
	defer c.G().CTrace(ctx, fmt.Sprintf("git.Crypto#Unbox(%s, vis:%v)", teamSpec.TeamID, teamSpec.Visibility), func() error { return err })()

	if metadata.V != 1 {
		return nil, fmt.Errorf("invalid EncryptedGitMetadata version: %d", metadata.V)
	}

	public := teamSpec.Visibility == keybase1.TLFVisibility_PUBLIC

	var needKeyGeneration keybase1.PerTeamKeyGeneration
	if !public {
		needKeyGeneration = metadata.Gen
	}
	team, err := c.loadTeam(ctx, teamSpec, needKeyGeneration)
	if err != nil {
		return nil, err
	}

	key := publicCryptKey
	if !public {
		key, err = team.ApplicationKeyAtGeneration(ctx, keybase1.TeamApplication_GIT_METADATA, metadata.Gen)
		if err != nil {
			return nil, err
		}
	}

	var encKey [libkb.NaclSecretBoxKeySize]byte = key.Key
	var naclNonce [libkb.NaclDHNonceSize]byte = metadata.N

	plaintext, ok := secretbox.Open(nil, metadata.E, &naclNonce, &encKey)
	if !ok {
		return nil, libkb.DecryptOpenError{}
	}
	return plaintext, nil
}
786243
func (n NACLSecretbox) Encrypt(data []byte) (*api.MaybeEncryptedRecord, error) {
	var nonce [24]byte
	if _, err := io.ReadFull(cryptorand.Reader, nonce[:]); err != nil {
		return nil, err
	}

	// Seal's first argument is an "out", the data that the new encrypted message should be
	// appended to.  Since we don't want to append anything, we pass nil.
	encrypted := secretbox.Seal(nil, data, &nonce, &n.key)
	return &api.MaybeEncryptedRecord{
		Algorithm: n.Algorithm(),
		Data:      encrypted,
		Nonce:     nonce[:],
	}, nil
}
1075366
func OpenBox(ciphertext []byte, secretKeyBytes []byte) ([]byte, error) {
	var secretKey [32]byte
	copy(secretKey[:], secretKeyBytes)

	var nonce [24]byte
	copy(nonce[:], ciphertext[:24])
	plaintext, ok := secretbox.Open(nil, ciphertext[24:], &nonce, &secretKey)
	if !ok {
		return []byte(""), fmt.Errorf("Cannot decrypt")
	}
	return plaintext, nil
}
119663
func (pc *PubcompPacket) Unpack(b io.Reader) {
	pc.MessageID = decodeUint16(b)
}
1226212
func Unpack(buf []byte, dotu bool) (fc *Fcall, err error, fcsz int) {
	var m uint16

	if len(buf) < 7 {
		return nil, &Error{"buffer too short", EINVAL}, 0
	}

	fc = new(Fcall)
	fc.Fid = NOFID
	fc.Afid = NOFID
	fc.Newfid = NOFID

	p := buf
	fc.Size, p = gint32(p)
	fc.Type, p = gint8(p)
	fc.Tag, p = gint16(p)

	if int(fc.Size) > len(buf) || fc.Size < 7 {
		return nil, &Error{fmt.Sprintf("buffer too short: %d expected %d",
				len(buf), fc.Size),
				EINVAL},
			0
	}

	p = p[0 : fc.Size-7]
	fc.Pkt = buf[0:fc.Size]
	fcsz = int(fc.Size)
	if fc.Type < Tversion || fc.Type >= Tlast {
		return nil, &Error{"invalid id", EINVAL}, 0
	}

	var sz uint32
	if dotu {
		sz = minFcsize[fc.Type-Tversion]
	} else {
		sz = minFcusize[fc.Type-Tversion]
	}

	if fc.Size < sz {
		goto szerror
	}

	err = nil
	switch fc.Type {
	default:
		return nil, &Error{"invalid message id", EINVAL}, 0

	case Tversion, Rversion:
		fc.Msize, p = gint32(p)
		fc.Version, p = gstr(p)
		if p == nil {
			goto szerror
		}

	case Tauth:
		fc.Afid, p = gint32(p)
		fc.Uname, p = gstr(p)
		if p == nil {
			goto szerror
		}

		fc.Aname, p = gstr(p)
		if p == nil {
			goto szerror
		}

		if dotu {
			if len(p) > 0 {
				fc.Unamenum, p = gint32(p)
			} else {
				fc.Unamenum = NOUID
			}
		} else {
			fc.Unamenum = NOUID
		}

	case Rauth, Rattach:
		p = gqid(p, &fc.Qid)

	case Tflush:
		fc.Oldtag, p = gint16(p)

	case Tattach:
		fc.Fid, p = gint32(p)
		fc.Afid, p = gint32(p)
		fc.Uname, p = gstr(p)
		if p == nil {
			goto szerror
		}

		fc.Aname, p = gstr(p)
		if p == nil {
			goto szerror
		}

		if dotu {
			if len(p) > 0 {
				fc.Unamenum, p = gint32(p)
			} else {
				fc.Unamenum = NOUID
			}
		}

	case Rerror:
		fc.Error, p = gstr(p)
		if p == nil {
			goto szerror
		}
		if dotu {
			fc.Errornum, p = gint32(p)
		} else {
			fc.Errornum = 0
		}

	case Twalk:
		fc.Fid, p = gint32(p)
		fc.Newfid, p = gint32(p)
		m, p = gint16(p)
		fc.Wname = make([]string, m)
		for i := 0; i < int(m); i++ {
			fc.Wname[i], p = gstr(p)
			if p == nil {
				goto szerror
			}
		}

	case Rwalk:
		m, p = gint16(p)
		fc.Wqid = make([]Qid, m)
		for i := 0; i < int(m); i++ {
			p = gqid(p, &fc.Wqid[i])
		}

	case Topen:
		fc.Fid, p = gint32(p)
		fc.Mode, p = gint8(p)

	case Ropen, Rcreate:
		p = gqid(p, &fc.Qid)
		fc.Iounit, p = gint32(p)

	case Tcreate:
		fc.Fid, p = gint32(p)
		fc.Name, p = gstr(p)
		if p == nil {
			goto szerror
		}
		fc.Perm, p = gint32(p)
		fc.Mode, p = gint8(p)
		if dotu {
			fc.Ext, p = gstr(p)
			if p == nil {
				goto szerror
			}
		}

	case Tread:
		fc.Fid, p = gint32(p)
		fc.Offset, p = gint64(p)
		fc.Count, p = gint32(p)

	case Rread:
		fc.Count, p = gint32(p)
		if len(p) < int(fc.Count) {
			goto szerror
		}
		fc.Data = p
		p = p[fc.Count:]

	case Twrite:
		fc.Fid, p = gint32(p)
		fc.Offset, p = gint64(p)
		fc.Count, p = gint32(p)
		if len(p) != int(fc.Count) {
			fc.Data = make([]byte, fc.Count)
			copy(fc.Data, p)
			p = p[len(p):]
		} else {
			fc.Data = p
			p = p[fc.Count:]
		}

	case Rwrite:
		fc.Count, p = gint32(p)

	case Tclunk, Tremove, Tstat:
		fc.Fid, p = gint32(p)

	case Rstat:
		m, p = gint16(p)
		p, err = gstat(p, &fc.Dir, dotu)
		if err != nil {
			return nil, err, 0
		}

	case Twstat:
		fc.Fid, p = gint32(p)
		m, p = gint16(p)
		p, _ = gstat(p, &fc.Dir, dotu)

	case Rflush, Rclunk, Rremove, Rwstat:
	}

	if len(p) > 0 {
		goto szerror
	}

	return

szerror:
	return nil, &Error{"invalid size", EINVAL}, 0
}
434548
func (b *Boxer) open(data chat1.EncryptedData, key libkb.NaclSecretBoxKey) ([]byte, error) {
	if len(data.N) != libkb.NaclDHNonceSize {
		return nil, libkb.DecryptBadNonceError{}
	}
	var nonce [libkb.NaclDHNonceSize]byte
	copy(nonce[:], data.N)

	plain, ok := secretbox.Open(nil, data.E, &nonce, (*[32]byte)(&key))
	if !ok {
		return nil, libkb.DecryptOpenError{}
	}
	return plain, nil
}
373244
func (engine *CryptoEngine) Decrypt(encryptedBytes []byte) (*message, error) {

	var err error
	msg := new(message)

	// convert the bytes to an encrypted message
	encryptedMessage, err := encryptedMessageFromBytes(encryptedBytes)
	if err != nil {
		return nil, err
	}

	decryptedMessageBytes, valid := secretbox.Open(nil, encryptedMessage.data, &encryptedMessage.nonce, &engine.secretKey)

	// if the verification failed
	if !valid {
		return nil, MessageDecryptionError
	}

	// means we successfully managed to decrypt
	msg, err = messageFromBytes(decryptedMessageBytes)
	return msg, nil

}
77284
func (c *Crypto) Box(ctx context.Context, plaintext []byte, teamSpec keybase1.TeamIDWithVisibility) (*keybase1.EncryptedGitMetadata, error) {
	team, err := c.loadTeam(ctx, teamSpec, 0)
	if err != nil {
		return nil, err
	}

	public := teamSpec.Visibility == keybase1.TLFVisibility_PUBLIC

	key := publicCryptKey
	if !public {
		key, err = team.GitMetadataKey(ctx)
		if err != nil {
			return nil, err
		}
	}

	nonce, err := libkb.RandomNaclDHNonce()
	if err != nil {
		return nil, err
	}

	var encKey [libkb.NaclSecretBoxKeySize]byte = key.Key
	sealed := secretbox.Seal(nil, plaintext, &nonce, &encKey)

	return &keybase1.EncryptedGitMetadata{
		V:   libkb.CurrentGitMetadataEncryptionVersion,
		E:   sealed,
		N:   nonce,
		Gen: key.KeyGeneration,
	}, nil
}
317462
func (k *Keyring) GenerateBoxKey() (*SecretKey, error) {
	ret, err := generateBoxKey()
	if err != nil {
		return nil, err
	}
	k.encKeys[ret.pub] = *ret
	return ret, nil
}
1297957
func (b *Boxer) signEncrypt(msg []byte, encryptionKey libkb.NaclSecretBoxKey,
	signingKeyPair libkb.NaclSigningKeyPair, prefix kbcrypto.SignaturePrefix) (chat1.SignEncryptedData, error) {
	if signingKeyPair.Private == nil {
		return chat1.SignEncryptedData{}, libkb.NoSecretKeyError{}
	}

	var nonce [signencrypt.NonceSize]byte
	if _, err := rand.Read(nonce[:]); err != nil {
		return chat1.SignEncryptedData{}, err
	}

	var encKey [signencrypt.SecretboxKeySize]byte = encryptionKey
	var signKey [ed25519.PrivateKeySize]byte = *signingKeyPair.Private

	signEncryptedBytes := signencrypt.SealWhole(
		msg, &encKey, &signKey, prefix, &nonce)
	signEncryptedInfo := chat1.SignEncryptedData{
		V: 1,
		E: signEncryptedBytes,
		N: nonce[:],
	}

	if b.testingSignatureMangle != nil {
		b.assertInTest()
		signEncryptedInfo.E = b.testingSignatureMangle(signEncryptedInfo.E)
	}

	return signEncryptedInfo, nil
}
1231818
func (c *ConnectPacket) Unpack(b io.Reader) {
	c.ProtocolName = decodeString(b)
	c.ProtocolVersion = decodeByte(b)
	options := decodeByte(b)
	c.ReservedBit = 1 & options
	c.CleanSession = 1&(options>>1) > 0
	c.WillFlag = 1&(options>>2) > 0
	c.WillQos = 3 & (options >> 3)
	c.WillRetain = 1&(options>>5) > 0
	c.PasswordFlag = 1&(options>>6) > 0
	c.UsernameFlag = 1&(options>>7) > 0
	c.KeepaliveTimer = decodeUint16(b)
	c.ClientIdentifier = decodeString(b)
	if c.WillFlag {
		c.WillTopic = decodeString(b)
		c.WillMessage = decodeBytes(b)
	}
	if c.UsernameFlag {
		c.Username = decodeString(b)
	}
	if c.PasswordFlag {
		c.Password = decodeBytes(b)
	}
}
529632
func (service *VboxPortType) IMachinegetRTCUseUTC(request *IMachinegetRTCUseUTC) (*IMachinegetRTCUseUTCResponse, error) {
	response := new(IMachinegetRTCUseUTCResponse)
	err := service.client.Call("", request, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}
913128
func (x *XC) Encrypt(ctx context.Context, plaintext []byte, recipients []string) ([]byte, error) {
	privKeyIDs := x.secring.KeyIDs()
	if len(privKeyIDs) < 1 {
		return nil, fmt.Errorf("no signing keys available on our keyring")
	}
	privKey := x.secring.Get(privKeyIDs[0])

	var compressed bool
	plaintext, compressed = compress(plaintext)

	// encrypt body (also generates a random session key)
	sk, chunks, err := encryptBody(plaintext)
	if err != nil {
		return nil, errors.Wrapf(err, "failed to encrypt body: %s", err)
	}

	// encrypt the session key per recipient
	header, err := x.encryptHeader(ctx, privKey, sk, recipients)
	if err != nil {
		return nil, errors.Wrapf(err, "failed to encrypt header: %s", err)
	}

	msg := &xcpb.Message{
		Version:    OnDiskVersion,
		Header:     header,
		Chunks:     chunks,
		Compressed: compressed,
	}

	return proto.Marshal(msg)
}
59028
func decryptData(
	encryptedData encryptedData, key [32]byte, nonce [24]byte) ([]byte, error) {
	switch encryptedData.Version {
	case EncryptionSecretbox:
		// We're good, no nonce check needed.
	case EncryptionSecretboxWithKeyNonce:
		if !bytes.Equal(nonce[:], encryptedData.Nonce) {
			return nil, errors.WithStack(InvalidNonceError{encryptedData.Nonce})
		}
	default:
		return nil, errors.WithStack(
			UnknownEncryptionVer{encryptedData.Version})
	}

	decryptedData, ok := secretbox.Open(
		nil, encryptedData.EncryptedData, &nonce, &key)
	if !ok {
		return nil, errors.WithStack(
			libkb.DecryptionError{Cause: errors.New("Cannot open secret box")})
	}

	return decryptedData, nil
}
114214
func UnboxBytes32(ctx context.Context, g *libkb.GlobalContext, getSecretUI func() libkb.SecretUI, arg keybase1.UnboxBytes32Arg) (bytes32 keybase1.Bytes32, err error) {
	encryptionKey, err := GetMySecretKey(ctx, g, getSecretUI, libkb.DeviceEncryptionKeyType, arg.Reason)
	if err != nil {
		return
	}

	return unboxBytes32(encryptionKey, arg.EncryptedBytes32, arg.Nonce, arg.PeersPublicKey)
}
1054884
func (ca *ConnackPacket) Unpack(b io.Reader) {
	ca.TopicNameCompression = decodeByte(b)
	ca.ReturnCode = decodeByte(b)
}
119155
func (p *PrivateKey) Decrypt(passphrase string) error {
	if !p.Encrypted {
		return nil
	}
	secretKey := p.deriveKey(passphrase)

	decrypted, ok := secretbox.Open(nil, p.EncryptedData, &p.Nonce, &secretKey)
	if !ok {
		return fmt.Errorf("decryption error")
	}
	copy(p.privateKey[:], decrypted)

	p.Encrypted = false
	return nil
}