Skip to content

Commit

Permalink
Clean newlines from PEM CRT (#5)
Browse files Browse the repository at this point in the history
* Clean newlines from PEM CRT

* Fix comment location

* Check also the key

* Extract whitelines array

* Apply PR comments
  • Loading branch information
trizz authored and robbinjanssen committed Feb 22, 2019
1 parent 51c95c0 commit aa9df85
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
7 changes: 6 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ All notable changes to `SSL converter` will be documented in this file.
Updates should follow the [Keep a CHANGELOG](http://keepachangelog.com/) principles.

## Unreleased
[Compare v0.0.2 - Unreleased](https://github.com/exonet/ssl-converter/compare/v0.0.1...develop)
[Compare v0.0.3 - Unreleased](https://github.com/exonet/ssl-converter/compare/v0.0.3...develop)

## [v0.0.3](https://github.com/exonet/ssl-converter/releases/tag/v0.0.3) - 2019-02-22
[Compare v0.0.2 - v0.0.3](https://github.com/exonet/ssl-converter/compare/v0.0.2...v0.0.3)
### Fixed
- When converting to PEM the CRT and key are now formatted correctly stripping all invalid newlines.

## [v0.0.2](https://github.com/exonet/ssl-converter/releases/tag/v0.0.2) - 2019-02-18
[Compare v0.0.1 - v0.0.2](https://github.com/exonet/ssl-converter/compare/v0.0.1...v0.0.2)
Expand Down
21 changes: 20 additions & 1 deletion src/Formats/Pem.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,27 @@ public function toString() : string
throw new MissingRequiredInformation('The following fields are required for PEM: CRT, CA Bundle.');
}

$possibleNewLines = ["\x0D", "\r", "\n", '\n', '\r'];

// Strip all kind of (wrong) newlines, indentations, etc. and create a correct certificate from the CRT.
$x509cert = str_replace($possibleNewLines, '', $crt);
$x509cert = str_replace('-----BEGIN CERTIFICATE-----', '', $x509cert);
$x509cert = str_replace('-----END CERTIFICATE-----', '', $x509cert);
$x509cert = str_replace(' ', '', $x509cert);
$x509cert = "-----BEGIN CERTIFICATE-----\n".chunk_split($x509cert, 64, "\n")."-----END CERTIFICATE-----\n";

// Clean the newlines in the key.
if ($key) {
$x509key = str_replace($possibleNewLines, '', $key);
$x509key = str_replace('-----BEGIN PRIVATE KEY-----', '', $x509key);
$x509key = str_replace('-----END PRIVATE KEY-----', '', $x509key);
$x509key = str_replace(' ', '', $x509key);
$x509key = "-----BEGIN PRIVATE KEY-----\n".chunk_split($x509key, 64, "\n")."-----END PRIVATE KEY-----\n";
}

// If there is a key, prepend the certificate content with the key.
$content = $key ? $key.$crt.$caBundle : $crt.$caBundle;
$content = $key ? $x509key.$x509cert.$caBundle : $x509cert.$caBundle;

if (!openssl_x509_read($content)) {
throw new InvalidResource('Invalid certificate provided.');
}
Expand Down

0 comments on commit aa9df85

Please sign in to comment.