Constructs (that is, encrypts) a new miniLock file from sender to recipients.
543802
def new(cls, file_name, file_or_contents, sender, recipients):
        
        assert_type_and_length('recipients', recipients, list, minL=1)
        assert_type_and_length('sender', sender, UserLock)
        for R in recipients:
            assert_type_and_length('recipient', R, (str, UserLock))   
        recipients = list(set(recipients))
        # Encrypt file with secret key using file_contents and file_name
        file_key   = os.urandom(32)
        file_nonce = os.urandom(16)
        file_cipher = SymmetricMiniLock.from_key(file_key)
        ciphertext = b''.join(file_cipher.encrypt(file_or_contents, file_name, file_nonce))
        file_info = {
            'fileKey'   : b64encode(file_key),
            'fileNonce' : b64encode(file_nonce),
            'fileHash'  : b64encode(pyblake2.blake2s(ciphertext).digest())
        }
        header = MiniLockHeader.new(file_info, sender, recipients)
        b_header = header.to_bytes()
        encrypted_file = b'miniLock' + len(b_header).to_bytes(4, 'little') + b_header + ciphertext
        return cls(encrypted_file)
312648
function create() {
		// Check form for errors
		if(!$("#privateKey").val() || !$("#recipient").val()) return alert('Missing parameter !');
		if(undefined === $("#amount").val() || !nem.utils.helpers.isTextAmountValid($("#amount").val())) return alert('Invalid amount !');
		if (!nem.model.address.isValid(nem.model.address.clean($("#recipient").val()))) return alert('Invalid recipent address !');

		// Set the private key in common object
		common.privateKey = $("#privateKey").val();

		// Check private key for errors
		if (common.privateKey.length !== 64 && common.privateKey.length !== 66) return alert('Invalid private key, length must be 64 or 66 characters !');
    	if (!nem.utils.helpers.isHexadecimal(common.privateKey)) return alert('Private key must be hexadecimal only !');

		// Set the cleaned amount into transfer transaction object
		transferTransaction.amount = nem.utils.helpers.cleanTextAmount($("#amount").val());

		// Recipient address must be clean (no hypens: "-")
		transferTransaction.recipient = nem.model.address.clean($("#recipient").val());

		// Set message
		transferTransaction.message = $("#message").val();

		// Prepare the updated transfer transaction object
		var transactionEntity = nem.model.transactions.prepare("transferTransaction")(common, transferTransaction, nem.model.network.data.testnet.id);

		// Create a key pair object from private key
		var kp = nem.crypto.keyPair.create(nem.utils.helpers.fixPrivateKey(common.privateKey));

		// Serialize the transaction
		var serialized = nem.utils.serialization.serializeTransaction(transactionEntity);

		// Sign the serialized transaction with keypair object
	    var signature = kp.sign(serialized);

	    // Build the object to send
	    var result = {
	        'data': nem.utils.convert.ua2hex(serialized),
	        'signature': signature.toString()
	    };

	    // Show the object to send in view
	    $("#result").val(JSON.stringify(result));
	}
1128274
def decrypt(self, recipient_key):
        
        if recipient_key.private_key is None:
            raise ValueError("Cannot decrypt with this key; no private key part found.")
        header = MiniLockHeader(self.header)
        # Create ephemeral public key for authenticated decryption of metadata.
        # TODO: Future-proof this by making it try to decrypt a b58 ephem ID if available?
        decryptInfo = header.decrypt(recipient_key)
        file_info = decryptInfo['fileInfo']
        file_hash = file_info['fileHash']
        if not b64decode(file_hash) == pyblake2.blake2s(self.chunks_block).digest():
            raise ValueError("ciphertext does not match given hash!")
        symbox = SymmetricMiniLock.from_key(b64decode(file_info['fileKey']))
        filename, *filechunks = symbox.decrypt(self.chunks_block, b64decode(file_info['fileNonce']))
        try:
            filename = filename.decode('utf8')
        except Exception as E:
            raise ValueError("Cannot decode filename to UTF8 string: '{}'".format(filename))
        sender = decryptInfo['senderID']
        return filename, sender, b''.join(filechunks)
1254302
def main_encrypt(A):
    ""
    profile = get_profile(A)
    localKeys = profile.get('local keys', [])
    if not localKeys:
        localKeys = [make_lock_securely(warn_only = A.ignore_entropy)]
    else:
        localKeys = [crypto.UserLock.private_from_b64(k['private_key']) for k in localKeys]
    # First key is considered "main"
    userKey = localKeys[0]
    print("User ID:", userKey.userID)
    if not os.path.exists(A.path):
        error_out("File or directory '{}' does not exist.".format(A.path))
    # Create, fetch or error out for recipient list:
    recipients = resolve_recipients(profile, A.recipient)
    recipients.append(userKey)
    print("Recipients:", *set(k.userID if isinstance(k, crypto.UserLock) else k for k in recipients))
    # Do files OR folders
    if os.path.isfile(A.path):
        crypted = encrypt_file(A.path, userKey, recipients)
    elif os.path.isdir(A.path):
        crypted = encrypt_folder(A.path, userKey, recipients)
    else:
        error_out("Specified path '{}' is neither a file nor a folder.".format(A.path))
    if A.base64:
        crypted = crypto.b64encode(crypted)
    if not A.output:
        A.output = hex(int.from_bytes(os.urandom(6),'big'))[2:] + ".minilock"
    print("Saving output to", A.output)
    with open(A.output, "wb") as O:
        O.write(crypted)
623777
function _constructPacketFromFields(userFields, AppSKey, NwkSKey, AppKey) {
    // if user fails to supply keys, construct a packet anyway
    var constructed = packet.fromFields(userFields);

    if (constructed != null) {
        if(constructed.isDataMessage() == true) {
            // to encrypt, need NwkSKey if port=0, else AppSKey
            if ((constructed.getFPort() == 0 && util.isBufferLength(NwkSKey, 16))
                || (constructed.getFPort() > 0 && util.isBufferLength(AppSKey, 16))) {

                // crypto is reversible (just XORs FRMPayload), so we can
                //  just do "decrypt" on the plaintext to get ciphertext
                var ciphertext = crypt.decrypt(constructed, AppSKey, NwkSKey);

                // overwrite payload with ciphertext
                constructed.getBuffers().FRMPayload = ciphertext;

                // recalculate buffers to be ready for MIC calc'n
                constructed.mergeGroupFields();

                if (util.isBufferLength(NwkSKey, 16)) {
                    mic.recalculateMIC(constructed, NwkSKey, AppKey);
                    constructed.mergeGroupFields();
                }
            }
        } else if(constructed.isJoinRequestMessage() == true) {
            if (util.isBufferLength(AppKey, 16)) {
                mic.recalculateMIC(constructed, NwkSKey, AppKey);
                constructed.mergeGroupFields();
            }
        } else if(constructed.isJoinAcceptMessage() == true) {
            if (util.isBufferLength(AppKey, 16)) {
                mic.recalculateMIC(constructed, NwkSKey, AppKey);
                constructed.mergeGroupFields();

                var ciphertext = crypt.decryptJoin(constructed, AppKey);

                // overwrite payload with ciphertext
                ciphertext.copy(constructed.getBuffers().MACPayloadWithMIC);
            }
        }
    }
    return constructed;
}
147159
private ContentCryptoMaterial newContentCryptoMaterial(
            EncryptionMaterialsProvider kekMaterialProvider,
            Map<String, String> materialsDescription, Provider provider,
            AmazonWebServiceRequest req) {
        EncryptionMaterials kekMaterials =
            kekMaterialProvider.getEncryptionMaterials(materialsDescription);
        if (kekMaterials == null) {
            return null;
        }
        return buildContentCryptoMaterial(kekMaterials, provider, req);
    }
241471
public static void encryptFile(File raw, File encryptedFile, String password) throws IOException {
        byte[] b = readBytes(raw);
        String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
        byte[] encryptedBytes = new RNCryptorNative().encrypt(encodedImage, password);
        writeBytes(encryptedFile, encryptedBytes);
    }
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
344649
def gpg_encrypt( fd_in, path_out, sender_key_info, recipient_key_infos, passphrase=None, config_dir=None ):
    

    if config_dir is None:
        config_dir = get_config_dir()

    # ingest keys 
    tmpdir = make_gpg_tmphome( prefix="encrypt", config_dir=config_dir )
    for key_info in recipient_key_infos:
        res = gpg_stash_key( "encrypt", key_info['key_data'], config_dir=config_dir, gpghome=tmpdir )
        if res is None:
            shutil.rmtree(tmpdir)
            return {'error': 'Failed to stash key %s' % key_info['key_id']}

    # copy over our key
    try:
        sender_privkey = gpg_export_key( sender_key_info['app_name'], sender_key_info['key_id'], include_private=True, config_dir=config_dir )
    except Exception, e:
        log.exception(e)
        shutil.rmtree(tmpdir)
        return {'error': 'No such private key'}

    res = gpg_stash_key( "encrypt", sender_privkey, config_dir=config_dir, gpghome=tmpdir )
    if res is None:
        shutil.rmtree(tmpdir)
        return {'error': 'Failed to load sender private key'}

    recipient_key_ids = [r['key_id'] for r in recipient_key_infos]

    # do the encryption
    gpg = gnupg.GPG( homedir=tmpdir )
    res = gpg.encrypt_file( fd_in, recipient_key_ids, sign=sender_key_info['key_id'], passphrase=passphrase, output=path_out, always_trust=True )
    shutil.rmtree(tmpdir)

    if res.status != 'encryption ok':
        log.debug("encrypt_file error: %s" % res.__dict__)
        log.debug("recipients: %s" % recipient_key_ids)
        log.debug("signer: %s" % sender_key_info['key_id'])
        return {'error': 'Failed to encrypt data'}
    
    return {'status': True}
386317
def encrypt(message, key: nil)

      raise ArgumentError.new('The message argument is required.') if message.blank?
      raise ArgumentError.new('The key argument is required.')     if key.blank?

      cipher = OpenSSL::Cipher::AES.new(256, 'CBC')
      cipher.encrypt
      cipher.padding = aes_256_padding
      cipher.key     = key

      cipher.update(message)+cipher.final

    end
1303512
def write(self, str):
        ''''''

        if self.closed: raise ValueError('File closed')
        if self._mode in _allowed_read:
            raise Exception('File opened for read only')

        if self._valid is not None:
            raise Exception('file already finalized')

        if not self._done_header:
            self._write_header()

        # Encrypt and write the data
        encrypted = self._crypto.encrypt(str)
        self._checksumer.update(encrypted)
        self._fp.write(encrypted)
1211494
def construct_message(self, email=None):
        
        # add subject, from and to
        self.multipart['Subject'] = self.subject
        self.multipart['From'] = self.config['EMAIL']
        self.multipart['Date'] = formatdate(localtime=True)
        if email is None and self.send_as_one:
            self.multipart['To'] = ", ".join(self.addresses)
        elif email is not None and self.send_as_one is False:
            self.multipart['To'] = email
        # add ccs
        if self.ccs is not None and self.ccs:
            self.multipart['Cc'] = ", ".join(self.ccs)
        # add html and text body
        html = MIMEText(self.html, 'html')
        alt_text = MIMEText(self.text, 'plain')
        self.multipart.attach(html)
        self.multipart.attach(alt_text)
        for file in self.files:
            self.multipart.attach(file)
710131
def customPRF512(key, amac, smac, anonce, snonce):
    """"""
    A = b"Pairwise key expansion"
    B = b"".join(sorted([amac, smac]) + sorted([anonce, snonce]))

    blen = 64
    i = 0
    R = b''
    while i <= ((blen * 8 + 159) / 160):
        hmacsha1 = hmac.new(key, A + chb(0x00) + B + chb(i), hashlib.sha1)
        i += 1
        R = R + hmacsha1.digest()
    return R[:blen]
914476
def final_key(master_key, keyfile_data = nil)
      key = Digest::SHA2.new.update(master_key).digest

      if keyfile_data
        keyfile_hash = extract_keyfile_hash(keyfile_data)
        key = master_key == '' ? keyfile_hash : Digest::SHA2.new.update(key + keyfile_hash).digest
      end

      aes = OpenSSL::Cipher.new('AES-256-ECB')
      aes.encrypt
      aes.key = @master_seed2
      aes.padding = 0

      @rounds.times do
        key = aes.update(key) + aes.final
      end

      key = Digest::SHA2.new.update(key).digest
      key = Digest::SHA2.new.update(@master_seed + key).digest
      key
    end
474054
def encrypt_file(self,
                     path,
                     output_path=None,
                     overwrite=False,
                     enable_verbose=True):
        
        path, output_path = files.process_dst_overwrite_args(
            src=path, dst=output_path, overwrite=overwrite,
            src_to_dst_func=files.get_encrpyted_path,
        )

        with open(path, "rb") as infile, open(output_path, "wb") as outfile:
            encrypt_bigfile(infile, outfile, self.his_pubkey)
237019
def create_lockfile(self):
        
        process = subprocess.Popen(
            self.pin_command,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        stdout, stderr = process.communicate()
        if process.returncode == 0:
            self.fix_lockfile()
        else:
            logger.critical("ERROR executing %s", ' '.join(self.pin_command))
            logger.critical("Exit code: %s", process.returncode)
            logger.critical(stdout.decode('utf-8'))
            logger.critical(stderr.decode('utf-8'))
            raise RuntimeError("Failed to pip-compile {0}".format(self.infile))
1194800
def encrypt(self, paddedPlaintext):
        
        # 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(paddedPlaintext) in (bytes, bytearray)) or type(paddedPlaintext) is unicode:
            paddedPlaintext = bytearray(paddedPlaintext.encode())
        else:
            paddedPlaintext = bytearray(paddedPlaintext)
        try:
            record = self.senderKeyStore.loadSenderKey(self.senderKeyName)
            senderKeyState = record.getSenderKeyState()
            senderKey = senderKeyState.getSenderChainKey().getSenderMessageKey()
            ciphertext = self.getCipherText(senderKey.getIv(), senderKey.getCipherKey(), paddedPlaintext)

            senderKeyMessage = SenderKeyMessage(senderKeyState.getKeyId(),
                                                senderKey.getIteration(),
                                                ciphertext,
                                                senderKeyState.getSigningKeyPrivate())

            senderKeyState.setSenderChainKey(senderKeyState.getSenderChainKey().getNext())
            self.senderKeyStore.storeSenderKey(self.senderKeyName, record)

            return senderKeyMessage.serialize()
        except InvalidKeyIdException as e:
            raise NoSessionException(e)