PHP解决RSA公私密钥换行处理

admin13302021-08-27

在RSA加密处理时,经常遇到RSA密钥为一行,但是在Linux下,需要换行处理,否则,无法进行加密处理。换行,只能按照指定的规则换行,否则无法加密,下面介绍下标准处理方法:

  1. public function TrasferRSA() {

  2. if (isset($_POST)) {

  3. $rsa_type    = intval($_POST['rsa_type']);

  4. $rsa_content = trim($_POST['rsa_content']);

  5. var_dump($rsa_content);

  6. if ($rsa_type == 1) {

  7. $start_key       = str_replace('-----BEGIN RSA PRIVATE KEY-----', '', $rsa_content);

  8. $start_key       = trim(str_replace('-----END RSA PRIVATE KEY-----', '', $start_key));

  9. //wordwrap 按照指定的长度,对字符串进行换行

  10. $private_content = wordwrap($start_key, 64, "\n", true);

  11. $key             = <<<EOF

  12. -----BEGIN RSA PRIVATE KEY-----

  13. {$private_content}

  14. -----END RSA PRIVATE KEY-----

  15. EOF;

  16. var_dump($key);

  17. //输出私钥

  18. } elseif ($rsa_type == 2) {

  19. $start_key      = str_replace('-----BEGIN PUBLIC KEY-----', '', $rsa_content);

  20. $start_key      = trim(str_replace('-----END PUBLIC KEY-----', '', $start_key));

  21. $public_content = wordwrap($start_key, 64, "\n", true);

  22. $key            = <<<EOF

  23. -----BEGIN PUBLIC KEY-----

  24. {$public_content}

  25. -----END PUBLIC KEY-----

  26. EOF;

  27. var_dump($key);

  28. //输出公钥

  29. }

  30. } else {

  31. $this->display();

  32. }

  33. }


网友评论