oauth2-server/src/Utils/KeyCrypt.php

87 lines
2.7 KiB
PHP
Raw Normal View History

2016-01-14 23:44:39 +00:00
<?php
/**
2016-02-19 18:09:39 -05:00
* Public/private key encryption.
2016-01-14 23:44:39 +00:00
*
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) Alex Bilbie
* @license http://mit-license.org/
2016-02-19 18:09:39 -05:00
*
2016-01-14 23:44:39 +00:00
* @link https://github.com/thephpleague/oauth2-server
*/
namespace League\OAuth2\Server\Utils;
class KeyCrypt
{
/**
2016-02-19 18:09:39 -05:00
* Encrypt data with a private key.
2016-01-14 23:44:39 +00:00
*
* @param string $unencryptedData
* @param string $pathToPrivateKey
*
* @return string
*/
public static function encrypt($unencryptedData, $pathToPrivateKey)
{
$privateKey = openssl_pkey_get_private($pathToPrivateKey);
$privateKeyDetails = @openssl_pkey_get_details($privateKey);
if ($privateKeyDetails === null) {
throw new \LogicException(sprintf('Could not get details of private key: %s', $pathToPrivateKey));
}
$chunkSize = ceil($privateKeyDetails['bits'] / 8) - 11;
$output = '';
while ($unencryptedData) {
$chunk = substr($unencryptedData, 0, $chunkSize);
$unencryptedData = substr($unencryptedData, $chunkSize);
if (openssl_private_encrypt($chunk, $encrypted, $privateKey) === false) {
2016-02-12 18:08:27 +00:00
// @codeCoverageIgnoreStart
2016-01-14 23:44:39 +00:00
throw new \LogicException('Failed to encrypt data');
2016-02-12 18:08:27 +00:00
// @codeCoverageIgnoreEnd
2016-01-14 23:44:39 +00:00
}
$output .= $encrypted;
}
openssl_free_key($privateKey);
return base64_encode($output);
}
/**
2016-02-19 18:09:39 -05:00
* Decrypt data with a public key.
2016-01-14 23:44:39 +00:00
*
* @param string $encryptedData
* @param string $pathToPublicKey
*
2016-02-12 10:00:41 +00:00
* @throws \LogicException
*
2016-01-14 23:44:39 +00:00
* @return string
*/
public static function decrypt($encryptedData, $pathToPublicKey)
{
$publicKey = openssl_pkey_get_public($pathToPublicKey);
$publicKeyDetails = @openssl_pkey_get_details($publicKey);
if ($publicKeyDetails === null) {
throw new \LogicException(sprintf('Could not get details of public key: %s', $pathToPublicKey));
}
$chunkSize = ceil($publicKeyDetails['bits'] / 8);
$output = '';
$encryptedData = base64_decode($encryptedData);
while ($encryptedData) {
$chunk = substr($encryptedData, 0, $chunkSize);
$encryptedData = substr($encryptedData, $chunkSize);
if (openssl_public_decrypt($chunk, $decrypted, $publicKey) === false) {
2016-02-12 18:08:27 +00:00
// @codeCoverageIgnoreStart
2016-01-14 23:44:39 +00:00
throw new \LogicException('Failed to decrypt data');
2016-02-12 18:08:27 +00:00
// @codeCoverageIgnoreEnd
2016-01-14 23:44:39 +00:00
}
$output .= $decrypted;
}
openssl_free_key($publicKey);
return $output;
}
}