Home  >  Article  >  Backend Development  >  How to convert cer file to pem format in php

How to convert cer file to pem format in php

PHPz
PHPzOriginal
2023-04-25 17:36:222436browse

When using PHP, you may need to send or receive encrypted data to the server. To ensure security, certificates are often used to encrypt and decrypt data. When interacting with other systems, it may be necessary to convert the certificate used from .cer format to .pem format. This article will explain how to convert a .cer certificate to a .pem format certificate in PHP.

  1. Determine the certificate type

In the process of converting .cer to .pem, you first need to determine the type of certificate currently used. If you are currently using an RSA key pair, you need to install the OpenSSL extension. You can check whether the OpenSSL extension is installed by using the following code:

if (!extension_loaded('openssl')) {
    die('OpenSSL 扩展未安装.');
}

?>

  1. Loading certificate

To convert .cer to .pem, you first need to load the certificate into PHP. The certificate can be loaded using the following code:

$cert = file_get_contents('/path/to/cert.cer');

?>

This will read the .cer file using the file_get_contents() function and store it in in the $cert variable.

  1. Convert .cer to .pem

To convert .cer to .pem, you need to use the x509 function in OpenSSL. The .cer file stored in the $cert variable can be converted to .pem format using the following code:

$pem = chunk_split(base64_encode(openssl_x509_export($cert)));

?>

This code will. cer file is exported to PEM format and stored in the $pem variable.

  1. Save Certificate

Now, the .cer file has been successfully converted to PEM format. It needs to be saved to the server. A certificate in PEM format can be saved to a file using the following code:

file_put_contents('/path/to/cert.pem', $pem);

?>

This will use the file_put_contents() function to Save the certificate to the specified path.

Summary

This article describes how to convert a .cer certificate to a .pem format certificate in PHP. This process can be easily accomplished by using the OpenSSL extension. First, you need to load the certificate into PHP and then use the x509 function to convert the .cer file to .pem format. Finally, save the certificate in PEM format to a file for use in future code.

The above is the detailed content of How to convert cer file to pem format in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn