// Encrypt seed for receiverKeys. Use senderKey to encrypt.
// Does not use the keyring at all. Attached for organizational purposes.
// Used when creating a new seed.
332888
func (s *PerUserKeyring) PrepareBoxesForDevices(m MetaContext, contents PerUserKeySeed,
	generation keybase1.PerUserKeyGeneration, receiverKeys []NaclDHKeyPair,
	senderKey GenericKey) (boxes []keybase1.PerUserKeyBox, err error) {
	// Do not lock self because we do not use self.

	if contents.IsBlank() {
		return nil, errors.New("attempt to box blank per-user-key")
	}

	senderKeyDH, ok := senderKey.(NaclDHKeyPair)
	if !ok {
		return nil, fmt.Errorf("Unexpected encryption key type: %T", senderKey)
	}

	for _, receiverKey := range receiverKeys {
		box, err := NewPerUserKeyBox(contents, receiverKey, senderKeyDH, generation)
		if err != nil {
			return nil, err
		}
		boxes = append(boxes, box)
	}
	return boxes, nil
}
249385
func (kw EcdhesKeyWrapDecrypt) KeyDecrypt(enckey []byte) ([]byte, error) {
	var keysize uint32
	switch kw.algorithm {
	case jwa.ECDH_ES_A128KW:
		keysize = 16
	case jwa.ECDH_ES_A192KW:
		keysize = 24
	case jwa.ECDH_ES_A256KW:
		keysize = 32
	default:
		return nil, errors.Wrap(ErrUnsupportedAlgorithm, "invalid ECDH-ES key wrap algorithm")
	}

	privkey := kw.privkey
	pubkey := kw.pubkey

	pubinfo := make([]byte, 4)
	binary.BigEndian.PutUint32(pubinfo, keysize*8)

	z, _ := privkey.PublicKey.Curve.ScalarMult(pubkey.X, pubkey.Y, privkey.D.Bytes())
	kdf := concatkdf.New(crypto.SHA256, []byte(kw.algorithm.String()), z.Bytes(), kw.apu, kw.apv, pubinfo, []byte{})
	kek := make([]byte, keysize)
	kdf.Read(kek)

	block, err := aes.NewCipher(kek)
	if err != nil {
		return nil, errors.Wrap(err, "failed to create cipher for ECDH-ES key wrap")
	}

	return keyunwrap(block, enckey)
}
788051
func (e *EMECipher) Encrypt(tweak []byte, inputData []byte) []byte {
	return Transform(e.bc, tweak, inputData, DirectionEncrypt)
}
1135883
func (es *EncryptionService) Encrypt(ctx context.Context, plaintext string) (c *CipherText, resp *APIResponse, err error) {

	c = &CipherText{}
	_, resp, err = es.client.postAction(ctx, &APIClientRequest{
		Path:         "admin/encrypt",
		ResponseBody: c,
		RequestBody: &map[string]string{
			"value": plaintext,
		},
		APIVersion: apiV1,
	})

	return
}
487722
func masterFromPreMasterSecret(version uint16, suite *cipherSuite, preMasterSecret, clientRandom, serverRandom []byte) []byte {
	seed := make([]byte, 0, len(clientRandom)+len(serverRandom))
	seed = append(seed, clientRandom...)
	seed = append(seed, serverRandom...)

	masterSecret := make([]byte, masterSecretLength)
	prfForVersion(version, suite)(masterSecret, preMasterSecret, masterSecretLabel, seed)
	return masterSecret
}
1174638
func (p *V1) Encrypt(key []byte, payload interface{}, footer interface{}) (string, error) {
	payloadBytes, err := infToByteArr(payload)
	if err != nil {
		return "", errors.Wrap(err, "failed to encode payload to []byte")
	}

	footerBytes, err := infToByteArr(footer)
	if err != nil {
		return "", errors.Wrap(err, "failed to encode footer to []byte")
	}

	var rndBytes []byte

	if p.nonce != nil {
		rndBytes = p.nonce
	} else {
		rndBytes = make([]byte, nonceSize)
		if _, err := io.ReadFull(rand.Reader, rndBytes); err != nil {
			return "", errors.Wrap(err, "failed to read from rand.Reader")
		}
	}

	macN := hmac.New(sha512.New384, rndBytes)
	if _, err := macN.Write(payloadBytes); err != nil {
		return "", errors.Wrap(err, "failed to hash payload")
	}
	nonce := macN.Sum(nil)[:32]

	encKey, authKey, err := splitKey(key, nonce[:16])
	if err != nil {
		return "", errors.Wrap(err, "failed to create enc and auth keys")
	}

	block, err := aes.NewCipher(encKey)
	if err != nil {
		return "", errors.Wrap(err, "failed to create aes cipher")
	}

	encryptedPayload := make([]byte, len(payloadBytes))
	cipher.NewCTR(block, nonce[16:]).XORKeyStream(encryptedPayload, payloadBytes)

	h := hmac.New(sha512.New384, authKey)
	if _, err := h.Write(preAuthEncode(headerV1, nonce, encryptedPayload, footerBytes)); err != nil {
		return "", errors.Wrap(err, "failed to create a signature")
	}

	mac := h.Sum(nil)

	body := make([]byte, 0, len(nonce)+len(encryptedPayload)+len(mac))
	body = append(body, nonce...)
	body = append(body, encryptedPayload...)
	body = append(body, mac...)

	return createToken(headerV1, body, footerBytes), nil
}
928774
func EncryptString(str, key string) string {
	s := []byte(str)
	k := []byte(key)
	b64 := base64.StdEncoding
	return b64.EncodeToString(Encrypt(s, k))
}
891225
func (kw KeyWrapEncrypt) KeyDecrypt(enckey []byte) ([]byte, error) {
	block, err := aes.NewCipher(kw.sharedkey)
	if err != nil {
		return nil, errors.Wrap(err, "failed to create cipher from shared key")
	}

	cek, err := keyunwrap(block, enckey)
	if err != nil {
		return nil, errors.Wrap(err, "failed to unwrap data")
	}
	return cek, nil
}
526426
func (x *XC) encryptForRecipient(ctx context.Context, sender *keyring.PrivateKey, sk []byte, recipient string) ([]byte, error) {
	recp := x.pubring.Get(recipient)
	if recp == nil {
		return nil, fmt.Errorf("recipient public key not available for %s", recipient)
	}

	var recipientPublicKey [32]byte
	copy(recipientPublicKey[:], recp.PublicKey[:])

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

	// we need to copy the byte silces to byte arrays for box
	var senderPrivateKey [32]byte
	pk := sender.PrivateKey()
	copy(senderPrivateKey[:], pk[:])

	var nonce [24]byte
	if _, err := io.ReadFull(crypto_rand.Reader, nonce[:]); err != nil {
		return nil, err
	}

	return box.Seal(nonce[:], sk, &nonce, &recipientPublicKey, &senderPrivateKey), nil
}
755180
func (s *secureSession) Encrypt(r io.Reader) (io.Reader, error) {
	packets := packetsFromBytes(r)
	var buf bytes.Buffer
	for _, p := range packets {
		var nonce [8]byte
		binary.LittleEndian.PutUint64(nonce[:], s.encryptCount)
		s.encryptCount++

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

		encrypted, mac, err := chacha20poly1305.EncryptAndSeal(s.encryptKey[:], nonce[:], p.value, bLength[:])
		if err != nil {
			return nil, err
		}

		buf.Write(bLength[:])
		buf.Write(encrypted)
		buf.Write(mac[:])
	}

	return &buf, nil
}
960328
func (kw EcdhesKeyWrapEncrypt) KeyEncrypt(cek []byte) (ByteSource, error) {
	kg, err := kw.generator.KeyGenerate()
	if err != nil {
		return nil, errors.Wrap(err, "failed to create key generator")
	}

	bwpk, ok := kg.(ByteWithECPrivateKey)
	if !ok {
		return nil, errors.New("key generator generated invalid key (expected ByteWithECPrivateKey)")
	}

	block, err := aes.NewCipher(bwpk.Bytes())
	if err != nil {
		return nil, errors.Wrap(err, "failed to generate cipher from generated key")
	}

	jek, err := keywrap(block, cek)
	if err != nil {
		return nil, errors.Wrap(err, "failed to wrap data")
	}

	bwpk.ByteKey = ByteKey(jek)

	return bwpk, nil
}
957637
func (s *ServerConfig) EncryptBytes() ([]byte, error) {
	return base64.StdEncoding.DecodeString(s.EncryptKey)
}
679711
func (d RSAPKCS15KeyDecrypt) KeyDecrypt(enckey []byte) ([]byte, error) {
	if debug.Enabled {
		debug.Printf("START PKCS.KeyDecrypt")
	}
	// Hey, these notes and workarounds were stolen from go-jose
	defer func() {
		// DecryptPKCS1v15SessionKey sometimes panics on an invalid payload
		// because of an index out of bounds error, which we want to ignore.
		// This has been fixed in Go 1.3.1 (released 2014/08/13), the recover()
		// only exists for preventing crashes with unpatched versions.
		// See: https://groups.google.com/forum/#!topic/golang-dev/7ihX6Y6kx9k
		// See: https://code.google.com/p/go/source/detail?r=58ee390ff31602edb66af41ed10901ec95904d33
		_ = recover()
	}()

	// Perform some input validation.
	expectedlen := d.privkey.PublicKey.N.BitLen() / 8
	if expectedlen != len(enckey) {
		// Input size is incorrect, the encrypted payload should always match
		// the size of the public modulus (e.g. using a 2048 bit key will
		// produce 256 bytes of output). Reject this since it's invalid input.
		return nil, fmt.Errorf(
			"input size for key decrypt is incorrect (expected %d, got %d)",
			expectedlen,
			len(enckey),
		)
	}

	var err error

	bk, err := d.generator.KeyGenerate()
	if err != nil {
		return nil, errors.New("failed to generate key")
	}
	cek := bk.Bytes()

	// When decrypting an RSA-PKCS1v1.5 payload, we must take precautions to
	// prevent chosen-ciphertext attacks as described in RFC 3218, "Preventing
	// the Million Message Attack on Cryptographic Message Syntax". We are
	// therefore deliberatly ignoring errors here.
	err = rsa.DecryptPKCS1v15SessionKey(rand.Reader, d.privkey, enckey, cek)
	if err != nil {
		return nil, errors.Wrap(err, "failed to decrypt via PKCS1v15")
	}

	return cek, nil
}
248703
func (ae *AESEncrypter) Encrypt(data []byte) []byte {
	ret := make([]byte, len(data))
	mode := cipher.NewCBCEncrypter(ae.block, ae.encryptionIV)
	mode.CryptBlocks(ret, data)
	return ret
}
56571
func (c *Cipher) Encrypt(value string) (string, error) {
	ciphertext := make([]byte, aes.BlockSize+len(value))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return "", fmt.Errorf("failed to create initialization vector %s", err)
	}

	stream := cipher.NewCFBEncrypter(c.Block, iv)
	stream.XORKeyStream(ciphertext[aes.BlockSize:], []byte(value))
	return base64.StdEncoding.EncodeToString(ciphertext), nil
}
660174
func (s *EDStore) Encrypt(pbuf *[]byte, data []byte) ([]byte, error) {
	var buf []byte
	// If given a buffer, use that one
	if pbuf != nil {
		buf = *pbuf
	}
	// Make sure size is ok, expand if necessary
	buf = util.EnsureBufBigEnough(buf, 1+s.nonceSize+s.cryptoOverhead+len(data))
	// If buffer was passed, update the reference
	if pbuf != nil {
		*pbuf = buf
	}
	buf[0] = s.code
	copy(buf[1:], s.nonce)
	copy(buf[1+s.nonceSize:], data)
	dst := buf[1+s.nonceSize : 1+s.nonceSize+len(data)]
	ed := s.gcm.Seal(dst[:0], s.nonce, dst, nil)
	for i := s.nonceSize - 1; i >= 0; i-- {
		s.nonce[i]++
		if s.nonce[i] != 0 {
			break
		}
	}
	return buf[:1+s.nonceSize+len(ed)], nil
}
1316550
func (kw KeyWrapEncrypt) KeyEncrypt(cek []byte) (ByteSource, error) {
	block, err := aes.NewCipher(kw.sharedkey)
	if err != nil {
		return nil, errors.Wrap(err, "failed to create cipher from shared key")
	}
	encrypted, err := keywrap(block, cek)
	if err != nil {
		return nil, errors.Wrap(err, `keywrap: failed to wrap key`)
	}
	return ByteKey(encrypted), nil
}