info
In this guide there will be some sample code provided for your refernce, please note that the sample code ONLY aims for reference and shall provide NO SUPPORT for any issue on the sample code.
Introduction
This is general walk-through for getting start iAM Smart APIs development of Signing Using Login with "iAM Smart"
use case.
Developers of Online Services adopting iAM Smart may find this guide useful when designing and developing application flows for signing adopting iAM Smart functions.
In this guide we will provide guides on:
Setting up your iAM Smart development environment
Request Signing
Open iAM Smart Mobile App for Getting Context
Online Service Acknowledge Signing Result
User Journey
Flow
Please find below the sequence diagram for the whole Signing Using Login with "iAM Smart"
process:
In this guide, we will focus on some of the key steps that online service and users will be involved into when adopting and using "iAM Smart".
Click sign by "iAM Smart"
UI Display
Online service shall display one of the following button depends on the scenario:
info
Please note that the request shall be initiated after the user clicked the "Signing with iAM Smart" button.
Online service is required to add a link / button, “More info” or “了解更多” in the initiation page. The link / button shall be linked to the “iAM Smart” thematic webpage based on language preference of user.The initiation page refers to the page that initiate the “iAM Smart” service, which user clicks the “iAM Smart” button to initiate the interaction with “iAM Smart” mobile application.
Language | Link |
---|---|
English | https://www.iamsmart.gov.hk/en/ |
Traditional Chinese | https://www.iamsmart.gov.hk/tc/ |
Simplified Chinese | https://www.iamsmart.gov.hk/sc/ |
Submit “Request Signing”
Composing Reuqest Body
Parameters | Data Type | Description | |
---|---|---|---|
businessID | string | businessID is a unique identifier for eService to differentiate different request. It should be ASCII string with length less than or equal to 36 chars. | |
accessToken | string | accessToken value | |
openID | string | Tokenised ID value | |
source | string | Request initiator. The supported source values can be found in part 0 of the Appendix in this specification. | |
redirectURI | string | callback URI. | |
state | string | (Optional) If state parameter is presented in the request message, the same state value will be returned to online service during callback. It is used to prevent the CSRF attack. The value of state is defined by online service and it should be a secure random value. It can be an ASCII string of any length less than or equal to 36 (UUID string length). Only ASCII letters, numbers, underscore and hyphen are accepted.URI. | |
hashCode | string | the document hash to be signed. Online Service should compute the hash and send this hash to iAM Smart System for signing. The value should be Base64 encoded. | |
sigAlgo | string | (Optional) signature algorithm to be used. Online Service can specify either SHA256withRSA or NONEwithRSA. The default value is SHA256withRSA. While using NONEwithRSA, hashCode provided must be hashed with SHA256. | |
HKICHash | string | Signing request will only be processed when the hash of the HKIC number of the iAM Smart user is matched with the HKICHash provided by Online Service. Online Service should convert the HKIC number into hash value using SHA256 before sending to iAM Smart System. Only the identifier of HKIC number will be hashed, no check digit is needed e.g. A123456. The value should be Base64 encoded. | |
department | string | (Optional)The department that initiates the signing request. | |
serviceName | string | The service name. | |
documentName | string | The document name that the user is going to sign. |
Your request body should look something like this:
{
"businessID": "bbb8aae57c104cda40c93843ad5e6db8",
"accessToken": "xxxa42e76bf4cb0846a68e6d83d6096",
"openID": "liR14%2BvX%2F5hSum5uf4ERczu0KcDnIJA5BM7FoM1ag9c%3D",
"source": "Android_Chrome",
"redirectURI": "https://<rp_domain>/<rp_context>/<call_back_endpoint>",
"state": "eddd527b6",
"hashCode": " 965e638fda4c70f667efc2d68c40c6111e5965bfc82356d",
"HKICHash": " 6ea37e641260714009a880a8057032a414009a80f667efc",
"department": " Digital Policy Office",
"serviceName": "OnlinOnline Service1",
"documentName": "Doc0001"
}
Encryption
To better protect the data in transit, an additional layer of data encryption will be applied to all APIs POST request (except the one that Online Service request for getting symmetric encryption key).
info
To encrypt the data, a Content Encryption Key is required, please refer to iAM Smart API Specification 6.3.1.1 or online mockup API
In this case we will use a mock-up Content Encryption Key (CEK), please find below a base64-encoded mock CEK:
pvD2Zc1mf7tKVh17JOftmzyTaDyVmcULg92nB9qeEoQ=
Online Service should check whether its CEK is still valid and use it to encrypt all the JSON data of the POST request body as ciphertext using encryption algorithm “AES/GCM/NoPadding”.
This algorithm requires an initialisation vector (“IV”) which is provided by Online Service. The ciphertext, IV and length of IV are then concatenated in the following sequence and BASE64 encoded to formulate the value of JSON name/value pair called “content”.
Content value:
4 bytes IV length + IV + ciphertext
You may refer to the psuedo code below for the encryption implementation:
// request body
byte[] contentByte = content.getBytes();
// using AES/GCM/NoPadding for encryption algorithm
SecretKeySpec sKeySpec = new SecretKeySpec(key, Constants.ALGORITHM_AES);
byte[] encrypted;
SecureRandom secureRandom = new SecureRandom();
byte[] iv = new byte[Constants.IV_LENGTH];
secureRandom.nextBytes(iv);
Cipher cipher = Cipher.getInstance(Constants.AES_GCM_NOPADDING);
GCMParameterSpec parameterSpec = new GCMParameterSpec(Constants.GCM_AUTH_TAG_LENGTH, iv);
// encrypt the request body
cipher.init(Cipher.ENCRYPT_MODE, sKeySpec, parameterSpec);
encrypted = cipher.doFinal(contentByte);
// concatenated IV_len + IV + ciphertext + authTag
ByteBuffer byteBuffer = ByteBuffer.allocate(Constants.INT_BYTE_LENGTH + iv.length + encrypted.length);
byteBuffer.putInt(iv.length);
byteBuffer.put(iv);
byteBuffer.put(encrypted);
byte[] cipherMessage = byteBuffer.array();
result = Base64.getEncoder().encodeToString(cipherMessage);
info
Please note that the psuedo code ONLY aims for reference and shall provide NO SUPPORT for any issue on the psuedo code.
Please find below an example of base64-encoded IV:
vM7EArooK0hCCX8E
If you use the above json and encrypt with the above CEK and IV, concatenated and base64 encoded, you should get the following result:
AAAADLzOxAK6KCtIQgl/BJRVECazUaNiaf13rfcGNApA3K0BI0qZkB5pMWAjcTF0z0PLOnsCyxCtVUytAbA/cm2U5W83FrRXvtZZ74SrCWY4cQiAlq38TLSeOY9B418Tc5dUr1JnbCVeHe8HNrEY81QyI3r7JMZfXGaWgRoz0os8C7zbzty88vPGPSmBE7WqZF5I84IJ7wzwpRs+ifz9DfpFqWzj55mftTHQERWDhcKRALgdZECoFCqtmNhRFERxAm+MrIkypZG/JAdcho0cLyIGTkw7KLqKT0/NmQgQ3vsi6IxGOF4u8gPfLHfRkLopZkU7sXXHNC5hVtEmGXz0zrp+Pq9diKIX6MyrAtwjhIxxKu5iI9MO7XB272hpeonpJYWA0dvh0F882tjNnN6oRJrQ1ZxPXfeA
Now put it in the value of JSON name/value pair called “content” as the request body:
{
"content": "AAAADLzOxAK6KCtIQgl/BJRVECazUaNiaf13rfcGNApA3K0BI0qZkB5pMWAjcTF0z0PLOnsCyxCtVUytAbA/cm2U5W83FrRXvtZZ74SrCWY4cQiAlq38TLSeOY9B418Tc5dUr1JnbCVeHe8HNrEY81QyI3r7JMZfXGaWgRoz0os8C7zbzty88vPGPSmBE7WqZF5I84IJ7wzwpRs+ifz9DfpFqWzj55mftTHQERWDhcKRALgdZECoFCqtmNhRFERxAm+MrIkypZG/JAdcho0cLyIGTkw7KLqKT0/NmQgQ3vsi6IxGOF4u8gPfLHfRkLopZkU7sXXHNC5hVtEmGXz0zrp+Pq9diKIX6MyrAtwjhIxxKu5iI9MO7XB272hpeonpJYWA0dvh0F882tjNnN6oRJrQ1ZxPXfeA"
}
Composing Request Header
Parameters | Data Type | Description |
---|---|---|
clientID | string | online service client identifier, the client ID will be assigned to online service at the initial registration |
signatureMethod | string | HmacSHA256 |
timestamp | integer | The timestamp is the request submit time expressed in the number of milliseconds since January 1, 1970 00:00:00 GMT. It is used to prevent replay attack. The value MUST be a positive integer and equal or greater than the timestamp used in previous requests. |
nonce | string | A nonce is a random string, uniquely generated for each request by Online Service. It is used to prevent replay attack. A nonce can be an ASCII string of any length less than or equal to 36 (UUID string length) as long as the uniqueness requirement is met. |
signature | string | It is a signature of the submitted data. Online Service uses clientSecret to sign the request body string and timestamp to get the signature. The pseudo code to generate the signature is shown at below. |
Online Service uses clientSecret to sign the concatenated string of clientID, signatureMethod, timestamp, nonce and request body to get the signature.
In this case, we will use the following parameter for signature generation:
> clientID: clientID20220817demo
> clientSecret: clientSecret20220817demo
> signatureMethod: HmacSHA256
> timestamp: 1660721425291
> nonce: nonce20220817
The concatenated string of clientID, signatureMethod, timestamp, nonce and request body should be as followed:
clientID20220817demoHmacSHA2561660721425291nonce20220817{"content": "AAAADLzOxAK6KCtIQgl/BJRVECazUaNiaf13rfcGNApA3K0BI0qZkB5pMWAjcTF0z0PLOnsCyxCtVUytAbA/cm2U5W83FrRXvtZZ74SrCWY4cQiAlq38TLSeOY9B418Tc5dUr1JnbCVeHe8HNrEY81QyI3r7JMZfXGaWgRoz0os8C7zbzty88vPGPSmBE7WqZF5I84IJ7wzwpRs+ifz9DfpFqWzj55mftTHQERWDhcKRALgdZECoFCqtmNhRFERxAm+MrIkypZG/JAdcho0cLyIGTkw7KLqKT0/NmQgQ3vsi6IxGOF4u8gPfLHfRkLopZkU7sXXHNC5hVtEmGXz0zrp+Pq9diKIX6MyrAtwjhIxxKu5iI9MO7XB272hpeonpJYWA0dvh0F882tjNnN6oRJrQ1ZxPXfeA"}
You may refer to the psuedo code below for the signature generation:
// Digest with HmacSha256
Mac sha256HMAC = null;
try {
sha256HMAC = Mac.getInstance(Constants.SIGNATURE_METHOD);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
if (sha256HMAC == null) {
return null;
}
SecretKeySpec secretKey = new SecretKeySpec(clientSecret.getBytes(), Constants.SIGNATURE_METHOD);
try {
sha256HMAC.init(secretKey);
} catch (InvalidKeyException e) {
e.printStackTrace();
}
// base64-encoded
String hash = Base64.getEncoder().encodeToString(sha256HMAC.doFinal(message.getBytes()));
// URL enconded
return URLEncoder.encode(hash, StandardCharsets.UTF_8);
With the parameters provided you should get the following result:
17uX5GHbU7x1mz1czXBLifRqOJ%2BwzZG105bj%2FWpuwU0%3D
Now construct the request header with all the parameters:
{
"clientID": "clientID20220817demo",
"signatureMethod": "HmacSHA256",
"timestamp": 1660721425291,
"nonce": "nonce20220817",
"signature": "17uX5GHbU7x1mz1czXBLifRqOJ%2BwzZG105bj%2FWpuwU0%3D"
}
The completed request should be like following;
// Request Headers
{
"clientID": "clientID20220817demo",
"signatureMethod": "HmacSHA256",
"timestamp": 1660721425291,
"nonce": "nonce20220817",
"signature": "17uX5GHbU7x1mz1czXBLifRqOJ%2BwzZG105bj%2FWpuwU0%3D"
}
// Request Body
{
"content": "AAAADLzOxAK6KCtIQgl/BJRVECazUaNiaf13rfcGNApA3K0BI0qZkB5pMWAjcTF0z0PLOnsCyxCtVUytAbA/cm2U5W83FrRXvtZZ74SrCWY4cQiAlq38TLSeOY9B418Tc5dUr1JnbCVeHe8HNrEY81QyI3r7JMZfXGaWgRoz0os8C7zbzty88vPGPSmBE7WqZF5I84IJ7wzwpRs+ifz9DfpFqWzj55mftTHQERWDhcKRALgdZECoFCqtmNhRFERxAm+MrIkypZG/JAdcho0cLyIGTkw7KLqKT0/NmQgQ3vsi6IxGOF4u8gPfLHfRkLopZkU7sXXHNC5hVtEmGXz0zrp+Pq9diKIX6MyrAtwjhIxxKu5iI9MO7XB272hpeonpJYWA0dvh0F882tjNnN6oRJrQ1ZxPXfeA"
}
Now initiate the request with POST method to the Request Signing enpoint.
> https://<iAM_Smart_domain>/api/v1/account/signing/initiateRequest
Upon success you should receive the encrypted response:
{
"txID": "<T=938ffb193b4b4370b6c2584372c6a588>",
"code": "D00000",
"message": "SUCCESS",
"content":"AAAADLzOxAK6KCtIQgl/BJRVECazUaNiaf13rfcGNApA3K0BI0qZkB5pMWAjcTF0z0PLOnsCyxCtVUytAbA/cm2U5W83FrRXvtZZ74SrCWY4cQiAlq38TLSeOY9B418Tc5dUr1JnbCVeHe8HNrEY81QyI3r7JMZfXGaWgRoz0os8C7zbzty88vPGPSmBE7WqZF5I84IJ7wzwpRs+ifz9DfpFqWzj55mftTHQERWDhcKRALgdZECoFCqtmNhRFERxAm+MrIkypZG/JAdcho0cLyIGTkw7KLqKT0/NmQgQ3vsi6IxGOF4u8gPfLHfRkLopZkU7sXXHNC5hVtEmGXz0zrp+Pq9diKIX6MyrAtwjhIxxKu5iI9MO7XB272hpeonpJYWA0dvh0F882tjNnN6oRJrQ1ZxPXfeA"
}
info
Noted the secretKey used for encryption is also provided in the response body, this is for when the request hits the time of updating the CEK, an old CEK is used to encrypt the reuqest, in this scenario online service may use the provided secretKey in the request body for decryption.
Decryption
The structure of the encrypted content of response body is the same as the encrypted trequest body:
4 bytes IV length + IV + ciphertext
To decrypt the encrypted content, you will have to locate the following data:
- 4 bytes IV length
- IV
- ciphertext
- authTag (if necessary)
You may refer to the psuedo code below for the decryption implementation:
// base64-decode the contnet
byte[] content = Base64.getDecoder().decode(base64Content);
SecretKeySpec sKeySpec = new SecretKeySpec(key, Constants.ALGORITHM_AES);
// locate IV and authTag
ByteBuffer byteBuffer = ByteBuffer.wrap(content);
int ivLength = byteBuffer.getInt();
if (ivLength != Constants.IV_LENGTH) {
throw new IllegalArgumentException("Invalid iv length");
}
byte[] iv = new byte[ivLength];
byteBuffer.get(iv);
byte[] cipherText = new byte[byteBuffer.remaining()];
byteBuffer.get(cipherText);
Cipher cipher = Cipher.getInstance(Constants.AES_GCM_NOPADDING);
GCMParameterSpec parameterSpec = new GCMParameterSpec(Constants.GCM_AUTH_TAG_LENGTH, iv);
// decrypt the encrypted content
cipher.init(Cipher.DECRYPT_MODE, sKeySpec, parameterSpec);
byte[] original = cipher.doFinal(cipherText);
result = new String(original);
info
Please note that the psuedo code ONLY aims for reference and shall provide NO SUPPORT for any issue on the psuedo code.
You should get the following result:
{
"txID": "<T=938ffb193b4b4370b6c2584372c6a588>",
"code": "D00000",
"content": {
"authByQR": true
}
}
Now we can proceed to calculate identification code.
Calculate identification code
After submitting signing request by sending access token, hash and tokenized ID, iAM Smart core system will acknowledge signing request and send response to Online Service server. When iAM Smart user has logged in the Online Service, both Online Service and iAM Smart System will compute and display a 4-digit identification code using the Document Hash and the hash of Tokenised ID of the iAM Smart.4-digit identification code generation algorithm is as follows:
- Concatenate the Document Hash and the Tokenised ID hash value (calculated with SHA-512), and perform the digital digest for the concatenation result with SHA-512
- Perform the MD5 calculation to obtain a unique MD5 hash value
- Divide the 128-bit MD5 hash value into four groups of 4 bytes binary value and then extract the fistt byte from each group as a data sample.
- Perform 4-bit unsigned right shift to each byte of the result obtained above for the hexadecimal data.
- Perform the modulo operation on each byte (modulo 10) to obtain a number of 0-9.
- Assemble the 4 numbers obtained above as a 4-digit identificatin code.
You may refer the pseudo code below for the calculation of identification code:
private static final char hexDigits[] = {‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’};
public static String getSignCode (String hashCode, String openlD) {
// Assume Document Hash is BASE64 encoded and perform decode
byte[] hashCodeBytes = Base64Util.base64Decode(hashCode);
// Calculate SHA-512 hashcode of Tokenised ID
byte[] openlDBytes = DigestUtil.digestToByte(openlD, Alg.SHA512);
char code[] = new char [4];
byte[] source = new byte[hashCodeBytes.length + openlDBytes.length];
System.arraycopy(hashCodeBytes, 0, source, 0, hashCodeBytes.length);
System.arraycopy(openlDBytes, 0, source, hashCodeBytes.length, openlDBytes.length);
// Calculate SHA-512 hashcode from concatenated Document Hash and
// SHA-512 hashed Tokenised ID
byte[] inData = DigestUtil.digestToByte(source, Alg.SHA512);
// Calculate MD% hashcode
byte[] digestMD5Data = DigestUtil.digestToByte(inData, Alg.MD5);
// Convert MD5 value 4-digit identification code
for (int i = 0; i < 4; i++) {
code[i] = hexDigits[(digestMD5Data[i * 4] >>> 4 & 0xf) % 10];
return new String(code);
}
info
Please note that the pseudo code ONLY aims for reference and shall provide NO SUPPORT for any issue on the pseudo code.
The next step will introduce Instruction Page for requesting signing
.
Instruction Page for requesting signing
After online service sends the initiate signing request to “iAM Smart” system, online service is required to instruct to open the “iAM Smart” app in his/her mobile phone
. Please refer to the table below for different scenarios.
Now we may proceed to request the "iAM Smart" QR Page/App broker page.
Open iAM Smart Mobile App for Getting Context
When iAM Smart Mobile App is opened, Online Service Website should keep synchronising with Online Service for signing processing result, such as polling. Online Service Website/app invokes iAM Smart Mobile App using URL Scheme with “ticketID” (set Context
as “hash-sign or “pdf-sign”
in URL Scheme).
Construct the URL Scheme
Parameters | Data Type | Description |
---|---|---|
ticketID | string | TicketID is a unique identifier provided by iAM Smart Core System, Online Service retrieve ticketID while requesting the context (Profile / Signing / Form Filling / Re-authentication). It is ASCII string with length less than or equal 36 chars. |
source | string | (Optional) This parameter is required only in anonymous form filling or anonymous signing workflows. Request initiator (App_Scheme, App_Link).The detail of supported source values can be found in Appendex B of this specification. |
redirectURI | string | (Optional) callback redirect URI. This parameter is required only in anonymous form filling or anonymous signing workflows and its value should be URL encoded. |
state | string | (Optional) If state parameter is presented in the request message, the same state value will be returned to Online Service during callback. It is used to prevent the CSRF attack. The value of state is defined by Online Service and it should be a secure random string of any length less than or equal to 36 (UUID string length). Only ASCII letters, numbers, underscore and hyphen are accepted. |
You request scheme should be something as following:
> hk.gov.digitalpolicy://hash-sign?ticketID=bbb8aae57c104cda40c93843ad5e6db8
Callback to Receive Signing Result
After iAM Smart user logs in iAM Smart Mobile App, reviews the signing authorisation request (e.g. continue or reject the request) and verify the 4-digit identification code with Online Service Website/app. iAM Smart user follows the instructions in iAM Smart Mobile App to complete signing operation. iAM Smart System invokes Online Service callback API to return the result with “businessID” of the signing request to Online Service server
.
Callback Parameters
Parameters | Data Type | Description |
---|---|---|
businessID | string | businessID is a unique identifier for Online Service to differentiate different request. Online Service can use the businessID to relate the callback message with the original request. |
state | string | (Optional) If the state parameter has been present in the request message, the exact value of state will be returned. It is used to prevent the CSRF attack. The value of state is defined by Online Service and it should be a secure random value. |
hashCode | string | (Optional) The document hash submitted by Online Service in the API request. |
timestamp | long | (Optional) Timestamp in milliseconds since January 1, 1970 00:00:00 GMT. iAM Smart System will provide this to Online Service only when signing is successful. |
signature | string | (Optional) Base64-encoded signature result string. iAM Smart System will provide this to Online Service only when signing is successful. |
cert | sting | (Optional) Base64-encoded DER format certificate for the iAM Smart user. iAM Smart System will provide this to Online Service only when the signing is successful. |
Upon success you should receive the encrypted response, after decryption, you should get the following result:
{
"txID": "<T=938ffb193b4b4370b6c2584372c6a588>",
"code": "D00000",
"message": "SUCCESS",
"content": {
"businessID": "2YotnFZFEjr1zCsicMWpAA",
"state": "unesidkd",
"hashCode": "tGzv3JOkF0XG5Qx2TlKWIA",
"timestamp": 1556450176000,
"signature": "nnoadisauflanefhykdjf",
"cert": "sdfGSDGsdfa*gDEHfjslgGQG……GSGjljlkjwmh",
}
}
Online Service Acknowledge Signing Result
Online Service Server completes the document signing process, verify the result and acknowledges iAM Smart System the signing result using iAM Smart API with the same “businessID” of the signing request
.
You may refer the pseudo code below for the verification of signing result:
public static boolean verifySignature(PublicKey publicKey, String algName, byte[] signatureByte, byte[] hash) {
boolean isCorrect = false;
try {
Signature signature = Signature.getInstance(algName);
signature.initVerify(publicKey);
signature.update(hash);
isCorrect = signature.verify(signatureByte);
} catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
e.printStackTrace();
}
return isCorrect;
}
Composing Request body
Parameters | Data Type | Description |
---|---|---|
businessID | string | businessID is a unique identifier for Online Service to differentiate different request. It should be ASCII string with length less than or equal to 36 chars. |
signingResult | string | "SR001": digital signature is accepted "SR002": digital signature is rejected "SR003": no digital signature was received. |
Your request body should look something like this:
{
"businessID": "bbb8aae57c104cda40c93843ad5e6db8",
"signingResult": "SR001",
}
Upon success you should receive the encrypted response, after decryption, you should receive the following result:
{
"txID": "<T=938ffb193b4b4370b6c2584372c6a588>",
"code": "D00000",
"message": "SUCCESS"
}
Online Service Server matches the result using the “businessID” and shows the signing result in corresponding Online Service Website.
Summary
Congratulations! You have sucessfully go through the following items.
- Setting up your iAM Smart development environment
- Request Signing
- Open iAM Smart Mobile App for Getting Context
- Online Service Acknowledge Signing Result
Next Steps
Get started with "iAM Smart" API:
- To learn about the Login and linkup with iAM Smart, refer to [Login linkup with iAM Smart] (Login and GetProfile)
- To learn about the use case of Digital Signing with iAM Smart, refer to [Digital Signing] (Digital Signing [After Authentication API] & Anonymouse Signing)
Further Reading
- "iAM Smart" API Specification v1.2.7,
Section 4.5.1, 4.5.2, 6.3.1, 6.3.2, 6.3.3, 6.3.4, 6.3.5, 6.4.5
- "iAM Smart" Developer Guide v1.2.7,
Section 3.6.1, 3.6.2