在PHP里实现PKCS7编码功能

发表于 2020-08-20 11:18:44
阅读 29

介绍

介绍

福哥需要在php里使用PKCS7编码功能,今天整理出来和大家分享一下

教程

PKCS7编码对象

PKCS7编码对象

class PKCS7Encoder{
    const BLOCK_SIZE = 32;

    function encode($text){
        $text_length = strlen($text);

        $amount_to_pad = PKCS7Encoder::BLOCK_SIZE - ($text_length % PKCS7Encoder::BLOCK_SIZE);
        if($amount_to_pad == 0){
            $amount_to_pad = PKCS7Encoder::BLOCK_SIZE;
        }

        $pad_chr = chr($amount_to_pad);
        $tmp = "";
        for($index = 0; $index < $amount_to_pad; $index++){
            $tmp .= $pad_chr;
        }

        return $text . $tmp;
    }

    function decode($text){
        $pad = ord(substr($text, -1));
        if($pad < 1 || $pad > PKCS7Encoder::BLOCK_SIZE){
            $pad = 0;
        }

        return substr($text, 0, (strlen($text) - $pad));
    }
}