Encryption of OpenSSL in PHP

  • 2021-08-28 19:38:18
  • OfStack

Recently, the encryption of OpenSSL and the interface verification of java are needed in the company project. When the test environment is upgraded to PHP7, there will be an error in encryption. Later, many inspections finally found the reason:

Replace openssl_get_privatekey method with openssl_pkey_get_private in PHP7 environment

It is necessary to convert the secret key under 1. There is a difference between the secret key format in window environment and Linux environment (it is not certain whether it is the relationship between the operating system for the time being)

PHP's secret key verification requires a head and tail.

Attached methods are attached here

Method of converting secret key format:


function transJavaRsaKeyToPhpOpenSSL($content) {
    if ($content) {
      return trim(chunk_split($content, 64, "\n"));
    }
    return false;
  }

The method of adding head and tail:


function appendFlags($content, $isPublic = true) {
    if ($isPublic) {
      return "-----BEGIN PUBLIC KEY-----\n" . $content . "\n-----END PUBLIC KEY-----\n";
    }
    else {
      return "-----BEGIN PRIVATE KEY-----\n" . $content . "\n-----END PRIVATE KEY-----\n";
    }
  }

The above is the little experience of OPENSSL encryption problem this time. If you still have any questions, leave a message below for discussion.


Related articles: