[START kms_list_cryptokey_versions]
335582
async function listCryptoKeyVersions(
  projectId = 'your-project-id', // Your GCP projectId
  keyRingId = 'my-key-ring', // name of the crypto key's key ring
  cryptoKeyId = 'my-key-ring' // name of the crypto key from which to list versions
) {
  // Import the library and create a client
  const kms = require('@google-cloud/kms');
  const client = new kms.KeyManagementServiceClient();

  // The location of the crypto key's key ring, e.g. "global"
  const locationId = 'global';

  // Get full path to crypto key
  const parent = client.cryptoKeyPath(
    projectId,
    locationId,
    keyRingId,
    cryptoKeyId
  );

  // Creates a new key ring
  const [versions] = await client.listCryptoKeyVersions({parent});
  if (versions.length) {
    versions.forEach(version => {
      console.log(`${version.name}:`);
      console.log(`  Created: ${new Date(version.createTime.seconds * 1000)}`);
      console.log(`  State: ${version.state}`);
    });
  } else {
    console.log('No crypto key versions found.');
  }
}
83844
private AWSKMSClient newAWSKMSClient(
            AWSCredentialsProvider credentialsProvider,
            ClientConfiguration clientConfig,
            CryptoConfiguration cryptoConfig,
            RequestMetricCollector requestMetricCollector
    ) {
        final AWSKMSClient kmsClient = new AWSKMSClient(
            credentialsProvider, clientConfig, requestMetricCollector);
        final Region kmsRegion = cryptoConfig.getAwsKmsRegion();
        if (kmsRegion != null)
            kmsClient.setRegion(kmsRegion);
        return kmsClient;
    }
1300458
def crypto_sign_keypair():
    
    pk = ffi.new("unsigned char[]", crypto_sign_PUBLICKEYBYTES)
    sk = ffi.new("unsigned char[]", crypto_sign_SECRETKEYBYTES)

    rc = lib.crypto_sign_keypair(pk, sk)
    ensure(rc == 0,
           'Unexpected library error',
           raising=exc.RuntimeError)

    return (
        ffi.buffer(pk, crypto_sign_PUBLICKEYBYTES)[:],
        ffi.buffer(sk, crypto_sign_SECRETKEYBYTES)[:],
    )
1047504
def common(request):
    
    ctx = {
        'SHIB_SUPPORTED': settings.SHIB_SUPPORTED,
        'org_name': settings.ACCOUNTS_ORG_NAME,
        'accounts_email': settings.ACCOUNTS_EMAIL,
        'is_admin': is_admin(request),
        'kgversion': __version__,
        'BUILD_DATE': settings.BUILD_DATE,
        'VCS_REF': settings.VCS_REF,
        'SLURM_VER': settings.SLURM_VER,
    }

    return ctx
835499
def should_add_ServerHello(self):
        
        if isinstance(self.mykey, PrivKeyRSA):
            kx = "RSA"
        elif isinstance(self.mykey, PrivKeyECDSA):
            kx = "ECDSA"
        usable_suites = get_usable_ciphersuites(self.cur_pkt.ciphers, kx)
        c = usable_suites[0]
        if self.preferred_ciphersuite in usable_suites:
            c = self.preferred_ciphersuite
        self.add_msg(TLSServerHello(cipher=c))
        raise self.ADDED_SERVERHELLO()
326176
def list_keypairs(call=None):
    '''
    
    '''
    if call != 'function':
        log.error(
            'The list_keypairs function must be called with -f or --function.'
        )
        return False

    fetch = True
    page = 1
    ret = {}

    while fetch:
        items = query(method='account/keys', command='?page=' + six.text_type(page) +
                      '&per_page=100')

        for key_pair in items['ssh_keys']:
            name = key_pair['name']
            if name in ret:
                raise SaltCloudSystemExit(
                    'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s '
                    'key pair list. Please change the key name stored by DigitalOcean. '
                    'Be sure to adjust the value of \'ssh_key_file\' in your cloud '
                    'profile or provider configuration, if necessary.'.format(
                        name
                    )
                )
            ret[name] = {}
            for item in six.iterkeys(key_pair):
                ret[name][item] = six.text_type(key_pair[item])

        page += 1
        try:
            fetch = 'next' in items['links']['pages']
        except KeyError:
            fetch = False

    return ret
176293
def update_keyjar(keyjar):
    
    for iss, kbl in keyjar.items():
        for kb in kbl:
            kb.update()
308428
def crypto_revision_from_aes_key(key_size, hardened)
            if key_size == 128
                version = revision = 4
            elsif key_size == 256
                version = 5
                if hardened
                    revision = 6
                else
                    revision = 5
                end
            else
                raise EncryptionError, "Invalid AES key length (Only 128 and 256 bits keys are supported)"
            end

            [ version, revision ]
        end
1070307
def get_ks_archs(self):
        '''  '''
        ks_archs = {
            'x16':     (KS_ARCH_X86,     KS_MODE_16),
            'x86':     (KS_ARCH_X86,     KS_MODE_32),
            'x64':     (KS_ARCH_X86,     KS_MODE_64),
            'arm':     (KS_ARCH_ARM,     KS_MODE_ARM),
            'arm_t':   (KS_ARCH_ARM,     KS_MODE_THUMB),
            'arm64':   (KS_ARCH_ARM64,   KS_MODE_LITTLE_ENDIAN),
            'mips32':  (KS_ARCH_MIPS,    KS_MODE_MIPS32),
            'mips64':  (KS_ARCH_MIPS,    KS_MODE_MIPS64),
            'ppc32':   (KS_ARCH_PPC,     KS_MODE_PPC32),
            'ppc64':   (KS_ARCH_PPC,     KS_MODE_PPC64),
            'hexagon': (KS_ARCH_HEXAGON, KS_MODE_BIG_ENDIAN),
            'sparc':   (KS_ARCH_SPARC,   KS_MODE_SPARC32),
            'sparc64': (KS_ARCH_SPARC,   KS_MODE_SPARC64),
            'systemz': (KS_ARCH_SYSTEMZ, KS_MODE_BIG_ENDIAN)
            }
        return ks_archs
1182408
protected function setCryptoKey($cryptokey): void
    {
        if (! is_string($cryptokey)) {
            throw StrictTypeException::cryptoKeyNotString($cryptokey);
        }
        if (ctype_xdigit($cryptokey)) {
            $len = strlen($cryptokey);
            $cryptokey = sodium_hex2bin($cryptokey);
        }
        // insert check here to make sure is binary integer
        if (! isset($len)) {
            $hex = sodium_bin2hex($cryptokey);
            $len = strlen($hex);
            sodium_memzero($hex);
        }
        if ($len !== 64) {
            throw InvalidArgumentException::wrongByteSizeKey($len);
        }
        if (ctype_print($cryptokey)) {
            throw InvalidArgumentException::secretOnlyPrintable();
        }
        //test that the key supplied works
        $string = 'ABC test 123 test xyz';
        $TEST_NONCE = sodium_hex2bin('74b9e852b172df7f57ff4ab4');
        if ($this->aesgcm) {
            $ciphertext = sodium_crypto_aead_aes256gcm_encrypt($string, $TEST_NONCE, $TEST_NONCE, $cryptokey);
            $test = sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $TEST_NONCE, $TEST_NONCE, $cryptokey);
        } else {
            $ciphertext = sodium_crypto_aead_chacha20poly1305_encrypt($string, $TEST_NONCE, $TEST_NONCE, $cryptokey);
            $test = sodium_crypto_aead_chacha20poly1305_decrypt($ciphertext, $TEST_NONCE, $TEST_NONCE, $cryptokey);
        }
        if ($string === $test) {
            $this->cryptokey = $cryptokey;
            $this->enabled = true;
            sodium_memzero($cryptokey);
            return;
        }
        return;
    }
311959
def list_():
    '''
    
    '''
    pki_dir = __salt__['config.get']('pki_dir', '')

    # We have to replace the minion/master directories
    pki_dir = pki_dir.replace('minion', 'master')

    # The source code below is (nearly) a copy of salt.key.Key.list_keys
    key_dirs = _check_minions_directories(pki_dir)

    ret = {}

    for dir_ in key_dirs:
        ret[os.path.basename(dir_)] = []
        try:
            for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
                if not fn_.startswith('.'):
                    if os.path.isfile(os.path.join(dir_, fn_)):
                        ret[os.path.basename(dir_)].append(fn_)
        except (OSError, IOError):
            # key dir kind is not created yet, just skip
            continue

    return ret
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());
    }
241681
async function disableCryptoKeyVersion(
  projectId = 'your-project-id', // Your GCP Project ID
  keyRingId = 'my-key-ring', // Name of the crypto key version's key ring
  cryptoKeyId = 'my-key', // Name of the version's crypto key
  version = 1234 // The version's id
) {
  // Import the library and create a client
  const kms = require('@google-cloud/kms');
  const client = new kms.KeyManagementServiceClient();

  // The location of the crypto key versions's key ring, e.g. "global"
  const locationId = 'global';

  // Get the full path to the crypto key
  const name = client.cryptoKeyVersionPath(
    projectId,
    locationId,
    keyRingId,
    cryptoKeyId,
    version
  );

  // Gets a crypto key version
  const [cryptoKeyVersion] = await client.getCryptoKeyVersion({name});
  cryptoKeyVersion.state = 'DISABLED';

  // Disables a crypto key version
  const [result] = await client.updateCryptoKeyVersion({
    cryptoKeyVersion,
    updateMask: ['state'],
  });
  console.log(`Crypto key version ${result.name} disabled.`);
}
71484
public static void main(String[] args)
	{
		try
		{
			if (args.length == 0)
			{

				System.err.println("Usage java " + Cryption.class.getName()
				+ " <text>");
				return;

			}

			final String decryptedPassword;

			if (args[0].equals("-d"))
			{
				if (args.length > 2)
				{
					StringBuilder p = new StringBuilder();
					for (int i = 1; i < args.length; i++)
					{
						if (i > 1)
							p.append(' ');

						p.append(args[i]);
					}

					decryptedPassword = p.toString();
				}
				else
				{
					decryptedPassword = args[1];
				}

				System.out.println(getCanonical().decryptText(decryptedPassword));
			}
			else
				System.out.println(CRYPTION_PREFIX
				+ getCanonical().encryptText(args[0]));

		}
		catch (Exception e)
		{

			e.printStackTrace();
		}

	}
91393
function _setupInlineCrypt()
    {
        $lambda_functions =& self::_getLambdaFunctions();

        // We create max. 10 hi-optimized code for memory reason. Means: For each $key one ultra fast inline-crypt function.
        // (Currently, for Blowfish, one generated $lambda_function cost on php5.5@32bit ~100kb unfreeable mem and ~180kb on php5.5@64bit)
        // After that, we'll still create very fast optimized code but not the hi-ultimative code, for each $mode one.
        $gen_hi_opt_code = (bool)(count($lambda_functions) < 10);

        // Generation of a unique hash for our generated code
        $code_hash = "Crypt_Blowfish, {$this->mode}";
        if ($gen_hi_opt_code) {
            $code_hash = str_pad($code_hash, 32) . $this->_hashInlineCryptFunction($this->key);
        }

        $safeint = $this->safe_intval_inline();

        if (!isset($lambda_functions[$code_hash])) {
            switch (true) {
                case $gen_hi_opt_code:
                    $p = $this->bctx['p'];
                    $init_crypt = '
                        static $sb_0, $sb_1, $sb_2, $sb_3;
                        if (!$sb_0) {
                            $sb_0 = $self->bctx["sb"][0];
                            $sb_1 = $self->bctx["sb"][1];
                            $sb_2 = $self->bctx["sb"][2];
                            $sb_3 = $self->bctx["sb"][3];
                        }
                    ';
                    break;
                default:
                    $p   = array();
                    for ($i = 0; $i < 18; ++$i) {
                        $p[] = '$p_' . $i;
                    }
                    $init_crypt = '
                        list($sb_0, $sb_1, $sb_2, $sb_3) = $self->bctx["sb"];
                        list(' . implode(',', $p) . ') = $self->bctx["p"];

                    ';
            }

            // Generating encrypt code:
            $encrypt_block = '
                $in = unpack("N*", $in);
                $l = $in[1];
                $r = $in[2];
            ';
            for ($i = 0; $i < 16; $i+= 2) {
                $encrypt_block.= '
                    $l^= ' . $p[$i] . ';
                    $r^= ' . sprintf($safeint, '(' . sprintf($safeint, '$sb_0[$l >> 24 & 0xff] + $sb_1[$l >> 16 & 0xff]') . ' ^
                          $sb_2[$l >>  8 & 0xff]) +
                          $sb_3[$l       & 0xff]') . ';

                    $r^= ' . $p[$i + 1] . ';
                    $l^= ' . sprintf($safeint, '(' . sprintf($safeint, '$sb_0[$r >> 24 & 0xff] + $sb_1[$r >> 16 & 0xff]') . '  ^
                          $sb_2[$r >>  8 & 0xff]) +
                          $sb_3[$r       & 0xff]') . ';
                ';
            }
            $encrypt_block.= '
                $in = pack("N*",
                    $r ^ ' . $p[17] . ',
                    $l ^ ' . $p[16] . '
                );
            ';

            // Generating decrypt code:
            $decrypt_block = '
                $in = unpack("N*", $in);
                $l = $in[1];
                $r = $in[2];
            ';

            for ($i = 17; $i > 2; $i-= 2) {
                $decrypt_block.= '
                    $l^= ' . $p[$i] . ';
                    $r^= ' . sprintf($safeint, '(' . sprintf($safeint, '$sb_0[$l >> 24 & 0xff] + $sb_1[$l >> 16 & 0xff]') . ' ^
                          $sb_2[$l >>  8 & 0xff]) +
                          $sb_3[$l       & 0xff]') . ';

                    $r^= ' . $p[$i - 1] . ';
                    $l^= ' . sprintf($safeint, '(' . sprintf($safeint, '$sb_0[$r >> 24 & 0xff] + $sb_1[$r >> 16 & 0xff]') . ' ^
                          $sb_2[$r >>  8 & 0xff]) +
                          $sb_3[$r       & 0xff]') . ';
                ';
            }

            $decrypt_block.= '
                $in = pack("N*",
                    $r ^ ' . $p[0] . ',
                    $l ^ ' . $p[1] . '
                );
            ';

            $lambda_functions[$code_hash] = $this->_createInlineCryptFunction(
                array(
                   'init_crypt'    => $init_crypt,
                   'init_encrypt'  => '',
                   'init_decrypt'  => '',
                   'encrypt_block' => $encrypt_block,
                   'decrypt_block' => $decrypt_block
                )
            );
        }
        $this->inline_crypt = $lambda_functions[$code_hash];
    }
119666
function decrypt(env, callback) {
  if (!env.AWS_DEFAULT_REGION) return callback(new Error('AWS_DEFAULT_REGION env var must be set'));
  var kms = new AWS.KMS({
    region: env.AWS_DEFAULT_REGION,
    maxRetries: 10
  });
  var q = queue();
  for (var key in env) {
    if (!(/^secure:/).test(env[key])) continue;
    q.defer(function(key, val, done) {
      kms.decrypt({
        CiphertextBlob: new Buffer(val, 'base64')
      }, function(err, data) {
        if (err) return done(err);
        done(null, { key: key, val: val, decrypted: (new Buffer(data.Plaintext, 'base64')).toString('utf8') });
      });
    }, key, env[key].replace(/^secure:/,''));
  }
  q.awaitAll(function(err, results) {
    if (err) return callback(err);
    callback(null, results);
  });
}
491372
def _parse_kexgss_complete(self, m):
        
        # client mode
        if self.transport.host_key is None:
            self.transport.host_key = NullHostKey()
        self.f = m.get_mpint()
        if (self.f < 1) or (self.f > self.P - 1):
            raise SSHException('Server kex "f" is out of range')
        mic_token = m.get_string()
        # This must be TRUE, if there is a GSS-API token in this message.
        bool = m.get_boolean()
        srv_token = None
        if bool:
            srv_token = m.get_string()
        K = pow(self.f, self.x, self.P)
        # okay, build up the hash H of
        # (V_C || V_S || I_C || I_S || K_S || e || f || K)
        hm = Message()
        hm.add(
            self.transport.local_version,
            self.transport.remote_version,
            self.transport.local_kex_init,
            self.transport.remote_kex_init,
        )
        hm.add_string(self.transport.host_key.__str__())
        hm.add_mpint(self.e)
        hm.add_mpint(self.f)
        hm.add_mpint(K)
        H = sha1(str(hm)).digest()
        self.transport._set_K_H(K, H)
        if srv_token is not None:
            self.kexgss.ssh_init_sec_context(
                target=self.gss_host, recv_token=srv_token
            )
            self.kexgss.ssh_check_mic(mic_token, H)
        else:
            self.kexgss.ssh_check_mic(mic_token, H)
        self.transport.gss_kex_used = True
        self.transport._activate_outbound()