encrypt

@param string $str
@param string $secret default 'ePHP'
@return string
333632
public static function encryptG($str, $secret = 'ePHP')
    {
        if (!$str) {
            return false;
        }

        $key = md5($secret . "30f7384ac1");

        $ciphertext_raw = openssl_encrypt($str, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
        return \ePHP\Misc\Func::safe_b64encode($ciphertext_raw);
    }
169470
public static function decrypt($str, $key) {
        if ($str == "") {
            return "";
        }
        $data   =    self::_des($key,$str,0);
        $expire = substr($data,0,10);
        if($expire > 0 && $expire < time()) {
            return '';
        }
        $data   = substr($data,10);
        return $data;
    }
630054
public function getCode($secret, $timeSlice = null)
    {
        if ($timeSlice === null) {
            $timeSlice = floor(time() / 30);
        }

        $secretkey = $this->_base32Decode($secret);

        // Pack time into binary string
        $time = chr(0).chr(0).chr(0).chr(0).pack('N*', $timeSlice);
        // Hash it with users secret key
        $hm = hash_hmac('SHA1', $time, $secretkey, true);
        // Use last nipple of result as index/offset
        $offset = ord(substr($hm, -1)) & 0x0F;
        // grab 4 bytes of the result
        $hashpart = substr($hm, $offset, 4);

        // Unpak binary value
        $value = unpack('N', $hashpart);
        $value = $value[1];
        // Only 32 bits
        $value = $value & 0x7FFFFFFF;

        $modulo = pow(10, $this->_codeLength);
        return str_pad($value % $modulo, $this->_codeLength, '0', STR_PAD_LEFT);
    }
1229868
private function encrypt(string $data)
  {
    $secret = explode(':', config('app.key'))[1];
    $secret = base64_decode($secret);

    return (new Encrypter($secret))->encrypt($data, 9);
  }
935805
protected function _base32Decode($secret)
    {
        if (empty($secret)) {
            return '';
        }

        $base32chars = $this->_getBase32LookupTable();
        $base32charsFlipped = array_flip($base32chars);

        $paddingCharCount = substr_count($secret, $base32chars[32]);
        $allowedValues = array(6, 4, 3, 1, 0);
        if (!in_array($paddingCharCount, $allowedValues)) {
            return false;
        }
        for ($i = 0; $i < 4; ++$i) {
            if ($paddingCharCount == $allowedValues[$i] &&
                substr($secret, -($allowedValues[$i])) != str_repeat($base32chars[32], $allowedValues[$i])) {
                return false;
            }
        }
        $secret = str_replace('=', '', $secret);
        $secret = str_split($secret);
        $binaryString = '';
        for ($i = 0; $i < count($secret); $i = $i + 8) {
            $x = '';
            if (!in_array($secret[$i], $base32chars)) {
                return false;
            }
            for ($j = 0; $j < 8; ++$j) {
                $x .= str_pad(base_convert(@$base32charsFlipped[@$secret[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT);
            }
            $eightBits = str_split($x, 8);
            for ($z = 0; $z < count($eightBits); ++$z) {
                $binaryString .= (($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48) ? $y : '';
            }
        }

        return $binaryString;
    }
132422
public function createSecret($secretLength = 16)
    {
        $validChars = $this->_getBase32LookupTable();

        // Valid secret lengths are 80 to 640 bits
        if ($secretLength < 16 || $secretLength > 128) {
            throw new Exception('Bad secret length');
        }
        $secret = '';
        $rnd = false;
        if (function_exists('random_bytes')) {
            $rnd = random_bytes($secretLength);
        } elseif (function_exists('mcrypt_create_iv')) {
            $rnd = mcrypt_create_iv($secretLength, MCRYPT_DEV_URANDOM);
        } elseif (function_exists('openssl_random_pseudo_bytes')) {
            $rnd = openssl_random_pseudo_bytes($secretLength, $cryptoStrong);
            if (!$cryptoStrong) {
                $rnd = false;
            }
        }
        if ($rnd !== false) {
            for ($i = 0; $i < $secretLength; ++$i) {
                $secret .= $validChars[ord($rnd[$i]) & 31];
            }
        } else {
            throw new Exception('No source of secure random');
        }

        return $secret;
    }
1013760
public function encrypt($plain_string,$base64_encode=true){
		if(!$this->verified) $this->verify();
		//add size atom to encrypted string
		$size = pack('N',strlen($plain_string));
		$plain_string = $size.$plain_string;
		//encrypt and return
		$enc_string = mcrypt_encrypt(
			 self::$crypt_cipher
			,base64_decode($this->key)
			,$plain_string
			,self::$crypt_mode
			,base64_decode($this->iv)
		);
		if($base64_encode) return base64_encode($enc_string);
		return $enc_string;
	}
1271726
public static function create($string): self
    {
        if ($string instanceof self) {
            return $string;
        }

        if (empty($string)) {
            throw new \InvalidArgumentException(
                    'Given string was null or empty, if you explicitly want to'
                    . ' create a Secret with value null use'
                    . ' Secret::forNull()'
            );
        }

        $self = new static();
        try {
            $encrypt = self::$encrypt;
            self::$store[$self->id] = ['payload' => $encrypt($string),
                                       'length'  => \iconv_strlen($string)
                                      ];
        } catch (\Throwable $t) {
            $t = null;
            // This intentionally catches *ALL* exceptions, in order not to fail
            // and produce a stacktrace containing arguments on the stack that
            // were supposed to be protected.
            unset(self::$store[$self->id]);
        }

        $string = str_repeat('*', strlen($string));
        $string = null;
        return $self;
    }
745939
public static function fromString(string $str) : Cookie
    {
        $err = false;
        $name = "";
        $value = "";
        $expires = null;
        $domain = null;
        $path = "/";
        $secure = false;
        $httpOnly = false;


        if ($str === "") {
            $err = "The string is not a valid representation of a cookie.";
        }


        if ($err === false) {
            $parts = array_map("trim", explode(";", $str));

            $nameValue = explode("=", $parts[0]);

            $name = $nameValue[0];
            $value = ((count($nameValue) === 2) ? $nameValue[1] : "");

            if (count($parts) > 1) {
                array_shift($parts);

                foreach ($parts as $p) {
                    $keyPair = array_map("trim", explode("=", $p));
                    if (count($keyPair) === 1) {
                        $keyPair[] = null;
                    }

                    $val = $keyPair[1];

                    switch (strtolower($keyPair[0])) {
                        case "expires":
                            if ($val !== null) {
                                if (is_numeric($val) === true) {
                                    $expires = new \DateTime();
                                    $expires->setTimestamp((int)$val);
                                } else {
                                    if (strpos(strtolower($val), " utc") !== false ||
                                        strpos(strtolower($val), " gmt") !== false) {
                                        $val = substr($val, 0, strlen($val) - 4);
                                    }
                                    $expires = \DateTime::createFromFormat("D, d M Y H:i:s", $val);
                                }
                            }
                            break;

                        case "domain":
                            $domain = $val;
                            break;

                        case "path":
                            $path = $val;
                            break;

                        case "secure":
                            $secure = true;
                            break;

                        case "httponly":
                            $httpOnly = true;
                            break;
                    }
                }
            }
        }


        if ($err === false) {
            return new Cookie($name, $value, $expires, $domain, $path, $secure, $httpOnly);
        } else {
            throw new \InvalidArgumentException($err);
        }
    }
17616
public static String decode(String content, String secret) {
        try {
            //1.构造密钥生成器，指定为AES算法,不区分大小写
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            //2.根据encodeRules规则初始化密钥生成器
            //生成一个256位的随机源,根据传入的字节数组
            keygen.init(256, new SecureRandom(secret.getBytes()));
            //3.产生原始对称密钥
            SecretKey original_key = keygen.generateKey();
            //4.获得原始对称密钥的字节数组
            byte[] raw = original_key.getEncoded();
            //5.根据字节数组生成AES密钥
            SecretKey key = new SecretKeySpec(raw, "AES");
            //6.根据指定算法AES自成密码器
            Cipher cipher = Cipher.getInstance("AES");
            //7.初始化密码器，第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作，第二个参数为使用的KEY
            cipher.init(Cipher.DECRYPT_MODE, key);
            //8.将加密并编码后的内容解码成字节数组
            byte[] byte_content = new BASE64Decoder().decodeBuffer(content);
            byte[] byte_decode = cipher.doFinal(byte_content);
            return new String(byte_decode, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //如果有错就返加null
        return null;
    }
1360101
protected function encrypt(string $string)
    {
        $pub_key = openssl_pkey_get_public($this->getRsaKey($this->pub_key));

        $length = openssl_pkey_get_details($pub_key)['bits'];

        $string = str_split($string, $length / 8 - 11);
        $encryptedString = '';

        foreach ($string as $value) {
            openssl_public_encrypt($value, $encrypted, $pub_key);
            $encryptedString .= $encrypted;
        }

        return base64_encode($encryptedString);
    }
292707
function encode($str) {
		return @htmlspecialchars($str,$this->hive['BITMASK'],
			$this->hive['ENCODING'])?:$this->scrub($str);
	}
707809
public static function rsaPublicDecrypt(
        $str,
        $publicKeyPath,
        $padding = OPENSSL_PKCS1_PADDING,
        $format = self::FORMAT_HEX
    )
    {
        $str = trim($str);

        switch ($format) {
            case self::FORMAT_HEX:
                $str = hex2bin($str);
                break;
            case self::FORMAT_BASE64:
                $str = EncodeHelper::base64Decode($str);
                break;
            default:
                $str = hex2bin($str);
        }

        openssl_public_decrypt(
            $str,
            $decrypted,
            openssl_get_publickey(file_get_contents($publicKeyPath)),
            $padding
        );

        return trim($decrypted);
    }
1299218
public function create($str) {

    $rand = $this->psl['crypt/rand'];
    $crypto = $this->psl['crypt/crypto'];

    switch($this->method) {
      case self::BCRYPT:
        $saltRnd = $rand->str(22, $this->charsets['itoa64']);
        $salt = sprintf('%s%s$%s', self::BCRYPT, $this->bcrypt_cost, $saltRnd);
        $hash = crypt($str, $salt);
      break;

      case self::PBKDF2:
        $salt = $rand->bytes(64);
        $hash = $crypto->pbkdf2($str, $salt, $this->pbkdf2_c, $this->pbkdf2_dkLen, $this->pbkdf2_prf);

        $hash = sprintf('$pbkdf2$c=%s&dk=%s&f=%s$%s$%s',
                       $this->pbkdf2_c,
                       $this->pbkdf2_dkLen,
                       $this->pbkdf2_prf,
                       base64_encode($hash),
                       base64_encode($salt)
                       );
      break;

      case self::DRUPAL;
        $setting  = '$S$';
        $setting .= $this->charsets['itoa64'][$this->drupal_count];
        $setting .= $this->b64Encode($rand->bytes(6), 6);

        return substr($this->phpassHash($str, $setting), 0, $this->drupal_hashLen);
      break;

      case self::SHA256:
      case self::SHA512:
        $saltRnd = $rand->str(16, $this->charsets['itoa64']);
        $salt = sprintf('%srounds=%s$%s', $this->method, $this->sha2_c, $saltRnd);
        $hash = crypt($str, $salt);
      break;
    }

    if(strlen($hash) > 13) {
      return $hash;
    }
    return false;
  }
619131
public static function decrypt_secret($secret)
    {
        global $CFG;
        if ( $secret === null || $secret === false ) return $secret;
        if ( ! startsWith($secret,'AES::') ) return $secret;
        $secret = substr($secret, 5);
        $decr = AesCtr::decrypt($secret, $CFG->cookiesecret, 256) ;
        return $decr;
    }
1314624
public function encodeQ($str, $position = 'text')
    {
        // There should not be any EOL in the string
        $pattern = '';
        $encoded = str_replace(array("\r", "\n"), '', $str);
        switch (strtolower($position)) {
            case 'phrase':
                // RFC 2047 section 5.3
                $pattern = '^A-Za-z0-9!*+\/ -';
                break;
            /** @noinspection PhpMissingBreakStatementInspection */
            case 'comment':
                // RFC 2047 section 5.2
                $pattern = '\(\)"';
                // intentional fall-through
                // for this reason we build the $pattern without including delimiters and []
            case 'text':
            default:
                // RFC 2047 section 5.1
                // Replace every high ascii, control, =, ? and _ characters
                $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
                break;
        }
        $matches = array();
        if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
            // If the string contains an '=', make sure it's the first thing we replace
            // so as to avoid double-encoding
            $eqkey = array_search('=', $matches[0]);
            if ($eqkey !== false) {
                unset($matches[0][$eqkey]);
                array_unshift($matches[0], '=');
            }
            foreach (array_unique($matches[0]) as $char) {
                $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
            }
        }
        // Replace every spaces to _ (more readable than =20)
        return str_replace(' ', '_', $encoded);
    }
171126
public static function encode(String $str) : String
    {
        $chars = self::$numericalCodes;

        return str_replace(array_keys($chars), array_values($chars), $str);
    }