// EncryptFRMPayload encrypts the FRMPayload (slice of bytes).
// Note that EncryptFRMPayload is used for both encryption and decryption.
515232
func EncryptFRMPayload(key AES128Key, uplink bool, devAddr DevAddr, fCnt uint32, data []byte) ([]byte, error) {
	pLen := len(data)
	if pLen%16 != 0 {
		// append with empty bytes so that len(data) is a multiple of 16
		data = append(data, make([]byte, 16-(pLen%16))...)
	}

	block, err := aes.NewCipher(key[:])
	if err != nil {
		return nil, err
	}
	if block.BlockSize() != 16 {
		return nil, errors.New("lorawan: block size of 16 was expected")
	}

	s := make([]byte, 16)
	a := make([]byte, 16)
	a[0] = 0x01
	if !uplink {
		a[5] = 0x01
	}

	b, err := devAddr.MarshalBinary()
	if err != nil {
		return nil, err
	}
	copy(a[6:10], b)
	binary.LittleEndian.PutUint32(a[10:14], uint32(fCnt))

	for i := 0; i < len(data)/16; i++ {
		a[15] = byte(i + 1)
		block.Encrypt(s, a)

		for j := 0; j < len(s); j++ {
			data[i*16+j] = data[i*16+j] ^ s[j]
		}
	}

	return data[0:pLen], nil
}
456759
func (p *V2) 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, chacha.XNonceSize)
		if _, err := io.ReadFull(rand.Reader, rndBytes); err != nil {
			return "", errors.Wrap(err, "failed to read from rand.Reader")
		}
	}

	hash, err := blake2b.New(chacha.XNonceSize, rndBytes)
	if err != nil {
		return "", errors.Wrap(err, "failed to create blake2b hash")
	}
	if _, err := hash.Write(payloadBytes); err != nil {
		return "", errors.Wrap(err, "failed to hash payload")
	}

	nonce := hash.Sum(nil)

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

	encryptedPayload := aead.Seal(payloadBytes[:0], nonce, payloadBytes, preAuthEncode(headerV2, nonce, footerBytes))

	return createToken(headerV2, append(nonce, encryptedPayload...), footerBytes), nil
}
123332
func (s *ServerReplicationParameters) SetEncrypted(v bool) *ServerReplicationParameters {
	s.Encrypted = &v
	return s
}
1220175
func (con *Connection) EncryptedWrite(b []byte) (int, error) {
	var buffer bytes.Buffer
	buffer.Write(b)
	encrypted, err := con.getEncrypter().Encrypt(&buffer)

	if err != nil {
		log.Info.Panic("Encryption failed:", err)
		err = con.connection.Close()
		return 0, err
	}

	encryptedBytes, err := ioutil.ReadAll(encrypted)
	n, err := con.connection.Write(encryptedBytes)

	return n, err
}
670243
func Encrypt(random io.Reader, pub *PublicKey, msg []byte) (c1, c2 *big.Int, err error) {
	pLen := (pub.P.BitLen() + 7) / 8
	if len(msg) > pLen-11 {
		err = errors.New("elgamal: message too long")
		return
	}

	// EM = 0x02 || PS || 0x00 || M
	em := make([]byte, pLen-1)
	em[0] = 2
	ps, mm := em[1:len(em)-len(msg)-1], em[len(em)-len(msg):]
	err = nonZeroRandomBytes(ps, random)
	if err != nil {
		return
	}
	em[len(em)-len(msg)-1] = 0
	copy(mm, msg)

	m := new(big.Int).SetBytes(em)

	k, err := rand.Int(random, pub.P)
	if err != nil {
		return
	}

	c1 = new(big.Int).Exp(pub.G, k, pub.P)
	s := new(big.Int).Exp(pub.Y, k, pub.P)
	c2 = s.Mul(s, m)
	c2.Mod(c2, pub.P)

	return
}
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
}
714500
func EncryptPGPKey(bundle *openpgp.Entity, passphrase string) error {
	passBytes := []byte(passphrase)

	if bundle.PrivateKey != nil && bundle.PrivateKey.PrivateKey != nil {
		// Primary private key exists and is not stubbed.
		if err := bundle.PrivateKey.Encrypt(passBytes, nil); err != nil {
			return err
		}
	}

	for _, subkey := range bundle.Subkeys {
		if subkey.PrivateKey == nil || subkey.PrivateKey.PrivateKey == nil {
			// There has to be a private key and not stubbed.
			continue
		}

		if err := subkey.PrivateKey.Encrypt(passBytes, nil); err != nil {
			return err
		}
	}

	return nil
}
1311283
func (p *PHYPayload) DecryptFRMPayload(key AES128Key) error {
	if err := p.EncryptFRMPayload(key); err != nil {
		return err
	}

	macPL, ok := p.MACPayload.(*MACPayload)
	if !ok {
		return errors.New("lorawan: MACPayload must be of type *MACPayload")
	}

	// the FRMPayload contains MAC commands, which we need to unmarshal
	var err error
	if macPL.FPort != nil && *macPL.FPort == 0 {
		macPL.FRMPayload, err = decodeDataPayloadToMACCommands(p.isUplink(), macPL.FRMPayload)
	}

	return err
}
68000
func (c *Cipher) encrypt(deadline uint64, b []byte) []byte {
	result := make([]byte, c.hdrLen+len(b))
	binary.BigEndian.PutUint64(result[c.sigLen:c.hdrLen], deadline)
	copy(result[c.hdrLen:], b)

	hash := hmac.New(c.hash, c.signKey)
	hash.Write(b)
	hash.Write(result[c.sigLen:c.hdrLen])
	copy(result, hash.Sum(nil)[:c.sigLen])

	return result
}
965921
func (csp *CSP) Encrypt(k bccsp.Key, plaintext []byte, opts bccsp.EncrypterOpts) ([]byte, error) {
	// Validate arguments
	if k == nil {
		return nil, errors.New("Invalid Key. It must not be nil.")
	}

	encryptor, found := csp.Encryptors[reflect.TypeOf(k)]
	if !found {
		return nil, errors.Errorf("Unsupported 'EncryptKey' provided [%v]", k)
	}

	return encryptor.Encrypt(k, plaintext, opts)
}
329687
func Aes128CFBEncrypt(key [16]byte, plainReader io.Reader) (cipherReader io.Reader, err error) {
	return aesCFBEnc(key[:], plainReader)
}
110193
func LoadCertificateFromPEMBytes(pemBytes []byte) (*Certificate, error) {
	block, _ := pem.Decode(pemBytes)
	if block == nil {
		return nil, fmt.Errorf("Unable to decode PEM encoded certificate")
	}
	return bytesToCert(block.Bytes)
}
942456
func (c *Crypter) Encrypt(dst io.Writer, src io.Reader) (err error) {
	salt := make([]byte, c.Key.Size())
	if _, err := rand.Read(salt); err != nil {
		return err
	}
	iv := make([]byte, blockSize)
	if _, err := rand.Read(iv); err != nil {
		return err
	}

	aesKey, hmacKey := c.Key.Derive(salt)
	header := c.encHeader(salt, iv, hmacKey)
	if _, err := dst.Write(header); err != nil {
		return err
	}
	mac := hmac.New(c.HashFunc, hmacKey)
	mac.Write(header)

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

	stream := cipher.NewCTR(block, iv)

	buf := make([]byte, c.bufSize())
	n := 0
	for {
		n, err = src.Read(buf)
		if err != nil {
			if err == io.EOF {
				break
			}
			return err
		}

		mac.Write(buf[:n])
		stream.XORKeyStream(buf[:n], buf[:n])
		if _, err = dst.Write(buf[:n]); err != nil {
			return err
		}
		if _, err = dst.Write(mac.Sum(nil)); err != nil {
			return err
		}
	}
	return nil
}
222639
func GetBytesPayload(payl *common.Payload) ([]byte, error) {
	bytes, err := proto.Marshal(payl)
	return bytes, errors.Wrap(err, "error marshaling Payload")
}
138784
func (msg *Message) Base64Payload() string {
	return base64.StdEncoding.EncodeToString([]byte(msg.Payload))
}
1359877
func (p *PHYPayload) EncryptFOpts(nwkSEncKey AES128Key) error {
	macPL, ok := p.MACPayload.(*MACPayload)
	if !ok {
		return errors.New("lorawan: MACPayload must be of type *MACPayload")
	}

	// nothing to encrypt
	if len(macPL.FHDR.FOpts) == 0 {
		return nil
	}

	var macB []byte
	for _, mac := range macPL.FHDR.FOpts {
		b, err := mac.MarshalBinary()
		if err != nil {
			return err
		}
		macB = append(macB, b...)
	}

	// aFCntDown is used on downlink when FPort > 1
	var aFCntDown bool
	if !p.isUplink() && macPL.FPort != nil && *macPL.FPort > 0 {
		aFCntDown = true
	}

	data, err := EncryptFOpts(nwkSEncKey, aFCntDown, p.isUplink(), macPL.FHDR.DevAddr, macPL.FHDR.FCnt, macB)
	if err != nil {
		return err
	}

	macPL.FHDR.FOpts = []Payload{
		&DataPayload{Bytes: data},
	}

	return nil
}
1113334
func EncryptPEMBlock(data, password []byte) (*pem.Block, error) {
	encryptedBytes, err := encryptPrivateKey(data, password)
	if err != nil {
		return nil, err
	}

	return &pem.Block{
		Type:    "ENCRYPTED PRIVATE KEY",
		Headers: map[string]string{},
		Bytes:   encryptedBytes,
	}, nil
}