encrypt leverages KMS encrypt and base64-encode encrypted blob

        More info on KMS encrypt API:
        https://docs.aws.amazon.com/kms/latest/APIReference/API_encrypt.html
181403
def encrypt(key, message):
    '''
    '''
    try:
        ret = kms.encrypt(KeyId=key, Plaintext=message)
        encrypted_data = base64.encodestring(ret.get('CiphertextBlob'))
    except Exception as e:
        # returns http 500 back to user and log error details in Cloudwatch Logs
        raise Exception("Unable to encrypt data: ", e)

    return encrypted_data.decode()
1014559
public String encryptBase64(String data, String charset) {
		return Base64.encode(encrypt(data, charset));
	}
180321
function _encryptedContentToAsn1(ec) {
  return [
    // ContentType, always Data for the moment
    asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
      asn1.oidToDer(forge.pki.oids.data).getBytes()),
    // ContentEncryptionAlgorithmIdentifier
    asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
      // Algorithm
      asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
        asn1.oidToDer(ec.algorithm).getBytes()),
      // Parameters (IV)
      asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
        ec.parameter.getBytes())
    ]),
    // [0] EncryptedContent
    asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
      asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
        ec.content.getBytes())
    ])
  ];
}
1090917
function _encodeBlob(blob) {
    return new Promise$1(function (resolve, reject) {
        var reader = new FileReader();
        reader.onerror = reject;
        reader.onloadend = function (e) {
            var base64 = btoa(e.target.result || '');
            resolve({
                __local_forage_encoded_blob: true,
                data: base64,
                type: blob.type
            });
        };
        reader.readAsBinaryString(blob);
    });
}
1220611
def encrypt_certificate(collector):
    """"""
    configuration = collector.configuration
    amazon = configuration['amazon']
    aws_syncr = configuration['aws_syncr']
    certificate = aws_syncr.artifact

    available = []

    for gateway_name, gateway in configuration.get('apigateway', {}, ignore_converters=True).items():
        for name, options in gateway.get("domain_names", {}).items():
            if "zone" in options:
                location = '.'.join(['apigateway', gateway_name, 'domain_names'])
                formatter = MergedOptionStringFormatter(configuration, location, value=options['zone'])
                available.append((gateway_name, "{0}.{1}".format(name, formatter.format())))

    if not available:
        raise AwsSyncrError("Please specify apigateway.<gateway_name>.domain_names.<domain_name>.name in the configuration")

    if not certificate:
        raise AwsSyncrError("Please specify certificate to encrypt with --artifact", available=[a[1] for a in available])

    if certificate not in [a[1] for a in available]:
        raise AwsSyncrError("Unknown certificate", available=[a[1] for a in available], got=certificate)

    gateway = [name for name, cert in available if cert == certificate][0]
    location, source = find_certificate_source(configuration, gateway, certificate)

    log.info("Gonna edit {0} in {1}".format(location, source))
    current = MergedOptions.using(yaml.load(open(source)))
    dest = current[location]

    try:
        key_id = input("Which kms key do you want to use? ")
        region = input("What region is this key in? ")
    except EOFError:
        raise UserQuit()

    # Make the filename completion work
    setup_completer()

    # Create the datakey to encrypt with
    data_key = amazon.kms.generate_data_key(region, key_id)
    plaintext_data_key = data_key["Plaintext"]
    encrypted_data_key = base64.b64encode(data_key["CiphertextBlob"]).decode('utf-8')

    # Encrypt our secrets
    secrets = {}
    for name, desc in (("body", "certificate's crt file"), ("key", "private key file"), ("chain", "certificate chain")):
        location = None
        while not location or not os.path.isfile(location):
            location = os.path.expanduser(filename_prompt("Where is the {0}? ".format(desc)))
            if not location or not os.path.isfile(location):
                print("Please give a location to a file that exists!")

        with open(location, 'rb') as fle:
            data = fle.read()

        counter = Counter.new(128)
        encryptor = AES.new(plaintext_data_key[:32], AES.MODE_CTR, counter=counter)
        secrets[name] = base64.b64encode(encryptor.encrypt(data)).decode('utf-8')

    # Add in the encrypted values
    dest['body'] = {"kms": secrets['body'], "location": region, "kms_data_key": encrypted_data_key}
    dest['key'] = {"kms": secrets['key'], "location": region, "kms_data_key": encrypted_data_key}
    dest['chain'] = {"kms": secrets['chain'], "location": region, "kms_data_key": encrypted_data_key}

    # And write to the file!
    yaml.dump(current.as_dict(), open(source, 'w'), explicit_start=True, indent=2, default_flow_style=False)
930806
def encrypt(api_context, request_bytes, custom_headers):
    

    key = Random.get_random_bytes(_AES_KEY_SIZE)
    iv = Random.get_random_bytes(_BLOCK_SIZE)
    _add_header_client_encryption_key(api_context, key, custom_headers)
    _add_header_client_encryption_iv(iv, custom_headers)
    request_bytes = _encrypt_request_bytes(request_bytes, key, iv)
    _add_header_client_encryption_hmac(request_bytes, key, iv, custom_headers)

    return request_bytes
393967
def encode(self, b64=False, always_bytes=True):
        """"""
        if self.binary and not b64:
            encoded_packet = six.int2byte(self.packet_type)
        else:
            encoded_packet = six.text_type(self.packet_type)
            if self.binary and b64:
                encoded_packet = 'b' + encoded_packet
        if self.binary:
            if b64:
                encoded_packet += base64.b64encode(self.data).decode('utf-8')
            else:
                encoded_packet += self.data
        elif isinstance(self.data, six.string_types):
            encoded_packet += self.data
        elif isinstance(self.data, dict) or isinstance(self.data, list):
            encoded_packet += self.json.dumps(self.data,
                                              separators=(',', ':'))
        elif self.data is not None:
            encoded_packet += str(self.data)
        if always_bytes and not isinstance(encoded_packet, binary_types):
            encoded_packet = encoded_packet.encode('utf-8')
        return encoded_packet
85811
public static byte[] encryptAES2Base64(byte[] data, byte[] key) {
        try {
            return Base64.getEncoder().encode(encryptAES(data, key));
        } catch (Exception e) {
            return null;
        }
    }
413966
function encodeBase64(json) {
    const text = JSON.stringify(json),
          buffer = Buffer.from(text, 'binary');

    return buffer.toString('base64');
}
600597
function contentEncryptCbc(aad, cek, cekEnc, plain, bits) {
  let iv = crypto.randomBytes(16);
  let bytes = bits >> 3;
  let cipher = crypto.createCipheriv(`AES-${bits}-CBC`, cek.slice(bytes), iv);
  let enc = Buffer.concat([cipher.update(plain), cipher.final()]);
  let len = aad.length << 3;
  let al = Buffer.from(`000000000000000${len.toString(16)}`.slice(-16), 'hex');
  let hmac = crypto.createHmac(`SHA${bits << 1}`, cek.slice(0, bytes));
  hmac.update(Buffer.from(aad)).update(iv).update(enc).update(al);
  let tag = buf2b64url(hmac.digest().slice(0, bytes));
  return `${aad}.${cekEnc}.${buf2b64url(iv)}.${buf2b64url(enc)}.${tag}`;
}
529402
def encrypt_password(raw_password, algorithm='sha1', salt=None):
    
    if salt is None:
        salt = binascii.hexlify(os.urandom(3))[:5]
    else:
        salt = salt.encode('utf-8')

    raw_password = raw_password.encode('utf-8')
    hash = hashlib.new(algorithm, salt+raw_password).hexdigest()
    return '{}${}${}'.format(algorithm, salt.decode('utf-8'), hash)
1081332
private static SecretKey cekByKMS(byte[] cekSecured, String keyWrapAlgo,
                                      EncryptionMaterials materials,
                                      ContentCryptoScheme contentCryptoScheme, AWSKMS kms) {
        DecryptRequest kmsreq = new DecryptRequest()
            .withEncryptionContext(materials.getMaterialsDescription())
            .withCiphertextBlob(ByteBuffer.wrap(cekSecured));
        DecryptResult result = kms.decrypt(kmsreq);
        return new SecretKeySpec(copyAllBytesFrom(result.getPlaintext()),
                                 contentCryptoScheme.getKeyGeneratorAlgorithm());
    }
1185580
def encrypt(data, digest=True):
    """"""
    alg = get_best_algorithm()
    enc = implementations["encryption"][alg](
        data, implementations["get_key"]()
    )
    return "%s$%s" % (alg, (_to_hex_digest(enc) if digest else enc))
1320368
def encryptstring(text, password):
    

    enc = []
    for i in enumerate(text):
        key_c = password[i[0] % len(password)]
        enc_c = chr((ord(i[1]) + ord(key_c)) % 256)
        enc.append(enc_c)
    return base64.urlsafe_b64encode("".join(enc).encode()).decode()
982023
public static CipherInputStream encrypt(StorageObjectMetadata meta,
                                          long originalContentLength,
                                          InputStream src,
                                          RemoteStoreFileEncryptionMaterial encMat,
                                          SnowflakeStorageClient client)
  throws InvalidKeyException,
         InvalidAlgorithmParameterException,
         NoSuchAlgorithmException,
         NoSuchProviderException,
         NoSuchPaddingException,
         FileNotFoundException,
         IllegalBlockSizeException,
         BadPaddingException
  {
    final byte[] decodedKey = Base64.decode(encMat.getQueryStageMasterKey());
    final int keySize = decodedKey.length;
    final byte[] fileKeyBytes = new byte[keySize];
    final byte[] ivData;
    final CipherInputStream cis;
    final int blockSz;
    {
      final Cipher fileCipher = Cipher.getInstance(FILE_CIPHER);
      blockSz = fileCipher.getBlockSize();

      // Create IV
      ivData = new byte[blockSz];
      getSecRnd().nextBytes(ivData);
      final IvParameterSpec iv = new IvParameterSpec(ivData);

      // Create file key
      getSecRnd().nextBytes(fileKeyBytes);
      SecretKey fileKey = new SecretKeySpec(fileKeyBytes, 0, keySize, AES);

      // Init cipher
      fileCipher.init(Cipher.ENCRYPT_MODE, fileKey, iv);

      // Create encrypting input stream
      cis = new CipherInputStream(src, fileCipher);
    }

    // Encrypt the file key with the QRMK
    {
      final Cipher keyCipher = Cipher.getInstance(KEY_CIPHER);
      SecretKey queryStageMasterKey =
          new SecretKeySpec(decodedKey, 0, keySize, AES);

      // Init cipher
      keyCipher.init(Cipher.ENCRYPT_MODE, queryStageMasterKey);
      byte[] encKeK = keyCipher.doFinal(fileKeyBytes);

      // Store metadata
      MatDesc matDesc =
          new MatDesc(encMat.getSmkId(), encMat.getQueryId(), keySize * 8);
      // Round up length to next multiple of the block size
      // Sizes that are multiples of the block size need to be padded to next
      // multiple
      long contentLength = ((originalContentLength + blockSz) / blockSz) * blockSz;
      client.addEncryptionMetadata(meta, matDesc, ivData, encKeK, contentLength);
    }

    return cis;
  }
1269909
function encrypt(input, secret) {
  if (!secret) {
    return new Error('A \'secret\' is required to encrypt');
  }


  var salt = cryptoLib.randomBytes(KEY_LENGTH / 8),
    iv = cryptoLib.randomBytes(16);

  try {

    var key = cryptoLib.pbkdf2Sync(secret, salt, ITERATIONS, KEY_LENGTH / 8, 'sha1'),
      cipher = cryptoLib.createCipheriv(CIPHER, key, iv);

    var encryptedValue = cipher.update(input, 'utf8', 'base64');
    encryptedValue += cipher.final('base64');

    var result = {
      cipher: CIPHER,
      keyDerivation: KEY_DERIVATION,
      keyLength: KEY_LENGTH,
      iterations: ITERATIONS,
      iv: iv.toString('base64'),
      salt: salt.toString('base64'),
      value: encryptedValue
    };
    return result;

  } catch (err) {
    return new Error('Unable to encrypt value due to: ' + err);
  }
}
676858
def encrypt_text(self, text, *args, **kwargs):
        
        b = text.encode("utf-8")
        token = self.encrypt(b, *args, **kwargs)
        return base64.b64encode(token).decode("utf-8")