Download - Center for Electronic Governance - United Nations ...

chairwomanlettersΛογισμικό & κατασκευή λογ/κού

13 Νοε 2013 (πριν από 3 χρόνια και 1 μήνα)

282 εμφανίσεις




























Extensible Messaging Gateway

– Enhanced Services


Technical Report


Elsa Estevez

Vincent Douwe

Tomasz Janowski



type
date
version

location

Technical Report
14 April 2009
1.0

www.egov.iist.unu.edu/outputs


UNU-IIST Center for Electronic Governance www.egov.iist.unu.edu































Copyright © 2009, UNU-IIST Center for Electronic Governance
UNU-IIST Center for Electronic Governance
Identity:
An International Center of
Excellence on research and practice
in Electronic Governance, part of
United Nations University - Interna-
tional Institute for Software Tech-
nology, located in Macao, China.

Activities:
Applied and policy research,
capacity building, and various forms of
development – strategy development,
software development, institutional
development and development of com-
munities of practice.
Mission:
To support govern-
ments in developing countries
in strategic use of technology
to transform the working of
public organizations and their
relationships with citizens,
businesses, civil society, and
with one another.


SUMMARY


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

i
SUMMARY
This document provides technical documentation about
enhanced functionality and new APIs for the Extensible
Messaging Gateway. The enhanced functionality com-
prises a new release of the Encryption/Decryption ex-
tension using certificates issued by Macao Post Office
(DSC) and modified versions of existing components
supporting the new extension. The new APIs enables
applications developed in Delphi and any other pro-
gramming language able to access the command line to
invoke the Gateway services. The document first
presents the scope of the Macao Data Exchange Gate-
way Project and the motivation for producing the deli-
verables presented in this report. Second, it specifies in
detail the new extension for encrypting and decrypting
messages. Third, it introduces the programming lan-
guages mostly used by applications deployed in Macao
Government agencies, presents new APIs for invoking
the Gateway services by applications developed in Del-
phi, and explains the use of two executable files for
sending and receiving messages that can be invoked by
any legacy application able to access the command line.
Fourth, it enumerates the deployment components and
explains the procedure for their deployment. Fifth,
some conclusions are drawn. Finally, technical artifacts –
like Java classes used by the Encryption extension, de-
tailed and summarized lists of government applications
and programming languages used by government agen-
cies, Delphi APIs, Java classes for sending and receiving
messages through the command line, and the new Ga-
teway configuration file; are included in the appendices.
This work was partly funded by Macao Foundation un-
der the e-Macao Program (www.emacao.gov.mo).

TABLE OF CONTENTS


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

ii
TABLE OF CONTENTS
Summary .................................................................................................................................................................................... i
Table of Contents ...................................................................................................................................................................... ii
List of Tables ............................................................................................................................................................................. iii
List of Figures ........................................................................................................................................................................... iii
Abbreviations ........................................................................................................................................................................... iv
Revisions .................................................................................................................................................................................. iv
1. Introduction .......................................................................................................................................................................... 1
2. Encrypting and Decrypting Messages .................................................................................................................................... 2
2.1. Enabling Encryption/Decryption Extension .................................................................................................................. 3
2.2. Setting the PIN ............................................................................................................................................................... 4
2.3. Configuring Encryption/Decryption Extension ............................................................................................................. 4
2.4. Disabling the Encrytion/Decryption Extension ............................................................................................................. 7
2.5. Sending an Encrypted Message ..................................................................................................................................... 8
2.6. Receiving an Encrypted Message .................................................................................................................................. 9
3. New APIs for Legacy Systems .............................................................................................................................................. 10
3.1. Programming Languages used by Macao Government Agencies ............................................................................... 10
3.2. APIs for Delphi ............................................................................................................................................................. 11
3.3. APIs for Sending and Receiving Messages from the Command Line .......................................................................... 13
4. Deployment Components and Procedure .......................................................................................................................... 16
4.1. Deployment Components ............................................................................................................................................ 16
4.2. Deployment Procedure................................................................................................................................................ 17
5. Conclusions ......................................................................................................................................................................... 19
References............................................................................................................................................................................... 20
Appendices .............................................................................................................................................................................. 21
A. Java Classes Used by the Encryption Extension .............................................................................................................. 21
B. Delphi APIs...................................................................................................................................................................... 31
C. Programming Languages and Tools Used by Government Applications ........................................................................ 51
D. Java Classes for Sending and Receiving Messages through the Command Line ............................................................ 60
E. Gateway Configuration File ............................................................................................................................................ 63



LIST OF TABLES AND FIGURES


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

iii
LIST OF TABLES
Table 1: Encrypting and Decrypting Messages using RSA and AES ............................................................................................ 2
Table 2: Programming Languages and Tools Mostly Used by Government Applications ........................................................ 10


LIST OF FIGURES
Figure 1: Smart Card Issued by Macao Post and Smart Card Reader ........................................................................................ 2
Figure 2: Enabling Encryption/Decryption Extension ................................................................................................................ 3
Figure 3: Setting the PIN ............................................................................................................................................................ 4
Figure 4: User Interface for Setting the PIN .............................................................................................................................. 5
Figure 5: Configuring Encryption/Decryption – Owner’s Side ................................................................................................... 5
Figure 6: Configuring Encryption/Decryption – Subscriber’s Side ............................................................................................. 6
Figure 7: Disabling Encryption/Decryption – Owner s’ Side ...................................................................................................... 7
Figure 8: Disabling Encryption/Decryption – Subscriber’s Side ................................................................................................. 7
Figure 9: Sending an Encrypted Message .................................................................................................................................. 8
Figure 10: Receiving an Encrypted Message ............................................................................................................................. 9
Figure 11: Send Class - Main Method ...................................................................................................................................... 14
Figure 12: Receive Class - Main Method ................................................................................................................................. 15
Figure 13: Extensible Message Gateway – Deployment Folders ............................................................................................. 16
Figure 14: Folder Structure for Receiving and Sending Messages through the Command Line .............................................. 18


ABBREVIATIONS AND REVISIONS


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

iv
ABBREVIATIONS
AES Advanced Encryption Standard
API Application Programming Interface
DSC Macao Post
EPS Electronic Public Service
RSA Encryption method proposed by R.L. Rivest, A. Shamir and L. Adleman
SAFP Public Administration and Civil Service Bureau
UNU United Nations University
UNU-IIST UNU International Institute for Software Technology
UNU-IIST-EGOV Center for Electronic Governance at UNU-IIST
XML eXtensible Markup Language

REVISIONS
DATE RESPONSIBLE SCOPE VERSION
13/02/2009 Elsa Estevez First draft version 0.95
28/02/2008 Vincent Douwe Second draft 0.96
04/03/2008 Elsa Estevez Second draft revised 0.98
14/04/2009 Tomasz Janowski Final version 1.0


















SECTION 1 – INTRODUCTION


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

1
1. INTRODUCTION
The provision of Electronic Public Services (EPS) in terms
of number, maturity and accessibility is central for mea-
suring the progress of Electronic Government develop-
ment. However, the rapid provision of mature EPS can-
not be achieved following a case-by-case approach as it
requires the availability of pre-existing components,
tools and artifacts that can be used for rapid develop-
ment, deployment and reliable delivery. These compo-
nents, tools and artifacts constitute the so-called Soft-
ware Infrastructure for Electronic Government. Such
infrastructure includes design-time artifacts – like ready-
to-customize domain models, guidelines and implemen-
tation frameworks that can be used for accelerating EPS
development; as well as run-time components and ser-
vices supporting or realizing common software functio-
nality required for the efficient and reliable delivery of
services – like submission of citizen data through elec-
tronic forms, notifications to applicants, and message
exchange between software applications. The availabili-
ty of such infrastructure is one of the major facilitators
for scaling up, rapidly and efficiently, the provision of
EPS.
In addition to the motivation explained above, main
benefits that can be gained by delivering such infrastruc-
ture for Electronic Government include: providing stan-
dardized services to all agencies based on common
technical standards; reducing the costs of developing
EPS by individual agencies; promoting the adoption of
standards across government; establishing a platform
for collaboration between agencies and between public
and private sector on EPS and infrastructure develop-
ment; facilitating the creation of cross-agency EPS; and
enabling the integration of applications built with differ-
ent technologies.
Based on the motivation and prospective benefits of
providing software infrastructure, the Software Infra-
structure for Electronic Government Project was defined
by the UNU-IIST Center for Electronic Governance to be
executed as part of the e-Macao Program during 2007.
The Message Exchange Gateway (Gateway), a major
infrastructure service, was delivered by this project. The
Gateway enables asynchronous exchange of messages
among registered members (e.g. software applications
or human users) through dynamically created and sub-
scribed channels. It comprises a core framework sup-
porting plain exchange of messages, and various exten-
sions providing enhanced functionality - such as mes-
sage logging, validation, transformation, encryp-
tion/decryption, mediation, and resource discovery,
enabled on the platform.
In 2008, the Macao Data Exchange Gateway Project was
carried out by UNU-IIST Center for Electronic Gover-
nance. The project aim was to develop a unified mes-
sage infrastructure based on the UNU’s Extensible Mes-
sage Gateway and DSC’s e-DocX Service – Unified Macao
Government Message Gateway. This integration leve-
rages the strengths of the two solutions to support inte-
gration of back-office applications, e-document ex-
change and multi-channel service delivery. For discuss-
ing the integration of the Extensible Message Gateway
and e-DocX Service, a meeting was held between SAFP,
DSC and UNU-IIST representatives. As a result, it was
concluded that it would be simpler for government
agencies to use both tools independently of the other,
based on specific needs. Following, the objectives of the
Macao Data Exchange Gateway Project were revised
producing the following:
o1) In order to facilitate the use of the Messaging Ga-
teway by Macao Government Agencies, UNU will
provide APIs for being able to invoke the Message
Gateway services by software applications running
on the IT platforms most commonly used by Macao
Government.
o2) The encryption-decryption extension of the Mes-
saging Gateway will be re-implemented using the
certificates provided by Macao Post Office.
o3) In order to facilitate the testing of the Messaging
Gateway by SAFP, UNU will submit the Message
Gateway Quality Assurance report.
o4) To develop a pilot e-service enabling the manage-
ment of customer queues by government agencies.
For achieving the former two objectives, a new release
of the Gateway was delivered including new APIs and
enhanced services. This report constitutes the technical
documentation of the new functionality and APIs pro-
vided by the Gateway. For fulfilling the third objective,
the Extensible Messaging Gateway – Quality Assurance
Report [1] was delivered to SAFP. For achieving the last
objective, two services were developed – Appointment
and Queuing. Therefore, in addition to the new release
of the Gateway - binary and source code; and this tech-
nical report, the deliverables of the Macao Data Ex-
change Gateway Project for 2008 include the software
(source and binary codes) of the e-Appointment and e-
Queuing services, and four technical reports – develop-
ment report and user manual for each service
[2][3][4][5].
The rest of this document is structured as follows. Sec-
tion 2 explains the new extension for encrypting and
decrypting messages using certificates issued by Macao
Post Office. Section 3 presents the motivation for devel-
oping the new APIs for legacy systems as well as tech-
nical documentation. Section 4 enumerates the deploy-
ment components and the procedure for their deploy-
ment. Section 5 draws some conclusions. Finally, a set of
appendices include the Java classes used by the Encryp-
tion extension, detailed and summarized lists of gov-
ernment applications and programming languages used
by government agencies, Delphi APIs, Java classes for
sending and receiving messages through the command
line, and the new configuration file.

SECTION 2 – ENCRYPTING AND DECRYPTING MESSAGES


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

2
2. ENCRYPTING AND DECRYPTING MESSAGES
Encryption/Decryption is one of the extensions provided
by the first release of the Extensible Messaging Gate-
way. The extension enables encoding of message con-
tents while messages are exchanged by members
through channels. In the first release, the extension
encoded messages using the RSA [6] method. The me-
thod, proposed by R.L. Rivest, A. Shamir and L. Adleman,
implements a private-public key cryptosystem enabling
exchange of ciphered messages without need to com-
municate keys along with the message. The RSA method
implemented by the Gateway extension assigned to the
Gateway Administrator – Admin member, the responsi-
bility for generating the pairs of private-public keys for
each member. Although the approach successfully
showed the behavior of the Encryption/Decryption ex-
tension, the use of these auto-generated keys should be
reviewed before adopting the Gateway in real e-
Government solutions.
One of the revised objectives of the Macao Data Ex-
change Gateway Project for 2008 was to replace the
private-public keys generated by the Gateway Adminis-
trator, by the certificates issued by Macao Post Office. In
support of the EDS Law no. 5/2005 promoting the use of
new technologies for assuring secure electronic transac-
tions over open communication networks, Macao Post
established eSignTrust – a Certification Service Provider
[8]. Among other tasks, eSignTrust is responsible for
issuing encipherment certificates which can be used for
encrypting and decrypting data, sending encrypted mes-
sages, decrypting messages, and acknowledging the
receipt of an encrypted message using digital signature.
Encipherment certificates and their public and private
keys are stored in smart cards, which can be read
through a wide range of industry smart card readers,
and are also available through their website. Figure 1
shows an example of smart card and smart card reader.
Figure 1: Smart Card Issued by Macao Post and Smart
Card Reader


Following the encryption approach suggested by
eSignTrust, the new release of the Gateway extension
encodes message contents using a hybrid combination
of RSA, the method used by the first release of the Ga-
teway, and Advanced Encryption Standard (AES) [7]
method. The AES algorithm is a symmetric block cipher
for encrypting and decrypting information. The ap-
proach implemented by the Gateway extension is as
follows. The message content (c) and a randomly gener-
ated key (k) are encrypted using AES, producing an en-
crypted content (c’). If the message is sent by a channel
subscriber, the generated key (k) is encrypted with the
public key of the channel owner (PuK) using the RSA
method producing an encoded key (k’). If the message is
sent by the channel owner, the generated key (k) is en-
crypted with the channel owner’s private key (PrK). Fi-
nally, the encoded content (c’) and the encrypted key
(k’) are sent. For decrypting the message, first the en-
crypted key (k’) is decrypted following the RSA method,
and the generated key (k) is obtained.

Table 1: Encrypting and Decrypting Messages using RSA and AES
SENDER
RECEIVER
NO
ACTION
NO
ACTION
1
k = generateKey
encrypt
AES
(c, k) = c’
1 If subscriber decrypt
RSA
(k’, Puk) = k
If owner
decrypt
RSA
(k’, PrK) = k
2 If subscriber
encrypt
RSA
(k, PuK) = k’
2
decrypt
AES
(c’, k) = c
If owner
encrypt
RSA
(k, PrK) = k’
3
send(k’, c’)
3
receive(c)



SECTION 2 – ENCRYPTING AND DECRYPTING MESSAGES


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

3
If the message recipient is a channel subscriber, the
encrypted key (k’) is decrypted using the channel own-
er’s public key (PuK); while, if the recipient is the chan-
nel owner, it is decrypted using its private key (PrK).
Second, the encrypted message (c’) is decrypted using
the generated key (k) following the AES method, pro-
ducing the plain message (c). Finally, the plain text of
the message (c) is received by the recipient application.
Table 1 summarizes this process.
Based on the motivations explained above, a new re-
lease of the Encryption/Decryption extension using the
certificates issued by eSignTrust is provided. The exten-
sion provides the following services:
a) Enabling Encryption/Decryption – after enabling the
extension for a channel, all messages sent through
the channel will be encrypted by the sender and
decrypted by the recipients using the public and
private keys of the channel owner.
b) Setting Pin – enables to define the Personal Identi-
fication Number (PIN) for the member to access the
smart card for reading the private/public keys.
c) Configuring Encryption/Decryption – involves dis-
tributing the public key of the channel owner
among channel subscribers.
d) Disabling Encryption/Decryption – after disabling
the extension, messages sent through the channel
are exchanged in plain text – they are no longer en-
crypted.
e) Sending an Encrypted Message – messages sent
through a channel having the Encryp-
tion/Decryption extension enabled and configured
are encrypted using the procedure defined in Table
1.
f) Receiving an Encrypted Message – messages re-
ceived through a channel having the Encryp-
tion/Decryption extension enabled and configured
are decrypted using the procedure defined in Table
1.
The following sections explain technical details for
enabling the extension (Section 2.1), setting the pin
(Section 2.2), configuring (Section 2.2) and disabling
(Section 2.3) the extension, and for sending (Section 2.4)
and receiving (Section 2.5) messages using the new ex-
tension release. The source code of the Java classes
used by the extension is included in Appendix A.
2.1. ENABLING ENCRYPTION/DECRYPTION
EXTENSION
The Encryption/Decryption extension is a channel-
oriented extension. In the new release, no changes were
introduced for enabling a channel-oriented extension.
The process is depicted in Figure 2 and explained as
follows. The External Application requests the member
acting on its behalf to enable the extension
(1:enableExtension). The member prepares the
message to be sent to the Gateway administrator


Figure 2: Enabling Encryption/Decryption Extension


SECTION 2 – ENCRYPTING AND DECRYPTING MESSAGES


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

4

(2:msgToAdminExtension) and sends the message
(3:sendMessage). The Admin member receives the
message (4:receiveMessage) and pushes it to the
application listener of the Gateway Administrator
(5:receiveMessage). The administrator processes
the request (6:requestExtension), which includes
creating a new object for enabling the extension on the
Administrator’s side (7:create), setting the extension
parameters (8:setParameters) – like the channel
identifier for which the extension is enabled, storing the
new enabled extension in the database
(9:storeExtension) and replying to the member
(10:sendMessage). Upon receiving the reply mes-
sage (11:receiveMessage), the member requests
the channel owner to enable the extension
(12:configureExtension). The channel forwards
the request to the object managing all channel-oriented
extensions (13:configureExtension). Finally, the
member replies the result to the external application
(14:recChExtensionReply). In the figure, the four
objects on the left – depicted in green, are located at
the member’s node, while the three objects on the right
– depicted in orange are located at the Gateway admin-
istrator’s node.
2.2. SETTING THE PIN
Configuring the Encryption/Decryption extension implies
distributing the public key of the channel owner to
channel subscribers. The public and private keys issued
by eSignTrust and used by the EncryptionDecryption
extension are stored in smart cards. For accessing a
smart card through the card reader, a PIN – Personal
Identification Number is requested. The PIN is given to
the card holder upon issuance of the smart card. There-
fore, if a member – owner of a channel, is willing to
enable the Encryption/Decryption extension on its
owned channel, it needs to know its PIN to be able to
access the public and private keys stored on the smart
card. A new operation was added to the IMember in-
terface – setPin, for addressing this need. The Mem-
ber class implements this operation.
Figure 3: Setting the PIN


Figure 3 presents the sequence diagram explaining the
implementation of the setPin operation. The external
application requires its member to set the PIN
(1:setPin). The member invokes the function for
setting the PIN provided by the ExtensionsUtil
class (2:setPin). The utility class encrypts the PIN and
the member identifier using the AES method
(3:encryptWithAES), and stores the PIN in a file
(4:storeToFile). The file is stored in the folder indi-
cated by the WorkFolder parameter of the Gateway
configuration file. The file name starts with “PIN-“
followed by the member identification, and ends with
“.xg2g”.
In addition to the Gateway libraries, the user interface
was modified to include the service for setting the PIN.
The interface is shown in Figure 4. The option for re-
questing the service is at the bottom of the Exten-
sion Menu on the left. Once selected, a window re-
questing to introduce the PIN number and to confirm
(Set button) is presented to the user. In the figure,
these features are highlighted by the ellipsis in red.
2.3. CONFIGURING ENCRYPTION/DECRYPTION
EXTENSION
Configuring the Encryption/Decryption extensions re-
quires reading the channel owner’s public key stored in
the smart card and distributing it to channel subscribers.
The process is explained in two parts: i) from the chan-
nel owner’s side, and ii) from the channel subscriber’s
side.
Figure 5 shows the process for configuring the extension
from the owner’s side. ExternalApplication re-
quests the member to configure the extension
(1:configureExtension). Five parameters are
required for configuring the extension. The parameters
and their corresponding values are as follows:
i) extension type – the value must be “channel”,
since Encryption is a channel-oriented extension;
ii) channel identifier – id of the channel for which the
extension is configured;
iii) extension name – the value must be “Message
Encryption”;
iv) parameter data – the value must be null, since the
data used for configuring the extension is the pub-
lic key of the channel owner which is read from the
smart card; and
v) parameter order – the value must be “1”, although
no data is used.

SECTION 2 – ENCRYPTING AND DECRYPTING MESSAGES


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

5

Figure 4: User Interface for Setting the PIN


Figure 5: Configuring Encryption/Decryption – Owner’s Side



SECTION 2 – ENCRYPTING AND DECRYPTING MESSAGES


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

6
Following the configuration request, Member asks Ex-
tensionsUtil to get the public and private keys
from the smart card (2:getKeys). To fulfill the re-
quest, ExtensionsUtil gets the configuration file
where details of the smart card reader are stored, reads
the keys from the smart card, and returns the pair of
keys (3:pair) to the member. Member prepares a
message to the Administrator
(4:msgToAdminConfigure) and invokes the opera-
tion for configuring the extension in the owned channel
object (5:configureExtension). In this particular
case, the message prepared to the Administrator is used
but not really sent since all parameters required to con-
figure the extension are locally available on the smart
card. Following the request from Member, Owned-
Channel requests ChAllExtMgr to configure the
extension (6:configureExtension). ChAl-
lExtMgr invokes its method for getting the object for
the specific extension (7:getExtension). Following
the request, an instance of Encryption is returned, and
ChAllExtMgr invokes the configureExtension
operation in this object (8:configureExtension).
For fulfilling the request, the Encryption object re-
quests its super class (ChAllExtension) to configure
the extension (9:configureExtension). This me-
thod request the object managing the extension para-
meters in the databae – ChExtParamManager, to
store the configuration parameters – public key – in the
database (10:storeParam). Finally, the Encryp-
tion object requests the member to forward its public
key to all subscribers
(11:forwardToAllSubscribers). Member for-
wards this message to all channel subscribers
(12:forwardMessage). And finally, the recConfigu-
reChExtension of the ApplicationListener is invoked.
Figure 6 presents the process for configuring the exten-
sion on the subscriber’s side. Upon receiving the mes-
sage (1:receive), the member identifies the message
was received by a subscribed channel and invokes the
method of this class (2:receive). Since it is a for-
warded message, it is passed to the member for
processing (3:recForwardReply). After identifying
the type of message, the member’s enableSubsEx-
tension method is invoked
(4:enableSubsExtension). The method requests
to the ChExtensionParam class to add the parame-
ter received – the channel owner’s public key (5:add),
and to the ChExtManager to store the parameter in
the database (6:store). After storing the parameter,
the member requests the subscribed channel to enable
the extension (7:enableExtension). The channel
forwards the message to the ChAllExtMgr
(8:enableExtension), which creates an instance of
the Encryption object (9:get) and adds it as an exten-
sion of the channel (10:put).

Figure 6: Configuring Encryption/Decryption – Subscriber’s Side




SECTION 2 – ENCRYPTING AND DECRYPTING MESSAGES


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

7
2.4. DISABLING THE ENCRYTION/DECRYPTION
EXTENSION
Disabling the Encryption/Decryption extension requires
some processing at the channel owner’s side and also at
the subscribers’ side.
Figure 7 shows the process executed at the owner’s side
including the one executed by the Administrator’s side.
The External Application requests its member to disable
the extension (1:disableExtension). The member
identifies it as a channel-oriented extension and invokes
the method for disabling this type of extension
(2:disableChannelExtension). This method
prepares the message to be sent to the Gateway admin-
istrator (3:msgToAdminExtension) and sends the
message (4:send). The Admin member receives the
message (5:receiveMessage) and pushes the mes-
sage to the Admin application (6:receiveMessage).
The administrator processes the request
(7:removeExtension), which includes removing
data about the disabled channel extension in the data-
base (8:removeExtension) and replying to the
member confirming the extension was disabled
(9:sendMessage). Upon receiving the reply message
(10:receiveMessage), and identifying the message
type, the Administrator’s reply is processed
(11:disableChExtension).

Figure 7: Disabling Encryption/Decryption – Owner s’ Side

Figure 8: Disabling Encryption/Decryption – Subscriber’s Side



SECTION 2 – ENCRYPTING AND DECRYPTING MESSAGES


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

8
The request for disabling the extension is forwarded to
the channel owned (12:disableExtension), who
passes the request to the ChAllExtMgr
(13:disableExtension). ChAllExtMgr requests
the ChannelExtensionManager to remove the
extension (14:removeExtension). Removing the
extension comprises removing the channel extension-
related information from the database and from the
array of channel extensions. Finally, a message is sent
to all channel subscribers
(15:forwardToAllSubscribers) requesting to
disable the extension.
Figure 8 presents the process for disabling the extension
on the subscriber’s side. Upon receiving the message
(1:receiveMessage), the member identifies the
message was received by a subscribed channel and in-
vokes the method of this class (2:receiveMessage).
Since it is a forwarded message, it is passed to the
member for processing (3:recForwardReply). After
identifying the type of message, the member’s method
for disabling the extension is invoked
(4:disableSubsExtension). The later method
comprises requesting the ChannelExtensionMa-
nager to remove the channel extension from the da-
tabase (5:remove), and requesting the subscribed
channel to disable the extension
(6:disableExtension). The subscribed channel
forwards the message to the ChAllExtMgr
(7:disableExtension), which deletes the Encryp-
tion/Decryption extension from the array of extensions
enabled for the channel.
2.5. SENDING AN ENCRYPTED MESSAGE
The process for sending a message is the same as in the
first release. The difference is only in the process-
Message method of the Encryption class.
Figure 9 presents the sequence diagram for sending an
encrypted message. The channel – may be owned or
subscribed, requests the ChAllExtMgr to process the
outgoing messages
(1:processOutgoingMessage). This method looks
for the corresponding extension – Encryption, and
requests the object to process the message
(2:processMessage). First, the extension gets the
encryption key (key); if the sender is the channel own-
er, by getting its private key (3:getPrivateKey);

Figure 9: Sending an Encrypted Message



SECTION 2 – ENCRYPTING AND DECRYPTING MESSAGES


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

9
otherwise, by getting the public key of the channel
owner (4:getPublicKey). Second, it requests the
ExtensionsUtil class to encrypt the message pro-
viding the message content (content) and the encryp-
tion key (key). For encrypting the message, Exten-
sionsUtil executes the following: i) generates an
AES session key (6:createAESKey) – generated-
Key; ii) encrypts, using the AES algorithm, the message
content (content) using generatedKey
(7:encryptAES); iii) encrypts, following the RSA me-
thod, generatedKey using the encryption key – key
(8:encryptRSA); and builds the reply by returning
the encrypted generated key – the result of 8, and the
encrypted content – the result of 7. Finally, the en-
crypted message is returned to the channel
(10,11,12:encryptedMsg).
2.6. RECEIVING AN ENCRYPTED MESSAGE
The process for receiving a message is the same as in
the previous release. The difference is only in the pro-
cessIncomingMessage method of the Encryp-
tion class.
Figure 10 presents the sequence diagram for receiving
an encrypted message. The channel – may be owned or
subscribed, requests the ChAllExtMgr to process the
incoming messages
(1:processIncomingMessage). This method looks
for the corresponding extension – Encryption, and
requests the object to process the message
(2:processMessage). First, the extension gets the
encryption key (key); if the sender is the channel own-
er, by getting its private key (3:getPrivateKey);
otherwise, by getting the public key of the channel
owner (4:getPublicKey). Second, it requests the
ExtensionsUtil class to decrypt the message pro-
viding the encrypted message (encMsg) and the en-
cryption key (key). For decrypting the message, Ex-
tensionsUtil executes the following: i) gets the
encrypted generated key (encKey) from the encrypted
message (6:getEncryptedKey); ii) gets the en-
crypted content (encContent) from the encrypted
message (7:getEncryptedContent); iii) decrypts,
following the RSA method, the encrypted generated key
(encKey – obtained in 6) using the encryption key –
key (8:decryptRSA); and iv) decrypts, following
the AES method, the encrypted content – the result of 7,
using the decrypted generated key – the result of 8
(9:decryptAES). Finally, the decrypted message is
returned to the channel
(10,11,12:decryptedMsg).

Figure 10: Receiving an Encrypted Message


SECTION 3 – NEW APIS FOR LEGACY SYSTEMS


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

10
3. NEW APIS FOR LEGACY SYSTEMS
One of the revised objectives of the Macao Data Ex-
change Gateway Project was to provide APIs for invok-
ing the Gateway services by non-Java applications. For
specifying the required APIs, programming languages
and tools used by legacy applications deployed in Gov-
ernment Agencies were retrieved from the survey car-
ried out as part of e-Macao Phase I [10]. The results
shown Delphi, Visual Basic, Visual FoxPro and FoxPro,
Access and COBOL are the languages and tools mostly
used. Following the results, since Delphi was largely the
most used language, APIs for Delphi applications was
developed. In addition, two executable files that can be
invoked from the command line are provided for send-
ing and receiving messages. These files aim at providing
a general solution for sending and receiving messages by
any legacy application able to access the command line,
regardless of the programming language used. The fol-
lowing three sections present the results about the pro-
gramming languages and development environments
mostly used by Macao SAR Government Agencies (Sec-
tion 3.1), the set of APIs developed for Delphi applica-
tions (Section 3.2), and the executable files and Java
classes for sending and receiving messages through the
command line (Section 3.3).
3.1. PROGRAMMING LANGUAGES USED BY
MACAO GOVERNMENT AGENCIES
Based on the information gathered during e-Macao
Phase I – Agency Survey [10], a detailed list of the appli-
cations used by Macao Government Agencies is pre-
sented in Appendix C.1. The list specifies the agency
code, the application name, and the programming lan-
guage or tool used for application development. Based
on the detailed list, a summarized list was prepared
indicating the total number of applications using each of
the programming languages and/or tools. The list is
presented in Appendix C.2. Finally, the latter list was
consolidated and the result is presented in Table 2.

Table 2: Programming Languages and Tools Mostly Used by Government Applications
PROGRAMMING LANGUAGE / TOOL
TOTAL
Delphi 71
Visual Basic 26
Visual FoxPro and FoxPro 23
Access 21
COBOL 21
AS/400 RPG 11
Borland C++ Builder 10
PowerBuilder 9
ASP 8
AS/400 Application development tools 4
Oracle tools 3
C 1
Clipper 1
DBASE 1
ESRI ArcIMS 1
Fortran 1

SECTION 3 – NEW APIS FOR LEGACY SYSTEMS


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

11
The consolidation presented in the above table was
done based on the following criteria: i) the total number
of applications was calculated based on the program-
ming language regardless of the specific version – for
instance, Access, Access 2000/97 and MS Access are
summarized under Access; ii) the first language was
considered in those cases where more than one lan-
guage was enumerated - for instance, an application
deployed in DSSOPT, “Professionals/Companies Regis-
tration System”, specifies Delphi, Delphi 400 and COBOL
as programming language; this application was consoli-
dated under the Delphi category; and iii) FoxPro was
consolidated with Visual FoxPro, and ASP with ASP.Net.
The results shows 71 applications were developed in
Delphi; 26 in Visual Basic; 23 in Visual FoxPro and Fox-
Pro; 21 in Access and in COBOL; 11 in AS/400 RPG; 10 in
Borland C++ Builder; 9 in PowerBuilder; 8 in ASP; 4 in
AS/400 Application Development tools; 3 in Oracle
tools; and 1 in C, Clipper, DBASE, ESRI ArcIMS and For-
tran. Based on these results, APIs for invoking the Gate-
way services by Delphi applications were developed,
and are explained in the following section.
3.2. APIS FOR DELPHI
As shown in the previous section, Delphi is the pro-
gramming language largely used by Government appli-
cations. Therefore, a set of APIs enabling Delphi applica-
tions to use the Messaging Gateway services shall be
provided. Different approaches can be followed to ena-
ble communications between Delphi and Java applica-
tions – like through the use of intermediate files, the use
of sockets or web services. Since, a more direct commu-
nication is required between Delphi applications and the
Gateway services; the use of Java Native Interface (JNI)
[14] was adopted.
JNI allows bi-directional invocations between Java and
native languages, like Delphi. JNI enables a native code
to create, inspect, and update java objects, as well as
call methods within Java classes. In addition, Java excep-
tions can be captured and processed in the native code
and in some cases, exceptions can be generated back to
the Java runtime environment. The behavior provided
by JNI precisely satisfies the requirements for enabling
Delphi applications invoke the Messaging services writ-
ten in Java. In summary, the proposed approach in-
cludes: the Gateway services in Java shall invoke call-
back methods in external applications written in Delphi,
and the different Gateway services shall be exposed as
Delphi services.
The Delphi API comprises two components:
1) XG2GWrapper class – It is available in the
XWrapper unit and exposes the operations in-
cluded in the Gateway IMember and IVisitor inter-
faces to Delphi applications. Therefore, Delphi ap-
plications can invoke the following functions:
a) function registerMemb-
er(name:string; description-
file:string):JObject –for registering a
new member given the member’s name (name pa-
rameter) and the name of the file (descrip-
tionfile parameter) describing the required
attributes for registering a member. The file is
stored in the Gateway working directory. If the op-
eration is executed successfully, a pointer to the
newly registered member is returned.
b) function getMemb-
er(memberId:string):JObject – for res-
tarting a Member given the member’s identifier
(memberId). Like registerMember, it returns a
pointer to the restarted member, if the operation is
executed succefully.
c) procedure sendMes-
sage(member:JObject;chId:string;msg
:string) – for sending a message. Three para-
meters are required: i) the member object (mem-
ber), the channel identifier through which the
message will be sent (chId); and the message it-
self (msg).
d) procedure receiveMes-
sage(member:JObject;msg:string) – for
receiving a message. The procedure requires two
parameters – the member object (member), and
the message to be received (msg). This method
was defined in the IMember interface to provide
the pull behavior for receiving messages from a
member – regardless of the channel. However, the
current implementation of the member follows a
push mechanism. Therefore, it is unlikey that any
message will be received by invoking this opera-
tion, unless the member’s behavior is modified.
Delphi applications will receive messages which are
pushed by the Gateway through the DelphiImpl
operation receiveMessage (msg:
string). This procedure was implemented only
to conform to all operations offered by the IM-
ember interface. See also n) getMessage be-
low.
e) procedure createChan-
nel(member:JObject;chName:string –
for creating a channel. Two parameters are re-
quired: i) the member object (member) and ii) the
channel name (chName).
f) procedure destroyChan-
nel(member:JObject;chId:string) – for
destroying a channel. Two parameters are re-
quired: i) the member object (member) and ii) the
channel identifier (chId).
g) procedure subscribeChan-
nel(member:JObject;chId:string;oId:

SECTION 3 – NEW APIS FOR LEGACY SYSTEMS


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

12
string) – for subscribing the member acting on
behalf of the Delphi application to a channel. Three
parameters are required: i) the member object
(member), ii) the channel identifier to which the
subscription is requested (chId), and iii) the chan-
nel owner identifier (oId).
h) procedure unsubscribeChan-
nel(member:JObject;chId:string;oId:
string) – for unsubscribing the member acting
on behalf of the Delphi application from a channel.
Three parameters are required: i) the member ob-
ject (member), ii) the channel identifier to which
the unsubscription is requested (chId), and iii) the
channel owner identifier (oId).
i) procedure unregisterMember(member:
JObject) – for unregistering the member acting
on behalf of the Delphi application. The required
parameter is the member object (member).
j) procedure enableExten-
sion(member:JObject;extType:string;
chId:string; extName:string) – for
enabling an extension. Four parameters are re-
quired: i) the member object (member), ii) the type
of extension to be enabled (extType) – possible
values are: Channel if it is a channel-oriented ex-
tension, and Member if it is a member-oriented ex-
tension; iii) channel identifier to which the channel-
oriented extension will be enabled (chId) – this
parameter should be null if a member-oriented ex-
tension is enabled; and iv) the extension name
(extName) – possible values are: Message
Logging (channel-oriented); Message Syntax
(channel-oriented); Message Transforma-
tion (channel-oriented); Message Semantics
(channel-oriented); Message Mediation
(channel-oriented); Message Encryption
(channel-oriented); and Message Discovery
(member-oriented).
k) procedure disableExten-
sion(member:JObject;extType:string;
chId:string;
extName:string) – for disabling an extension.
The four required parameters are the same as
those required for enabling the extension.
l) procedure configureExten-
sion(member:JObject;extType:string;
chId:string
;extName:string;data:string;order:I
nteger) – for configuring an extension. Six para-
meters are required. The first four are the same as
those required for enabling an extension. The last
two comprises: i) the name of the resource in the
Gateway central repository to be used as an exten-
sion parameter (data); and ii) the parameter order
(order). For example, Message Syntax requires to
be configured with one parameter – the name of
the XML Schema used for validating messages.
Suppose, the XML Schema is a Gateway resource
called XML-Food-License, then the data para-
meter should be precisely that name (XML-Food-
License), and the order should be 1.
m) procedure forwardMes-
sage(member:JObject;chId:string;msg
:string) – for forwarding a message through a
channel. Three parameters are required: the mem-
ber object (member); ii) the channel identifier
through which the message will be sent (chId);
and iii) the message to be forwarded (msg).
n) getMessage(member:JObject;
chId:string):string – for pulling a re-
ceived message from a particular channel. Two pa-
rameters are required: i) the member object (mem-
ber); and ii) the channel identifier through which
the message was received (chId). The operation
assumes messages are received by the member
and are stored in the local database. This operation
pulls a message that was received through a given
channel, and stored by the member in the local da-
tabase.
o) procedure setPin(member:JObject;
pin:string) – for setting the member’s PIN to
be used for reading the certificates stored in smart
cards issued by Macao Post. This operation is re-
quired if Message Encryption is used. It should be
executed after enabling the extension to a channel,
and before its configuration. Two parameters are
required: i) the member object (member) and ii)
the PIN to be used (pin).
2) DelphiApplicationListener class – It is
an implementation of the Gateway Applica-
tionListener interface. It is used internally as a
parameter to register and to restart a member. The
class does not provide implementation for the dif-
ferent methods. Instead, it declares them as native
and the implementation should be provided in an
external library (dll file). The DelphiImpl library
defines the skeleton of such methods. In the cur-
rent release, a default implementation is provided
for these methods, comprising the print out of re-
ceived messages to the console. A customized be-
havior of these methods can be provided by im-
plementing the following operations: receive-
Message(msg: string), recSendMessa-
geReply(msg: string), recRegister-
Reply(msg: string), recUnRegister-
Reply(msg: string), recCreateChanne-
lReply(msg: string), recDestroyChan-
nelReply(msg: string), recSubscribe-
ChannelReply(msg: string), recUnsub-
scribeChannelReply(msg: string),
recChExtensionReply(msg: string),

SECTION 3 – NEW APIS FOR LEGACY SYSTEMS


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

13
recReceiveMessageReply(msg:
string), recManageReply(msg:
string), recForwardReply(msg:
string), recGetMemberReply(msg:
string), recConfigureChExtensionRep-
ly(msg: string) and recMemberUnsub-
scribe(msg: string). These methods cor-
respond to the ones defined in the Applica-
tionListener interface of the Gateway,
3.3. APIS FOR SENDING AND RECEIVING
MESSAGES FROM THE COMMAND LINE
The previous section described a set of APIs for invoking
the Gateway services from applications developed in
Delphi programming language. This set of APIs can be
taken as example, for developing APIs for any given
language. However, aiming at providing a more general
solution, two executable files are provided for enabling
applications, written in any programming language or
tool to invoke the command line, to send and receive
messages using the Gateway.
The two executable files are: Send.bat – enabling an
application to send a message; and Receive.bat –
allowing an application to receive a message. Both files
comprise the enumeration of all Java libraries used by
the Gateway and the invocation of the main method of
the corresponding Java classes – Send and Receive,
respectively. The main methods of these classes are
explained in the following sections; while the procedure
for invoking the executable files are presented below.
For sending a message an application needs to invoke
the “Send” command from the command line. At least,
three parameters are required for invoking this com-
mand:
1) identifier of the member who is sending the mes-
sage;
2) identifier of the channel used for sending the mes-
sage;
3) name of the file containing the message content to
be sent.
The rest of the parameters correspond to the names of
the files which should be sent as message attachments.
These file names must include the complete path to the
files.
Files containing the message contents should be placed
in a local sub-folder labeled as: <<memberIdentifi-
er>> + <<File.separator>> + “send. The two
variables indicated within angle brackets (<< >>) are
replaced by the first parameter – the member identifier;
and by the system-dependent default name-separator
character – for instance, “\”; respectively. This sub-
folder should be located in the folder indicated by the
WorkFolder parameter of the Gateway configuration
file.
For example, an application running on a Windows envi-
ronment will have the “\” as the name separator charac-
ter; the value of the WorkFolder parameter in the
Gateway configuration files is “D:\Gateway\tmp”, if
the following command is invoked:
Send 100010 500037
F2009022416553001.xml
D\attach\A2009022416553001.pdf
it means that the member 100010 is requesting to
send a message, through the channel 500037; the
message content is stored in the file
“D:\Gateway\tmp\100010\send\F200902241
6553001.xml, and the file
“D:\attach\A2009022416553001.pdf
should be attached.
To receive a message, an application needs to invoke
the “Receive” command from the command line. One
parameter is required for invoking the command: the
identifier of the member who is receiving the message.
When the command is executed, the first message re-
ceived is stored in a file in the local subfolder labeled as
<<memberIdentifier>> +
<<File.separator>> + “receive. The variables
indicated within angle brackets (<< >>) are replaced as
explained above for the Send command. The name of
the file storing the received message is <<memberI-
dentifier>> + <<date>> + “.xml”.
For example, following the same assumptions described
for illustrating the Send command, if the following
command is executed:
Receive 100010
It means that the first message received for the member
100010, regardless of the channel, is saved in the file:
D:\Gateway\tmp\100010\receive\10001
0022520090142551.xml
assuming the request for receiving the message was
executed on 25 February 2009 at 01:42:55 pm.

SECTION 3 – NEW APIS FOR LEGACY SYSTEMS


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

14
Figure 11: Send Class - Main Method


3.3.1. SEND CLASS – MAIN METHOD
The behavior of the Send class main method is de-
picted in Figure 11 and explained below.
The main method requires the same parameters as
those used for invoking the Send command. The me-
thod validates that the number of parameters is correct
(1:validatesParametersNumber) and that the
filename indicated as the third parameter exists in the
corresponding folder (2:verifiesFileExist).
These two functions are not implemented as separate
methods, but as part of the method logic. After validat-
ing the parameters, a new instance of LegacyAppli-
cationListener object is created (3:new) and as a
result, the listener object is returned
(4:listener). A new instance of the Anon member is
instantiated (5:new), to whom the request for getting
the member is sent (6:getMember). The parameters
for getting the member include the member identifier –
the first argument of the main method (args[0]), and
the application listener recently created (listener).
The Anon Member instantiates the Member object
(7:new) and the object is returned as result
(8:Member). The message to be sent is read from the
file (9:readsFile) - this function is implemented
within the method logic. After reading the message, the
member is requested to format it
(10:formatMessage), returning the message to be
sent (11:msg); and to send it (12:sendMessage).
The method source code is included in Appendix D.1.
3.3.2. RECEIVE CLASS – MAIN METHOD
The main method of the Receive class requires the
same parameters as those used for invoking the Re-
ceive command. Its behavior is depicted in Figure 12,
and its source code is included in Appendix D.2.
The method validates that the number of parameters is
correct (1:validatesParametersNumber). This
function is not implemented as a separate method, but
as part of the method logic. After validating the parame-
ter, a new instance of LegacyApplicationLis-
tener object is created (2:new) and as a result, the
listener object is returned (3:listener). A new
instance of the Anon member is instantiated (4:new),
to whom the request for getting the member is sent
(5:getMember). The parameters for getting the mem-
ber include the member identifier – the first argument
of the main method (args[0]), and the application
listener recently created (listener). The Anon
Member instantiates the Member object (6:new) and
the object is returned as result (7:Member). Finally, a
thread is started for 10 seconds. While the member is
active, the first message received triggers the invocation
of the method for receiving a message in the Application
Listener (9:receiveMessage), and the listener
writes the message to a fie (10:writesFile).

SECTION 3 – NEW APIS FOR LEGACY SYSTEMS


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

15
Figure 12: Receive Class - Main Method




SECTION 4 – DEPLOYMENT COMPONENTS AND PROCEDURE


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

16
4. DEPLOYMENT COMPONENTS AND
PROCEDURE
The following two sections explain the deployment
components of the new release, as well as new required
steps for the deployment procedure.
4.1. DEPLOYMENT COMPONENTS
The current release of the Extensible Message Gateway
delivers the software components structured in five
main folders, as presented in Figure 13. The content of
each of these folders is described below:
1) xg2g – includes four subfolders: i) xg2g-Admin -
contains libraries implementing the Gateway Ad-
ministrator member, ii) xg2g-Communication
services – includes the Gateway APIs providing
core and extended messaging services, iii) xg2g-
Configuration file – contains the file for
configuring the Gateway, and iv) xg2g-Web
services – includes the two web services used
by the Gateway for implementing the communica-
tion layer and the semantic extensions.
2) xg2g-Repository – includes the web applica-
tion supporting the Gateway Administrator func-
tion and managing the Gateway central repository.
3) xg2g-Services – includes the software applica-
tion providing the user interface for invoking the
Gateway services.
4) xg2g-Delphi – includes the APIs for invoking
the Gateway services from applications developed
in Delphi programming language.
5) xg2g-OtherLegacy – includes the library and
executable files enabling sending and receiving
messages from the command line.
The first three sub-folders were included in the previous
release and their content is explained in details in [11].
An explanation of the modified components and the
reasons for their modification follows. The last two sub-
folders are included in this release and their content is
explained below.

Figure 13: Extensible Message Gateway – Deployment Folders


SECTION 4 – DEPLOYMENT COMPONENTS AND PROCEDURE


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

17
The components highlighted in red in Figure 13 are the
modified components in the new release. The justifica-
tion for their modifications follows.
o xg2g-Admin – i) removing the functions for ge-
nerating the public and private keys required by the
previous release of the Encryption/Decryption ex-
tension;
o xg2g-Communication services – i) replac-
ing the Encryption/Decryption extension with the
new release; and ii) adding the new service for set-
ting the PIN – part of the Extended Services.
o xg2g-Configuration file – a new parame-
ter – CardReaderConfigFile, was added for
specifying the location of the configuration file for
the card reader used by the new extension release.
o xg2g-Services – adding the new service for
setting the PIN.
The xg2g-Delphi folder includes two subfolders: i)
bin – containing the binary code; and ii) src – contain-
ing the source files. The content of these folders follows.
The bin folder contains:
o libs  a folder containing all the libraries used
by the Gateway;
o logs – a folder for storing the log files;
o config – contains the config.properties file for
specifying the path to the Java Virtual Machine li-
brary and the name of the library to be loaded by
DelphiApplicationListener;
o DelphiImpl.dll – is the default implementa-
tion of the Gateway Application Listener.
The src folder contains:
o DelphiApplicationListener.java – is
the implementation of the Gateway Application Lis-
teener that will be used by Delphi applications;
o DelphiImpl.dpr – is the default implementa-
tion of DelphiImpl library;
o JNI.pas  is a Delphi implementation of JNI;
o JNI.dcu – is required by JNI.pas;
o JNI_MD.INC – is required by JNI.pas;
o JNIUtils.pas – is a collection of utility methods
for using JNI.pas;
o JNIUtils.dcu – is required by JNI-
Utils.pas;
o XWrapper.pas – is responsible for invoking the
Gateway methods;
o XWrapper.dcu – is required by XWrap-
per.pas.
Similar structure as the one provided for xg2g-
Delphi is followed for xg2g-OtherLegacy. The
content of the two subfolders is as follows.
The bin folder contains:
o lib  a folder containing all the libraries used by
the Gateway;
o logs – a folder for storing the log files;
o Send.bat – the executable file for sending mes-
sages;
o Receive.bat – the executable file for receiving
messages.
The src folder contains the source code of the three
Java classes – Send, Receive and LegacyAppli-
cationListener.
4.2. DEPLOYMENT PROCEDURE
The deployment procedure for the application imple-
menting the Gateway Administrator member (xg2g-
Admin), the Gateway APIs (xg2g-Communication
Services), the web services responsible for exchang-
ing messages and providing the semantic extensions
(xg2g-Web Services), the Administrator repository
(xg2g-Repository), and the User Interface (xg2g-
User Interface) were not changed with respect to
the previous release and are explained in details in the
Extensible Message Gateway - User Manual [11], Chap-
ter 4.
Compared with the previous release, only one change
was introduced to the procedure for deploying the Ga-
teway configuration file (xg2g-Configuration
File). For the previous release, a detailed description
for the procedure was provided in [11]. In the new re-
lease, there is one more parameter in the file requiring
personalization – CardReaderConfigFile. If the
Encryption/Decryption extension will be used in a node,
the configuration file of the smart card reader shall be
stored in a local folder. The value of the CardReader-
ConfigFile parameter shall be the full path plus the
name of this file. For example, the default value of the
parameter is C:\\config\\pkcs11.cfg. It means
that the folder config exists on drive C: and the file
pkcs11.cfg placed in that folder is the configuration

SECTION 4 – DEPLOYMENT COMPONENTS AND PROCEDURE


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

18
file of the smart card reader to be used by the Encryp-
tion/Decryption extension.
The deployment of the Dephi APIs is as follows:
1) Copy the bin folder to the desired library;
2) Modify the DelphiImpl library by providing suit-
able implementations for the different methods;
3) Generate the library (dll file);
4) Edit the config.properties file of the con-
fig folder. Two parameters shall be personalized:
a. jvm.path - specifying the path to the
jvm.dll file of the JRE;
b. library.name - defining the name of
the library used by DelphiApplica-
tionListener;
5) Add a reference to the unit XWrapper.pas in
your Delphi project.
In order to successfully run your code, the generated
library, the config and libs folders should be in the
same folder as your project (or executable).
The deployment of the executable files for sending and
receiving messages from the command line requires:
1) copy the content of the bin folder to the folder
in which the executable files will be executed;
2) For each member using these files:
a. Create a folder labeled with the member
identifier within the folder used as the
working folder of the Gateway – indi-
cated by the WorkFolder parameter of
the configuration file.
b. Create the sub-folders send and re-
ceive within the member’s folder.
Figure 14: Folder Structure for Receiving and Sending
Messages through the Command Line


For example, assuming the working folder of the Gate-
way is D:\Gateway\tmp, and three members –
100007, 100014, and 100062; are registered in the
node and are willing to use the executable files, Figure
14 shows the folders that are required, according to the
above procedure. In the case of the folders for receiving
files, if the folders do not exist, they are created at run-
time.

SECTION 5 – CONCLUSIONS


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

19
5. CONCLUSIONS
This report presents technical details of the new release
of the Extensible Messaging Gateway implementing a
new version of the Message Encryption extension, as
well as the new sets of APIs provided for facilitating the
use of the Gateway by legacy applications. The software
developed was produced by the UNU-IIST Center for
Electronic Government during 2008 for the Government
of Macao SAR, under the Macao Data Exchange Gate-
way Project, part of the e-Macao Program.
The new release of the Gateway provides a new version
of the Encryption/Decryption extension which uses the
certificates issued by Macao Post Office. The certificates
are provided in a smart card, and a PIN is required for
accessing them. The new extension defines a new ser-
vice (setting PIN) enabling the member to store this
information. Replacing the Encryption/Decryption ex-
tension involved modifying the following Gateway com-
ponents: i) the Administrator application for eliminating
the generation of the keys used by the previous release
of the extension, and adding the reply to the message
requesting to set the member’s PIN; ii) the Gateway APIs
for including the new service (set PIN); iii) the user inter-
face for invoking the service for setting the PIN; and iv)
the configuration file for adding a parameter indicating
the location and name of the configuration file for the
smart card reader.
A new set of APIs and executable files are provided
enabling legacy applications to invoke the Gateway ser-
vices. Based on the analysis of the programming lan-
guages mostly used by applications deployed in Macao
Government agencies, a set of Delphi-APIS and two ex-
ecutable files are provided. The Delphi-APIs enable ap-
plication written in Delphi to invoke the Gateway servic-
es. The two executable files enable any application writ-
ten in any language able to invoke the command line to
send and receive messages through the Gateway. Other
services offered by the Gateway, like those configuring
the communication structures – register and unregister
member, create and destroy channel, subscribe and
unsubscribe member to/from a channel, enable, confi-
gure and disable an extension; can be requested
through the user interface.
This report presented the following sequence of topics.
An introduction to the project scope, its aim and objec-
tives were presented in Section 1. Section 2 introduced
technical details for the new release of the Encryp-
tion/Decryption extension – the provided services and
their implementation. Section 3 presented the study
about the programming languages mostly used by Ma-
cao government applications, new APIs developed for
requesting the services by Delphi applications – the
programming language mostly used; and executable
files for sending and receiving messages from the com-
mand line. These files can be invoked by any legacy ap-
plication, able to access the command line, regardless of
the programming language in which it was developed.
Section 4 explains the deployment components, the
modified components compared with the previous re-
lease, and the modifications to the deployment proce-
dure. Finally, the following appendices present some of
the technical artifacts used by the new Gateway release
and set of APIs.

REFERENCES


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

20
REFERENCES
[1] Elsa Estevez, Vincent Douwe and Tomasz Janowski,
Extensible Messaging Gateway – Quality Assurance
Report, UNU-IIST-EGOV, September 2008.
[2] Elsa Estevez, Vincent Douwe and Tomasz Janowski,
e-Appointment Service – Development Report, Ma-
cao Data Exchange Gateway Project, UNU-IIST-
EGOV, February 2009.
[3] Elsa Estevez, Vincent Douwe and Tomasz Janowski,
e-Appointment Service – User Manual, Macao Data
Exchange Gateway Project, UNU-IIST-EGOV, Febru-
ary 2009.
[4] Elsa Estevez, Vincent Douwe and Tomasz Janowski,
Queuing Service – Development Report, Macao Da-
ta Exchange Gateway Project, UNU-IIST-EGOV, Feb-
ruary 2009.
[5] Elsa Estevez, Vincent Douwe and Tomasz Janowski,
Queuing Service – User Manual, Macao Data Ex-
change Gateway Project, UNU-IIST-EGOV, February
2009.
[6] R.L. Rivest, A. Shamir, and L. Adleman, A Method
for Obtaining Digital Signatures and Public-Key
Cryptosystems, available at February 2009.
[7] National Institute of Standards and Technology
(NIST), Announcing the Advanced Encryption Stan-
dard (AES), November 2001, available at
http://csrc.nist.gov/publications/fips/fips197/fips-
197.pdf, visited on 26 February 2009.
[8] eSignTrust, About eSignTrust, available at
http://www.esigntrust.com/en/m1.php?pageID=1,
last visited February 16,2009.
[9] Cisco, Advanced Encryption Standard (AES), availa-
ble at http://www.cisco.com/en/US/docs/
ios/12_2t/12 _2t13/feature/guide/ft_aes.html, vi-
sited on February 16, 2009.
[10] Tomasz Janowski, Adegboyega Ojo and Elsa Estevez
(Eds), The State of Electronic Government in Macao,
Volume 2 Agencies, e-Macao Project, available at
www.emacao.gov.mo, Deliverables - Survey, report
2, visited on 25 January 2009.
[11] Elsa Estevez, Vincent Douwe and Tomasz Janowski,
Extensible Message Gateway, User Manual, Soft-
ware Infrastructure for Electronic Government
Project, e-Macao Program, 2007.
[12] SUN MicroSystems, Java Cryptography Architecture
reference guide, available at
http://java.sun.com/javase/6/docs/technotes/guid
es/security/crypto/CryptoSpec.html, visited on
February 16, 2009.
[13] SUN MicroSystems, Java PKCS#11 Reference Guide,
available at
http://java.sun.com/javase/6/docs/technotes/guid
es/security/crypto/CryptoSpec.html, visited on
February 16, 2009
[14] Sheng Liang, The Java Native Interface Program-
mer’s Guide and Specification, Addison-Wesley,
June 1999, also available at
http://java.sun.com/docs/books/jni/
[15] Matthew Mead, Using the Java Native Interface
with Delphi, available at
http://www.pacifier.com/~mmead/jni/delphi, vi-
sited on February 16, 2009.
[16] Keith Wood, Go Native, available at
http://www.pacifier.com/~mmead/jni/delphi/infor
mant/ di200309kw.htm, visited on Febraury 16,
2009.

APPENDICES


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

21
APPENDICES
A. JAVA CLASSES USED BY THE ENCRYPTION EXTENSION
A.1. ENCRYPTION CLASS
Java Class 1: Encryption
package edu.unu.iist.emacao.xg2g.extensions;

import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Collection;
import java.util.Map;

import org.apache.commons.codec.binary.Hex;
import org.apache.log4j.Logger;
import org.apache.xmlbeans.XmlObject;

import edu.unu.iist.emacao.gateway.xmlUtil.ExtAction;
import edu.unu.iist.emacao.gateway.xmlUtil.ForwardMessage;
import edu.unu.iist.emacao.gateway.xmlUtil.UserMessage;
import edu.unu.iist.emacao.xg2g.core.Member;
import edu.unu.iist.emacao.xg2g.core.Message;
import edu.unu.iist.emacao.xg2g.database.ChExtensionParam;
import edu.unu.iist.emacao.xg2g.database.ChannelExtension;
import edu.unu.iist.emacao.xg2g.database.ChannelExtensionManager;
import edu.unu.iist.emacao.xg2g.util.ExtensionsUtil;

public class Encryption extends ChAllExtension {

private static final Logger logger = Logger.getLogger(Encryption.class);
private ExtensionsUtil util;
private KeyPair pair;

public Encryption(ChannelExtension extension, Member member) {
super(extension, ChAllExtensionFactory.encryption, member);
util = new ExtensionsUtil();
}

@Override
public String processIncomingMessage(String message) throws Exception {
// This method is used for processing incoming messages.

APPENDICES


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

22
// This consists typically to getting the key and decrypting the message
String msgToReturn = null;
try {
// Saves the user message to a file
Message msgAux = new Message(message);
UserMessage usrMsg = UserMessage.Factory.parse(msgAux
.getUserDefinedMessage());
String pp = XmlObject.Factory.parse(usrMsg.getContent().toString())
.xmlText();
logger.info("Encrypting the message : " + pp);
// gets the schema
Key val = null;
if (isOwner)
val = getPrivateKey();
else {
String encoded = getEncodedPublicKey();
if (encoded == null)
throw new Exception(
"The encryption extension is not properly confi-
gured");
val = getPublicKey(Hex.decodeHex(encoded.toCharArray()));
}
String text = util.decrypt(pp, val);
usrMsg.setContent(XmlObject.Factory.parse(text));
msgToReturn = msgAux.setUserDefinedMessage(usrMsg.toString());

} catch (Exception e) {
logger.error("Exception ", e);
}
return msgToReturn;
}

private String getEncodedPublicKey() throws Exception {

if (isOwner) {
return new String(Hex.encodeHex(getPublicKey().getEncoded()));
} else {
ChannelExtensionManager chMgr = new ChannelExtensionManager();
Collection<ChExtensionParam> listParam = chMgr
.getParameter(extension);
if (listParam == null || listParam.size() == 0)
throw new Exception("Unable to find the key for encryption");
for (ChExtensionParam ts : listParam) {
return ts.getChExtParam();
}
}

APPENDICES


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

23
return null;

}

@Override
public String processMessage(String message) throws Exception {
// This method is used for processing outgoing messages
// This typically consists to getting the key and encrypting the message
String msgToReturn = null;
try {
// Saves the user message to a file
Message msgAux = new Message(message);
UserMessage usrMsg = UserMessage.Factory.parse(msgAux
.getUserDefinedMessage());
String pp = XmlObject.Factory.parse(usrMsg.getContent().toString())
.xmlText();
logger.info("Encrypting the message : " + pp);
Key val = null;
if (isOwner)
val = getPrivateKey();
else {
String encoded = getEncodedPublicKey();
if (encoded == null)
throw new Exception(
"The encryption extension is not properly confi-
gured");
val = getPublicKey(Hex.decodeHex(encoded.toCharArray()));
}
String text = util.encrypt(pp, val);
usrMsg.setContent(XmlObject.Factory.parse(text));
msgToReturn = msgAux.setUserDefinedMessage(usrMsg.toString());

} catch (Exception e) {
logger.error("Exception ", e);
}
return msgToReturn;
}

@Override
public void configureExtension(Map<Integer, String> msg) throws Exception {
super.configureExtension(msg);
String data = msg.get(1);
member.forwardToAllSubscribers(ExtAction.ENABLE, extension.getChannel()
.getChannelId(), name, data);
}


APPENDICES


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

24
private PrivateKey getPrivateKey() throws Exception {
if (isOwner)
return getPair().getPrivate();
throw new Exception("Member is not the owner of the channel");
}

private PublicKey getPublicKey() throws Exception {
if (isOwner) {
return getPair().getPublic();
}
throw new Exception("Member is not the owner of the channel");

}

private PublicKey getPublicKey(byte[] encoded) throws Exception {
KeyFactory kfactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keys = new X509EncodedKeySpec(encoded);
PublicKey keyp = kfactory.generatePublic(keys);
return keyp;
}

@Override
public void newSubscriber(String mId) throws Exception {
// String data = getChExtParam(PRIVATE_KEY).getChExtParam();
String data = getEncodedPublicKey();
ForwardMessage fm = ForwardMessage.Factory.newInstance();
fm.setAction(ExtAction.ENABLE);
fm.setChannelId(extension.getChannel().getChannelId());
fm.setData(data);
fm.setMemberId(mId);
fm.setExtName(name);
member.forwardMessage(mId, fm.toString());

}

private KeyPair getPair() throws Exception {
if (pair == null)
pair = new ExtensionsUtil().getKeys(member.getMemberId());
return pair;
}
}


APPENDICES


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

25
A.2. EXTENSIONSUTIL CLASS
Java Class 2: ExtensionsUtil
package edu.unu.iist.emacao.xg2g.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.util.Enumeration;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import sun.security.pkcs11.SunPKCS11;

public class ExtensionsUtil {

public String Transforme(String doc, String xlst) {
return null;

}

public String validate(String doc, String schema) {
return null;
}

private MessageDigest createDigest() throws Exception {
return MessageDigest.getInstance("MD5");
}


APPENDICES


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

26
private byte[] getDigest(byte[] data) throws Exception {
if (data == null)
throw new Exception("The data can not be null");
byte[] result = null;
MessageDigest d = createDigest();
int length = d.getDigestLength();
result = new byte[length];
d.update(data);
d.update(result, 0, length);
return result;
}

public String encrypt(String plainText, Key key) throws Exception {
byte[] textToEncrypt = plainText.getBytes();
// generate the session key
SecretKey aesKey = createAESKey();
// encrypt the plaintext using this session key
byte[] encryptedBytes = encryptAES(textToEncrypt, aesKey);
byte[] keyBytes = aesKey.getEncoded();
// System.out.println("The size of the key is "+keyBytes.length);
byte[] encryptedKey = encryptRSA(keyBytes, key);
StringBuilder builder = new StringBuilder("<value>");
builder.append("<a>");
builder.append(stringFromBytes(encryptedKey));
builder.append("</a>");
builder.append("<b>");
builder.append(stringFromBytes(encryptedBytes));
builder.append("</b>");
builder.append("</value>");
return builder.toString();

}

// use a combinaison of RSA and AES to provide decryption functionalities
public String decrypt(String cipherText, Key key) throws Exception {
// get the aes key
String aesKey = getA(cipherText);
// get the encrypted content
String encrypted = getB(cipherText);
// get the aes key
byte[] aesByteKey = bytesFromString(aesKey);
// Generate the key
byte[] res = decryptRSA(aesByteKey, key);
SecretKeySpec skeySpec = new SecretKeySpec(res, "AES");
// compute the content

APPENDICES


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

27
return new String(decryptAES(bytesFromString(encrypted), skeySpec));

}

private Cipher createRSACipher() throws Exception {
return Cipher.getInstance("RSA/ECB/PKCS1Padding");
}

private Cipher createAESCipher() throws Exception {
return Cipher.getInstance("AES/ECB/PKCS5Padding");
}

private SecretKey createAESKey() throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
return kgen.generateKey();
}

private byte[] encryptRSA(byte[] text, Key key) throws Exception {
Cipher cipher = createRSACipher();
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(text);
}

private byte[] encryptAES(byte[] text, Key key) throws Exception {
Cipher cipher = createAESCipher();
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(text);
}

private byte[] decryptRSA(byte[] text, Key key) throws Exception {
Cipher cipher = createRSACipher();
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(text);
}

private byte[] decryptAES(byte[] text, Key key) throws Exception {
Cipher cipher = createAESCipher();
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(text);
}

public String stringFromBytes(byte[] value) throws Exception {
BASE64Encoder b64 = new BASE64Encoder();
return b64.encode(value);

APPENDICES


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

28
}

public byte[] bytesFromString(String text) throws Exception {
BASE64Decoder b64 = new BASE64Decoder();
return b64.decodeBuffer(text);
}

private String getA(String text) throws Exception {
int index1 = text.indexOf("<a>");
int index2 = text.indexOf("</a>");
if ((index1 > -1) && ((index2 > -1)))
return text.substring(index1 + 3, index2);
return null;
}

private String getB(String text) throws Exception {
int index1 = text.indexOf("<b>");
int index2 = text.indexOf("</b>");
if ((index1 > -1) && ((index2 > -1)))
return text.substring(index1 + 3, index2);
return null;
}

public KeyPair getPairKey() throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1026);
return keyGen.generateKeyPair();
}

public String encryptWithAES(String plainText, String password)
throws Exception {
byte[] plainBytes = plainText.getBytes();
byte[] key = getDigest(password.getBytes());
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(key);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] result = cipher.doFinal(plainBytes);
return stringFromBytes(result);

}

public String decryptWithAES(String cipherText, String password)
throws Exception {
byte[] plainBytes = bytesFromString(cipherText);

APPENDICES


UNU-IIST CENTER FOR ELECTRONIC GOVERNANCE | www.egov.iist.unu.edu

29
byte[] key = getDigest(password.getBytes());
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(key);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] result = cipher.doFinal(plainBytes);
return new String(result).trim();
}

public String readPin(String memberId) throws Exception {
File f = new File(GlobalVariables.getWorkFolder()
+ java.io.File.separator + "PIN-" + memberId + ".xg2g");
if (!f.exists())
throw new Exception("The PIN is not available. Set the PIN first");
FileInputStream stream = new FileInputStream(f);
byte[] result = new byte[stream.available()];
stream.read(result);
String val = new String(result);
return decryptWithAES(val, memberId);
}

public void setPin(String memberId, String pin) throws Exception {