最近,项目中遇到需要将 150 多个文件中的公钥处理成 php 可以使用的 pem 文件,然后,在项目中的配置文件为每一个 pem 单独添加对应的配置项。如果手工处理的话需要很久,所以写了个小脚本实现,记录在下面。
//获取目录下所有文件名
$pubPath = '/pro/source_file_path/';
$allPubfile = scandir($pubPath);
// var_dump($allPubfile);die;
foreach($allPubfile as $pubFileName){
if(strlen($pubFileName)>12 && strpos($pubFileName,'txt')>0){
$file_path = $pubPath.$pubFileName;
if (file_exists($file_path)) {
$fp = fopen($file_path, "r");
$str = fread($fp, filesize($file_path));//指定读取大小,这里把整个文件内容读取出来
preg_match("/\[([0-9a-z]+)\]/",$str, $res);
// var_dump($str, $res[1]); die;
$pub_str = $res[1];
$pos_id = substr($pubFileName, 0 , strpos($pubFileName,'.'));
$conf_txt = <<<EOT
// {$start}
\$config['pay']['{$pos_id}'] = array(
'POSID' => '{$pos_id}', //柜台号
//公钥
'POSPUBKEY' => '{$pub_str}',
'POSPUBKEY_FILE' => '/certs/pay/pos_{$pos_id}_public.pem',
);
EOT
;
echo $conf_txt,PHP_EOL;
$pub_file_path = '/certs/pay/pos_'.$pos_id.'_public.pem';
if(!file_exists($pub_file_path)){
$poshexPkcs8Public = $pub_str;
$pospkcs8PublicKey = "-----BEGIN PUBLIC KEY-----\r\n" . $this->formatRsaKey(base64_encode($this->hexToStr($poshexPkcs8Public))) . "\r\n-----END PUBLIC KEY-----";
file_put_contents($pub_file_path, $pospkcs8PublicKey);
}
}
}
}
注意:
EOT 后面的要顶格写,且加“;”的后面不能有空格。
Heredoc 技术,是一种Perl风格的字符串输出技术。
网友评论