// Decrypt is used to decrypt the ciphertext.
544497
func (s *GCPCKMSSeal) Decrypt(ctx context.Context, in *physical.EncryptedBlobInfo) (pt []byte, err error) {
	defer func(now time.Time) {
		metrics.MeasureSince([]string{"seal", "decrypt", "time"}, now)
		metrics.MeasureSince([]string{"seal", "gcpckms", "decrypt", "time"}, now)

		if err != nil {
			metrics.IncrCounter([]string{"seal", "decrypt", "error"}, 1)
			metrics.IncrCounter([]string{"seal", "gcpckms", "decrypt", "error"}, 1)
		}
	}(time.Now())

	metrics.IncrCounter([]string{"seal", "decrypt"}, 1)
	metrics.IncrCounter([]string{"seal", "gcpckms", "decrypt"}, 1)

	if in.Ciphertext == nil {
		return nil, fmt.Errorf("given ciphertext for decryption is nil")
	}

	// Default to mechanism used before key info was stored
	if in.KeyInfo == nil {
		in.KeyInfo = &physical.SealKeyInfo{
			Mechanism: GCPKMSEncrypt,
		}
	}

	var plaintext []byte
	switch in.KeyInfo.Mechanism {
	case GCPKMSEncrypt:
		resp, err := s.client.Decrypt(ctx, &kmspb.DecryptRequest{
			Name:       s.parentName,
			Ciphertext: in.Ciphertext,
		})
		if err != nil {
			return nil, errwrap.Wrapf("failed to decrypt data: {{err}}", err)
		}

		plaintext = resp.Plaintext

	case GCPKMSEnvelopeAESGCMEncrypt:
		resp, err := s.client.Decrypt(ctx, &kmspb.DecryptRequest{
			Name:       s.parentName,
			Ciphertext: in.KeyInfo.WrappedKey,
		})
		if err != nil {
			return nil, errwrap.Wrapf("failed to decrypt envelope: {{err}}", err)
		}

		envInfo := &seal.EnvelopeInfo{
			Key:        resp.Plaintext,
			IV:         in.IV,
			Ciphertext: in.Ciphertext,
		}
		plaintext, err = seal.NewEnvelope().Decrypt(envInfo)
		if err != nil {
			return nil, errwrap.Wrapf("error decrypting data with envelope: {{err}}", err)
		}

	default:
		return nil, fmt.Errorf("invalid mechanism: %d", in.KeyInfo.Mechanism)
	}

	return plaintext, nil
}
635463
func (sk *SecretKey) Encrypt(in []byte) ([]byte, error) {
	return sk.Key.Encrypt(in)
}
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
}
227164
func (s *SphinxErrorDecrypter) DecryptError(reason lnwire.OpaqueReason) (*ForwardingError, error) {

	source, failureData, err := s.OnionErrorDecrypter.DecryptError(reason)
	if err != nil {
		return nil, err
	}

	r := bytes.NewReader(failureData)
	failureMsg, err := lnwire.DecodeFailure(r, 0)
	if err != nil {
		return nil, err
	}

	return &ForwardingError{
		ErrorSource:    source,
		FailureMessage: failureMsg,
	}, nil
}
208110
func Decrypt(payload []byte, secret string) ([]byte, error) {
	salt := payload[:saltLength]
	key := encryptionKeyToBytes(secret, string(salt))

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

	// The IV needs to be unique, but not secure. Therefore it's common to
	// include it at the beginning of the ciphertext.
	if len(payload) < aes.BlockSize {
		return nil, errors.New("payload too short")
	}
	iv := payload[saltLength : saltLength+aes.BlockSize]
	payload = payload[saltLength+aes.BlockSize:]
	payloadDst := make([]byte, len(payload))

	stream := cipher.NewCFBDecrypter(block, iv)

	// XORKeyStream can work in-place if the two arguments are the same.
	stream.XORKeyStream(payloadDst, payload)
	return payloadDst, nil
}
326870
func (*V2) Decrypt(token string, key []byte, payload interface{}, footer interface{}) error {
	body, footerBytes, err := splitToken([]byte(token), headerV2)
	if err != nil {
		return errors.Wrap(err, "failed to decode token")
	}

	if len(body) < chacha.XNonceSize {
		return errors.Wrap(ErrIncorrectTokenFormat, "incorrect token size")
	}

	nonce := body[:chacha.XNonceSize]
	encryptedPayload := body[chacha.XNonceSize:]

	aead, err := chacha20poly1305.NewXCipher(key)
	if err != nil {
		return errors.Wrap(err, "failed to create chacha20poly1305 cipher")
	}

	decryptedPayload, err := aead.Open(encryptedPayload[:0], nonce, encryptedPayload, preAuthEncode(headerV2, nonce, footerBytes))
	if err != nil {
		return ErrInvalidTokenAuth
	}

	if payload != nil {
		if err := fillValue(decryptedPayload, payload); err != nil {
			return errors.Wrap(err, "failed to decode payload")
		}
	}

	if footer != nil {
		if err := fillValue(footerBytes, footer); err != nil {
			return errors.Wrap(err, "failed to decode footer")
		}
	}
	return nil
}
99218
func Decrypt(in io.Reader, out io.Writer, keydir string, userSuppliedPrivateKey string) error {
	data, err := ioutil.ReadAll(in)
	if err != nil {
		return err
	}

	pubkey, err := json.ExtractPublicKey(data)
	if err != nil {
		return err
	}

	privkey, err := findPrivateKey(pubkey, keydir, userSuppliedPrivateKey)
	if err != nil {
		return err
	}

	myKP := crypto.Keypair{
		Public:  pubkey,
		Private: privkey,
	}

	decrypter := myKP.Decrypter()
	walker := json.Walker{
		Action: decrypter.Decrypt,
	}

	newdata, err := walker.Walk(data)
	if err != nil {
		return err
	}

	_, err = out.Write(newdata)

	return err
}
1356506
func decrypt(encBundle stellar1.EncryptedAccountBundle, puk libkb.PerUserKeySeed) (stellar1.AccountBundleSecretVersioned, error) {
	var empty stellar1.AccountBundleSecretVersioned
	if encBundle.V != 1 {
		return empty, errors.New("invalid stellar secret account bundle encryption version")
	}

	// Derive key
	reason := libkb.DeriveReasonPUKStellarAcctBundle
	symmetricKey, err := puk.DeriveSymmetricKey(reason)
	if err != nil {
		return empty, err
	}

	// Secretbox
	clearpack, ok := secretbox.Open(nil, encBundle.E,
		(*[libkb.NaclDHNonceSize]byte)(&encBundle.N),
		(*[libkb.NaclSecretBoxKeySize]byte)(&symmetricKey))
	if !ok {
		return empty, errors.New("stellar bundle secret box open failed")
	}

	// Msgpack (inner)
	var bver stellar1.AccountBundleSecretVersioned
	err = libkb.MsgpackDecode(&bver, clearpack)
	if err != nil {
		return empty, err
	}
	return bver, nil
}
819266
func (con *Connection) DecryptedRead(b []byte) (int, error) {
	if con.readBuffer == nil {
		buffered := bufio.NewReader(con.connection)
		decrypted, err := con.getDecrypter().Decrypt(buffered)
		if err != nil {
			if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
				// Ignore timeout error #77
			} else {
				log.Debug.Println("Decryption failed:", err)
				err = con.connection.Close()
			}
			return 0, err
		}

		con.readBuffer = decrypted
	}

	n, err := con.readBuffer.Read(b)

	if n < len(b) || err == io.EOF {
		con.readBuffer = nil
	}

	return n, err
}
31444
func decodeAndDecrypt(s string) (string, error) {
	// Bail out if empty string since it'll cause a segfault in util.Decrypt
	if s == "" {
		return "", nil
	}
	decoded, err := base64.StdEncoding.DecodeString(s)
	if err != nil {
		return "", err
	}
	decrypted, err := util.Decrypt(decoded, setting.SecretKey)
	if err != nil {
		return "", err
	}
	return string(decrypted), nil
}
1308831
func DecryptBlock(
	encryptedBlock EncryptedBlock, tlfCryptKey TLFCryptKey,
	blockServerHalf BlockCryptKeyServerHalf) ([]byte, error) {
	switch encryptedBlock.encryptedData.Version {
	case EncryptionSecretbox:
		nonce, err := encryptedBlock.encryptedData.Nonce24()
		if err != nil {
			return nil, err
		}

		key := UnmaskBlockCryptKey(blockServerHalf, tlfCryptKey)
		return decryptData(encryptedBlock.encryptedData, key.Data(), nonce)
	case EncryptionSecretboxWithKeyNonce:
		key := MakeBlockHashKey(blockServerHalf, tlfCryptKey)
		return decryptData(
			encryptedBlock.encryptedData, key.cryptKey(), key.nonce())
	default:
		return nil, errors.WithStack(
			InvalidEncryptionVer{encryptedBlock.encryptedData.Version})
	}
}
1316255
func (c *aesCBC) Decrypt(src io.Reader) io.Reader {
	return &cbcDecryptReader{
		decrypter: c.decrypter,
		src:       src,
		padder:    c.padder,
	}
}
1183393
func Decrypt(buf []byte, alg jwa.KeyEncryptionAlgorithm, key interface{}) ([]byte, error) {
	msg, err := Parse(buf)
	if err != nil {
		return nil, errors.Wrap(err, "failed to parse buffer for Decrypt")
	}

	return msg.Decrypt(alg, key)
}
569489
func (c *ServerContext) DecryptMessage(msg []byte, seqno uint32) (uint32, []byte, error) {
	return decryptMessage(c.sctxt, msg, seqno)
}
1287639
func (g *gRPCService) Decrypt(cipher []byte) ([]byte, error) {
	ctx, cancel := context.WithTimeout(context.Background(), g.callTimeout)
	defer cancel()

	if err := g.checkAPIVersion(ctx); err != nil {
		return nil, err
	}

	request := &kmsapi.DecryptRequest{Cipher: cipher, Version: kmsapiVersion}
	response, err := g.kmsClient.Decrypt(ctx, request)
	if err != nil {
		return nil, err
	}
	return response.Plain, nil
}
1061167
func (csp *impl) Decrypt(k bccsp.Key, ciphertext []byte, opts bccsp.DecrypterOpts) (plaintext []byte, err error) {
	return nil, nil
}
221948
func (b *AESGCMBarrier) Decrypt(ctx context.Context, key string, ciphertext []byte) ([]byte, error) {
	b.l.RLock()
	if b.sealed {
		b.l.RUnlock()
		return nil, ErrBarrierSealed
	}

	// Verify the term
	term := binary.BigEndian.Uint32(ciphertext[:4])

	// Get the GCM by term
	// It is expensive to do this first but it is not a
	// normal case that this won't match
	gcm, err := b.aeadForTerm(term)
	b.l.RUnlock()
	if err != nil {
		return nil, err
	}
	if gcm == nil {
		return nil, fmt.Errorf("no decryption key available for term %d", term)
	}

	// Decrypt the ciphertext
	plain, err := b.decrypt(key, gcm, ciphertext)
	if err != nil {
		return nil, errwrap.Wrapf("decryption failed: {{err}}", err)
	}

	return plain, nil
}