// Decrypt implements Protocol.Decrypt
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
}
561437
func (f Fernet) Decrypt(record api.MaybeEncryptedRecord) ([]byte, error) {
	if record.Algorithm != f.Algorithm() {
		return nil, fmt.Errorf("record is not a Fernet message")
	}

	// -1 skips the TTL check, since we don't care about message expiry
	out := fernet.VerifyAndDecrypt(record.Data, -1, []*fernet.Key{&f.key})
	// VerifyandDecrypt returns a nil message if it can't be verified and decrypted
	if out == nil {
		return nil, fmt.Errorf("no decryption key for record encrypted with %s", f.Algorithm())
	}
	return out, nil
}
845525
func (c *Cipher) Decrypt(dst, src []byte) {
	l := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3])
	r := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7])
	l, r = decryptBlock(l, r, c)
	dst[0], dst[1], dst[2], dst[3] = byte(l>>24), byte(l>>16), byte(l>>8), byte(l)
	dst[4], dst[5], dst[6], dst[7] = byte(r>>24), byte(r>>16), byte(r>>8), byte(r)
}
257564
func (m *Message) Decrypt(alg jwa.KeyEncryptionAlgorithm, key interface{}) ([]byte, error) {
	var err error

	if len(m.Recipients) == 0 {
		return nil, errors.New("no recipients, can not proceed with decrypt")
	}

	enc := m.ProtectedHeader.ContentEncryption

	h := NewHeader()
	if err := h.Copy(m.ProtectedHeader.Header); err != nil {
		return nil, errors.Wrap(err, `failed to copy protected headers`)
	}
	h, err = h.Merge(m.UnprotectedHeader)
	if err != nil {
		if debug.Enabled {
			debug.Printf("failed to merge unprotected header")
		}
		return nil, errors.Wrap(err, "failed to merge headers for message decryption")
	}

	aad, err := m.AuthenticatedData.Base64Encode()
	if err != nil {
		return nil, errors.Wrap(err, "failed to base64 encode authenticated data for message decryption")
	}
	ciphertext := m.CipherText.Bytes()
	iv := m.InitializationVector.Bytes()
	tag := m.Tag.Bytes()

	cipher, err := buildContentCipher(enc)
	if err != nil {
		return nil, errors.Wrap(err, "unsupported content cipher algorithm '"+enc.String()+"'")
	}
	keysize := cipher.KeySize()

	var plaintext []byte
	for _, recipient := range m.Recipients {
		if debug.Enabled {
			debug.Printf("Attempting to check if we can decode for recipient (alg = %s)", recipient.Header.Algorithm)
		}
		if recipient.Header.Algorithm != alg {
			continue
		}

		h2 := NewHeader()
		if err := h2.Copy(h); err != nil {
			if debug.Enabled {
				debug.Printf("failed to copy header: %s", err)
			}
			continue
		}

		h2, err := h2.Merge(recipient.Header)
		if err != nil {
			if debug.Enabled {
				debug.Printf("Failed to merge! %s", err)
			}
			continue
		}

		k, err := BuildKeyDecrypter(h2.Algorithm, h2, key, keysize)
		if err != nil {
			if debug.Enabled {
				debug.Printf("failed to create key decrypter: %s", err)
			}
			continue
		}

		cek, err := k.KeyDecrypt(recipient.EncryptedKey.Bytes())
		if err != nil {
			if debug.Enabled {
				debug.Printf("failed to decrypt key: %s", err)
			}
			continue
		}

		plaintext, err = cipher.decrypt(cek, iv, ciphertext, tag, aad)
		if err == nil {
			break
		}
		if debug.Enabled {
			debug.Printf("DecryptMessage: failed to decrypt using %s: %s", h2.Algorithm, err)
		}
		// Keep looping because there might be another key with the same algo
	}

	if plaintext == nil {
		return nil, errors.New("failed to find matching recipient to decrypt key")
	}

	if h.Compression == jwa.Deflate {
		output := bytes.Buffer{}
		w, _ := flate.NewWriter(&output, 1)
		in := plaintext
		for len(in) > 0 {
			n, err := w.Write(in)
			if err != nil {
				return nil, errors.Wrap(err, `failed to write to compression writer`)
			}
			in = in[n:]
		}
		if err := w.Close(); err != nil {
			return nil, errors.Wrap(err, "failed to close compression writer")
		}
		plaintext = output.Bytes()
	}

	return plaintext, nil
}
22365
func (n NACLSecretbox) Decrypt(record api.MaybeEncryptedRecord) ([]byte, error) {
	if record.Algorithm != n.Algorithm() {
		return nil, fmt.Errorf("not a NACL secretbox record")
	}
	if len(record.Nonce) != naclSecretboxNonceSize {
		return nil, fmt.Errorf("invalid nonce size for NACL secretbox: require 24, got %d", len(record.Nonce))
	}

	var decryptNonce [naclSecretboxNonceSize]byte
	copy(decryptNonce[:], record.Nonce[:naclSecretboxNonceSize])

	// Open's first argument is an "out", the data that the decrypted message should be
	// appended to.  Since we don't want to append anything, we pass nil.
	decrypted, ok := secretbox.Open(nil, record.Data, &decryptNonce, &n.key)
	if !ok {
		return nil, fmt.Errorf("no decryption key for record encrypted with %s", n.Algorithm())
	}
	return decrypted, nil
}
1289437
func decrypt(random io.Reader, priv *PrivateKey, c *big.Int) (m *big.Int, err error) {
	// TODO(agl): can we get away with reusing blinds?
	if c.Cmp(priv.N) > 0 {
		err = ErrDecryption
		return
	}

	var ir *big.Int
	if random != nil {
		// Blinding enabled. Blinding involves multiplying c by r^e.
		// Then the decryption operation performs (m^e * r^e)^d mod n
		// which equals mr mod n. The factor of r can then be removed
		// by multiplying by the multiplicative inverse of r.

		var r *big.Int

		for {
			r, err = rand.Int(random, priv.N)
			if err != nil {
				return
			}
			if r.Cmp(bigZero) == 0 {
				r = bigOne
			}
			var ok bool
			ir, ok = modInverse(r, priv.N)
			if ok {
				break
			}
		}
		bigE := big.NewInt(int64(priv.E))
		rpowe := new(big.Int).Exp(r, bigE, priv.N)
		cCopy := new(big.Int).Set(c)
		cCopy.Mul(cCopy, rpowe)
		cCopy.Mod(cCopy, priv.N)
		c = cCopy
	}

	if priv.Precomputed.Dp == nil {
		m = new(big.Int).Exp(c, priv.D, priv.N)
	} else {
		// We have the precalculated values needed for the CRT.
		m = new(big.Int).Exp(c, priv.Precomputed.Dp, priv.Primes[0])
		m2 := new(big.Int).Exp(c, priv.Precomputed.Dq, priv.Primes[1])
		m.Sub(m, m2)
		if m.Sign() < 0 {
			m.Add(m, priv.Primes[0])
		}
		m.Mul(m, priv.Precomputed.Qinv)
		m.Mod(m, priv.Primes[0])
		m.Mul(m, priv.Primes[1])
		m.Add(m, m2)

		for i, values := range priv.Precomputed.CRTValues {
			prime := priv.Primes[2+i]
			m2.Exp(c, values.Exp, prime)
			m2.Sub(m2, m)
			m2.Mul(m2, values.Coeff)
			m2.Mod(m2, prime)
			if m2.Sign() < 0 {
				m2.Add(m2, prime)
			}
			m2.Mul(m2, values.R)
			m.Add(m, m2)
		}
	}

	if ir != nil {
		// Unblind.
		m.Mul(m, ir)
		m.Mod(m, priv.N)
	}

	return
}
115507
func DecryptRequest(client io.Writer, r *http.Request, bucket, object string, metadata map[string]string) (io.WriteCloser, error) {
	return DecryptRequestWithSequenceNumber(client, r, bucket, object, 0, metadata)
}
1312025
func (cs *ChaChaStream) Decrypt(data []byte) []byte {
	ret := make([]byte, len(data))
	cs.cipher.XORKeyStream(ret, data)
	return ret
}
314978
func Decrypt(key []byte, cryptoText string) string {
	ciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)

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

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

	stream := cipher.NewCFBDecrypter(block, iv)

	// XORKeyStream can work in-place if the two arguments are the same.
	stream.XORKeyStream(ciphertext, ciphertext)

	return fmt.Sprintf("%s", ciphertext)
}
769409
func (d DecrypterJSON) decryptJSON(data map[string]interface{}, decryptFunc DecryptFunc) error {
	for k, v := range data {
		switch t := v.(type) {
		case string:
			if s := strings.TrimPrefix(t, d.prefix); s != t {
				s, err := base64.URLEncoding.DecodeString(s)
				if err != nil {
					return err
				}

				decryptedData, err := decryptFunc(s)
				if err != nil {
					return err
				}

				data[k] = string(decryptedData)
			}
		case map[string]interface{}:
			err := d.decryptJSON(t, decryptFunc)
			if err != nil {
				return err
			}
		}
	}

	return nil
}
72640
func decryptReader(r io.Reader, config *Config) *decReader {
	return &decReader{
		config:    *config,
		src:       r,
		firstRead: true,
	}
}
1153947
func (v *AzureKeyVaultSeal) 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", "azurekeyvault", "decrypt", "time"}, now)

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

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

	if in == nil {
		return nil, errors.New("given input for decryption is nil")
	}

	if in.KeyInfo == nil {
		return nil, errors.New("key info is nil")
	}

	// Unwrap the key
	params := keyvault.KeyOperationsParameters{
		Algorithm: keyvault.RSAOAEP256,
		Value:     to.StringPtr(string(in.KeyInfo.WrappedKey)),
	}
	resp, err := v.client.UnwrapKey(ctx, v.buildBaseURL(), v.keyName, in.KeyInfo.KeyID, params)
	if err != nil {
		return nil, err
	}

	keyBytes, err := base64.URLEncoding.WithPadding(base64.NoPadding).DecodeString(to.String(resp.Result))
	if err != nil {
		return nil, err
	}
	envInfo := &seal.EnvelopeInfo{
		Key:        keyBytes,
		IV:         in.IV,
		Ciphertext: in.Ciphertext,
	}
	return seal.NewEnvelope().Decrypt(envInfo)
}
266620
func Decrypt(ciphertext []byte, key *[32]byte) (plaintext []byte, err error) {
	block, err := aes.NewCipher(key[:])
	if err != nil {
		return nil, err
	}

	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}

	if len(ciphertext) < gcm.NonceSize() {
		return nil, errors.New("malformed ciphertext")
	}

	return gcm.Open(nil,
		ciphertext[:gcm.NonceSize()],
		ciphertext[gcm.NonceSize():],
		nil,
	)
}
244594
func Decrypt(priv *PrivateKey, in []byte) ([]byte, error) {
	// IV + Curve params/X/Y + 1 block + HMAC-256
	if len(in) < aes.BlockSize+70+aes.BlockSize+sha256.Size {
		return nil, errInputTooShort
	}

	// read iv
	iv := in[:aes.BlockSize]
	offset := aes.BlockSize

	// start reading pubkey
	if !bytes.Equal(in[offset:offset+2], ciphCurveBytes[:]) {
		return nil, errUnsupportedCurve
	}
	offset += 2

	if !bytes.Equal(in[offset:offset+2], ciphCoordLength[:]) {
		return nil, errInvalidXLength
	}
	offset += 2

	xBytes := in[offset : offset+32]
	offset += 32

	if !bytes.Equal(in[offset:offset+2], ciphCoordLength[:]) {
		return nil, errInvalidYLength
	}
	offset += 2

	yBytes := in[offset : offset+32]
	offset += 32

	pb := make([]byte, 65)
	pb[0] = byte(0x04) // uncompressed
	copy(pb[1:33], xBytes)
	copy(pb[33:], yBytes)
	// check if (X, Y) lies on the curve and create a Pubkey if it does
	pubkey, err := ParsePubKey(pb, S256())
	if err != nil {
		return nil, err
	}

	// check for cipher text length
	if (len(in)-aes.BlockSize-offset-sha256.Size)%aes.BlockSize != 0 {
		return nil, errInvalidPadding // not padded to 16 bytes
	}

	// read hmac
	messageMAC := in[len(in)-sha256.Size:]

	// generate shared secret
	ecdhKey := GenerateSharedSecret(priv, pubkey)
	derivedKey := sha512.Sum512(ecdhKey)
	keyE := derivedKey[:32]
	keyM := derivedKey[32:]

	// verify mac
	hm := hmac.New(sha256.New, keyM)
	hm.Write(in[:len(in)-sha256.Size]) // everything is hashed
	expectedMAC := hm.Sum(nil)
	if !hmac.Equal(messageMAC, expectedMAC) {
		return nil, ErrInvalidMAC
	}

	// start decryption
	block, err := aes.NewCipher(keyE)
	if err != nil {
		return nil, err
	}
	mode := cipher.NewCBCDecrypter(block, iv)
	// same length as ciphertext
	plaintext := make([]byte, len(in)-offset-sha256.Size)
	mode.CryptBlocks(plaintext, in[offset:len(in)-sha256.Size])

	return removePKCSPadding(plaintext)
}
886479
func (secret SecretKey) Decrypt(mechanism pkcs11.Mechanism, ciphertext []byte) ([]byte, error) {
	s := secret.session
	s.Lock()
	defer s.Unlock()
	err := s.ctx.DecryptInit(s.handle, []*pkcs11.Mechanism{&mechanism}, secret.objectHandle)
	if err != nil {
		return nil, err
	}
	out, err := s.ctx.Decrypt(s.handle, ciphertext)
	if err != nil {
		return nil, err
	}
	return out, nil
}
1149236
func (d DirectDecrypt) Decrypt() ([]byte, error) {
	cek := make([]byte, len(d.Key))
	copy(cek, d.Key)
	return cek, nil
}
829844
func (kp *kmsKeyHandler) DecryptKey(key []byte) ([]byte, error) {
	out, err := kp.kms.Decrypt(&kms.DecryptInput{
		EncryptionContext: map[string]*string(kp.CipherData.MaterialDescription),
		CiphertextBlob:    key,
		GrantTokens:       []*string{},
	})
	if err != nil {
		return nil, err
	}
	return out.Plaintext, nil
}