// SessionEncryptMessage encrypts a given plaintext in a WhisperMessage or a PreKeyWhisperMessage,
// depending on whether there a session with the peer exists or needs to be established.
548349
func (sc *SessionCipher) SessionEncryptMessage(plaintext []byte) ([]byte, int32, error) {
	sc.SessionStore.Lock()
	defer sc.SessionStore.Unlock()

	sr, err := sc.SessionStore.LoadSession(sc.RecipientID, sc.DeviceID)
	if err != nil {
		return nil, 0, err
	}
	ss := sr.sessionState
	chainKey := ss.getSenderChainKey()
	messageKeys, err := chainKey.getMessageKeys()
	if err != nil {
		return nil, 0, err
	}
	senderEphemeral := ss.getSenderRatchetKey()
	previousCounter := ss.getPreviousCounter()
	ciphertext, err := Encrypt(messageKeys.CipherKey, messageKeys.Iv, plaintext)
	if err != nil {
		return nil, 0, err
	}
	version := ss.getSessionVersion()

	wm, err := newWhisperMessage(byte(version), messageKeys.MacKey, senderEphemeral, chainKey.Index,
		previousCounter, ciphertext, ss.getLocalIdentityPublic(), ss.getRemoteIdentityPublic())
	if err != nil {
		return nil, 0, err
	}
	msg := wm.serialize()
	msgType := int32(textsecure.Envelope_CIPHERTEXT)

	if ss.hasUnacknowledgedPreKeyMessage() {
		items := ss.getUnacknowledgedPreKeyMessageItems()
		pkwm, err := newPreKeyWhisperMessage(byte(version), ss.getLocalRegistrationID(),
			items.preKeyID, uint32(items.signedPreKeyID), items.baseKey,
			ss.getLocalIdentityPublic(), wm)
		if err != nil {
			return nil, 0, nil
		}
		msg = pkwm.serialize()
		msgType = int32(textsecure.Envelope_PREKEY_BUNDLE)
	}

	ss.setSenderChainKey(chainKey.getNextChainKey())
	err = sc.SessionStore.StoreSession(sc.RecipientID, sc.DeviceID, sr)
	if err != nil {
		return nil, 0, err
	}

	return msg, msgType, nil
}
1086626
func (c *Ctx) DecryptDigestUpdate(sh SessionHandle, cipher []byte) ([]byte, error) {
	var (
		part    C.CK_BYTE_PTR
		partlen C.CK_ULONG
	)
	e := C.DecryptDigestUpdate(c.ctx, C.CK_SESSION_HANDLE(sh), cMessage(cipher), C.CK_ULONG(len(cipher)), &part, &partlen)
	if toError(e) != nil {
		return nil, toError(e)
	}
	h := C.GoBytes(unsafe.Pointer(part), C.int(partlen))
	C.free(unsafe.Pointer(part))
	return h, nil
}
609652
func (c *Ctx) Encrypt(sh SessionHandle, message []byte) ([]byte, error) {
	var (
		enc    C.CK_BYTE_PTR
		enclen C.CK_ULONG
	)
	e := C.Encrypt(c.ctx, C.CK_SESSION_HANDLE(sh), cMessage(message), C.CK_ULONG(len(message)), &enc, &enclen)
	if toError(e) != nil {
		return nil, toError(e)
	}
	s := C.GoBytes(unsafe.Pointer(enc), C.int(enclen))
	C.free(unsafe.Pointer(enc))
	return s, nil
}
1123949
func EncryptBytes(data, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}
	nonce, err := CreateRandBytes(uint32(gcm.NonceSize()))
	if err != nil {
		return nil, err
	}
	return gcm.Seal(nonce, nonce, data, nil), nil
}
643904
func privateEncrypt(key *rsa.PrivateKey, data []byte) (enc []byte, err error) {
	k := (key.N.BitLen() + 7) / 8
	tLen := len(data)

	// rfc2313, section 8:
	// The length of the data D shall not be more than k-11 octets
	if tLen > k-11 {
		err = errors.New("Data too long")
		return
	}
	em := make([]byte, k)
	em[1] = 1
	for i := 2; i < k-tLen-1; i++ {
		em[i] = 0xff
	}
	copy(em[k-tLen:k], data)
	c := new(big.Int).SetBytes(em)
	if c.Cmp(key.N) > 0 {
		err = nil
		return
	}
	var m *big.Int
	var ir *big.Int
	if key.Precomputed.Dp == nil {
		m = new(big.Int).Exp(c, key.D, key.N)
	} else {
		// We have the precalculated values needed for the CRT.
		m = new(big.Int).Exp(c, key.Precomputed.Dp, key.Primes[0])
		m2 := new(big.Int).Exp(c, key.Precomputed.Dq, key.Primes[1])
		m.Sub(m, m2)
		if m.Sign() < 0 {
			m.Add(m, key.Primes[0])
		}
		m.Mul(m, key.Precomputed.Qinv)
		m.Mod(m, key.Primes[0])
		m.Mul(m, key.Primes[1])
		m.Add(m, m2)

		for i, values := range key.Precomputed.CRTValues {
			prime := key.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, key.N)
	}
	enc = m.Bytes()
	return
}
586406
func NewSessionCipher(identityStore IdentityStore, preKeyStore PreKeyStore, signedPreKeyStore SignedPreKeyStore, sessionStore SessionStore, recipientID string, deviceID uint32) *SessionCipher {
	return &SessionCipher{
		RecipientID:  recipientID,
		DeviceID:     deviceID,
		SessionStore: sessionStore,
		PreKeyStore:  preKeyStore,
		Builder:      NewSessionBuilder(identityStore, preKeyStore, signedPreKeyStore, sessionStore, recipientID, deviceID),
	}
}
828590
func Encrypt(data []byte, key []byte) []byte {
	if data == nil || len(data) == 0 {
		return data
	}
	return toBytes(encrypt(toUint32s(data, true), toUint32s(key, false)), false)
}
1322579
func (b *AESGCMBarrier) encrypt(path string, term uint32, gcm cipher.AEAD, plain []byte) ([]byte, error) {
	// Allocate the output buffer with room for tern, version byte,
	// nonce, GCM tag and the plaintext
	capacity := termSize + 1 + gcm.NonceSize() + gcm.Overhead() + len(plain)
	size := termSize + 1 + gcm.NonceSize()
	out := make([]byte, size, capacity)

	// Set the key term
	binary.BigEndian.PutUint32(out[:4], term)

	// Set the version byte
	out[4] = b.currentAESGCMVersionByte

	// Generate a random nonce
	nonce := out[5 : 5+gcm.NonceSize()]
	n, err := rand.Read(nonce)
	if err != nil {
		return nil, err
	}
	if n != len(nonce) {
		return nil, errors.New("unable to read enough random bytes to fill gcm nonce")
	}

	// Seal the output
	switch b.currentAESGCMVersionByte {
	case AESGCMVersion1:
		out = gcm.Seal(out, nonce, plain, nil)
	case AESGCMVersion2:
		aad := []byte(nil)
		if path != "" {
			aad = []byte(path)
		}
		out = gcm.Seal(out, nonce, plain, aad)
	default:
		panic("Unknown AESGCM version")
	}

	return out, nil
}
39559
func (p *PrivateKey) Encrypt(passphrase string) error {
	p.Salt = make([]byte, saltLength)
	if n, err := crypto_rand.Read(p.Salt); err != nil || n < len(p.Salt) {
		return err
	}
	secretKey := p.deriveKey(passphrase)

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

	p.EncryptedData = secretbox.Seal(nil, p.privateKey[:], &nonce, &secretKey)
	return nil
}
674390
func (s *AddOutputRequest) SetEncryption(v *Encryption) *AddOutputRequest {
	s.Encryption = v
	return s
}
493921
func (c *Conversation) sigMessage() ([]byte, error) {
	c.ake.keys.ourKeyID++

	encryptedSig, err := c.generateEncryptedSignature(&c.ake.sigKey)
	if err != nil {
		return nil, err
	}

	macSig := sumHMAC(c.ake.sigKey.m2, encryptedSig, c.version)
	sigMsg := sig{
		encryptedSig: encryptedSig,
		macSig:       macSig,
	}

	return sigMsg.serialize(c.version), nil
}
66592
func (c *Cipher) Encrypt64(dst, src []uint64) {
    c.encrypt(src, dst)
}
299536
func (s *SecurityConfiguration) SetEncryptionConfiguration(v *EncryptionConfiguration) *SecurityConfiguration {
	s.EncryptionConfiguration = v
	return s
}
256305
func (engine *CryptoEngine) NewEncryptedMessage(msg message) (EncryptedMessage, error) {

	m := EncryptedMessage{}

	// derive nonce
	nonce, err := deriveNonce(engine.nonceKey, engine.salt, engine.context, engine.fetchAndIncrement())
	if err != nil {
		return m, err
	}

	m.nonce = nonce

	encryptedData := secretbox.Seal(nil, msg.toBytes(), &m.nonce, &engine.secretKey)

	// assign the encrypted data to the message
	m.data = encryptedData

	// calculate the overall size of the message
	m.length = uint64(len(m.data) + len(m.nonce) + 8)

	return m, nil

}
957637
func (s *ServerConfig) EncryptBytes() ([]byte, error) {
	return base64.StdEncoding.DecodeString(s.EncryptKey)
}
177213
func Encrypt(plaintext []byte, encrypter Encrypter) ([]byte, error) {
	if encrypter == nil {
		return nil, fmt.Errorf("no encrypter specified")
	}

	encryptedRecord, err := encrypter.Encrypt(plaintext)
	if err != nil {
		return nil, errors.Wrap(err, "unable to encrypt data")
	}

	data, err := proto.Marshal(encryptedRecord)
	if err != nil {
		return nil, errors.Wrap(err, "unable to marshal as MaybeEncryptedRecord")
	}

	return data, nil
}
1260859
func (e MultiEncrypt) Encrypt(plaintext []byte) (*Message, error) {
	bk, err := e.KeyGenerator.KeyGenerate()
	if err != nil {
		if debug.Enabled {
			debug.Printf("Failed to generate key: %s", err)
		}
		return nil, errors.Wrap(err, "failed to generate key")
	}
	cek := bk.Bytes()

	if debug.Enabled {
		debug.Printf("Encrypt: generated cek len = %d", len(cek))
	}

	protected := NewEncodedHeader()
	protected.Set("enc", e.ContentEncrypter.Algorithm())

	// In JWE, multiple recipients may exist -- they receive an
	// encrypted version of the CEK, using their key encryption
	// algorithm of choice.
	recipients := make([]Recipient, len(e.KeyEncrypters))
	for i, enc := range e.KeyEncrypters {
		r := NewRecipient()
		r.Header.Set("alg", enc.Algorithm())
		if v := enc.Kid(); v != "" {
			r.Header.Set("kid", v)
		}
		enckey, err := enc.KeyEncrypt(cek)
		if err != nil {
			if debug.Enabled {
				debug.Printf("Failed to encrypt key: %s", err)
			}
			return nil, errors.Wrap(err, `failed to encrypt key`)
		}
		r.EncryptedKey = enckey.Bytes()
		if hp, ok := enckey.(HeaderPopulater); ok {
			hp.HeaderPopulate(r.Header)
		}
		if debug.Enabled {
			debug.Printf("Encrypt: encrypted_key = %x (%d)", enckey.Bytes(), len(enckey.Bytes()))
		}
		recipients[i] = *r
	}

	// If there's only one recipient, you want to include that in the
	// protected header
	if len(recipients) == 1 {
		protected.Header, err = protected.Header.Merge(recipients[0].Header)
		if err != nil {
			return nil, errors.Wrap(err, "failed to merge protected headers")
		}
	}

	aad, err := protected.Base64Encode()
	if err != nil {
		return nil, errors.Wrap(err, "failed to base64 encode protected headers")
	}

	// ...on the other hand, there's only one content cipher.
	iv, ciphertext, tag, err := e.ContentEncrypter.Encrypt(cek, plaintext, aad)
	if err != nil {
		if debug.Enabled {
			debug.Printf("Failed to encrypt: %s", err)
		}
		return nil, errors.Wrap(err, "failed to encrypt payload")
	}

	if debug.Enabled {
		debug.Printf("Encrypt.Encrypt: cek        = %x (%d)", cek, len(cek))
		debug.Printf("Encrypt.Encrypt: aad        = %x", aad)
		debug.Printf("Encrypt.Encrypt: ciphertext = %x", ciphertext)
		debug.Printf("Encrypt.Encrypt: iv         = %x", iv)
		debug.Printf("Encrypt.Encrypt: tag        = %x", tag)
	}

	msg := NewMessage()
	msg.AuthenticatedData.Base64Decode(aad)
	msg.CipherText = ciphertext
	msg.InitializationVector = iv
	msg.ProtectedHeader = protected
	msg.Recipients = recipients
	msg.Tag = tag

	return msg, nil
}