// Decrypt decrypts encrypted content info for recipient cert and private key
423488
func (p7 *PKCS7) Decrypt(cert *x509.Certificate, pk crypto.PrivateKey) ([]byte, error) {
	data, ok := p7.raw.(envelopedData)
	if !ok {
		return nil, ErrNotEncryptedContent
	}
	recipient := selectRecipientForCertificate(data.RecipientInfos, cert)
	if recipient.EncryptedKey == nil {
		return nil, errors.New("pkcs7: no enveloped recipient for provided certificate")
	}
	if priv := pk.(*rsa.PrivateKey); priv != nil {
		var contentKey []byte
		contentKey, err := rsa.DecryptPKCS1v15(rand.Reader, priv, recipient.EncryptedKey)
		if err != nil {
			return nil, err
		}
		return data.EncryptedContentInfo.decrypt(contentKey)
	}
	fmt.Printf("Unsupported Private Key: %v\n", pk)
	return nil, ErrUnsupportedAlgorithm
}
956688
func Decrypt(password string, encrypted []byte) (plaintext []byte, err error) {
	// Pull apart packet.
	pkt := encrypted
	if len(pkt) < 1+8+4+2*aes.BlockSize+sha1.Size {
		return nil, fmt.Errorf("encrypted packet too short")
	}
	vers, pkt := pkt[:1], pkt[1:]
	salt, pkt := pkt[:8], pkt[8:]
	hash, pkt := pkt[:4], pkt[4:]
	iv, pkt := pkt[:aes.BlockSize], pkt[aes.BlockSize:]
	enc, sig := pkt[:len(pkt)-sha1.Size], pkt[len(pkt)-sha1.Size:]

	if vers[0] != version || len(enc)%aes.BlockSize != 0 {
		return nil, fmt.Errorf("malformed encrypted packet")
	}

	// Derive key and check against hash.
	aesKey, hmacKey, keyHash := deriveKey(password, salt)
	if !bytes.Equal(hash, keyHash) {
		return nil, fmt.Errorf("incorrect password - %x vs %x", hash, keyHash)
	}

	// Verify signature.
	h := hmac.New(sha1.New, hmacKey)
	h.Write(encrypted[:len(encrypted)-len(sig)])
	if !bytes.Equal(sig, h.Sum(nil)) {
		return nil, fmt.Errorf("cannot authenticate encrypted packet")
	}

	// Decrypt.
	aesBlock, err := aes.NewCipher(aesKey)
	if err != nil {
		// Cannot happen - key is right size.
		panic("aes: " + err.Error())
	}
	m := cipher.NewCBCDecrypter(aesBlock, iv)
	dec := make([]byte, len(enc))
	m.CryptBlocks(dec, enc)

	// Unpad.
	pad := dec[len(dec)-1]
	if pad <= 0 || pad > aes.BlockSize {
		return nil, fmt.Errorf("malformed packet padding")
	}
	for _, b := range dec[len(dec)-int(pad):] {
		if b != pad {
			return nil, fmt.Errorf("malformed packet padding")
		}
	}
	dec = dec[:len(dec)-int(pad)]

	// Success!
	return dec, nil
}
1329068
func (m MultiDecrypter) Decrypt(r api.MaybeEncryptedRecord) ([]byte, error) {
	decrypters, ok := m.decrypters[r.Algorithm]
	if !ok {
		return nil, fmt.Errorf("cannot decrypt record encrypted using %s",
			api.MaybeEncryptedRecord_Algorithm_name[int32(r.Algorithm)])
	}
	var rerr error
	for _, d := range decrypters {
		result, err := d.Decrypt(r)
		if err == nil {
			return result, nil
		}
		rerr = err
	}
	return nil, rerr
}
525871
func Decrypt(encryptd []byte, decrypter Decrypter) ([]byte, error) {
	if decrypter == nil {
		return nil, ErrCannotDecrypt{msg: "no decrypter specified"}
	}
	r := api.MaybeEncryptedRecord{}
	if err := proto.Unmarshal(encryptd, &r); err != nil {
		// nope, this wasn't marshalled as a MaybeEncryptedRecord
		return nil, ErrCannotDecrypt{msg: "unable to unmarshal as MaybeEncryptedRecord"}
	}
	plaintext, err := decrypter.Decrypt(r)
	if err != nil {
		return nil, ErrCannotDecrypt{msg: err.Error()}
	}
	return plaintext, nil
}
1172787
func (e RSA) Decrypt(key interface{}, ciphertextEl *etree.Element) ([]byte, error) {
	rsaKey, err := validateRSAKey(key, ciphertextEl)
	if err != nil {
		return nil, err
	}

	ciphertext, err := getCiphertext(ciphertextEl)
	if err != nil {
		return nil, err
	}

	{
		digestMethodEl := ciphertextEl.FindElement("./EncryptionMethod/DigestMethod")
		if digestMethodEl == nil {
			return nil, fmt.Errorf("cannot find required DigestMethod element")
		}
		hashAlgorithmStr := digestMethodEl.SelectAttrValue("Algorithm", "")
		digestMethod, ok := digestMethods[hashAlgorithmStr]
		if !ok {
			return nil, ErrAlgorithmNotImplemented(hashAlgorithmStr)
		}
		e.DigestMethod = digestMethod
	}

	return e.keyDecrypter(e, rsaKey, ciphertext)
}
734402
func (x *XC) decryptSessionKey(ctx context.Context, hdr *xcpb.Header) ([]byte, error) {
	// find a suiteable decryption key, i.e. a recipient entry which was encrypted
	// for one of our private keys
	recp, err := x.findDecryptionKey(hdr)
	if err != nil {
		return nil, errors.Wrapf(err, "unable to find decryption key")
	}

	// we need the senders public key to decrypt/verify the message, since the
	// box algorithm ties successful decryption to successful verification
	sender, err := x.findPublicKey(hdr.Sender)
	if err != nil {
		return nil, errors.Wrapf(err, "unable to find sender pub key for signature verification: %s", hdr.Sender)
	}

	// unlock recipient key
	if err := x.decryptPrivateKey(ctx, recp); err != nil {
		return nil, err
	}

	// this is the per recipient ciphertext, we need to decrypt it to extract
	// the session key
	ciphertext := hdr.Recipients[recp.Fingerprint()]

	// since box works with byte arrays (or: pointers thereof) we need to copy
	// the slice to fixed arrays
	var nonce [24]byte
	copy(nonce[:], ciphertext[:24])

	var privKey [32]byte
	pk := recp.PrivateKey()
	copy(privKey[:], pk[:])

	// now we can try to decrypt/verify the ciphertext. unfortunately box doesn't give
	// us any diagnostic information in case it fails, i.e. we can't discern between
	// a failed decryption and a failed verification
	decrypted, ok := box.Open(nil, ciphertext[24:], &nonce, &sender.PublicKey, &privKey)
	if !ok {
		return nil, fmt.Errorf("failed to decrypt session key")
	}
	return decrypted, nil
}
174766
func (handle *ContextHandle) Decrypt(session mPkcs11.SessionHandle, cypher []byte) ([]byte, error) {

	handle.lock.RLock()
	defer handle.lock.RUnlock()

	return handle.ctx.Decrypt(session, cypher)
}
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
}
552158
func (el EncryptedMerkleLeaf) Decrypt(codec kbfscodec.Codec,
	privKey kbfscrypto.TLFPrivateKey, nonce *[24]byte,
	ePubKey kbfscrypto.TLFEphemeralPublicKey) (MerkleLeaf, error) {
	eLeaf := kbfscrypto.MakeEncryptedMerkleLeaf(
		el.Version, el.EncryptedData, nonce)
	leafBytes, err := kbfscrypto.DecryptMerkleLeaf(privKey, ePubKey, eLeaf)
	if err != nil {
		return MerkleLeaf{}, err
	}
	// decode the leaf
	var leaf MerkleLeaf
	if err := codec.Decode(leafBytes, &leaf); err != nil {
		return MerkleLeaf{}, err
	}
	return leaf, 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
}
906049
func decryptPEMBlock(c *Client, block *pem.Block, path string, key []byte) ([]byte, error) {
	fileurl := fmt.Sprintf("cert:///%s", filepath.ToSlash(path))
	url, err := url.Parse(fileurl)
	if err != nil {
		return nil, err
	}
	credHelper, input := c.credHelperContext.GetCredentialHelper(nil, url)

	input["username"] = ""

	creds, err := credHelper.Fill(input)
	if err != nil {
		tracerx.Printf("Error filling credentials for %q: %v", fileurl, err)
		return nil, err
	}
	pass := creds["password"]
	decrypted, err := x509.DecryptPEMBlock(block, []byte(pass))
	if err != nil {
		credHelper.Reject(creds)
		return nil, err
	}
	credHelper.Approve(creds)

	// decrypted is a DER blob, but we need a PEM-encoded block.
	toEncode := &pem.Block{Type: block.Type, Headers: nil, Bytes: decrypted}
	buf := pem.EncodeToMemory(toEncode)
	return buf, nil
}
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)
}
469677
func (k NaclDHKeyPair) Decrypt(nei *NaclEncryptionInfo) (plaintext []byte, sender keybase1.KID, err error) {
	if k.Private == nil {
		err = NoSecretKeyError{}
		return
	}
	if nei.EncryptionType != kbcrypto.KIDNaclDH {
		err = DecryptBadPacketTypeError{}
		return
	}
	var nonce [NaclDHNonceSize]byte
	if len(nei.Nonce) != NaclDHNonceSize {
		err = DecryptBadNonceError{}
		return
	}
	copy(nonce[:], nei.Nonce)

	var gk GenericKey
	if gk, err = ImportKeypairFromKID(keybase1.KIDFromSlice(nei.Sender)); err != nil {
		return
	}

	var senderDH NaclDHKeyPair
	var ok bool
	if senderDH, ok = gk.(NaclDHKeyPair); !ok {
		err = DecryptBadSenderError{}
		return
	}

	rkid := keybase1.KIDFromSlice(nei.Receiver)
	if k.GetKID().NotEqual(rkid) {
		err = DecryptWrongReceiverError{}
		return
	}

	if plaintext, ok = box.Open(plaintext, nei.Ciphertext, &nonce,
		((*[32]byte)(&senderDH.Public)), ((*[32]byte)(k.Private))); !ok {
		err = DecryptOpenError{}
		return
	}
	sender = senderDH.GetKID()
	return
}
1239509
func (a *AES256Decrypter) Decrypt(ed []byte) ([]byte, error) {
	var aesKey *AES256Key
	var ciphertext []byte
	var err error

	ciphertext, aesKey, err = parseMsg(a.Passphrase, ed)
	if err != nil {
		return nil, err
	}

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

	if len(ciphertext) < aes.BlockSize {
		return nil, errors.New("Ciphertext too short")
	}

	iv := ciphertext[:aes.BlockSize]
	ciphertext = ciphertext[aes.BlockSize:]
	stream := cipher.NewCFBDecrypter(block, iv)
	stream.XORKeyStream(ciphertext, ciphertext)

	return ciphertext, nil
}
491489
func (s *secureSession) Decrypt(r io.Reader) (io.Reader, error) {
	var buf bytes.Buffer
	for {
		var length uint16
		if err := binary.Read(r, binary.LittleEndian, &length); err != nil {
			if err == io.EOF {
				break
			}
			return nil, err
		}

		if length > PacketLengthMax {
			return nil, fmt.Errorf("Packet size too big %d", length)
		}

		var b = make([]byte, length)
		if err := binary.Read(r, binary.LittleEndian, &b); err != nil {
			return nil, err
		}

		var mac [16]byte
		if err := binary.Read(r, binary.LittleEndian, &mac); err != nil {
			return nil, err
		}

		var nonce [8]byte
		binary.LittleEndian.PutUint64(nonce[:], s.decryptCount)
		s.decryptCount++

		lengthBytes := make([]byte, 2)
		binary.LittleEndian.PutUint16(lengthBytes, uint16(length))

		decrypted, err := chacha20poly1305.DecryptAndVerify(s.decryptKey[:], nonce[:], b, mac, lengthBytes)

		if err != nil {
			return nil, fmt.Errorf("Data encryption failed %s", err)
		}

		buf.Write(decrypted)

		// Finish when all bytes fit in b
		if length < PacketLengthMax {
			break
		}
	}

	return &buf, nil
}
712595
func (m *Mocker) Decrypt(ctx context.Context, ciphertext []byte) ([]byte, error) {
	return ciphertext, nil
}
1131513
func (priv *PrivateKey) Decrypt(rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error) {
	if opts == nil {
		return DecryptPKCS1v15(rand, priv, ciphertext)
	}

	switch opts := opts.(type) {
	case *OAEPOptions:
		return DecryptOAEP(opts.Hash.New(), rand, priv, ciphertext, opts.Label)

	case *PKCS1v15DecryptOptions:
		if l := opts.SessionKeyLen; l > 0 {
			plaintext = make([]byte, l)
			if _, err := io.ReadFull(rand, plaintext); err != nil {
				return nil, err
			}
			if err := DecryptPKCS1v15SessionKey(rand, priv, ciphertext, plaintext); err != nil {
				return nil, err
			}
			return plaintext, nil
		} else {
			return DecryptPKCS1v15(rand, priv, ciphertext)
		}

	default:
		return nil, errors.New("crypto/rsa: invalid options for Decrypt")
	}
}