Create a MultiTenantEncryptor from configured keys.
973408
def configure_encryptor(graph):
    
    encryptor = graph.multi_tenant_key_registry.make_encryptor(graph)

    # register the encryptor will each encryptable type
    for encryptable in EncryptableMixin.__subclasses__():
        encryptable.register(encryptor)

    return encryptor
1320385
def generate_rsa_key_pair():
    """"""

    key = rsa.generate_private_key(
        backend=default_backend(), public_exponent=65537, key_size=2048)

    public_key = key.public_key().public_bytes(
        serialization.Encoding.OpenSSH,
        serialization.PublicFormat.OpenSSH).decode("utf-8")

    pem = key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption()).decode("utf-8")

    return public_key, pem
1242258
def make_key(self, *parts):
        """"""
        separator = getattr(self.model_class, 'index_separator', '.')
        parts = map(decode, parts)
        return '%s%s' % (self._base_key, separator.join(map(str, parts)))
659364
def encrypt_var(source, keys):
    """"""
    cmd = flatten([gnupg_bin(), "--armor", "--encrypt", gnupg_verbose(),
                   recipients_args(keys)])
    output = stderr_with_input(cmd, source)
    return output
62723
def crypto_config_from_kwargs(fallback, **kwargs):
    
    try:
        crypto_config = kwargs.pop("crypto_config")
    except KeyError:
        try:
            fallback_kwargs = {"table_name": kwargs["TableName"]}
        except KeyError:
            fallback_kwargs = {}
        crypto_config = fallback(**fallback_kwargs)
    return crypto_config, kwargs
557411
def GenerateKeys(config, overwrite_keys=False):
  """"""
  if not hasattr(key_utils, "MakeCACert"):
    raise OpenSourceKeyUtilsRequiredError(
        "Generate keys can only run with open source key_utils.")
  if (config.Get("PrivateKeys.server_key", default=None) and
      not overwrite_keys):
    print(config.Get("PrivateKeys.server_key"))
    raise KeysAlreadyExistError(
        "Config %s already has keys, use --overwrite_keys to "
        "override." % config.parser)

  length = grr_config.CONFIG["Server.rsa_key_length"]
  print("All keys will have a bit length of %d." % length)
  print("Generating executable signing key")
  executable_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=length)
  config.Set("PrivateKeys.executable_signing_private_key",
             executable_key.AsPEM())
  config.Set("Client.executable_signing_public_key",
             executable_key.GetPublicKey().AsPEM())

  print("Generating CA keys")
  ca_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=length)
  ca_cert = key_utils.MakeCACert(ca_key)
  config.Set("CA.certificate", ca_cert.AsPEM())
  config.Set("PrivateKeys.ca_key", ca_key.AsPEM())

  print("Generating Server keys")
  server_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=length)
  server_cert = key_utils.MakeCASignedCert(u"grr", server_key, ca_cert, ca_key)
  config.Set("Frontend.certificate", server_cert.AsPEM())
  config.Set("PrivateKeys.server_key", server_key.AsPEM())

  print("Generating secret key for csrf protection.")
  _GenerateCSRFKey(config)
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
1188610
def encode_keys(self, keys):
        
        return dict(((k, self.encode(v)) for k, v in six.iteritems(keys) if not
                     is_null(v)))
93255
def __get_keys(self, name='master', passphrase=None):
        '''
        
        '''
        path = os.path.join(self.opts['pki_dir'],
                            name + '.pem')
        if not os.path.exists(path):
            log.info('Generating %s keys: %s', name, self.opts['pki_dir'])
            gen_keys(self.opts['pki_dir'],
                     name,
                     self.opts['keysize'],
                     self.opts.get('user'),
                     passphrase)
        if HAS_M2:
            key_error = RSA.RSAError
        else:
            key_error = ValueError
        try:
            key = get_rsa_key(path, passphrase)
        except key_error as e:
            message = 'Unable to read key: {0}; passphrase may be incorrect'.format(path)
            log.error(message)
            raise MasterExit(message)
        log.debug('Loaded %s key: %s', name, path)
        return key
205960
def _transform_key(self, masterkey):
        """"""

        aes = AES.new(self._transf_randomseed, AES.MODE_ECB)

        # Encrypt the created hash
        for _ in range(self._key_transf_rounds):
            masterkey = aes.encrypt(masterkey)

        # Finally, hash it again...
        sha_obj = SHA256.new()
        sha_obj.update(masterkey)
        masterkey = sha_obj.digest()
        # ...and hash the result together with the randomseed
        sha_obj = SHA256.new()
        sha_obj.update(self._final_randomseed + masterkey)
        return sha_obj.digest()
165688
def iterkeys(self):
        """"""
        patterns = self.patterns
        replace = self.replace
        seen = set()
        for key in six.iterkeys(self.base):
            for pattern in patterns:
                m = pattern.match(key)
                if m:
                    ret = m.group('key') if replace else m.group()
                    if ret not in seen:
                        seen.add(ret)
                        yield ret
                    break
        for key in DictMethods.iterkeys(self):
            if key not in seen:
                yield key
471177
def from_text(textring):
    """"""

    keyring = {}
    for keytext in textring:
        keyname = dns.name.from_text(keytext)
        secret = base64.decodestring(textring[keytext])
        keyring[keyname] = secret
    return keyring
434514
function(key, cb, reader) {
        var decrypt, finished, gunzip, jsParse;
        if (!devices) {
          if (typeof cb === "function") {
            cb('no devices', null);
          }
          return typeof done === "function" ? done() : void 0;
        } else {
          jsParse = new jsonStream.parse('*');
          decrypt = crypto.createDecipher(algorithm, settings.ENCRYPTION_KEY || settings.SESSION_SECRET || '5random7493nonsens!e');
          gunzip = zlib.createGunzip();
          finished = false;
          return async.eachSeries(devices, function(device, callback) {
            var calledBack, st;
            if (!finished) {
              calledBack = false;
              if (!reader) {
                reader = device.getReadStream(key);
              }
              st = reader;
              if (doencrypt) {
                st = st.pipe(decrypt);
              }
              if (dozip) {
                st = st.pipe(gunzip);
              }
              st.pipe(jsParse).pipe(es.mapSync(function(data) {
                finished = true;
                calledBack = true;
                if (typeof cb === "function") {
                  cb(null, data);
                }
                if (typeof done === "function") {
                  done();
                }
                return callback();
              }));
              reader.on('error', function(e) {
                if (!calledBack) {
                  calledBack = true;
                  return callback();
                }
              });
              st.on('error', function(e) {
                if (!calledBack) {
                  calledBack = true;
                  finished = true;
                  if (typeof cb === "function") {
                    cb('encrypt error', null);
                  }
                  return callback();
                }
              });
              jsParse.on('error', function(e) {
                return console.log('Error parsing database - have you changed your encryption key or turned encryption on or off?  If so, update your database using ndx-framework.');
              });
              return st.on('end', function() {
                if (!calledBack) {
                  calledBack = true;
                  return callback();
                }
              });
            } else {
              return callback();
            }
          }, function() {
            if (!finished) {
              if (typeof cb === "function") {
                cb('nothing found', null);
              }
              return typeof done === "function" ? done() : void 0;
            }
          });
        }
      }
55249
private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes) throws NoSuchAlgorithmException, InvalidKeySpecException {

    final PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);
    final SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
    return skf.generateSecret(spec).getEncoded();
  }
1227540
static RSAPublicKey from(final byte[] key)
      throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException {

    final String s = new String(key);
    final byte[] encoded;
    final String decoded;
    if (s.startsWith(RSA_LABEL)) {
      decoded = s.split(" ")[1];
      encoded = Base64.decodeBase64(decoded);
    } else {
      encoded = key;
      decoded = Base64.encodeBase64String(key);
    }

    final Iterator<byte[]> fields = new ByteIterator(encoded);
    final String sigType = new String(fields.next());
    if (!sigType.equals(RSA_LABEL)) {
      throw new RuntimeException(String.format(
          "Unknown key type %s. This code currently only supports %s.", sigType, RSA_LABEL));
    }

    final RSAPublicKeySpec keySpec =
        TraditionalKeyParser.parsePemPublicKey(RSA_LABEL + " " + decoded + " ");
    final KeyFactory keyFactory = KeyFactory.getInstance("Rsa");
    return (RSAPublicKey) keyFactory.generatePublic(keySpec);
  }
438909
def FromPublicKey(cls, public_key):
    """"""
    # Our CN will be the first 64 bits of the hash of the public key
    # in MPI format - the length of the key in 4 bytes + the key
    # prefixed with a 0. This weird format is an artifact from the way
    # M2Crypto handled this, we have to live with it for now.
    n = public_key.GetN()
    raw_n = binascii.unhexlify("%x" % n)

    mpi_format = struct.pack(">i", len(raw_n) + 1) + b"\x00" + raw_n

    digest = binascii.hexlify(hashlib.sha256(mpi_format).digest()[:8])
    return cls("C.{}".format(digest.decode("ascii")))
1202452
def encrypt(self, key, iv="", cek="", **kwargs):
        

        _msg = as_bytes(self.msg)
        if "zip" in self:
            if self["zip"] == "DEF":
                _msg = zlib.compress(_msg)
            else:
                raise ParameterError("Zip has unknown value: %s" % self["zip"])

        kwarg_cek = cek or None

        _enc = self["enc"]
        iv = self._generate_iv(_enc, iv)
        cek = self._generate_key(_enc, cek)
        self["cek"] = cek

        logger.debug("cek: %s, iv: %s" % ([c for c in cek], [c for c in iv]))

        _encrypt = RSAEncrypter(self.with_digest).encrypt

        _alg = self["alg"]
        if kwarg_cek:
            jwe_enc_key = ''
        elif _alg == "RSA-OAEP":
            jwe_enc_key = _encrypt(cek, key, 'pkcs1_oaep_padding')
        elif _alg == "RSA-OAEP-256":
            jwe_enc_key = _encrypt(cek, key, 'pkcs1_oaep_256_padding')
        elif _alg == "RSA1_5":
            jwe_enc_key = _encrypt(cek, key)
        else:
            raise NotSupportedAlgorithm(_alg)

        jwe = JWEnc(**self.headers())

        try:
            _auth_data = kwargs['auth_data']
        except KeyError:
            _auth_data = jwe.b64_encode_header()

        ctxt, tag, key = self.enc_setup(_enc, _msg, key=cek, iv=iv,
                                        auth_data=_auth_data)
        return jwe.pack(parts=[jwe_enc_key, iv, ctxt, tag])