We recommend that you first review the guide for this method.
Below you will find code samples in different languages to show you how to create the Access Token.
These code samples are ready to run and you are welcome to use them in your code. Alternatively, you can use these samples as a reference to develop your own code.
using System;
namespace CreateAccessToken
{
class Program
{
private static string[] helpLines =
{
"Usage: CreateAccessToken.exe <Certificate file path> <API Key> <Absolute time>",
"Certificate file path: .cer as downloaded from https://service.pcibooking.net/api",
"API Key: As generated in your PCI Booking account",
"Absolute time: local time in format HH:MM:ss (up to 1 hour from now), e.g: 18:20:34"
};
static void Main(string[] args)
{
if (args.Length != 3)
Usage("Invalid number of arguments; expected 3");
// read certificate
System.Security.Cryptography.X509Certificates.X509Certificate2 cert = null;
try
{
cert= new System.Security.Cryptography.X509Certificates.X509Certificate2(args[0]);
}
catch (Exception ex)
{
Usage("Cannot load certificate file: " + args[0] + " Error: " + ex.Message);
}
// read time and convert to absolute date time in UTC
DateTime expectedExpirationLocalTime;
if (!DateTime.TryParse(args[2], out expectedExpirationLocalTime))
{
Usage("Invalid expected time: " + args[2]);
}
TimeSpan expiresIn = expectedExpirationLocalTime.Subtract(DateTime.Now);
if (expiresIn > TimeSpan.FromHours(1) || expiresIn<TimeSpan.Zero)
{
Usage(string.Format("Invalid expected time [{0}]. Should be up to one hour ahead ", args[2]));
}
DateTime expectedExpirationUTC = expectedExpirationLocalTime.ToUniversalTime();
// Generate a guid
string guid = Guid.NewGuid().ToString().Replace("-","");
// Construct data block
string dataBlock = string.Format("{0}#{1}#{2}", args[1], guid, expectedExpirationUTC.ToString("o"));
// encode the string to clear bytes
byte[] clearBytes = System.Text.Encoding.UTF8.GetBytes(dataBlock);
// obtain crypto provider with public key
System.Security.Cryptography.RSACryptoServiceProvider rsaCryptoServiceProvider = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PublicKey.Key;
// perform the encryption
byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt(clearBytes, false);
// convert byte array to hex string
string accessToken = string.Concat(Array.ConvertAll(encryptedBytes, b => b.ToString("X2")));
Console.WriteLine(accessToken);
}
private static void Usage(string message = "")
{
if (!string.IsNullOrEmpty(message))
Console.WriteLine(message);
foreach (var line in helpLines)
{
Console.WriteLine(line);
}
Environment.Exit(0);
}
}
}
import java.io.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.UUID;
import javax.crypto.Cipher;
public class CreateAccessToken {
private static final String[] helpLines
= {
"Usage: CreateAccessToken.exe <Certificate file path> <API Key> <Absolute time>",
"Certificate file path: .cer as downloaded from https://service.pcibooking.net/api",
"API Key: As generated in your PCI Booking account",
"Absolute time: local time in format HH:MM:ss (up to 1 hour from now), e.g: 18:20:34"
};
public static void main(String[] args) {
if (args.length != 3) {
Usage("Invalid number of arguments; expected 3");
}
// read certificate
Certificate cert = null;
try {
InputStream fis = new FileInputStream(args[0]);
BufferedInputStream bis = new BufferedInputStream(fis);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
cert = cf.generateCertificate(bis);
} catch (Exception ex) {
Usage("Cannot load certificate file: " + args[0] + " Error: " + ex);
}
// read time and convert to absolute date time in UTC
Date expectedExpirationLocalTime = null;
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String cDate=formatter.format(date);
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
expectedExpirationLocalTime = formatter.parse(cDate+" "+args[2]);
} catch (Exception ex) {
Usage("Invalid expected time: " + args[2] + " Error: " + ex);
}
Calendar cal = Calendar.getInstance();
long expiresIn = expectedExpirationLocalTime.getTime() - cal.getTime().getTime();
if (expiresIn > 3600000 || expiresIn < 0) {
Usage("Invalid expected time [" + args[2] + "]. Should be up to one hour ahead ");
}
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date expectedExpirationUTC = null;
try {
expectedExpirationUTC = formatter.parse(formatter.format(expectedExpirationLocalTime));
} catch (Exception ex) {
Usage("Cannot convert time to UniversalTime: Error: " + ex);
}
// format to ISO 8601
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
String asISO8601 = df.format(expectedExpirationUTC);
// Generate a guid
String guid = UUID.randomUUID().toString().replace("-", "");
// Construct data block
String dataBlock = String.format("%1$s#%2$s#%3$s", args[1], guid, asISO8601);
// encode the string to clear bytes
byte[] clearBytes = null;
try {
clearBytes = dataBlock.getBytes("UTF-8");
} catch (Exception ex) {
Usage("Cannot encode to UTF8: Error: " + ex);
}
byte[] encryptedBytes = null;
// perform the encryption
try {
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance("RSA");
// encrypt the plain text using the public key
cipher.init(Cipher.ENCRYPT_MODE, cert.getPublicKey());
encryptedBytes = cipher.doFinal(clearBytes);
} catch (Exception ex) {
Usage("Cannot encrypt: Error: " + ex);
}
// convert byte array to hex string
String accessToken = byteArrayToHex(encryptedBytes);
// display the access token
System.out.println(accessToken);
}
private static void Usage(String message) {
if (!message.isEmpty()) {
System.out.println(message);
}
for (String line : helpLines) {
System.out.println(line);
}
System.exit(0);
}
private static String byteArrayToHex(byte[] a) {
StringBuilder sb = new StringBuilder(a.length * 2);
for (byte b : a) {
sb.append(String.format("%02X", b & 0xff));
}
return sb.toString();
}
}
<?php
require('vendor/autoload.php');
class CreateAccessToken
{
private $certificate;
private $apiKey;
private $expirationTime;
public function __construct($certificate, $apiKey, DateTime $expirationTime)
{
$this->certificate = $certificate;
$this->apiKey = $apiKey;
$this->expirationTime = $expirationTime;
}
public function createToken()
{
$cert = openssl_get_publickey($this->certificate);
$this->expirationTime->setTimeZone(new DateTimeZone('UTC'));
$expirationAsISO8601 = $this->expirationTime->format(DateTime::ISO8601);
$guid = $this->generateUUID();
$dataBlock = sprintf('%s#%s#%s', $this->apiKey, $guid, $expirationAsISO8601);
openssl_public_encrypt($dataBlock, $encryptedData, $cert);
$encryptedDataHex = strtoupper(bin2hex($encryptedData));
return $encryptedDataHex;
}
private function generateUUID()
{
return str_replace('-', '', Ramsey\Uuid\Uuid::uuid4());
}
}
import binascii
import uuid
import pytz
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.x509 import load_pem_x509_certificate
def create_access_token(cert_file, api_key, expiration_time):
cert = load_pem_x509_certificate(cert_file.read(), default_backend())
public_key = cert.public_key()
try:
expiration_time = pytz.utc.localize(expiration_time)
except ValueError:
pass
expiration_string = expiration_time.isoformat()
data_block = '{}#{}#{}'.format(api_key, uuid.uuid4(), expiration_string)
ciphertext = public_key.encrypt(data_block, padding.PKCS1v15())
return binascii.hexlify(ciphertext)
def main():
import datetime
import sys
if len(sys.argv) != 4:
print("Usage: {} cert_file api_key, expiration_timestamp".format(
sys.argv[0]))
exit(1)
with open(sys.argv[1], "rb") as cert_file:
expiration_time = datetime.datetime.fromtimestamp(int(sys.argv[3]))
print(create_access_token(cert_file, sys.argv[2], expiration_time))
if __name__ == '__main__':
main()