function ooyala_decrypt($data)
{
    $key = hex2bin('4b3d32bed59fb8c54ab8a190d5d147f0e4f0cbe6804c8e0721175ab68b40cb01');
    $iv = hex2bin('00020406080a0c0ea0a2a4a6a8aaacae');
    $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($data), MCRYPT_MODE_CBC, $iv);
    $decrypted = pkcs5_unpad($decrypted);
    $decrypted = substr($decrypted, 6);
    return gzinflate($decrypted);
}
示例#2
0
function idtag_des_decode2($key, $encrypted)
{
    $encrypted = base64_decode($encrypted);
    $td = mcrypt_module_open(MCRYPT_DES, '', MCRYPT_MODE_CBC, '');
    //使用MCRYPT_DES算法,cbc模式
    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    $ks = mcrypt_enc_get_key_size($td);
    mcrypt_generic_init($td, $key, $key);
    //初始处理
    $decrypted = mdecrypt_generic($td, $encrypted);
    //解密
    mcrypt_generic_deinit($td);
    //结束
    mcrypt_module_close($td);
    $y = pkcs5_unpad($decrypted);
    return $y;
}
示例#3
0
/**
 *
 * diaspora_decode($importer,$xml)
 *   array $importer -> from user table
 *   string $xml -> urldecoded Diaspora salmon 
 *
 * Returns array
 * 'message' -> decoded Diaspora XML message
 * 'author' -> author diaspora handle
 * 'key' -> author public key (converted to pkcs#8)
 *
 * Author and key are used elsewhere to save a lookup for verifying replies and likes
 */
function diaspora_decode($importer, $xml)
{
    $public = false;
    $basedom = parse_xml_string($xml);
    $children = $basedom->children('https://joindiaspora.com/protocol');
    if ($children->header) {
        $public = true;
        $author_link = str_replace('acct:', '', $children->header->author_id);
    } else {
        $encrypted_header = json_decode(base64_decode($children->encrypted_header));
        $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
        $ciphertext = base64_decode($encrypted_header->ciphertext);
        $outer_key_bundle = '';
        openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
        $j_outer_key_bundle = json_decode($outer_key_bundle);
        $outer_iv = base64_decode($j_outer_key_bundle->iv);
        $outer_key = base64_decode($j_outer_key_bundle->key);
        $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
        $decrypted = pkcs5_unpad($decrypted);
        /**
         * $decrypted now contains something like
         *
         *  <decrypted_header>
         *     <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
         *     <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
         ***** OBSOLETE
         *     <author>
         *       <name>Ryan Hughes</name>
         *       <uri>acct:galaxor@diaspora.pirateship.org</uri>
         *     </author>
         ***** CURRENT
         *     <author_id>galaxor@diaspora.priateship.org</author_id>
         ***** END DIFFS
         *  </decrypted_header>
         */
        logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
        $idom = parse_xml_string($decrypted, false);
        $inner_iv = base64_decode($idom->iv);
        $inner_aes_key = base64_decode($idom->aes_key);
        $author_link = str_replace('acct:', '', $idom->author_id);
    }
    $dom = $basedom->children(NAMESPACE_SALMON_ME);
    // figure out where in the DOM tree our data is hiding
    if ($dom->provenance->data) {
        $base = $dom->provenance;
    } elseif ($dom->env->data) {
        $base = $dom->env;
    } elseif ($dom->data) {
        $base = $dom;
    }
    if (!$base) {
        logger('mod-diaspora: unable to locate salmon data in xml ');
        http_status_exit(400);
    }
    // Stash the signature away for now. We have to find their key or it won't be good for anything.
    $signature = base64url_decode($base->sig);
    // unpack the  data
    // strip whitespace so our data element will return to one big base64 blob
    $data = str_replace(array(" ", "\t", "\r", "\n"), array("", "", "", ""), $base->data);
    // stash away some other stuff for later
    $type = $base->data[0]->attributes()->type[0];
    $keyhash = $base->sig[0]->attributes()->keyhash[0];
    $encoding = $base->encoding;
    $alg = $base->alg;
    $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
    // decode the data
    $data = base64url_decode($data);
    if ($public) {
        $inner_decrypted = $data;
    } else {
        // Decode the encrypted blob
        $inner_encrypted = base64_decode($data);
        $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
        $inner_decrypted = pkcs5_unpad($inner_decrypted);
    }
    if (!$author_link) {
        logger('mod-diaspora: Could not retrieve author URI.');
        http_status_exit(400);
    }
    // Once we have the author URI, go to the web and try to find their public key
    // (first this will look it up locally if it is in the fcontact cache)
    // This will also convert diaspora public key from pkcs#1 to pkcs#8
    logger('mod-diaspora: Fetching key for ' . $author_link);
    $key = get_diaspora_key($author_link);
    if (!$key) {
        logger('mod-diaspora: Could not retrieve author key.');
        http_status_exit(400);
    }
    $verify = rsa_verify($signed_data, $signature, $key);
    if (!$verify) {
        logger('mod-diaspora: Message did not verify. Discarding.');
        http_status_exit(400);
    }
    logger('mod-diaspora: Message verified.');
    return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
}
示例#4
0
function AES256CBC_decrypt($data, $key, $iv)
{
    return pkcs5_unpad(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, str_pad($key, 32, ""), $data, MCRYPT_MODE_CBC, str_pad($iv, 16, "")));
}
示例#5
0
/**
 * DES解密函数
 *
 * @param string $input
 * @param string $key
 */
function desdecrypt($encrypted, $key)
{
    $encrypted = base64_decode($encrypted);
    $td = mcrypt_module_open('des', '', 'ecb', '');
    //使用MCRYPT_DES算法,cbc模式
    $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    $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 = pkcs5_unpad($decrypted);
    return $y;
}
示例#6
0
 protected function processEncryptedNode(ProtocolNode $node)
 {
     if ($this->parent->getAxolotlStore() == null) {
         return;
     }
     //is a chat encrypted message
     $from = $node->getAttribute('from');
     if (strpos($from, Constants::WHATSAPP_SERVER) !== false) {
         $author = ExtractNumber($node->getAttribute('from'));
         $version = $node->getChild(0)->getAttribute('v');
         $encType = $node->getChild(0)->getAttribute('type');
         $encMsg = $node->getChild('enc')->getData();
         if (!$this->parent->getAxolotlStore()->containsSession($author, 1)) {
             //we don't have the session to decrypt, save it in pending and process it later
             $this->parent->addPendingNode($node);
             $this->parent->logFile('info', 'Requesting cipher keys from {from}', ['from' => $author]);
             $this->parent->sendGetCipherKeysFromUser($author);
         } else {
             //decrypt the message with the session
             if ($node->getChild('enc')->getAttribute('count') == '') {
                 $this->parent->setRetryCounter($node->getAttribute('id'), 1);
             }
             if ($version == '2') {
                 if (!in_array($author, $this->parent->getv2Jids())) {
                     $this->parent->setv2Jids($author);
                 }
             }
             $plaintext = $this->decryptMessage($from, $encMsg, $encType, $node->getAttribute('id'), $node->getAttribute('t'));
             //$plaintext ="A";
             if ($plaintext === false) {
                 $this->parent->sendRetry($this->node, $from, $node->getAttribute('id'), $node->getAttribute('t'));
                 $this->parent->logFile('info', 'Couldn\'t decrypt message with {id} id from {from}. Retrying...', ['id' => $node->getAttribute('id'), 'from' => ExtractNumber($from)]);
                 return $node;
                 // could not decrypt
             }
             if (isset($this->parent->retryNodes[$node->getAttribute('id')])) {
                 unset($this->parent->retryNodes[$node->getAttribute('id')]);
             }
             if (isset($this->parent->retryCounters[$node->getAttribute('id')])) {
                 unset($this->parent->retryCounters[$node->getAttribute('id')]);
             }
             switch ($node->getAttribute('type')) {
                 case 'text':
                     $node->addChild(new ProtocolNode('body', null, null, $plaintext));
                     break;
                 case 'media':
                     switch ($node->getChild('enc')->getAttribute('mediatype')) {
                         case 'image':
                             $image = new ImageMessage();
                             $image->parseFromString($plaintext);
                             $keys = (new HKDFv3())->deriveSecrets($image->getRefKey(), hex2bin('576861747341707020496d616765204b657973'), 112);
                             $iv = substr($keys, 0, 16);
                             $keys = substr($keys, 16);
                             $parts = str_split($keys, 32);
                             $key = $parts[0];
                             $macKey = $parts[1];
                             $refKey = $parts[2];
                             //should be changed to nice curl, no extra headers :D
                             $file_enc = file_get_contents($image->getUrl());
                             //requires mac check , last 10 chars
                             $mac = substr($file_enc, -10);
                             $cipherImage = substr($file_enc, 0, strlen($file_enc) - 10);
                             $decrypted_image = pkcs5_unpad(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $cipherImage, MCRYPT_MODE_CBC, $iv));
                             //$save_file = tempnam(sys_get_temp_dir(),"WAIMG_");
                             //file_put_contents($save_file,$decrypted_image);
                             $child = new ProtocolNode('media', ['size' => $image->getLength(), 'caption' => $image->getCaption(), 'url' => $image->getUrl(), 'mimetype' => $image->getMimeType(), 'filehash' => bin2hex($image->getSha256()), 'width' => 0, 'height' => 0, 'file' => $decrypted_image, 'type' => 'image'], null, $image->getThumbnail());
                             $node->addChild($child);
                             break;
                     }
                     break;
             }
             $this->parent->logFile('info', 'Decrypted message with {id} from {from}', ['id' => $node->getAttribute('id'), 'from' => ExtractNumber($from)]);
             return $node;
         }
     } else {
         $author = ExtractNumber($node->getAttribute('participant'));
         $group_number = ExtractNumber($node->getAttribute('from'));
         $childs = $node->getChildren();
         foreach ($childs as $child) {
             if ($child->getAttribute('type') == 'pkmsg' || $child->getAttribute('type') == 'msg') {
                 if (!$this->parent->getAxolotlStore()->containsSession($author, 1)) {
                     $this->parent->addPendingNode($node);
                     $this->parent->sendGetCipherKeysFromUser($author);
                     break;
                 } else {
                     //decrypt senderKey and save it
                     $encType = $child->getAttribute('type');
                     $encMsg = $child->getData();
                     $from = $node->getAttribute('participant');
                     $version = $child->getAttribute('v');
                     if ($node->getChild('enc')->getAttribute('count') == '') {
                         $this->parent->setRetryCounter($node->getAttribute('id'), 1);
                     }
                     if ($version == '2') {
                         if (!in_array($author, $this->parent->getv2Jids())) {
                             $this->parent->setv2Jids($author);
                         }
                     }
                     $skip_unpad = $node->getChild('enc', ['type' => 'skmsg']) == null;
                     $senderKeyBytes = $this->decryptMessage($from, $encMsg, $encType, $node->getAttribute('id'), $node->getAttribute('t'), $node->getAttribute('from'), $skip_unpad);
                     if ($senderKeyBytes) {
                         if (!$skip_unpad) {
                             $senderKeyGroupMessage = new SenderKeyGroupMessage();
                             $senderKeyGroupMessage->parseFromString($senderKeyBytes);
                         } else {
                             $senderKeyGroupMessage = new SenderKeyGroupData();
                             try {
                                 $senderKeyGroupMessage->parseFromString($senderKeyBytes);
                             } catch (Exception $ex) {
                                 try {
                                     $senderKeyGroupMessage->parseFromString(substr($senderKeyBytes, 0, -1));
                                 } catch (Exception $ex) {
                                     return $node;
                                 }
                             }
                             $message = $senderKeyGroupMessage->getMessage();
                             $senderKeyGroupMessage = $senderKeyGroupMessage->getSenderKey();
                         }
                         $senderKey = new SenderKeyDistributionMessage(null, null, null, null, $senderKeyGroupMessage->getSenderKey());
                         $groupSessionBuilder = new GroupSessionBuilder($this->parent->axolotlStore);
                         $groupSessionBuilder->processSender($group_number . ':' . $author, $senderKey);
                         if (isset($message)) {
                             $this->parent->sendReceipt($node, 'receipt', $this->parent->getJID($this->phoneNumber));
                             $node->addChild(new ProtocolNode('body', null, null, $message));
                         }
                     }
                 }
             } elseif ($child->getAttribute('type') == 'skmsg') {
                 $version = $child->getAttribute('v');
                 if ($version == '2') {
                     if (!in_array($author, $this->parent->v2Jids)) {
                         $this->parent->setv2Jids($author);
                     }
                 }
                 $plaintext = $this->decryptMessage([$group_number, $author], $child->getData(), $child->getAttribute('type'), $node->getAttribute('id'), $node->getAttribute('t'));
                 if (!$plaintext) {
                     $this->parent->sendRetry($this->node, $from, $node->getAttribute('id'), $node->getAttribute('t'), $node->getAttribute('participant'));
                     $this->parent->logFile('info', 'Couldn\'t decrypt group message with {id} id from {from}. Retrying...', ['id' => $node->getAttribute('id'), 'from' => $from]);
                     return $node;
                     // could not decrypt
                 } else {
                     if (isset($this->parent->retryNodes[$node->getAttribute('id')])) {
                         unset($this->parent->retryNodes[$node->getAttribute('id')]);
                     }
                     if (isset($this->parent->retryCounters[$node->getAttribute('id')])) {
                         unset($this->parent->retryCounters[$node->getAttribute('id')]);
                     }
                     $this->parent->logFile('info', 'Decrypted group message with {id} from {from}', ['id' => $node->getAttribute('id'), 'from' => $from]);
                     $this->parent->sendReceipt($node, 'receipt', $this->parent->getJID($this->phoneNumber));
                     $node->addChild(new ProtocolNode('body', null, null, $plaintext));
                 }
             }
         }
     }
 }
示例#7
0
文件: index.php 项目: 4v4t4r/CryptOMG
    $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);
}
if (isset($_GET['c'])) {
    $cipherText = @$_GET['c'];
} else {
    $cipherText = encode(encrypt(pkcs5_pad(genNonce(16) . "|" . $directory . "/home", $blocksize), $cipher, $mode, $key, $iv), $p_encoding);
}
if (!is_null(@$cipherText)) {
    $plainText = pkcs5_unpad(decrypt(decode($cipherText, $p_encoding), $cipher, $mode, $key, $iv), $blocksize);
    //$plainText2 = substr($plainText2, 16, strlen($plainText2));
    $file = explode("|", $plainText);
    $plainText2 = $file[sizeof($file) - 1];
    if ($plainText2) {
        if (file_exists($plainText2) && !is_dir($plainText2)) {
            //$output = str_replace("\n", "<br />", file_get_contents($plainText2));
            $theData = str_replace("\n", "<br />", file_get_contents($plainText2));
            $fileName = explode("/", $plainText2);
            $title = ucwords($fileName[sizeof($fileName) - 1]);
            $heading = $title;
        } else {
            header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");
            $title = "File not found";
            $header = $title;
        }
示例#8
0
/**
* Php AES decryption function * 
* @param string $ key key 
* @param string $ encrypted encrypted string 
* @return string
*/
function des_decode($key, $encrypted)
{
    $encrypted = base64_decode($encrypted);
    $td = mcrypt_module_open(MCRYPT_DES, '', MCRYPT_MODE_CBC, '');
    //Use MCRYPT_DES algorithm, cbc mode
    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    $ks = mcrypt_enc_get_key_size($td);
    mcrypt_generic_init($td, $key, $key);
    //Initial treatment
    $decrypted = mdecrypt_generic($td, $encrypted);
    //Decryption
    mcrypt_generic_deinit($td);
    //结束
    mcrypt_module_close($td);
    return pkcs5_unpad($decrypted);
}
示例#9
0
<?php

// Image decoder for WhatsApp encoded images!
// Use at your risk. If you set up a server with the script make me know about it!
// This has been borrowed from ChatAPI
// Check URL
if (!preg_match("/https:\\/\\/[a-z0-9]+\\.whatsapp\\.net/", $_GET["url"])) {
    die("URL not valid!\n");
}
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);
}
$file_enc = file_get_contents($_GET["url"]);
$cipherImage = substr($file_enc, 0, strlen($file_enc) - 10);
$key = hex2bin($_GET["key"]);
$iv = hex2bin($_GET["iv"]);
$img = pkcs5_unpad(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $cipherImage, MCRYPT_MODE_CBC, $iv));
header("Content-Type: image/jpg");
echo $img;
示例#10
0
function dechiffrementlist()
{
    $json_source = $_GET['inputStream'];
    $json_data = json_decode($json_source);
    $maxConteur = count($json_data->conteneurFichier);
    $conteur = 0;
    /* Charge un chiffrement */
    $td = mcrypt_module_open('rijndael-128', '', 'cbc', '');
    $size = mcrypt_get_block_size('rijndael-128', 'cbc');
    /* Crée le VI et détermine la taille de la clé */
    $iv = imap_base64($json_data->IV);
    /* Crée la clé */
    $key = 'a7bc27daf59679de';
    /* Initialise le module de chiffrement pour le déchiffrement */
    mcrypt_generic_init($td, $key, $iv);
    /* Déchiffre les données */
    $identifiant = $json_data->identifiant;
    $identifiant = base64url_decode($identifiant);
    $decryptedMdp = mdecrypt_generic($td, $identifiant);
    $decryptedMdp = pkcs5_unpad($decryptedMdp, $size);
    $json_data->identifiant = $decryptedMdp;
    /* Libère le gestionnaire de déchiffrement, et ferme le module */
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    /* Charge un chiffrement */
    $td = mcrypt_module_open('rijndael-128', '', 'cbc', '');
    $size = mcrypt_get_block_size('rijndael-128', 'cbc');
    /* Crée le VI et détermine la taille de la clé */
    $iv = imap_base64($json_data->IV);
    /* Crée la clé */
    $key = 'a7bc27daf59679de';
    /* Initialise le module de chiffrement pour le déchiffrement */
    mcrypt_generic_init($td, $key, $iv);
    /* Déchiffre les données */
    $code = $json_data->code;
    $code = base64url_decode($code);
    $decryptedMdp = mdecrypt_generic($td, $code);
    $decryptedMdp = pkcs5_unpad($decryptedMdp, $size);
    $json_data->code = $decryptedMdp;
    /* Libère le gestionnaire de déchiffrement, et ferme le module */
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    for ($conteur = 0; $conteur < $maxConteur; $conteur++) {
        /* Charge un chiffrement */
        $td = mcrypt_module_open('rijndael-128', '', 'cbc', '');
        $size = mcrypt_get_block_size('rijndael-128', 'cbc');
        /* Crée le VI et détermine la taille de la clé */
        $iv = imap_base64($json_data->IV);
        /* Crée la clé */
        $key = 'a7bc27daf59679de';
        /* Initialise le module de chiffrement pour le déchiffrement */
        mcrypt_generic_init($td, $key, $iv);
        /* Déchiffre les données */
        $name = $json_data->conteneurFichier[$conteur]->name;
        $name = base64url_decode($name);
        $decryptedMdp = mdecrypt_generic($td, $name);
        $decryptedMdp = pkcs5_unpad($decryptedMdp);
        $json_data->conteneurFichier[$conteur]->name = $decryptedMdp;
        /* Libère le gestionnaire de déchiffrement, et ferme le module */
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        /* Charge un chiffrement */
        $td = mcrypt_module_open('rijndael-128', '', 'cbc', '');
        $size = mcrypt_get_block_size('rijndael-128', 'cbc');
        /* Crée le VI et détermine la taille de la clé */
        $iv = imap_base64($json_data->IV);
        /* Crée la clé */
        $key = 'a7bc27daf59679de';
        /* Initialise le module de chiffrement pour le déchiffrement */
        mcrypt_generic_init($td, $key, $iv);
        /* Déchiffre les données */
        $content = $json_data->conteneurFichier[$conteur]->content;
        $content = base64url_decode($content);
        $decryptedMdp = mdecrypt_generic($td, $content);
        $decryptedMdp = pkcs5_unpad($decryptedMdp);
        $json_data->conteneurFichier[$conteur]->content = $decryptedMdp;
        /* Libère le gestionnaire de déchiffrement, et ferme le module */
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        /* Charge un chiffrement */
        $td = mcrypt_module_open('rijndael-128', '', 'cbc', '');
        $size = mcrypt_get_block_size('rijndael-128', 'cbc');
        /* Crée le VI et détermine la taille de la clé */
        $iv = imap_base64($json_data->IV);
        /* Crée la clé */
        $key = 'a7bc27daf59679de';
        /* Initialise le module de chiffrement pour le déchiffrement */
        mcrypt_generic_init($td, $key, $iv);
        /* Déchiffre les données */
        $path = $json_data->conteneurFichier[$conteur]->path;
        $path = base64url_decode($path);
        $decryptedMdp = mdecrypt_generic($td, $path);
        $decryptedMdp = pkcs5_unpad($decryptedMdp);
        $json_data->conteneurFichier[$conteur]->path = $decryptedMdp;
        /* Libère le gestionnaire de déchiffrement, et ferme le module */
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        /* Charge un chiffrement */
        $td = mcrypt_module_open('rijndael-128', '', 'cbc', '');
        $size = mcrypt_get_block_size('rijndael-128', 'cbc');
        /* Crée le VI et détermine la taille de la clé */
        $iv = imap_base64($json_data->IV);
        /* Crée la clé */
        $key = 'a7bc27daf59679de';
        /* Initialise le module de chiffrement pour le déchiffrement */
        mcrypt_generic_init($td, $key, $iv);
        /* Déchiffre les données */
        $updated_at = $json_data->conteneurFichier[$conteur]->updated_at;
        $updated_at = base64url_decode($updated_at);
        $decryptedMdp = mdecrypt_generic($td, $updated_at);
        $decryptedMdp = pkcs5_unpad($decryptedMdp);
        $json_data->conteneurFichier[$conteur]->updated_at = $decryptedMdp;
        /* Libère le gestionnaire de déchiffrement, et ferme le module */
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
    }
    return $json_data;
}
示例#11
0
{
    $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);
}
$key = "20C86125F86DB932D0139D32D9208CEF52BAEC98F1E9BA2A";
$key = pack("H48", $key);
$iv = "0102030405060708";
$iv = pack("H16", $iv);
$td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
mcrypt_generic_init($td, $key, $iv);
$str = base64_encode(mcrypt_generic($td, pkcs5_pad("123456", 8)));
echo $str;
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
$td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
mcrypt_generic_init($td, $key, $iv);
$ttt = pkcs5_unpad(mdecrypt_generic($td, base64_decode($str)));
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
#echo $ttt;