0

I want to match keys from file which looks like this:

KEY_ID: 1
STATUS: VALID
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEaq6djyzkpHdX7kt8DsSt6IuSoXjp
WVlLfnZPoLaGKc/2BSfYQuFIO2hfgueQINJN3ZdujYXfUJ7Who+XkcJqHQ==
-----END PUBLIC KEY-----

I want to subtract KEY ID and the key itself from it via preg_match_all. I tried this one:

preg_match_all('/-----BEGIN PUBLIC KEY-----(.*)-----END PUBLIC KEY-----/', $ECDS_KEYS, $matches);

But I got empty array from this one. Can you help me out? Thanks

Michael Tichoň
  • 281
  • 2
  • 10

3 Answers3

4

by default, "." doesn't match line breaks. You have to add an "s" at the end of your regex to catch it:

preg_match_all('/-----BEGIN PUBLIC KEY-----(.*)-----END PUBLIC KEY-----/s', $ECDS_KEYS, $matches);

result: https://regex101.com/r/rN7oZ1/1

EDIT:

If you wish to seperate each key, you don't need "preg_match_all", you don't need linebreaks before and after your first catch, and you have to explode it after the regex:

// catch all keys
preg_match('/-----BEGIN PUBLIC KEY-----\n(.*)\n-----END PUBLIC KEY-----/s', $ECDS_KEYS, $groupedKeys);
// once you get a list of key, seperate them with an explode on linebreaks
$lonelyKeys = explode("\n", $groupedKeys[1]);

use "\n" or "\r\n", depending what you receive.

Random
  • 3,158
  • 1
  • 15
  • 25
1

If you take in account that you need to load a file and to compile and search with a regex pattern, You should consider this another way that is faster and use less memory:

$fh = fopen($filename, 'r');

$start = "-----BEGIN PUBLIC KEY-----\n";
$end = "\n-----END PUBLIC KEY-----";
$maxSizeBetweenKeys = 262144;
$results = [];

while ( stream_get_line($fh, $maxSizeBetweenKeys, $start) !== false &&
        ($key = stream_get_line($fh, 4096, $end)) !== false )
    $results[] = $key;

fclose($fh);

If you compare it with:

$fileContent = file_get_contents($filename);
if (preg_match_all('~^-----BEGIN PUBLIC KEY-----\n\K.*+(?>\n.*)*?(?=\n-----END PUBLIC KEY-----)~m', $fileContent, $matches))
    $results = $matches[0];

that is a little shorter but slower.

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
1

Pattern for test public and private keys

(-----BEGIN PUBLIC KEY-----(\n|\r|\r\n)([0-9a-zA-Z\+\/=]{64}(\n|\r|\r\n))*([0-9a-zA-Z\+\/=]{1,63}(\n|\r|\r\n))?-----END PUBLIC KEY-----)|(-----BEGIN PRIVATE KEY-----(\n|\r|\r\n)([0-9a-zA-Z\+\/=]{64}(\n|\r|\r\n))*([0-9a-zA-Z\+\/=]{1,63}(\n|\r|\r\n))?-----END PRIVATE KEY-----)

Tests Regex101.com - PEM RSA KEY PATTERN - ECMASCRIPT - PCRE

enter image description here

Joma
  • 3,520
  • 1
  • 29
  • 32