Secure the keychain
358867
def lock
      cmd = Xcode::Shell::Command.new "security"
      cmd << "lock-keychain"
      cmd << "\"#{@path}\""
      cmd.execute
    end
283018
def ensureKeysAreSetup(self):
        
        if not areKeysSetup(self.name, self.keys_dir):
            raise REx(REx.reason.format(self.name) + self.keygenScript)
804255
function (wallet) {
    var data = JSON.stringify(wallet, null, 2)
    var enc = Blockchain.WalletCrypto.encryptWallet(data, password, wallet.options.pbkdf2_iterations, 2.0)
    var check = sha256(enc).toString('hex')

    // Throws if there is an encryption error
    Blockchain.WalletCrypto.decryptWallet(enc, password, function () {}, function () {
      throw 'Failed to confirm successful encryption when generating new wallet'
    })

    var postData = {
      guid: wallet.guid,
      sharedKey: wallet.sharedKey,
      length: enc.length,
      payload: enc,
      checksum: check,
      method: 'insert',
      format: 'plain'
    }

    if (email) postData.email = email

    return Blockchain.API.securePost('wallet', postData).then(function () {
      if (isHdWallet) {
        var account = wallet.hd_wallets[0].accounts[0]
        return { guid: wallet.guid, address: account.xpub, label: account.label }
      } else {
        var firstKey = wallet.keys[0]
        return { guid: wallet.guid, address: firstKey.addr, label: firstKey.label, warning: warnings.CREATED_NON_HD }
      }
    })
  }
637533
function(keyId) {
    var res = this.get("25519KeysignedKey" + keyId);
    if (res !== undefined) {
      if (!(res.pubKey instanceof ArrayBuffer)) {
        res.pubKey = convertToArrayBuffer(res.pubKey);
      }
      if (!(res.privKey instanceof ArrayBuffer)) {
        res.privKey = convertToArrayBuffer(res.privKey);
      }
      res = { pubKey: res.pubKey, privKey: res.privKey };
    }
    return Promise.resolve(res);
  }
1033519
def file_decrypt( blockchain_id, hostname, sender_blockchain_id, sender_key_id, input_path, output_path, passphrase=None, config_path=CONFIG_PATH, wallet_keys=None ):
    
    config_dir = os.path.dirname(config_path)
    decrypted = False
    old_key = False
    old_key_index = 0
    sender_old_key_index = 0

    # get the sender key 
    sender_key_info = file_key_lookup( sender_blockchain_id, None, None, key_id=sender_key_id, config_path=config_path, wallet_keys=wallet_keys ) 
    if 'error' in sender_key_info:
        log.error("Failed to look up sender key: %s" % sender_key_info['error'])
        return {'error': 'Failed to lookup sender key'}

    if 'stale_key_index' in sender_key_info.keys():
        old_key = True
        sender_old_key_index = sender_key_info['sender_key_index']

    # try each of our keys
    # current key...
    key_info = file_key_lookup( blockchain_id, 0, hostname, config_path=config_path, wallet_keys=wallet_keys )
    if 'error' not in key_info:
        res = file_decrypt_from_key_info( sender_key_info, blockchain_id, 0, hostname, input_path, output_path, passphrase=passphrase, config_path=config_path, wallet_keys=wallet_keys )
        if 'error' in res:
            if not res['status']:
                # permanent failure 
                log.error("Failed to decrypt: %s" % res['error'])
                return {'error': 'Failed to decrypt'}

        else:
            decrypted = True

    else:
        # did not look up key 
        log.error("Failed to lookup key: %s" % key_info['error'])

    if not decrypted:
        # try old keys 
        for i in xrange(1, MAX_EXPIRED_KEYS):
            res = file_decrypt_from_key_info( sender_key_info, blockchain_id, i, hostname, input_path, output_path, passphrase=passphrase, config_path=config_path, wallet_keys=wallet_keys )
            if 'error' in res:
                # key is not online, but don't try again 
                log.error("Failed to decrypt: %s" % res['error'])
                return {'error': 'Failed to decrypt'}
            else:
                decrypted = True
                old_key = True
                old_key_index = i
                break

    if decrypted:
        log.debug("Decrypted with %s.%s" % (blockchain_id, hostname))

        ret = {'status': True}
        if old_key:
            ret['warning'] = "Used stale key"
            ret['stale_key_index'] = old_key_index
            ret['stale_sender_key_index'] = sender_old_key_index

        return ret

    else:
        return {'error': 'No keys could decrypt'}
1028042
def key_pair(i, region):
    """"""
    if i == 0:
        return ("{}_{}".format(RAY, region),
                os.path.expanduser("~/.ssh/{}_{}.pem".format(RAY, region)))
    return ("{}_{}_{}".format(RAY, i, region),
            os.path.expanduser("~/.ssh/{}_{}_{}.pem".format(RAY, i, region)))
1251547
function hmac(data, key) {
  mctx.init(key);
  mctx.update(data);
  return mctx.finish();
}
828471
def keyring_view(**kwargs):
    
    ctx = Context(**kwargs)
    ctx.execute_action('keyring:view', **{
        'storage': ctx.repo.create_secure_service('storage'),
    })
1243587
def _random_key(self):
        
        hashstr = '%s%s' % (random.random(), self.time_module.time())
        return hashlib.md5(hashstr).hexdigest()
541805
function genKey(bytes, callback) {
  // bytes is optional
  if (arguments.length < 2) {
    callback = bytes;
    bytes = 32;
  }
  if (typeof callback !== 'function') {
    throw("Callback required");
  }
  crypto.randomBytes(bytes, function(err, buf) {
    if (err) return callback (err);
    return callback(null, buf);
  });
}
626649
def default_keychain(name, domain="user", user=None):
    '''
    

    '''
    ret = {'name': name,
           'result': True,
           'comment': '',
           'changes': {}}

    if not os.path.exists(name):
        ret['result'] = False
        ret['comment'] += "Keychain not found at {0}".format(name)
    else:
        out = __salt__['keychain.get_default_keychain'](user, domain)

        if name in out:
            ret['comment'] += "{0} was already the default keychain.".format(name)
        else:
            out = __salt__['keychain.set_default_keychain'](name, domain, user)
            if not out:
                ret['changes']['default'] = name
            else:
                ret['result'] = False
                ret['comment'] = 'Failed to install keychain. {0}'.format(out)

    return ret
900164
def key_sign(rsakey, message, digest):
    """"""
    padding = _asymmetric.padding.PKCS1v15()
    signature = rsakey.sign(message, padding, digest)
    return signature
56739
def gen_key(path):
    '''
    
    '''
    cmd = 'ssh-keygen -P "" -f {0} -t rsa -q'.format(path)
    if not os.path.isdir(os.path.dirname(path)):
        os.makedirs(os.path.dirname(path))
    subprocess.call(cmd, shell=True)
1360814
def open(cls, blob, username, password):
        """"""
        return cls(blob, blob.encryption_key(username, password))
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])
946584
function(password, keyFile) {
    var that = this;
    this.ready = Promise.all([
        this.setPassword(password),
        this.setKeyFile(keyFile)
    ]).then(function() {
        return that;
    });
}
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());
    }