Encrypts plain buffer with the import key
        :param plain:
        :return:
771038
def encrypt_with_import_key(self, plain):
        

        n, e = TemplateProcessor.read_serialized_rsa_pub_key(self.import_key['key'])
        n_bit_size = long_bit_size(n)
        bs = 0
        if n_bit_size > 1024-10 and n_bit_size < 1024+10:
            bs = 128
        elif n_bit_size > 2048-10 and n_bit_size < 2048+10:
            bs = 256
        else:
            raise CryptoError('Unknown RSA modulus size: %d', n_bit_size)

        padded = PKCS15.pad(plain, bs=bs, bt=2)
        return rsa_enc(padded, n, e)
989179
public static String encrypt(String salt, String password, String plainText) {
        SecretKey secret = getKey(salt, password);
        return encryptBouncyCastle(secret, plainText);
    }
355219
def to_plaintext(options = :DEFAULT, width = 120)
      opts = Config.process_options(options, :render)
      _render_plaintext(opts, width).force_encoding('utf-8')
    end
1292302
def crypto_box_open(ciphertext, nonce, pk, sk):
    
    if len(nonce) != crypto_box_NONCEBYTES:
        raise exc.ValueError("Invalid nonce size")

    if len(pk) != crypto_box_PUBLICKEYBYTES:
        raise exc.ValueError("Invalid public key")

    if len(sk) != crypto_box_SECRETKEYBYTES:
        raise exc.ValueError("Invalid secret key")

    padded = (b"\x00" * crypto_box_BOXZEROBYTES) + ciphertext
    plaintext = ffi.new("unsigned char[]", len(padded))

    res = lib.crypto_box_open(plaintext, padded, len(padded), nonce, pk, sk)
    ensure(res == 0, "An error occurred trying to decrypt the message",
           raising=exc.CryptoError)

    return ffi.buffer(plaintext, len(padded))[crypto_box_ZEROBYTES:]
1165067
def _encrypt_private(self, ret, dictkey, target):
        '''
        
        '''
        # encrypt with a specific AES key
        pubfn = os.path.join(self.opts['pki_dir'],
                             'minions',
                             target)
        key = salt.crypt.Crypticle.generate_key_string()
        pcrypt = salt.crypt.Crypticle(
            self.opts,
            key)
        try:
            pub = salt.crypt.get_rsa_pub_key(pubfn)
        except (ValueError, IndexError, TypeError):
            return self.crypticle.dumps({})
        except IOError:
            log.error('AES key not found')
            return {'error': 'AES key not found'}

        pret = {}
        if not six.PY2:
            key = salt.utils.stringutils.to_bytes(key)
        if HAS_M2:
            pret['key'] = pub.public_encrypt(key, RSA.pkcs1_oaep_padding)
        else:
            cipher = PKCS1_OAEP.new(pub)
            pret['key'] = cipher.encrypt(key)
        pret[dictkey] = pcrypt.dumps(
            ret if ret is not False else {}
        )
        return pret
724495
def encrypt(self, password, kdf=None, iterations=None):
        '''
        
        '''
        return self._publicapi.encrypt(self.privateKey, password, kdf=kdf, iterations=iterations)
731329
def encrypted_to(self, raw_data):
        """"""
        # TODO: make this support multiple keys.
        result = self._gpg.list_packets(raw_data)
        if not result.key:
            raise LookupError(
                "Content is not encrypted to a GnuPG key!")
        try:
            return self.find_key_by_keyid(result.key)
        except:
            return self.find_key_by_subkey(result.key)
414570
def encrypt(data, raw_pubkey)
      raise ArgumentError, "invalid pubkey of length #{raw_pubkey.size}" unless raw_pubkey.size == 64
      Crypto::ECIES.encrypt data, raw_pubkey
    end
234817
def encrypt_audio(header, buf)
      raise 'No secret key found, despite encryption being enabled!' unless @secret_key

      box = RbNaCl::SecretBox.new(@secret_key)

      # The nonce is the header of the voice packet with 12 null bytes appended
      nonce = header + ([0] * 12).pack('C*')

      box.encrypt(nonce, buf)
    end
357779
def encrypt(v, key=None, keyfile=None):
    
    cipher = functions.get_cipher(key, keyfile)
    return cipher.encrypt(v)
641679
def decrypt_aes_cbc(ciphertext, key, iv):
    
    if not isinstance(ciphertext, bytes):
        raise TypeError("content to decrypt must by bytes.")
    
    # Just decrypt the content with the created key
    aes = AES.new(key, AES.MODE_CBC, iv)
    decrypted_content = aes.decrypt(ciphertext)
    padding = ord(decrypted_content[-1:len(decrypted_content)])  # This is a difference in python2 vs python3, so we are explicit about
                                            # the range so that return value is the same.
    decrypted_content = decrypted_content[:len(decrypted_content) - padding]
    return decrypted_content
1269514
def encrypt(self, paddedMessage):
        
        # TODO: make this less ugly and python 2 and 3 compatible
        # paddedMessage = bytearray(paddedMessage.encode() if (sys.version_info >= (3, 0) and not type(paddedMessage) in (bytes, bytearray)) or type(paddedMessage) is unicode else paddedMessage)
        if (sys.version_info >= (3, 0) and
                not type(paddedMessage) in (bytes, bytearray)) or type(paddedMessage) is unicode:
            paddedMessage = bytearray(paddedMessage.encode())
        else:
            paddedMessage = bytearray(paddedMessage)

        sessionRecord = self.sessionStore.loadSession(self.recipientId, self.deviceId)
        sessionState = sessionRecord.getSessionState()
        chainKey = sessionState.getSenderChainKey()
        messageKeys = chainKey.getMessageKeys()
        senderEphemeral = sessionState.getSenderRatchetKey()
        previousCounter = sessionState.getPreviousCounter()
        sessionVersion = sessionState.getSessionVersion()

        ciphertextBody = self.getCiphertext(sessionVersion, messageKeys, paddedMessage)
        ciphertextMessage = WhisperMessage(sessionVersion, messageKeys.getMacKey(),
                                           senderEphemeral, chainKey.getIndex(),
                                           previousCounter, ciphertextBody,
                                           sessionState.getLocalIdentityKey(),
                                           sessionState.getRemoteIdentityKey())

        if sessionState.hasUnacknowledgedPreKeyMessage():
            items = sessionState.getUnacknowledgedPreKeyMessageItems()
            localRegistrationid = sessionState.getLocalRegistrationId()

            ciphertextMessage = PreKeyWhisperMessage(sessionVersion, localRegistrationid, items.getPreKeyId(),
                                                     items.getSignedPreKeyId(), items.getBaseKey(),
                                                     sessionState.getLocalIdentityKey(),
                                                     ciphertextMessage)
        sessionState.setSenderChainKey(chainKey.getNextChainKey())
        self.sessionStore.storeSession(self.recipientId, self.deviceId, sessionRecord)

        return ciphertextMessage
320236
def encrypt_aes_cbc(cleartext, key, iv):
    
    if isinstance(cleartext, unicode):
        cleartext = cleartext.encode('utf8')
    elif isinstance(cleartext, bytearray):
        cleartext = bytes(cleartext)
    if not isinstance(cleartext, bytes):
        raise TypeError("content to encrypt must by bytes.")
    
    aes = AES.new(key, AES.MODE_CBC, iv)
    padding = AES.block_size - (len(cleartext) % AES.block_size)
    cleartext += chr(padding).encode('utf-8') * padding # the encode() is for py3k compat
    return aes.encrypt(cleartext)
934633
def crypto_secretbox(message, nonce, key):
    
    if len(key) != crypto_secretbox_KEYBYTES:
        raise exc.ValueError("Invalid key")

    if len(nonce) != crypto_secretbox_NONCEBYTES:
        raise exc.ValueError("Invalid nonce")

    padded = b"\x00" * crypto_secretbox_ZEROBYTES + message
    ciphertext = ffi.new("unsigned char[]", len(padded))

    res = lib.crypto_secretbox(ciphertext, padded, len(padded), nonce, key)
    ensure(res == 0, "Encryption failed", raising=exc.CryptoError)

    ciphertext = ffi.buffer(ciphertext, len(padded))
    return ciphertext[crypto_secretbox_BOXZEROBYTES:]
1318406
def cycle_file(source_plaintext_filename):
    
    # Create a static random master key provider
    key_id = os.urandom(8)
    master_key_provider = StaticRandomMasterKeyProvider()
    master_key_provider.add_master_key(key_id)

    ciphertext_filename = source_plaintext_filename + ".encrypted"
    cycled_plaintext_filename = source_plaintext_filename + ".decrypted"

    # Encrypt the plaintext source data
    with open(source_plaintext_filename, "rb") as plaintext, open(ciphertext_filename, "wb") as ciphertext:
        with aws_encryption_sdk.stream(mode="e", source=plaintext, key_provider=master_key_provider) as encryptor:
            for chunk in encryptor:
                ciphertext.write(chunk)

    # Decrypt the ciphertext
    with open(ciphertext_filename, "rb") as ciphertext, open(cycled_plaintext_filename, "wb") as plaintext:
        with aws_encryption_sdk.stream(mode="d", source=ciphertext, key_provider=master_key_provider) as decryptor:
            for chunk in decryptor:
                plaintext.write(chunk)

    # Verify that the "cycled" (encrypted, then decrypted) plaintext is identical to the source
    # plaintext
    assert filecmp.cmp(source_plaintext_filename, cycled_plaintext_filename)

    # Verify that the encryption context used in the decrypt operation includes all key pairs from
    # the encrypt operation
    #
    # In production, always use a meaningful encryption context. In this sample, we omit the
    # encryption context (no key pairs).
    assert all(
        pair in decryptor.header.encryption_context.items() for pair in encryptor.header.encryption_context.items()
    )
    return ciphertext_filename, cycled_plaintext_filename
848576
def encrypt_with_ad(self, ad: bytes, plaintext: bytes) -> bytes:
        
        if self.n == MAX_NONCE:
            raise NoiseMaxNonceError('Nonce has depleted!')

        if not self.has_key():
            return plaintext

        ciphertext = self.cipher.encrypt(self.k, self.n, ad, plaintext)
        self.n = self.n + 1
        return ciphertext
562230
public String encryptPassword(String plain) {
    Preconditions.checkArgument(this.encryptors.size() > 0,
        "A master password needs to be provided for encrypting passwords.");

    try {
      return this.encryptors.get(0).encrypt(plain);
    } catch (Exception e) {
      throw new RuntimeException("Failed to encrypt password", e);
    }
  }