1. Go to this page and download the library: Download charlesportwoodii/ncryptf library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
charlesportwoodii / ncryptf example snippets
use DateTime;
use ncryptf\Token;
use ncryptf\Authorization;
$date = new DateTime;
$token = new Token(
$accessToken,
$refreshToken,
\base64_decode($ikm), // IKM must be in it's byte form, as oppose to the base64 representation returned by the server
\base64_decode($signature), // Signature is the same,
$expiresAt
);
$auth = new Authorization(
$httpMethod,
$uri,
$token,
new DateTime,
$payload
);
$header = $auth->getHeader();
use DateTime;
use ncryptf\Token;
use ncryptf\Authorization;
$date = new DateTime;
$token = new Token(
'7XF56VIP7ZQQOLGHM6MRIK56S2QS363ULNB5UKNFMJRQVYHQH7IA',
'MA2JX5FXWS57DHW4OIHHQDCJVGS3ZKKFCL7XM4GNOB567I6ER4LQ',
\base64_decode('bDEyECRvKKE8w81fX4hz/52cvHsFPMGeJ+a9fGaVvWM='),
\base64_decode('7v/CdiGoEI7bcj7R2EyDPH5nrCd2+7rHYNACB+Kf2FMx405und2KenGjNpCBPv0jOiptfHJHiY3lldAQTGCdqw=='),
1472678411
);
$auth = new Authorization(
'POST',
'/api/v1/test',
$token,
new DateTime,
[
'foo' => 'bar'
]
);
$header = $auth->getHeader();
$header = $auth->getHeader();
$auth = new Authorization(
$httpMethod,
$uri,
$token,
new DateTime,
$payload,
1
);
$auth->getHeader(),
use DateTime;
use ncryptf\Authorization;
use ncryptf\Token as NcryptfToken;
public function authenticate($user, $request, $response)
{
// Extract the parameters from the header string
$params = Authorization::extractParamsFromHeaderString($request->getHeaders()->get('Authorization'));
if ($params) {
// Your API should implement a method to fetch all token data from the access token
// Typically this is stored in a cache of some kind, such as Redis
if ($token = $this->getTokenFromAccessToken($params['access_token'])) {
try {
// Determine the appropriate date to use, depending upon the version
$date = new DateTime($params['date'] ?? $request->getHeaders()->get('X-Date'));
// Construct a new server side Authorization object
$auth = new Authorization(
$request->getHttpMethod(), // GET, POST, PUT... etc
$request->getUrl(), // The URI with query parameters
$token->getNcryptfToken(), // Your token object should support data extraction to an ncryptf/Token type
$date,
$request->getRawBody(), // The raw JSON in the request. If you're using encrypted requests, this should be decrypted
$params['v'], // The version of the HMAC header to validate
\base64_decode($params['salt']) // The salt value from the parameters
);
// Verify the HMAC submitted against the newly generated auth object
if ($auth->verify(\base64_decode($params['hmac']), $auth)) {
// Do your login here
//
//
}
} catch (\Exception $e) {
// Handle exceptions here
}
}
}
// Handle authentication failures
}
use ncryptf\Request;
use ncryptf\Utils;
use ncryptf\exceptions\EncryptionFailedException;
try {
// Generate your request keypair for your local device.
$keypair = Utils::generateKeypair();
$signatureKp = Utils::generateSigningKeypair()
// Create a new request object with your private key
// and the servers private key
$request = new Request(
$privateKeypair->getSecretKey(),
$signatureKp->getSecretKey
);
// Encrypt JSON
$encryptedRequest = $request->encrypt(
'{ "foo": "bar" }',
$remotePublicKey
);
} catch (EncryptionFailedException $e) {
// Encrypting the body failed
}
use ncryptf\Response;
use ncryptf\exceptions\DecryptionFailedException;
use ncryptf\exceptions\InvalidChecksumException;
use ncryptf\exceptions\InvalidSignatureException;
// Represents the httpResponse
try {
// Create a new request object with your private key
// and the servers private key
$response = new Response(
\sodium_crypto_box_secretkey($privateKeypair['secret']),
);
// Extract the raw body from the response
$rawBody = \base64_decode($httpResponse->getBody());
$jsonResponse = $response->decrypt(
$rawBody,
$remotePublicKey
);
} catch (DecryptionFailedException $e) {
// Decryption failed
} catch (InvalidChecksumException $e) {
// Request checksum failed
} catch (InvalidSignatureException $e) {
// Signature verification failed
}
use ncryptf\middleware\AbstractAuthentication;
final class Authentication extends AbstractAuthentication
{
/**
* Given an access token, return an `ncryptf\Token` instance.
*/
protected function getTokenFromAccessToken(string $accessToken) :? Token
{
// Search for token in database
return \ncryptf\Token(...);
}
protected function getUserFromToken(Token $token)
{
// Convert a token to a user.
return User::find()
->where(['access_token' => $token['access_token']])
->one();
}
}
use Authentication;
use Middlewares\Utils\Dispatcher;
$response = Dispatcher::run([
new Authentication,
function ($request, $next) {
// This is your user, do whatever you need to do here.
$user = $request->getAttribute('ncryptf-user');
return $next->handle($request);
}
], $request);
use ncryptf\middleware\RequestParser;
use Middlewares\Utils\Dispatcher;
$PSR16CacheInterface = new class implements \Psr\SimpleCache\CacheInterface {};
$response = Dispatcher::run([
new RequestParser($PSR16CacheInterface),
function ($request, $next) {
// This is the plain-text decrypted body
$decryptedBody = $request->getAttribute('ncryptf-decrypted-body');
// The parsed body
$params = $request->getParsedBody();
return $next->handle($request);
}
], $request);
use Authentication;
use ncryptf\middleware\EncryptionKeyInterface;
use ncryptf\middleware\ResponseFormatter;
use ncryptf\middleware\RequestParser;
use Middlewares\Utils\Dispatcher;
$PSR16CacheInterface = new class implements \Psr\SimpleCache\CacheInterface {};
$response = Dispatcher::run([
new RequestParser($PSR16CacheInterface),
new Authentication,
new ResponseFormatter($PSR16CacheInterface, $EncryptionKeyInterface::class)
function ($request, $next) {
return new JsonResponse(['hello' => 'world'])
}
], $request);
composer
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.