webconsole 6 年之前
父節點
當前提交
7ec4ebbabe
共有 8 個文件被更改,包括 858 次插入0 次删除
  1. 17 0
      composer.json
  2. 71 0
      src/Base64.php
  3. 85 0
      src/Crypt.php
  4. 240 0
      src/Des.php
  5. 70 0
      src/Hmac.php
  6. 71 0
      src/McryptDes.php
  7. 185 0
      src/Rsa.php
  8. 119 0
      src/Xxtea.php

+ 17 - 0
composer.json

@@ -0,0 +1,17 @@
+{
+    "name": "jrtk/php-crypto",
+    "description":  "crypto",
+    "keywords": ["crypto"],
+    "license": "MIT",
+    "require": {
+        "php": ">=5.6.0"
+    },
+    "require-dev": {
+        "phpunit/phpunit": "^5"
+    },
+    "autoload": {
+        "psr-4": {
+            "Crypto\\": "src/"
+        }
+    }
+}

+ 71 - 0
src/Base64.php

@@ -0,0 +1,71 @@
+<?php
+// +----------------------------------------------------------------------
+// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
+// +----------------------------------------------------------------------
+// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
+// +----------------------------------------------------------------------
+// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
+// +----------------------------------------------------------------------
+// | Author: liu21st <liu21st@gmail.com>
+// +----------------------------------------------------------------------
+namespace Crypto;
+/**
+ * Base64 加密实现类
+ * @category   ORG
+ * @package  ORG
+ * @subpackage  Crypt
+ * @author    liu21st <liu21st@gmail.com>
+ */
+class Base64 {
+
+    /**
+     * 加密字符串
+     * @access static
+     * @param string $str 字符串
+     * @param string $key 加密key
+     * @return string
+     */
+    public static function encrypt($data,$key) {
+        $key    =   md5($key);
+        $data   =   base64_encode($data);
+        $x=0;
+		$len = strlen($data);
+		$l = strlen($key);
+        for ($i=0;$i< $len;$i++) {
+            if ($x== $l) $x=0;
+            $char   .=substr($key,$x,1);
+            $x++;
+        }
+        for ($i=0;$i< $len;$i++) {
+            $str    .=chr(ord(substr($data,$i,1))+(ord(substr($char,$i,1)))%256);
+        }
+        return $str;
+    }
+
+    /**
+     * 解密字符串
+     * @access static
+     * @param string $str 字符串
+     * @param string $key 加密key
+     * @return string
+     */
+    public static function decrypt($data,$key) {
+        $key    =   md5($key);
+        $x=0;
+		$len = strlen($data);
+		$l = strlen($key);
+        for ($i=0;$i< $len;$i++) {
+            if ($x== $l) $x=0;
+            $char   .=substr($key,$x,1);
+            $x++;
+        }
+        for ($i=0;$i< $len;$i++) {
+            if (ord(substr($data,$i,1))<ord(substr($char,$i,1))) {
+                $str    .=chr((ord(substr($data,$i,1))+256)-ord(substr($char,$i,1)));
+            }else{
+                $str    .=chr(ord(substr($data,$i,1))-ord(substr($char,$i,1)));
+            }
+        }
+        return base64_decode($str);
+    }
+}

+ 85 - 0
src/Crypt.php

@@ -0,0 +1,85 @@
+<?php
+// +----------------------------------------------------------------------
+// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
+// +----------------------------------------------------------------------
+// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
+// +----------------------------------------------------------------------
+// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
+// +----------------------------------------------------------------------
+// | Author: liu21st <liu21st@gmail.com>
+// +----------------------------------------------------------------------
+
+/**
+ * Crypt 加密实现类
+ * @category   ORG
+ * @package  ORG
+ * @subpackage  Crypt
+ * @author    liu21st <liu21st@gmail.com>
+ */
+class Crypt {
+
+    /**
+     * 加密字符串
+     * @access static
+     * @param string $str 字符串
+     * @param string $key 加密key
+     * @return string
+     */
+    function encrypt($str,$key,$toBase64=false){
+        $r = md5($key);
+        $c=0;
+        $v = "";
+		$len = strlen($str);
+		$l = strlen($r);
+        for ($i=0;$i<$len;$i++){
+         if ($c== $l) $c=0;
+         $v.= substr($r,$c,1) .
+             (substr($str,$i,1) ^ substr($r,$c,1));
+         $c++;
+        }
+        if($toBase64) {
+            return base64_encode(self::ed($v,$key));
+        }else {
+            return self::ed($v,$key);
+        }
+
+    }
+
+    /**
+     * 解密字符串
+     * @access static
+     * @param string $str 字符串
+     * @param string $key 加密key
+     * @return string
+     */
+    function decrypt($str,$key,$toBase64=false) {
+        if($toBase64) {
+            $str = self::ed(base64_decode($str),$key);
+        }else {
+            $str = self::ed($str,$key);
+        }
+        $v = "";
+		$len = strlen($str);
+        for ($i=0;$i<$len;$i++){
+         $md5 = substr($str,$i,1);
+         $i++;
+         $v.= (substr($str,$i,1) ^ $md5);
+        }
+        return $v;
+    }
+
+
+   function ed($str,$key) {
+      $r = md5($key);
+      $c=0;
+      $v = "";
+	  $len = strlen($str);
+	  $l = strlen($r);
+      for ($i=0;$i<$len;$i++) {
+         if ($c==$l) $c=0;
+         $v.= substr($str,$i,1) ^ substr($r,$c,1);
+         $c++;
+      }
+      return $v;
+   }
+}

文件差異過大導致無法顯示
+ 240 - 0
src/Des.php


+ 70 - 0
src/Hmac.php

@@ -0,0 +1,70 @@
+<?php
+// +----------------------------------------------------------------------
+// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
+// +----------------------------------------------------------------------
+// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
+// +----------------------------------------------------------------------
+// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
+// +----------------------------------------------------------------------
+// | Author: cevin <cevin1991@gmail.com>
+// +----------------------------------------------------------------------
+namespace Crypto;
+/**
+ * HMAC 加密实现类
+ * @category   ORG
+ * @package  ORG
+ * @subpackage  Crypt
+ * @author    cevin <cevin1991@gmail.com>
+ */
+class Hmac {
+
+    /**
+     * SHA1加密
+     * @access static
+     * @param string $key 加密key
+     * @param string $str 字符串
+     * @return string
+     */
+	public static function sha1($key,$str) {
+        $blocksize=64;
+        $hashfunc='sha1';
+        if (strlen($key)>$blocksize)
+            $key=pack('H*', $hashfunc($key));
+        $key=str_pad($key,$blocksize,chr(0x00));
+        $ipad=str_repeat(chr(0x36),$blocksize);
+        $opad=str_repeat(chr(0x5c),$blocksize);
+        $hmac = pack(
+                    'H*',$hashfunc(
+                        ($key^$opad).pack(
+                            'H*',$hashfunc(
+                                ($key^$ipad).$str
+                            )
+                        )
+                    )
+                );
+        return $hmac;
+    }
+
+    /**
+     * MD5加密
+     * @access static
+     * @param string $key 加密key
+     * @param string $str 字符串
+     * @return string
+     */
+	public static function md5($key, $str) {
+        $b = 64;
+        if (strlen($key) > $b) {
+            $key = pack("H*",md5($key));
+        }
+
+        $key = str_pad($key, $b, chr(0x00));
+        $ipad = str_pad('', $b, chr(0x36));
+        $opad = str_pad('', $b, chr(0x5c));
+        $k_ipad = $key ^ $ipad ;
+        $k_opad = $key ^ $opad;
+
+        return md5($k_opad . pack("H*",md5($k_ipad . $str)));
+    }
+
+}

+ 71 - 0
src/McryptDes.php

@@ -0,0 +1,71 @@
+<?php
+namespace Crypto;
+
+class McryptDes {
+   var $key;
+   var $iv;
+   function McryptDes($key, $iv){
+    $this->key = $key;
+    $this->iv = $iv;
+   }
+   function encrypt($input){
+     $size = mcrypt_get_block_size(MCRYPT_DES,MCRYPT_MODE_CBC); //3DES加密将MCRYPT_DES改为MCRYPT_3DES
+     $input = $this->pkcs5_pad($input, $size); //如果采用PaddingPKCS7,请更换成PaddingPKCS7方法。
+     $key = str_pad($this->key,8,'0'); //3DES加密将8改为24
+     $td = mcrypt_module_open(MCRYPT_DES, '', MCRYPT_MODE_CBC, '');
+     if( $this->iv == '' )
+     {
+       $iv = @mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
+     }
+     else
+     {
+       $iv = $this->iv;
+     }
+     @mcrypt_generic_init($td, $key, $iv);
+     $data = mcrypt_generic($td, $input);
+     mcrypt_generic_deinit($td);
+     mcrypt_module_close($td);
+     $data = base64_encode($data);//如需转换二进制可改成 bin2hex 转换
+     return $data;
+   }
+   function decrypt($encrypted){
+     $encrypted = base64_decode($encrypted); //如需转换二进制可改成 bin2hex 转换
+     $key = str_pad($this->key,8,'0'); //3DES加密将8改为24
+     $td = mcrypt_module_open(MCRYPT_DES,'',MCRYPT_MODE_CBC,'');//3DES加密将MCRYPT_DES改为MCRYPT_3DES
+     if( $this->iv == '' )
+     {
+       $iv = @mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
+     }
+     else
+     {
+       $iv = $this->iv;
+     }
+     $ks = mcrypt_enc_get_key_size($td);
+     @mcrypt_generic_init($td, $key, $iv);
+     $decrypted = mdecrypt_generic($td, $encrypted);
+     mcrypt_generic_deinit($td);
+     mcrypt_module_close($td);
+     $y=$this->pkcs5_unpad($decrypted);
+     return $y;
+   }
+   function pkcs5_pad ($text, $blocksize) {
+     $pad = $blocksize - (strlen($text) % $blocksize);
+     return $text . str_repeat(chr($pad), $pad);
+   }
+   function pkcs5_unpad($text){
+     $pad = ord($text{strlen($text)-1});
+     if ($pad > strlen($text)) {
+       return false;
+     }
+     if (strspn($text, chr($pad), strlen($text) - $pad) != $pad){
+       return false;
+     }
+     return substr($text, 0, -1 * $pad);
+   }
+   function PaddingPKCS7($data) {
+     $block_size = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_CBC);//3DES加密将MCRYPT_DES改为MCRYPT_3DES
+     $padding_char = $block_size - (strlen($data) % $block_size);
+     $data .= str_repeat(chr($padding_char),$padding_char);
+     return $data;
+   }
+}

+ 185 - 0
src/Rsa.php

@@ -0,0 +1,185 @@
+<?php
+// +----------------------------------------------------------------------
+// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
+// +----------------------------------------------------------------------
+// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
+// +----------------------------------------------------------------------
+// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
+// +----------------------------------------------------------------------
+// | Author: liu21st <liu21st@gmail.com>
+// +----------------------------------------------------------------------
+namespace Crypto;
+define("BCCOMP_LARGER", 1);
+/**
+ * Rsa 加密实现类
+ * @category   ORG
+ * @package  ORG
+ * @subpackage  Crypt
+ * @author    liu21st <liu21st@gmail.com>
+ */
+class Rsa {
+
+    /**
+     * 加密字符串
+     * @access static
+     * @param string $str 字符串
+     * @param string $key 加密key
+     * @return string
+     */
+    public static function encrypt($message, $public_key, $modulus, $keylength) {
+        $padded = self::add_PKCS1_padding($message, true, $keylength / 8);
+        $number = self::binary_to_number($padded);
+        $encrypted = self::pow_mod($number, $public_key, $modulus);
+        $result = self::number_to_binary($encrypted, $keylength / 8);
+        return $result;
+    }
+
+    /**
+     * 解密字符串
+     * @access static
+     * @param string $str 字符串
+     * @param string $key 加密key
+     * @return string
+     */
+    public static function decrypt($message, $private_key, $modulus, $keylength) {
+        $number = self::binary_to_number($message);
+        $decrypted = self::pow_mod($number, $private_key, $modulus);
+        $result = self::number_to_binary($decrypted, $keylength / 8);
+
+        return self::remove_PKCS1_padding($result, $keylength / 8);
+    }
+
+    function sign($message, $private_key, $modulus, $keylength) {
+        $padded = self::add_PKCS1_padding($message, false, $keylength / 8);
+        $number = self::binary_to_number($padded);
+        $signed = self::pow_mod($number, $private_key, $modulus);
+        $result = self::number_to_binary($signed, $keylength / 8);
+        return $result;
+    }
+
+    function verify($message, $public_key, $modulus, $keylength) {
+        return decrypt($message, $public_key, $modulus, $keylength);
+    }
+
+    function pow_mod($p, $q, $r) {
+        // Extract powers of 2 from $q
+        $factors = array();
+        $div = $q;
+        $power_of_two = 0;
+        while(bccomp($div, "0") == BCCOMP_LARGER)
+        {
+            $rem = bcmod($div, 2);
+            $div = bcdiv($div, 2);
+
+            if($rem) array_push($factors, $power_of_two);
+            $power_of_two++;
+        }
+        // Calculate partial results for each factor, using each partial result as a
+        // starting point for the next. This depends of the factors of two being
+        // generated in increasing order.
+        $partial_results = array();
+        $part_res = $p;
+        $idx = 0;
+        foreach($factors as $factor)
+        {
+            while($idx < $factor)
+            {
+                $part_res = bcpow($part_res, "2");
+                $part_res = bcmod($part_res, $r);
+
+                $idx++;
+            }
+            array_push($partial_results, $part_res);
+        }
+        // Calculate final result
+        $result = "1";
+        foreach($partial_results as $part_res)
+        {
+            $result = bcmul($result, $part_res);
+            $result = bcmod($result, $r);
+        }
+        return $result;
+    }
+
+    //--
+    // Function to add padding to a decrypted string
+    // We need to know if this is a private or a public key operation [4]
+    //--
+    function add_PKCS1_padding($data, $isPublicKey, $blocksize) {
+        $pad_length = $blocksize - 3 - strlen($data);
+
+        if($isPublicKey)
+        {
+            $block_type = "\x02";
+
+            $padding = "";
+            for($i = 0; $i < $pad_length; $i++)
+            {
+                $rnd = mt_rand(1, 255);
+                $padding .= chr($rnd);
+            }
+        }
+        else
+        {
+            $block_type = "\x01";
+            $padding = str_repeat("\xFF", $pad_length);
+        }
+        return "\x00" . $block_type . $padding . "\x00" . $data;
+    }
+
+    //--
+    // Remove padding from a decrypted string
+    // See [4] for more details.
+    //--
+    function remove_PKCS1_padding($data, $blocksize) {
+        assert(strlen($data) == $blocksize);
+        $data = substr($data, 1);
+
+        // We cannot deal with block type 0
+    if($data{0} == '\0')
+            die("Block type 0 not implemented.");
+
+        // Then the block type must be 1 or 2
+    assert(($data{0} == "\x01") || ($data{0} == "\x02"));
+
+        // Remove the padding
+    $offset = strpos($data, "\0", 1);
+        return substr($data, $offset + 1);
+    }
+
+    //--
+    // Convert binary data to a decimal number
+    //--
+    function binary_to_number($data) {
+        $base = "256";
+        $radix = "1";
+        $result = "0";
+
+        for($i = strlen($data) - 1; $i >= 0; $i--)
+        {
+            $digit = ord($data{$i});
+            $part_res = bcmul($digit, $radix);
+            $result = bcadd($result, $part_res);
+            $radix = bcmul($radix, $base);
+        }
+        return $result;
+    }
+
+    //--
+    // Convert a number back into binary form
+    //--
+    function number_to_binary($number, $blocksize) {
+        $base = "256";
+        $result = "";
+        $div = $number;
+        while($div > 0)
+        {
+            $mod = bcmod($div, $base);
+            $div = bcdiv($div, $base);
+
+            $result = chr($mod) . $result;
+        }
+        return str_pad($result, $blocksize, "\x00", STR_PAD_LEFT);
+    }
+
+}

+ 119 - 0
src/Xxtea.php

@@ -0,0 +1,119 @@
+<?php
+// +----------------------------------------------------------------------
+// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
+// +----------------------------------------------------------------------
+// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
+// +----------------------------------------------------------------------
+// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
+// +----------------------------------------------------------------------
+// | Author: liu21st <liu21st@gmail.com>
+// +----------------------------------------------------------------------
+namespace Crypto;
+/**
+ * Xxtea 加密实现类
+ * @category   ORG
+ * @package  ORG
+ * @subpackage  Crypt
+ * @author    liu21st <liu21st@gmail.com>
+ */
+class Xxtea {
+
+    /**
+     * 加密字符串
+     * @access static
+     * @param string $str 字符串
+     * @param string $key 加密key
+     * @return string
+     */
+    public static function encrypt($str, $key) {
+        if ($str == "") {
+            return "";
+        }
+        $v = self::str2long($str, true);
+        $k = self::str2long($key, false);
+        $n = count($v) - 1;
+
+        $z = $v[$n];
+        $y = $v[0];
+        $delta = 0x9E3779B9;
+        $q = floor(6 + 52 / ($n + 1));
+        $sum = 0;
+        while (0 < $q--) {
+            $sum = self::int32($sum + $delta);
+            $e = $sum >> 2 & 3;
+            for ($p = 0; $p < $n; $p++) {
+                $y = $v[$p + 1];
+                $mx = self::int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ self::int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
+                $z = $v[$p] = self::int32($v[$p] + $mx);
+            }
+            $y = $v[0];
+            $mx = self::int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ self::int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
+            $z = $v[$n] = self::int32($v[$n] + $mx);
+        }
+        return self::long2str($v, false);
+    }
+
+    /**
+     * 解密字符串
+     * @access static
+     * @param string $str 字符串
+     * @param string $key 加密key
+     * @return string
+     */
+    public static function decrypt($str, $key) {
+        if ($str == "") {
+            return "";
+        }
+        $v = self::str2long($str, false);
+        $k = self::str2long($key, false);
+        $n = count($v) - 1;
+
+        $z = $v[$n];
+        $y = $v[0];
+        $delta = 0x9E3779B9;
+        $q = floor(6 + 52 / ($n + 1));
+        $sum = self::int32($q * $delta);
+        while ($sum != 0) {
+            $e = $sum >> 2 & 3;
+            for ($p = $n; $p > 0; $p--) {
+                $z = $v[$p - 1];
+                $mx = self::int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ self::int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
+                $y = $v[$p] = self::int32($v[$p] - $mx);
+            }
+            $z = $v[$n];
+            $mx = self::int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ self::int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
+            $y = $v[0] = self::int32($v[0] - $mx);
+            $sum = self::int32($sum - $delta);
+        }
+        return self::long2str($v, true);
+    }
+
+    private static function long2str($v, $w) {
+        $len = count($v);
+        $s = array();
+        for ($i = 0; $i < $len; $i++) {
+            $s[$i] = pack("V", $v[$i]);
+        }
+        if ($w) {
+            return substr(join('', $s), 0, $v[$len - 1]);
+        }else{
+            return join('', $s);
+        }
+    }
+
+    private static function str2long($s, $w) {
+        $v = unpack("V*", $s. str_repeat("\0", (4 - strlen($s) % 4) & 3));
+        $v = array_values($v);
+        if ($w) {
+            $v[count($v)] = strlen($s);
+        }
+        return $v;
+    }
+
+    private static function int32($n) {
+        while ($n >= 2147483648) $n -= 4294967296;
+        while ($n <= -2147483649) $n += 4294967296;
+        return (int)$n;
+    }
+
+}