PHP解决RSA公私密钥换行处理
在RSA加密处理时,经常遇到RSA密钥为一行,但是在Linux下,需要换行处理,否则,无法进行加密处理。换行,只能按照指定的规则换行,否则无法加密,下面介绍下标准处理方法:
public function TrasferRSA() {
if (isset($_POST)) {
$rsa_type = intval($_POST['rsa_type']);
$rsa_content = trim($_POST['rsa_content']);
var_dump($rsa_content);
if ($rsa_type == 1) {
$start_key = str_replace('-----BEGIN RSA PRIVATE KEY-----', '', $rsa_content);
$start_key = trim(str_replace('-----END RSA PRIVATE KEY-----', '', $start_key));
//wordwrap 按照指定的长度,对字符串进行换行
$private_content = wordwrap($start_key, 64, "\n", true);
$key = <<<EOF
-----BEGIN RSA PRIVATE KEY-----
{$private_content}
-----END RSA PRIVATE KEY-----
EOF;
var_dump($key);
//输出私钥
} elseif ($rsa_type == 2) {
$start_key = str_replace('-----BEGIN PUBLIC KEY-----', '', $rsa_content);
$start_key = trim(str_replace('-----END PUBLIC KEY-----', '', $start_key));
$public_content = wordwrap($start_key, 64, "\n", true);
$key = <<<EOF
-----BEGIN PUBLIC KEY-----
{$public_content}
-----END PUBLIC KEY-----
EOF;
var_dump($key);
//输出公钥
}
} else {
$this->display();
}
}