/*
Use this method if you have a hex-encoded private key
and you want to initialize your private key.
If you have a private key, you can derive your public key
and also your sin.
@param string
542624
public function setHex($hex)
    {
        $this->hex = $hex;
        $this->dec = Util::decodeHex($this->hex);
    }
235705
public function encode($string)
    {

        if (empty($string) || empty($this->key)) {
            throw new \Exception("Can not encrypt with an empty key or no data");
            return false;
        }

        $publicKey = $this->generateKey($string);
        $privateKey = $this->key;


        //Get a SHA-1 hashKey 
        $hashKey = sha1($privateKey . "+" . (string)$publicKey);

        $stringArray = str_split($string);
        $hashArray = str_split($hashKey);
        $cipherNoise = str_split($publicKey, 2);

        $counter = 0;

        for ($i = 0; $i < sizeof($stringArray); $i++) {
            if ($counter > 40)
                $counter = 0;
            $cryptChar = ord((string)$stringArray[$i]) + ord((string)$hashArray[$counter]);
            $cryptChar -= floor($cryptChar / 127) * 127;
            $cipherStream[$i] = dechex($cryptChar);
            $counter++;
        }
        //print_R($cipherNoise);

        $cipherNoiseSize = count($cipherNoise);

        $cipher = implode("|x", $cipherStream);
        $cipher .= "|x::|x" . ord((string)$cipherNoiseSize) . "|x";
        $cipher .= implode("|x", $cipherNoise);


        //echo $cipher;

        return $cipher;
    }
605106
public void init(byte[] blob, int start, int len) throws SshException {

		try {

			ByteArrayInputStream is = new ByteArrayInputStream(blob, start, len);

			CertificateFactory cf = JCEProvider
					.getProviderForAlgorithm(JCEAlgorithms.JCE_X509) == null ? CertificateFactory
					.getInstance(JCEAlgorithms.JCE_X509) : CertificateFactory
					.getInstance(JCEAlgorithms.JCE_X509, JCEProvider
							.getProviderForAlgorithm(JCEAlgorithms.JCE_X509));

			this.cert = (X509Certificate) cf.generateCertificate(is);
			if (!(cert.getPublicKey() instanceof RSAPublicKey))
				throw new SshException(
						"Certificate public key is not an RSA public key!",
						SshException.BAD_API_USAGE);

			this.pubKey = (RSAPublicKey) cert.getPublicKey();

		} catch (Throwable ex) {
			throw new SshException(ex.getMessage(), SshException.JCE_ERROR, ex);
		}
	}
751231
function init(ctx) {
        var server = ctx.server;

        if (!privateKey) {
            throw new Error('Please set config.security.token.privateKey');
        }

        server.ext('onPreAuth', validateToken);

        return new Q(ctx);
    }
172354
public void init(byte[] blob, int start, int len) throws SshException {

		ByteArrayReader bar = new ByteArrayReader(blob, start, len);

		try {
			DSAPublicKeySpec dsaKey;

			// Extract the key information
			String header = bar.readString();

			if (!header.equals(getAlgorithm())) {
				throw new SshException("The encoded key is not DSA",
						SshException.INTERNAL_ERROR);
			}

			BigInteger p = bar.readBigInteger();
			BigInteger q = bar.readBigInteger();
			BigInteger g = bar.readBigInteger();
			BigInteger y = bar.readBigInteger();
			dsaKey = new DSAPublicKeySpec(y, p, q, g);

			KeyFactory kf = JCEProvider
					.getProviderForAlgorithm(JCEAlgorithms.JCE_DSA) == null ? KeyFactory
					.getInstance(JCEAlgorithms.JCE_DSA) : KeyFactory
					.getInstance(JCEAlgorithms.JCE_DSA, JCEProvider
							.getProviderForAlgorithm(JCEAlgorithms.JCE_DSA));
			pubkey = (DSAPublicKey) kf.generatePublic(dsaKey);

		} catch (Exception ex) {
			throw new SshException(
					"Failed to obtain DSA key instance from JCE",
					SshException.INTERNAL_ERROR, ex);

		} finally {
			try {
				bar.close();
			} catch (IOException e) {
			}
		}
	}
348317
function _rsapem_privateKeyToPkcs1HexString(rsaKey) {
    var result = _rsapem_derEncodeNumber(0);
    result += _rsapem_derEncodeNumber(rsaKey.n);
    result += _rsapem_derEncodeNumber(rsaKey.e);
    result += _rsapem_derEncodeNumber(rsaKey.d);
    result += _rsapem_derEncodeNumber(rsaKey.p);
    result += _rsapem_derEncodeNumber(rsaKey.q);
    result += _rsapem_derEncodeNumber(rsaKey.dmp1);
    result += _rsapem_derEncodeNumber(rsaKey.dmq1);
    result += _rsapem_derEncodeNumber(rsaKey.coeff);

    var fullLen = _rsapem_encodeLength(result.length / 2);
    return '30' + fullLen + result;
}
1034347
public function CreateEncrpytionKey()
	{
		if (function_exists('random_bytes'))
		{
			return base64_encode(random_bytes(32));
		}
		if (function_exists('openssl_random_pseudo_bytes'))
		{
			return base64_encode(openssl_random_pseudo_bytes(32));
		}
		throw new GrabzItException("Your installation of PHP does not support a method for making a cryptographically secure encryption key. Please upgrade to at least PHP 5.3", GrabzItException::GENERIC_ERROR);		
	}
335779
public HMac init(String algorithm, byte[] key){
		return init(algorithm, (null == key) ? null : new SecretKeySpec(key, algorithm));
	}
401214
public static function _init()
	{
		static::$crypter = new Crypt_AES();
		static::$hasher = new Crypt_Hash('sha256');

		// load the config
		\Config::load('crypt', true);
		static::$config = \Config::get('crypt', array ());

		// generate random crypto keys if we don't have them or they are incorrect length
		$update = false;
		foreach(array('crypto_key', 'crypto_iv', 'crypto_hmac') as $key)
		{
			if ( empty(static::$config[$key]) or (strlen(static::$config[$key]) % 4) != 0)
			{
				$crypto = '';
				for ($i = 0; $i < 8; $i++)
				{
					$crypto .= static::safe_b64encode(pack('n', mt_rand(0, 0xFFFF)));
				}
				static::$config[$key] = $crypto;
				$update = true;
			}
		}

		// update the config if needed
		if ($update === true)
		{
			try
			{
				\Config::save('crypt', static::$config);
			}
			catch (\FileAccessException $e)
			{
				// failed to write the config file, inform the user
				echo \View::forge('errors/crypt_keys', array(
					'keys' => static::$config
				));
				die();
			}
		}

		static::$crypter->enableContinuousBuffer();

		static::$hasher->setKey(static::safe_b64decode(static::$config['crypto_hmac']));
	}
88396
protected function _sign($parameters)
    {
        // Fixup our private key, copy-pasting the key might lead to whitespace faults
        if (!preg_match('/-----BEGIN (RSA )?PRIVATE KEY-----(.*)-----END (RSA )?PRIVATE KEY-----/si', $this->client->getPrivateKey(), $matches)) {
            die('<p>Could not find your private key, please supply your private key in the ApiSettings file. You can request a new private key in your TransIP Controlpanel.</p>');
        }

        $key = $matches[2];
        $key = preg_replace('/\s*/s', '', $key);
        $key = chunk_split($key, 64, "\n");

        $key = "-----BEGIN PRIVATE KEY-----\n" . $key . "-----END PRIVATE KEY-----";

        $digest = $this->_sha512Asn1($this->_encodeParameters($parameters));
        if (!@openssl_private_encrypt($digest, $signature, $key)) {
            die('<p>Could not sign your request, please supply your private key in the ApiSettings file. You can request a new private key in your TransIP Controlpanel.</p>');
        }

        return base64_encode($signature);
    }
422968
public function setPrivateKey($privateKey)
    {
        $privateKey = <<<PKEY
-----BEGIN RSA PRIVATE KEY-----
$privateKey
-----END RSA PRIVATE KEY-----
PKEY;

        if (!$privateKey = @openssl_pkey_get_private($privateKey)) {
            throw new \Exception("Invalid private key given.");
        }

        $this->privateKey = $privateKey;
    }
780564
public function Generate($pubkey)
    {
        if (empty($pubkey) === true) {
            throw new \Exception('Missing or invalid public key parameter for Sin::Generate.');
        }

        /* take the sha256 hash of the public key in binary form and returning binary */
        $this->rawHashes['step1'] = hash('sha256', $this->binConv($pubkey), true);

        /* take the ripemd160 hash of the sha256 hash in binary form returning hex */
        $this->rawHashes['step2'] = hash('ripemd160', $this->rawHashes['step1']);

        /* prepend the hex SINversion and hex SINtype to the hex form of the ripemd160 hash */
        $this->rawHashes['step3'] = $this->SINversion . $this->SINtype . $this->rawHashes['step2'];

        /*
         * convert the appended hex string back to binary and double sha256 hash it leaving
         * it in binary both times
         */
        $this->rawHashes['step4'] = hash('sha256', hash('sha256', $this->binConv($this->rawHashes['step3']), true), true);

        /* convert it back to hex and take the first 4 hex bytes */
        $this->rawHashes['step5'] = substr(bin2hex($this->rawHashes['step4']), 0, 8);

        /* append the first 4 bytes to the fully appended string in step 3 */
        $this->rawHashes['step6'] = $this->rawHashes['step3'] . $this->rawHashes['step5'];

        /* finally base58 encode it */
        $this->encoded = $this->encodeBase58($this->rawHashes['step6']);

        if (empty($this->encoded) === true) {
            throw new \Exception('Failed to generate valid SIN value. Empty or NULL value was obtained.');
        }

        return $this->encoded;
    }
1285832
function _prepareKey($key)
    {
        static $shifts = array( // number of key bits shifted per round
            1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1
        );

        // pad the key and remove extra characters as appropriate.
        $key = str_pad(substr($key, 0, 8), 8, chr(0));

        $temp = unpack('Na/Nb', $key);
        $key = array($temp['a'], $temp['b']);
        $msb = array(
            ($key[0] >> 31) & 1,
            ($key[1] >> 31) & 1
        );
        $key[0] &= 0x7FFFFFFF;
        $key[1] &= 0x7FFFFFFF;

        $key = array(
            (($key[1] & 0x00000002) << 26) | (($key[1] & 0x00000204) << 17) |
            (($key[1] & 0x00020408) <<  8) | (($key[1] & 0x02040800) >>  1) |
            (($key[0] & 0x00000002) << 22) | (($key[0] & 0x00000204) << 13) |
            (($key[0] & 0x00020408) <<  4) | (($key[0] & 0x02040800) >>  5) |
            (($key[1] & 0x04080000) >> 10) | (($key[0] & 0x04080000) >> 14) |
            (($key[1] & 0x08000000) >> 19) | (($key[0] & 0x08000000) >> 23) |
            (($key[0] & 0x00000010) >>  1) | (($key[0] & 0x00001000) >> 10) |
            (($key[0] & 0x00100000) >> 19) | (($key[0] & 0x10000000) >> 28)
        ,
            (($key[1] & 0x00000080) << 20) | (($key[1] & 0x00008000) << 11) |
            (($key[1] & 0x00800000) <<  2) | (($key[0] & 0x00000080) << 16) |
            (($key[0] & 0x00008000) <<  7) | (($key[0] & 0x00800000) >>  2) |
            (($key[1] & 0x00000040) << 13) | (($key[1] & 0x00004000) <<  4) |
            (($key[1] & 0x00400000) >>  5) | (($key[1] & 0x40000000) >> 14) |
            (($key[0] & 0x00000040) <<  9) | ( $key[0] & 0x00004000       ) |
            (($key[0] & 0x00400000) >>  9) | (($key[0] & 0x40000000) >> 18) |
            (($key[1] & 0x00000020) <<  6) | (($key[1] & 0x00002000) >>  3) |
            (($key[1] & 0x00200000) >> 12) | (($key[1] & 0x20000000) >> 21) |
            (($key[0] & 0x00000020) <<  2) | (($key[0] & 0x00002000) >>  7) |
            (($key[0] & 0x00200000) >> 16) | (($key[0] & 0x20000000) >> 25) |
            (($key[1] & 0x00000010) >>  1) | (($key[1] & 0x00001000) >> 10) |
            (($key[1] & 0x00100000) >> 19) | (($key[1] & 0x10000000) >> 28) |
            ($msb[1] << 24) | ($msb[0] << 20)
        ); 

        $keys = array();
        for ($i = 0; $i < 16; $i++) {
            $key[0] <<= $shifts[$i];
            $temp = ($key[0] & 0xF0000000) >> 28;
            $key[0] = ($key[0] | $temp) & 0x0FFFFFFF;

            $key[1] <<= $shifts[$i];
            $temp = ($key[1] & 0xF0000000) >> 28;
            $key[1] = ($key[1] | $temp) & 0x0FFFFFFF;

            $temp = array(
                (($key[1] & 0x00004000) >>  9) | (($key[1] & 0x00000800) >>  7) |
                (($key[1] & 0x00020000) >> 14) | (($key[1] & 0x00000010) >>  2) |
                (($key[1] & 0x08000000) >> 26) | (($key[1] & 0x00800000) >> 23)
            ,
                (($key[1] & 0x02400000) >> 20) | (($key[1] & 0x00000001) <<  4) |
                (($key[1] & 0x00002000) >> 10) | (($key[1] & 0x00040000) >> 18) |
                (($key[1] & 0x00000080) >>  6)
            ,
                ( $key[1] & 0x00000020       ) | (($key[1] & 0x00000200) >>  5) |
                (($key[1] & 0x00010000) >> 13) | (($key[1] & 0x01000000) >> 22) |
                (($key[1] & 0x00000004) >>  1) | (($key[1] & 0x00100000) >> 20)
            ,
                (($key[1] & 0x00001000) >>  7) | (($key[1] & 0x00200000) >> 17) |
                (($key[1] & 0x00000002) <<  2) | (($key[1] & 0x00000100) >>  6) |
                (($key[1] & 0x00008000) >> 14) | (($key[1] & 0x04000000) >> 26)
            ,
                (($key[0] & 0x00008000) >> 10) | ( $key[0] & 0x00000010       ) |
                (($key[0] & 0x02000000) >> 22) | (($key[0] & 0x00080000) >> 17) |
                (($key[0] & 0x00000200) >>  8) | (($key[0] & 0x00000002) >>  1)
            ,
                (($key[0] & 0x04000000) >> 21) | (($key[0] & 0x00010000) >> 12) |
                (($key[0] & 0x00000020) >>  2) | (($key[0] & 0x00000800) >>  9) |
                (($key[0] & 0x00800000) >> 22) | (($key[0] & 0x00000100) >>  8)
            ,
                (($key[0] & 0x00001000) >>  7) | (($key[0] & 0x00000088) >>  3) |
                (($key[0] & 0x00020000) >> 14) | (($key[0] & 0x00000001) <<  2) |
                (($key[0] & 0x00400000) >> 21)
            ,
                (($key[0] & 0x00000400) >>  5) | (($key[0] & 0x00004000) >> 10) |
                (($key[0] & 0x00000040) >>  3) | (($key[0] & 0x00100000) >> 18) |
                (($key[0] & 0x08000000) >> 26) | (($key[0] & 0x01000000) >> 24)
            );

            $keys[] = $temp;
        }

        $temp = array(
            CRYPT_DES_ENCRYPT => $keys,
            CRYPT_DES_DECRYPT => array_reverse($keys)
        );

        return $temp;
    }
817041
function setKey($key)
    {
        $this->key = $key;

        if ( CRYPT_RC4_MODE == CRYPT_RC4_MODE_MCRYPT ) {
            return;
        }

        $keyLength = strlen($key);
        $keyStream = array();
        for ($i = 0; $i < 256; $i++) {
            $keyStream[$i] = $i;
        }
        $j = 0;
        for ($i = 0; $i < 256; $i++) {
            $j = ($j + $keyStream[$i] + ord($key[$i % $keyLength])) & 255;
            $temp = $keyStream[$i];
            $keyStream[$i] = $keyStream[$j];
            $keyStream[$j] = $temp;
        }

        $this->encryptIndex = $this->decryptIndex = array(0, 0);
        $this->encryptStream = $this->decryptStream = $keyStream;
    }
585050
public function signature ( $request, $base_string, $consumer_secret, $token_secret )
	{
		// Fetch the private key cert based on the request
		$cert = $this->fetch_private_cert($request);
		
		// Pull the private key ID from the certificate
		$privatekeyid = openssl_get_privatekey($cert);
		
		// Sign using the key
		$sig = false;
		$ok  = openssl_sign($base_string, $sig, $privatekeyid);   
		
		// Release the key resource
		openssl_free_key($privatekeyid);
		  
		return $request->urlencode(base64_encode($sig));
	}
1350228
private function checkKey()
    {
        if (empty($this->key) || empty($this->authentication)) {
            $key = $this->secureRandomKey();
            $message = 'No binary key provided to encrypt/decrypt data.';

            if ($key !== null) {
                $message .= sprintf(" For example: base64_decode('%s')", base64_encode($key));
            }

            throw new RuntimeException($message);
        }
    }
910843
function setKey($key) {
		$this->cnxn->confirmTransaction('setKey');
		$currKey = $this->key;
		if (!is_null($currKey) && is_null($key)) {
			$this->cnxn->unregisterStructWithKey($this, $currKey);
		} else if (is_null($currKey) && !is_null($key)) {
			$this->cnxn->registerStructWithKey($this, $key);
		} else if ($currKey != $key) {
			$this->cnxn->unregisterStructWithKey($this, $currKey);
			$this->cnxn->registerStructWithKey($this, $key);
		}
		$this->key = $key;
	}