create a keystore, compress and encrypt to file
342557
def save(keystorerc=None, keystore=None, files=[], verbose=False):
  ''''''

  config = None
  if keystorerc:
    config = config_reader.read(keystorerc)
    if not config:
      print('No configuration found.', file=sys.stderr)
      sys.exit(-1)
  elif keystore and len(files) > 0:
    config = {
      'keystore': keystore,
      'files': files
    }

  if 'verbose' in config and config['verbose']:
    verbose = True

  keystore_path = None
  if 'keystore' not in config:
    print('.keystorerc needs to specify a keystore file path.', file=sys.stderr)
    sys.exit(-1)

  keystore_path = os.path.expanduser(config['keystore'])
  if os.path.isdir(keystore_path):
    print('keystore cannot be a folder: {}'.format(config['keystore']), file=sys.stderr)
    sys.exit(-1)
  elif not os.path.isfile(keystore_path):
    # If keystore file does not exist already, attempt to create one
    try:
      pathlib.Path(keystore_path).touch()
    except OSError as err:
      print('keystore cannot be accessed: {}\n{}'.format(config['keystore'], err), file=sys.stderr)
      sys.exit(-1)

  # iterate through keys and add them here

  keystore = {}
  try:
    for p in config['files']:

      expanded_path = os.path.expanduser(p)
      path = pathlib.Path(expanded_path)
      if verbose: print('Inspecting {}:'.format(expanded_path))

      if not path.exists():
        print('Error: File or folder does not exist: {}'.format(p), file=sys.stderr)
        sys.exit(-1)
      if path.is_dir():
        for dirpath, dirnames, filenames in os.walk(expanded_path):
          for name in filenames:
            fullpath = os.path.join(dirpath, name)
            if verbose: print('Adding {} ...'.format(fullpath))
            with open(fullpath, 'rb') as keyfile:
              b64_bytes = base64.encodebytes(keyfile.read()).decode('utf-8')
              keystore[fullpath] = b64_bytes
      elif path.is_file():
        fullpath = expanded_path
        if verbose: print('Adding {} ...'.format(fullpath))
        with open(fullpath, 'rb') as keyfile:
          b64_bytes = base64.encodebytes(keyfile.read()).decode('utf-8')
          keystore[fullpath] = b64_bytes

    if verbose: print('Added {} key(s) to keystore.\n'.format(len(keystore)))

    # prompt user for a one-time passphase for encryption

    do_passphrases_match = False
    passphrase = None
    print('This passphrase is used to decrypt your keystore. Please remember it.')
    while not do_passphrases_match:
      passphrase = getpass.getpass('Please enter a passphrase: ')
      passphrase_verify = getpass.getpass('Please verify your passphrase: ')
      do_passphrases_match = passphrase != '' and passphrase == passphrase_verify
      if passphrase == '':
        print('Passphrase cannot be empty.')
      elif not do_passphrases_match:
        print('Passphrases do not match. Please try again.')
    if verbose: print('Passphrase accepted. Encrypting ...')

    # serialise, compress, encrypt

    serial_keystore = json.dumps(keystore)
    compressed_keystore = gzip.compress(serial_keystore.encode('utf-8'))
    try:
      encrypted_keystore = simplecrypt.encrypt(passphrase, compressed_keystore)
    except simplecrypt.EncryptionException as err:
      print('You managed to bump into a very, very rare issue with AES.\nPlease contact the author. {}'.format(err), file=sys.stder)
      sys.exit(-1)

    # save encrypted keystore to file
    keystore_path = os.path.expanduser(keystore_path)
    if verbose: print('Writing to keystore file {}'.format(keystore_path))

    with open(keystore_path, 'wb') as keystore_file:
      keystore_file.write(encrypted_keystore)

    if verbose: print('Keystore successfully created: ')
    # if verbose: print(encrypted_keystore)

  except KeyError as err:
    print('.keystorerc config is missing `files` attribute: {}'.format(err), file=sys.stderr)
    sys.exit(-1)
  except TypeError as err:
    print('Error: {}'.format(err), file=sys.stderr)
    traceback.print_exc()
    sys.exit(-1)
  except OSError as err:
    print('The file system gave an error: {}'.format(err), file=sys.stderr)
    sys.exit(-1)
  except Exception as err:
    print('Serious error. Please report this bug to the author: {}'.format(err), file=sys.stderr)
    sys.exit(-1)
359734
def encrypt(self, data):
        '''
        
        '''
        aes_key, hmac_key = self.keys
        pad = self.AES_BLOCK_SIZE - len(data) % self.AES_BLOCK_SIZE
        if six.PY2:
            data = data + pad * chr(pad)
        else:
            data = data + salt.utils.stringutils.to_bytes(pad * chr(pad))
        iv_bytes = os.urandom(self.AES_BLOCK_SIZE)
        if HAS_M2:
            cypher = EVP.Cipher(alg='aes_192_cbc', key=aes_key, iv=iv_bytes, op=1, padding=False)
            encr = cypher.update(data)
            encr += cypher.final()
        else:
            cypher = AES.new(aes_key, AES.MODE_CBC, iv_bytes)
            encr = cypher.encrypt(data)
        data = iv_bytes + encr
        sig = hmac.new(hmac_key, data, hashlib.sha256).digest()
        return data + sig
712419
protected void createKeystore() {

		java.security.cert.Certificate signingCert = null;
		PrivateKey  caPrivKey  = null;

		if(_caCert == null || _caPrivKey == null)
		{
			try
			{
				log.debug("Keystore or signing cert & keypair not found.  Generating...");

				KeyPair caKeypair = getRSAKeyPair();
				caPrivKey = caKeypair.getPrivate();
				signingCert = CertificateCreator.createTypicalMasterCert(caKeypair);

				log.debug("Done generating signing cert");
				log.debug(signingCert);

				_ks.load(null, _keystorepass);

				_ks.setCertificateEntry(_caCertAlias, signingCert);
				_ks.setKeyEntry(_caPrivKeyAlias, caPrivKey, _keypassword, new java.security.cert.Certificate[] {signingCert});

				File caKsFile = new File(root, _caPrivateKeystore);

				OutputStream os = new FileOutputStream(caKsFile);
				_ks.store(os, _keystorepass);

				log.debug("Wrote JKS keystore to: " +
						caKsFile.getAbsolutePath());

				// also export a .cer that can be imported as a trusted root
				// to disable all warning dialogs for interception

				File signingCertFile = new File(root, EXPORTED_CERT_NAME);

				FileOutputStream cerOut = new FileOutputStream(signingCertFile);

				byte[] buf = signingCert.getEncoded();

				log.debug("Wrote signing cert to: " + signingCertFile.getAbsolutePath());

				cerOut.write(buf);
				cerOut.flush();
				cerOut.close();

				_caCert = (X509Certificate)signingCert;
				_caPrivKey  = caPrivKey;
			}
			catch(Exception e)
			{
				log.error("Fatal error creating/storing keystore or signing cert.", e);
				throw new Error(e);
			}
		}
		else
		{
			log.debug("Successfully loaded keystore.");
			log.debug(_caCert);

		}

	}
787853
def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None,
            region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    r = {}
    try:
        ciphertext = conn.encrypt(
            key_id,
            plaintext,
            encryption_context=encryption_context,
            grant_tokens=grant_tokens
        )
        r['ciphertext'] = ciphertext['CiphertextBlob']
    except boto.exception.BotoServerError as e:
        r['error'] = __utils__['boto.get_error'](e)
    return r
806636
public static void createFile(SshKeyPair key, String passphrase,
			String comment, int format, File toFile) throws IOException {

		SshPrivateKeyFile pub = create(key, passphrase, comment, format);

		FileOutputStream out = new FileOutputStream(toFile);

		try {
			out.write(pub.getFormattedKey());
			out.flush();
		} finally {
			out.close();
		}
	}
738797
def encrypt(source, dest, keys):
    """"""
    cmd = flatten([gnupg_bin(), "--armor", "--output", dest, gnupg_verbose(),
                   gnupg_home(), recipients_args(keys),
                   "--encrypt", source])

    stderr_output(cmd)
    return True
785427
def public_keys_as_files(self):
        """"""
        if not self.public_keys_tempfiles:
            for pk in self.public_keys():
                f = tempfile.NamedTemporaryFile(prefix='trezor-ssh-pubkey-', mode='w')
                f.write(pk)
                f.flush()
                self.public_keys_tempfiles.append(f)

        return self.public_keys_tempfiles
276689
def _encrypt(data):
    """"""
    BS = AES.block_size

    def pad(s):
        n = BS - len(s) % BS
        char = chr(n).encode('utf8')
        return s + n * char

    password = settings.GECKOBOARD_PASSWORD
    salt = Random.new().read(BS - len('Salted__'))
    key, iv = _derive_key_and_iv(password, salt, 32, BS)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    encrypted = b'Salted__' + salt + cipher.encrypt(pad(data))
    return base64.b64encode(encrypted)
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
490937
def _encrypt(self):
        """"""
        from M2Crypto import BIO, SMIME, X509

        # Iterate through the fields and pull out the ones that have a value.
        plaintext = 'cert_id=%s\n' % self.cert_id
        for name, field in self.fields.items():
            value = None
            if name in self.initial:
                value = self.initial[name]
            elif field.initial is not None:
                value = field.initial
            if value is not None:
                plaintext += u'%s=%s\n' % (name, value)
        plaintext = plaintext.encode('utf-8')

        # Begin crypto weirdness.
        s = SMIME.SMIME()
        s.load_key_bio(BIO.openfile(self.private_cert), BIO.openfile(self.public_cert))
        p7 = s.sign(BIO.MemoryBuffer(plaintext), flags=SMIME.PKCS7_BINARY)
        x509 = X509.load_cert_bio(BIO.openfile(self.paypal_cert))
        sk = X509.X509_Stack()
        sk.push(x509)
        s.set_x509_stack(sk)
        s.set_cipher(SMIME.Cipher('des_ede3_cbc'))
        tmp = BIO.MemoryBuffer()
        p7.write_der(tmp)
        p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY)
        out = BIO.MemoryBuffer()
        p7.write(out)
        return out.read().decode()
804606
def load(keystorerc=None, keystore=None, copyto=None, verbose=False):
  ''''''

  config = None
  if keystorerc:
    config = config_reader.read(keystorerc)
    if not config:
      print('No configuration found.', file=sys.stderr)
      sys.exit(-1)
  elif keystore:
    config = {
      'keystore': keystore,
      'files': []
    }

  if 'verbose' in config and config['verbose']:
    verbose = True

  keystore_path = None
  if 'keystore' not in config:
    print('.keystorerc needs to specify a keystore file path.', file=sys.stderr)
    sys.exit(-1)
  elif not pathlib.Path(os.path.expanduser(config['keystore'])).is_file():
    # If keystore file does not exist, nothing to load and exits
    print('keystore does not exist: {}'.format(config['keystore']), file=sys.stderr)
    sys.exit(-1)
  else:
    keystore_path = config['keystore']

  if copyto and not pathlib.Path(os.path.expanduser(copyto)).is_dir():
    print('The folder to copy to does not exist: {}'.format(copyto), file=sys.stderr)
    sys.exit(-1)

  # load and attempt to unencrypt keystore by passphrase

  encrypted_keystore = None
  try:
    with open(os.path.expanduser(keystore_path), 'rb') as keystore_file:
      encrypted_keystore = keystore_file.read()

    if verbose: print('Located encrypted keystore at {}.'.format(keystore_path))

    decrypted = False
    decrypted_keystore = None
    while not decrypted:
      try:
        passphrase = getpass.getpass('Please enter the passphrase: ')
        decrypted_keystore = simplecrypt.decrypt(passphrase, encrypted_keystore)
        decrypted = True
      except simplecrypt.DecryptionException as err:
        print('Invalid passphrase. Please try again.')
      except UnicodeDecodeError as err:
        print('Keyring cannot be decrypted.\nError: {}'.format(err), file=sys.stderr)
        sys.exit(-1)

  except OSError as err:
    print('keystore cannot be opened: {}'.format(err), file=sys.stderr)
    sys.exit(-1)

  # attempt to uncompress the keystore

  decompressed_keystore = gzip.decompress(decrypted_keystore)

  # attempt to unserialise the keystore

  try:
    keystore = json.loads(decompressed_keystore)
  except json.decoder.JSONDecodeError as err:
    print('Please contact the author about this as this is a serious problem. {}'.format(err), file=sys.stderr)
    sys.exit(-1)

  if verbose: print('Keystore decrypted successfully.')

  count = 0
  for filepath, key in keystore.items():
    expanded_filepath = os.path.expanduser(filepath)
    if copyto:
      expanded_filepath = os.path.join(copyto, os.path.basename(filepath))

    confirmed = False
    overwrite = False
    if not pathlib.Path(expanded_filepath).exists():
      confirmed = True
      overwrite = True

    while not confirmed:
      overwrite = input('File {} exists. Are you sure you want to overwrite? (y)/n: '.format(expanded_filepath))
      if overwrite == '' or overwrite == 'y' or overwrite == 'Y':
        overwrite = True
        confirmed = True
      elif overwrite == 'n' or overwrite == 'N':
        overwrite = False
        confirmed = True
      else:
        print('Please enter y or n.')
    if not overwrite:
      continue

    # key ready to be created
    if verbose: print('Writing key to {} ...'.format(expanded_filepath))
    try:
      with open(expanded_filepath, 'wb') as keyfile:
        b64_decoded = base64.decodebytes(key.encode('utf-8'))
        keyfile.write(b64_decoded)
      count += 1
    except OSError as err:
      print('File system threw an error: {}'.format(err), file=sys.stderr)
      print('Skipping {}'.format(expanded_filepath))

  if verbose: print('Keystore restored {} keys.'.format(count))
877290
def encrypt_item(table_name, aws_cmk_id):
    """"""
    index_key = {"partition_attribute": {"S": "is this"}, "sort_attribute": {"N": "55"}}
    plaintext_item = {
        "example": {"S": "data"},
        "some numbers": {"N": "99"},
        "and some binary": {"B": b"\x00\x01\x02"},
        "leave me": {"S": "alone"},  # We want to ignore this attribute
    }
    # Collect all of the attributes that will be encrypted (used later).
    encrypted_attributes = set(plaintext_item.keys())
    encrypted_attributes.remove("leave me")
    # Collect all of the attributes that will not be encrypted (used later).
    unencrypted_attributes = set(index_key.keys())
    unencrypted_attributes.add("leave me")
    # Add the index pairs to the item.
    plaintext_item.update(index_key)

    # Create a normal client.
    client = boto3.client("dynamodb")
    # Create a crypto materials provider using the specified AWS KMS key.
    aws_kms_cmp = AwsKmsCryptographicMaterialsProvider(key_id=aws_cmk_id)
    # Create attribute actions that tells the encrypted client to encrypt all attributes except one.
    actions = AttributeActions(
        default_action=CryptoAction.ENCRYPT_AND_SIGN, attribute_actions={"leave me": CryptoAction.DO_NOTHING}
    )
    # Use these objects to create an encrypted client.
    encrypted_client = EncryptedClient(client=client, materials_provider=aws_kms_cmp, attribute_actions=actions)

    # Put the item to the table, using the encrypted client to transparently encrypt it.
    encrypted_client.put_item(TableName=table_name, Item=plaintext_item)

    # Get the encrypted item using the standard client.
    encrypted_item = client.get_item(TableName=table_name, Key=index_key)["Item"]

    # Get the item using the encrypted client, transparently decyrpting it.
    decrypted_item = encrypted_client.get_item(TableName=table_name, Key=index_key)["Item"]

    # Verify that all of the attributes are different in the encrypted item
    for name in encrypted_attributes:
        assert encrypted_item[name] != plaintext_item[name]
        assert decrypted_item[name] == plaintext_item[name]

    # Verify that all of the attributes that should not be encrypted were not.
    for name in unencrypted_attributes:
        assert decrypted_item[name] == encrypted_item[name] == plaintext_item[name]

    # Clean up the item
    encrypted_client.delete_item(TableName=table_name, Key=index_key)
542841
def encrypt(pubkey, password):
    
    key = load_key(pubkey)
    encrypted_password = key.encrypt(password, PKCS1v15())
    return base64.b64encode(encrypted_password)
918549
def encrypt_key(password, salt)
      iterations, length = CRYPTERATIONS, HASH_BYTE_SIZE
      OpenSSL::PKCS5::pbkdf2_hmac_sha1(password, salt, iterations, length)
    end
719567
def download_encrypted_file(job, input_args, name):
    
    work_dir = job.fileStore.getLocalTempDir()
    key_path = input_args['ssec']
    file_path = os.path.join(work_dir, name)
    url = input_args[name]

    with open(key_path, 'r') as f:
        key = f.read()
    if len(key) != 32:
        raise RuntimeError('Invalid Key! Must be 32 bytes: {}'.format(key))

    key = generate_unique_key(key_path, url)

    encoded_key = base64.b64encode(key)
    encoded_key_md5 = base64.b64encode(hashlib.md5(key).digest())
    h1 = 'x-amz-server-side-encryption-customer-algorithm:AES256'
    h2 = 'x-amz-server-side-encryption-customer-key:{}'.format(encoded_key)
    h3 = 'x-amz-server-side-encryption-customer-key-md5:{}'.format(encoded_key_md5)
    try:
        subprocess.check_call(['curl', '-fs', '--retry', '5', '-H', h1, '-H', h2, '-H', h3, url, '-o', file_path])
    except OSError:
        raise RuntimeError('Failed to find "curl". Install via "apt-get install curl"')
    assert os.path.exists(file_path)
    return job.fileStore.writeGlobalFile(file_path)
199170
public function generateKeyFile()
    {
        $this->output->outputLine();

        if ( file_exists($this->createFilePath([$this->localBackupTarget, 'key'])) ) {
            $this->output->outputLine('<b>You have already a keyfile!</b>');
            $this->output->outputLine('If you generate a new one, all existing Backups are worthless.');
            $this->output->outputLine();
            $this->output->outputLine('Call \'./flow backup:clear --force\' to delete all Backups and the Keyfile.');
            $this->output->outputLine();
            return;
        }

        $this->output->outputLine('<b>Generate a new Crypto Key</b>');
        $this->output->outputLine();

        $this->files->createDirectoryRecursively($this->localBackupTarget);

        try {
            $key = \Crypto::createNewRandomKey();
            file_put_contents($this->createFilePath([$this->localBackupTarget, 'key']), $key);
            // WARNING: Do NOT encode $key with bin2hex() or base64_encode(),
            // they may leak the key to the attacker through side channels.
        } catch (Ex\CryptoTestFailedException $ex) {
            die('Cannot safely create a key');
        } catch (Ex\CannotPerformOperationException $ex) {
            die('Cannot safely create a key');
        }

        $this->output->outputLine('done');
        $this->output->outputLine();

    }
1133590
function zip(data, options) {
		var flags = 0,
			level,
			crc, out = [];

		if (!options) {
			options = {};
		}
		level = options.level || DEFAULT_LEVEL;

		if (typeof data === 'string') {
			data = Array.prototype.map.call(data, function (char) {
				return char.charCodeAt(0);
			});
		}

		// magic number marking this file as GZIP
		putByte(ID1, out);
		putByte(ID2, out);

		putByte(compressionMethods['deflate'], out);

		if (options.name) {
			flags |= possibleFlags['FNAME'];
		}

		putByte(flags, out);
		putLong(options.timestamp || parseInt(Date.now() / 1000, 10), out);

		// put deflate args (extra flags)
		if (level === 1) {
			// fastest algorithm
			putByte(4, out);
		} else if (level === 9) {
			// maximum compression (fastest algorithm)
			putByte(2, out);
		} else {
			putByte(0, out);
		}

		// OS identifier
		putByte(osMap[os], out);

		if (options.name) {
			// ignore the directory part
			putString(options.name.substring(options.name.lastIndexOf('/') + 1), out);

			// terminating null
			putByte(0, out);
		}

		deflate.deflate(data, level).forEach(function (byte) {
			putByte(byte, out);
		});

		putLong(parseInt(crc32(data), 16), out);
		putLong(data.length, out);

		return out;
	}