More Related Content
Similar to Session06 handling xml data (20)
Session06 handling xml data
- 2. V 1.0 © Aptech Limited
Creates an object with no data that implements
the SQLXMLinterface.
New methods have been added in the existing Connection, ResultSet, CallableStatement,
and PreparedStatement interfaces such as the getSQLXML() method that allows you to retrieve
XML value from databases. Moreover, these interfaces also have methods for updating an XML value in
databases. All these methods throw SQLException in the case of data handling failure.
Table 6.1 displays the list of methods available for working with an XML value in the databases.
The SQLXMLinterface provides the JOBC'ssupport for SQLXML data type to Java. In other words, XML
values can be assigned to or retrieved from SQLXMLobjects. In the JOBC4.0 specification, the java.
sql. Connection interface allows the creation of an SQLXMLobject. Initially, this object will not have
any data, but lateryou can add data tothe object by invoking the setString (), setBinaryStream () ,
setCharacterStream (), or setResul t () methods. The SQLXML interface provides methods
for manipulating the XML value within a database as a String, Reader or Writer, or as a Stream
object.
Before working with SQLXML interface, the programmer needs to check whether the data source
associated with the connection supports SQLXM L.Thischecking isdone by invoking the getType Info ()
method of the DatabaseMetaData class.This method will return a ResultSet object that will include a
DATA_TYPEcolumn set of all the standard SQLtypes supported by a database.
6.2 SQLXML and XML Data Types
A large amount of data is stored in XML format. To meet this requirement, databases have extended
their support for XML type by defining a standard XML data type in SQL2003 standard specifications.
With the inclusion of the XML data type in most of the databases, an XML dataset could be one of the
fields or column values in a row of database tables. J2EEdevelopers are required to store XML data
within relational databases, and then retrieve the XML elements and attributes. An SQLdata type for
handling XML type columns and a Java data type that maps to the SQLdata type will enable the storing
and retrieving of XML documents in a relational database. The SQL 2003 standard specifications now
supports such a data type, called XML data type for storing XML documents in a relational database. JOBC
version 4.0 and later supports a new data type, called SQLXMLthat maps to the new XML data type that
is defined in SQL2003 standard specifications. It also introduced SQLXMLinterface for manipulating the
new data type.
A digital signature isan electronic signature that is usedto authenticate a document or a message.An XM L
digital signature can be used to sign XML data or any binary data. These are mainly used in Web based
transactions where business data is exchanged in the form of XML documents. Since, these documents
are confidential between the sender and the receiver, the data is encrypted. For example, when you are
making online payment through credit card you would not like anyone to read the credit card details.
6.1 Introduction
Unleash your potential
Handling XML Data
TM
Apfech ::~
COMPUTEREDUCATION
- 3. TM
V 1.0 © Aptech Limited
Table 6.2: Methods in SQLXML Interface
Method Description
public InputStream Retrieves the XML value as an InputStream object. It
getBinaryStream() returns InputStream object.
public Reader Retrieves the XML value as a Reader object. It returns
getCharacterStream() a Reader object.
public String getString() Retrieves the XML value as a String object. It returns
a String object.
public Output Stream Retrieves a binary output stream that can be used
setBinaryStream() to write the XML value as a stream. It returns a
OutputStream object to which data can be written.
public Writer Retrieves a binary output stream that can be used
setCharacterStream() to write the XML value as a stream. It returns a
Output Stream object to which data can be written.
public void setString (String Setsthe XML value to the provided String object.
value)
public void free () Releasesall resources that are held up by an SQLXML
object.
Table 6.1: New Methods in Existing Interfaces to Handle XML Data
You have to use getSQLXML (int columnlndex) or getSQLXML (String columnName) of the
Resul tSet interface to obtain the SQLXML object for XML type column. Then, to output the XML
document from the SQLXML object, use any methods present in the SQLXML interface.
Table 6.2 describes methods in the new SQLXML interface for accessing XML values in databases as
String,Reader,Writer,or Stream object. All these methods throw SQLException.
Method Description
ResultSet.getSQLXML(int Retrieves the value as a SQLXMLobject from the
columnlndex) specified column that is identified by column index.
ResultSet.getSQLXML(String Retrieves the value as a SQLXMLobject from a
ColumnName) specified column that is identified by column label.
ResultSet.updateSQLXML(int Updates the specified column that is identified by
Columnlndex, SQLXML xmlObject) column index, with SQLXMLvalue.
ResultSet.updateSQLXML(String Updates the specified column that is identified by
ColumnName,SQLXML xmlObject) column label, with SQLXMLvalue .
PreparedStatement .setSQLXML(int Sets the specified SQLparameter to the user-
parameterlndex, SQLXML xmlObject) provided SQLXMLobject.
CallableStatement.setSQLXML( String Sets the specified SQLparameter to the user-
paramName, SQLXML xmlobject) provided SQLXMLobject.
CallableStatement.getSQLXML(String Retrieves the value from a specified SQLparameter
paramName) as a SQLXMLobject.
Unleashyour potential
Handling XML Data
Apfech ::~
COMPUTER EDUCATION
- 4. TM
V 1.0 © Aptech Limited
String strSQL = "Create table Invoice(Id int, OrderDetails xml)";
boolean result = stmtDetails.execute(strSQL);
cn.createStatement();Statement stmtDetails
Connection cn = DriverManager.getConnection(jdbcUrl, jdbcUser,
jdbcpassword) ;
try {
hythmMusicLibrary;";
String jdbcUser = "sa";
String jdbcPassword = "playware 123";
String jdbcUrl ="jdbc:sqlserver://10.2.10.72SQLExpress;databaseName=MyR
public static void main(String[] args)
The code defines the structure of XML data containing the product details.
Code Snippet 2 shows how to create an SQLXML object and insert an XML document, OrderDetai1s
into a column of a table using the SQLXML object.
Code Snippet 2:
<name>DVD P1ayer</name>
<quantity>3</quantity>
<unitprice>103.95</unitprice>
<litem>
</items>
</order>
<item id="2">
<name>Book</name>
<quantity>5</quantity>
<unitprice>15.95</unitprice>
<litem>
<item id="l">
<items>
<order id="0101">
Code Snippet 1 shows the details of the XML document Orderdetails.xml.
Code Snippet 1:
Unleash your pot ential
Handling XML Data
Apfech ::~
COMPUTER EDUCATION
- 5. TM
V 1.0 © Aptech Limited
The code displays how to store XML data into a database table using an SQLXML object. For doing this,
first it establishes a connection with the database using the DriverManager. getConnection ()
method. Once the connection has been established, the code instantiate a Statement object from the
Connection object by invoking the createStatement () method. Next, a table is created named
Invoice containing two columns of INTEGER and XML data type. The id and order details will be stored in
these columns respectively. Next, the executet) method of the Statement class is invoked containing the
SQLCREATE statement as an argument. Before inserting an XML data type into the database, an SQLXML
object needs to be instantiated. The createSQLXML ()method of the Connection class is invoked to
instantiate an object that will implement the SQLXML interface. Initially, the SQLXML object does not
have any data, but you add data by invoking the setString ()method.
The prepareStatement () method of the Connection class is invoked containing the SQL INSERT
statement as an argument.
String SQLString = "Insert into Invoice (Id, OrderDetai1s) va1ues(?,?)";
PreparedStatement pstDetai1s = cn.prepareStatement(SQLString);
pstDetai1s.setInt(1,1000) ;
pstDetai1s.setSQLXML(2,order);
pstDetai1s.executeUpdate();
order.free();
catch(Exception e) {}
"</item>"+
"</items>"+
"</order>") ;
"<name>DVD P1ayer</name>"+
"<quantity>3</quantity>"+
"<unitprice>103.95</unitprice>"+
"<name>Book</name>" +
"<quantity>5</quantity>" +
"<unitprice>15.95</unitprice>" +
"</item>"+
"<item id="2">"+
"<item id="l">" +
"<items>" +
SQLXML order = cn.createSQLXML();
order.setString("<order id ="0101">"+
Unleash your potential
Handling XML Data
Apfech ::~
COMPUTER EDUCATION
- 6. V 1.0 © Aptech Limited
"</item>"+
"<name>MP3 Player</name>"+
"<quantity>3</quantity>"+
"<unitprice>12.4S</unitprice>"+
"<item id="3">"+
"<items>"+
Connection cn = DriverManager.getConnection(jdbcUrl, jdbcUser,
jdbcPassword) ;
Statement stmtDetails = cn.createStatement(ResultSet.TYPE SCROLL SENSITIVE,
ResultSet.CONCUR_UPDATABLE) ;
SQLXML order = cn.createSQLXML();
order.setString("<order id="OlOl">"+
The code retrieves the records from the database including the XML data type value. The
PreparedStatement object is instantiated containing the SQL query. Next, a Resul tSet object is
instantiated containing the retrieved results of the query. The getSQLXML (2) method returns the
records of OrderDetail s document from the second column of every result set into the SQLXML object,
sqlXML.The getString ()method returns the String representation of the XML value.
Code Snippet 4 shows how to update an SQLXML object.
Code Snippet 4:
pstDetails = cn.prepareStatement("SELECT * FROM Invoice WHERE Id=?");
pstDetails.setInt(l, 1000);
ResultSet rsDetails = pstDetails.executeQuery();
while (rsDetails.next ()) {
SQLXML sqlXML = rsDetails.getSQLXML(2);
System.out.println(sqlXML.getString());
The setInt(int parameterIndex, int value) and setSQLXML(int parameterIndex,
SQLXML value) methods of PreparedStatement interface sets the integer and SQLXML values at the
specified index respectively. The executeUpdate ()method updates the database. Finally, the SQLXML
resources are released by invoking the free ()method.
Code Snippet 3 shows how to retrieve an SQLXML object.
Code Snippet 3:
Unleash your potential
Handling XML Data
TM
Apfech ::~
COMPUTEREDUCATION
- 7. TM
V 1.0 © Aptech Limited
The code creates a Connection object, en.It then creates a Statement object with the ResultSet
cursor type as TYPE_SCROLL SENSITIVE and CONCUR_UPDATABLE that allows scrolling and updation
of data simultaneously.
Connection cn = DriverManager.getConnection(jdbcUrl, jdbcUser,
jdbcPassword) ;
Statement stmtDetails = cn.createStatement(ResultSet.TYPE SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE) ;
ResultSet rsDetails = stmtDetails.executeQuery("Select * from Invoice");
XMLStreamReader streamReader = null;
ResultSet rsDetails = stmtDetails.executeQuery("Select * from Invoice");
rsDetails.next();
SQLXML sqlXML = rsDetails.getSQLXML(2);
InputStream bStream = sqlXML.getBinaryStream();
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader streamReader = factory.createXMLStreamReader(bStream);
while (streamReader.hasNext())
int parseEvent = streamReader.next();
System.out.println("" + parseEvent);
The code creates a Connection object, cn. It then creates a Statement object with the cursor type
as TYPE_SCROLL_SENSITIVE and CONCUR_UPDATABLE that allows scrolling and updation of data
simultaneously. An order object of SQLXML data type is created using the createSQLXML () method.
It is then set to a new XML value. The Resul tSet cursor is moved to insert a row. The SQLXML object,
order isinserted into the result set using the updateSQLXML ()method. The updateSQLXML ()method
does not update the database. To update the database, the insertRow ()method is invoked.
Code Snippet 5 shows how to retrieve the element type in an XML stream.
Code Snippet 5:
ResultSet rsDetails = stmtDetails.executeQuery("SELECT * from Invoice");
rsDetails.moveToInsertRow() ;
rsDetails.updateInt(l, 3);
rsDetails.updateSQLXML(2, order);
rsDetails.insertRow();
"</items>"+
"<Iorder>") ;
Unleash your potential
Handling XML Data
Apfech ::~
COMPUTER EDUCATION
- 8. V 1.0 © Aptech Limited
-+ Enveloped Signature
An enveloped signature is a signature of a document that is embedded within the signed data as
shown in figure 6.1.
A digital signature specifies the user that a digital message or a document is authentic. A digital signature
is a value that is computed using a cryptographic algorithm. It is appended to a data object so that any
receiver of the data can use the signature to verify its origin and integrity. These are frequently used in
scenarios, such as financial transactions where it is important to detect tampering and forgery.
XMLdigital signatures canbe used in XMLtransactions. These can provide authentication and data integrity.
An XML signature can be used to sign a part of an XMLdocument instead of the entire document. This is
required to guarantee authenticity, integrity, and nonrepudiation. Authenticity guarantees the credibility
of the person who has sent the document. Integrity ensures that a document has not been tampered.
Nonrepudiation ensures that the sender cannot deny sending the document. This is beneficial because
an author of an XML document can only sign his part, leaving the remaining part to others for adding
their own signatures. With an XML signature you can sign different types of resources, such as HTML,
JPG,XML document, and a part of an XML document. The resource that needs to be digitally signed must
have an Uniform Resource Identifier (URI).
XML signatures can be any of the following three types:
6.3 XML Digital Signatures
Next, a Resul tSet object is instantiated to store the retrieved result of the SQLquery. The Resul tSet
cursor is moved to the next row. The getSQLXML(2) method returns the records of the second column
of the Invoice table for every result set into the SQLXMLobject, sqlXML. The code now retrieves the
SQLXMLobject, sqlXML as a stream using the getBinaryStream () method and assignsthe stream to
an InputStream object, bStream.
To read this binary input stream as an XML data, first create an instance of XMLlnputFactory named
factory, and then invoke the createXMLStreamReader () method. This method accepts the input
stream, bStream that is to be read as an argument and then creates a new XMLStreamReader object.
The XMLStreamReader interface reads the SQLXMLobject, sqlXML with an event iterator.
The next () method returns the event types representing the various XML document elements such as
comment, root element, child elements, and so on. These event types are expressed in numbers ranging
from 1 to S. Note that 1 represents the comment, 2 represents the characters section, 3 represents the
CDATA section, 4 represents the next characters section, and 5 represents the END_ELEMENT in an XML
document.
Unleashyour potential
Handling XML Data
TM
Apfech ::~
COMPUTEREDUCATION
- 9. TM
V 1.0 © Aptech Limited
Figure 6.3: Detached Signature
The digital signature of a message and its verification requires public-key cryptography. A unique hash
value or a message digest is created using a mathematical transformation, also known as the digest
algorithm. The message digest is then encrypted using the sender's private key. The encrypted hash is
called a digital signature.
Once the receiver receives the digitally signed messageand the public key of the sender, he/she verifies it
by creating a message hash using the same digest algorithm. It is then decrypted by using the public key
of the sender. The user then compares the generated and decrypted hashes. If both the hashes match,
it means that the document is authentic and has not been tampered with. Since, the receiver does not
have the private key of the sender, the nonrepudiation is also guaranteed.
An XML digital signature consists of different elements as shown in figure 6.4.
ISigned XML Datal
XML Signature
XML Resource
-+ Detached Signature
A detached signature is a signature where the signed data and signature stay separately from each
other as shown in figure 6.3.
Figure 6.2: Enveloping XML Signature
XML Resource
Signed XML Data
XML Signature
-+ Enveloping Signature
An enveloping signature isa signature within which the signed data is embedded asshown in figure
6.2.
Figure 6.1: Enveloped Signature
XML Resource
XML Signature
Signed XML Data
Unleash your potential
Handling XML Data
Apfech ::~
COMPUTER EDUCATION
- 10. V 1.0 © Aptech Limited
The <SignedInfo> element identifies the portion of an XML document that will require the signature. All
the contents of <SignedInfo> element are responsible for this signature. The <SignedInfo> element
consists of <CanonicalizationMethod>, <SignatureMethod>, and <Reference> child elements.
The <CanonicalizationMethod> element usesan algorithm to perform the canonicalization process.
An XML canonicalization process ensures that XML signature for two documents remains same even if
the document differs only due to unnecessary white spaces. After the completion of this process, the
XML document is digitally signed using a signing algorithm that is available in the <SignatureMethod>
child element. The <CanonicalizationMethod> and <SignatureMethod> sub elements protect
the signature from getting tampered.
A <Reference> element is a part of the signature that identifies a data object to be digested through an
URI. A data object consists of data that is to be signed. The <Reference> element consists of optional
elements named <Transforms>, <DigestMethod>, and <DigestValue>. The <Transforms>
element consistsof one or more <Trans form> elements. Eachofthese <Transf orm> element describes
a transformation algorithm that will transform the data before it is digested, signed, and validated. The
<DigestMethod> element specifies the digest algorithm to be applied on the signed object, and the
<DigestVal ue> element contains the encoded digest value.
Figure 6.4: Components of XML Signature
An XML Signature consists of a <Signature> element that is the root element. The <Signature>
element consists of child elements named <SignedInfo>, <SignatureValue>, optional <KeyInfo>,
and zero or more <Object> elements.
- <Signature>
- <Signedlnfo>
<CanonicalizationMethod/>
<SignatureMethod/>
- <Reference>
<DigestMethod/>
+ <DigestValue>
</Reference>
</Signedlnfo>
+ <SignatureValue>
- <Keylnfo>
+ <Object>
</Keylnfo>
</Signature>
Unleash your p otential
Handling XML Data
TM
Apfech ::~
COMPUTEREDUCATION
- 11. TM
V 1.0 © Aptech Limited
-+ Canonicalization (c14n)
The creation of an XML Signatures from an XML document is more complex than that of a digital
signature. An XML document may have unnecessary white spaces within elements that are still
syntactically correct, for example, <name> and <name>.However, the signature will be different for
both cases because of white spaces.
Canonicalization is abbreviated as cl4n. An XML canonicalization algorithm ensures that the XML
signature for two XML documents that differ only due to unnecessary white spaces will always be
same. It is mandatory that an XML document be submitted for canonicalization before a digital
signature is created for it. Code Snippet 7 demonstrates the use of canonicalization.
The code places the resource URI of image.gif within the <Reference> element. The algorithm
used to calculate the digest value of the URI is placed in the <OigestMethod> element. The
<OigestValue> element contains the calculated digest value.
<Reference URI="http://www.abc.com/image.gif">
<OigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#shal" />
<OigestValue>j61xyz3rvEPOOvKtMup4ur=</OigestValue>
</Reference>
-+ Calculate Resource Digest
A resource for which the digest is to be created is placed within the <Reference> element. The di-
gest is a fixed-size bit string that represents the encoded resource. Any change in the digest would
mean a change in the document. The resource digest is calculated using a relevant algorithm, such
as SHAl, and the calculated value is placed in a <OigestValue> element. The <OigestMethod>
element identifies the relevant digest algorithm. Code Snippet 6 demonstrates an XML signature.
Code Snippet 6:
An XML document may have many resources, such as HTML pages, JPGfiles, and so on. You need
to decide on these resources that will require digital signatures. Use URIto identify a resource, such
as http://www.abc.com/image.gif.
-+ Decide Resources
Creating an XML digital signature is a complex process. The following steps are required to create an XML
digital signature:
6.3.1 Creating XML Digital Signatures
The <SignatureValue> element contains the actual digital signature value. The <KeyInfo> element
contains the public key information such as the keys, names, certificates, and so on that a recipient will
need to validate the signature.
Unleash your potential
Handling XML Data
Apfech ::~
COMPUTER EDUCATION
- 12. V 1.0 © Aptech Limited
The code adds a digital certificate within the <KeyInfo> element.
<X509SubjectName>CN=Robbert, O=Excel Inc.,ST=OTTAWA,C=CA
</X509SubjectName>
<X509Certificate>MXYZjabcO+gA ...D56</X509Certificate>
</X509Data>
</KeyInfo>
<KeyInfo>
<X509Data>
Code Snippet 8:
-+ Adding X.SOgCertificate
The step is optional. X.509 certificates include public keys for digital signature verification. If it is
present then its data are placed within <KeyInfo> element. Code Snippet 8 shows the use of
KeyInfo element.
-+ Signing
The digest of the <SignedInfo> element is calculated in this step, and then it is digitally signed
and placed within a <SignatureValue> element.
The code creates a <CanonicalizationMethod> element within the <SignedInfo> element.
The <CanonicalizationMethod> element specifies the necessary algorithm URI and the
<SignatureMethod> specifies the digital signature algorithm URI.
<DigestValue>j6lxyz3rvEPOOvKtMup4ur=</DigestValue>
</Reference>
</SignedInfo>
<SignatureMethod Algorithm
shalu />
<Reference URI = "http://www.abc.com/image.gifu>
<DigestMethod Algorithm = "http://www.w3.org/2000/09/xmldsig#shalU />
"http://www.w3.org/2000/09/xmldsig#dsa-
"http://www.w3.org/TR/2001/REC-
<SignedInfo Id = "slu>
<CanonicalizationMethod Algorithm
xml-c14n-20010315u/>
Code Snippet 7:
Unleash your potential
Handling XML Data
TM
Apfech ::~
COMPUTEREDUCATION
- 13. TM
V 1.0 © Aptech Limited
The output of the XML document is shown in figure 6.5.
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo Id="sl">
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-
xml-c14n-2001031S"/>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#dsa-
shal" />
<Reference URI="http://www.abc.com/image.gif">
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#shal" />
<DigestValue>j61xyz3rvEPOOvKtMup4ur=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>XZOlTS=</SignatureValue>
<Key Info>
<XS09Data>
<XS09SubjectName>CN=Robbert, O=Excel Inc.,ST=OTTAWA,C=CA
</XS09SubjectName>
<XS09Certificate>MXYZjabcO+gA ...DS6</XS09Certificate>
</XS09Data>
</KeyInfo>
</Signature>
<?xml version="l.O" encoding="UTF-8"?>
-+ Wrapping of XML Signature
The <Signature> element contains the generated XML digital signature. The signature can be
produced using Java XML Digital Signature APls. The <SignedInfo>, <SignatureValue>, and
<KeyInfo> elements are placed within a <Signature> element.
Code Snippet 9 shows the structure of an XML document.
Code Snippet 9:
Unleash your potential
Handling XML Data
Apfech ::~
COMPUTER EDUCATION
- 14. V 1.0 © Aptech limited
-+ Signature Validation
The digital signature is present in the <SignedInfo> element. Recalculate the digest of the digital
signature using the digest algorithm that is present in the <SignatureMethod> element. Then,
compare the signature value to the value that is present in the <SignatureValue> element.
Figure 6.6 shows the validation process of an XMl signature.
Recalculate the digests of all references within the <SignedInfo> element and compare these to
digest values in each <Reference> element's child element named <OigestValue>. This step
confirms that the signatures are verified properly.
-+ Reference Validation
The validation ensures that an XMl document is authentic, complete, and acceptable. An XMl signature
can be validated using a procedure known as Core Validation. The steps are as follows:
6.3.2 Validation of Digital Signatures
Figure 6.S:An XMl Digital Signature
<7xmlversion="1.0"encoding="UTF-8"7>
- <Signaturexmlns=''http://www.w3.org/2000/09/xmldsig#''>
- <SignedlnfoId="sl">
<CanonicalizationMetilodAlgorithm=''http://www.w3.org/TR/2001/REC-xml-c14n-2001031S'' />
<SignatureMetilodAlgorithm=''http://www.w3.org/2000/09/xmldsig#dsa-shal'' />
- <ReferenceURI=..http://www.abc.com/image.gif n >
<DigestMethodAlgoritilm=''http://www.w3.org/2000/09/xmldsig#shal'' />
<DigestValLle>j6Ixyz3rvEPOOvKtMup4ur= </DigestValue>
</Reference>
</Signedlnfo>
<SignatureValue>XZO1TS=</SignatureValue>
- <Keylnfo>
- <X509Data>
<X509SubjectName>CN=Robbert, 0=Excel Inc., ST=OTTAWA,C=CA</X509SubjectName>
<X509Certificate>MXYZjabcO+gA...DS6</X509Certificate>
</X509Data>
</Keylnfo>
</Signature>
Unleashyour potential
Handling XML Data
TM
Apfech ::':
COMPUTEREDUCATION
- 15. TM
V 1.0 © Aptech Limited
-+ Modify both resource digest and signature value
In case both are modified, it will result in resource digest and signature value error.
-+ Modify the signature value
The value in <SignatureValue> element can be changed accidentally or intentionally. This will
result in <SignatureValue> element error.
-+ Modify the resource digest
A resource in an XML document can be modified either accidentally or intentionally, such as modi-
fication of an image or a URI.The resource digest will change that will show reference validity er-
ror.
Figure 6.6: Validation XML Signature
Figure 6.6 shows a four step process to validate an XML signature. In step 1, the data within the
target XML document is canonicalized, and then digested. In step 2, the digest value obtained from
step 1 is compared against the digest value within the <Reference> element. This ensures that
the elements in the target document have not been tampered. In steps 3 and 4, the digest value of
the canonicalized <SignedInfo> element is calculated, and decrypted with sender's public key.
The decrypted digest value is compared with the digest value of <SignedInfo> element. If both
the signatures of the <SignedInfo> element and each of the digest values of the <Reference>
element are same, then the XML signature is considered as valid.
An XML document can be tampered in one of the following ways:
Handling XML Data Unleashyourpotential
2 1
Digest Value Compare
Harsh
XML
<SignedInfo>
il
Canonicalize
Document
Element
Target
~
4
U 3
<Signedlnfo>
Decrypt
Harsh ElementCompare Canonicalize
Reference Signature
Apfech ::~
COMPUTER EDUCATION
- 16. V 1.0 © Aptech Limited
Table 6.3 lists the important classesand interfaces available in the XML digital signature API.
6.3.4 Classes and Interfaces
These packages contain DOM-specific classesfor processing XML documents.
-+ javax.xml.crypto.dom and javax.xml .crypto.dsig.dom.
-+ javax.xml.crypto.dsig.spec
This package includes interfaces and classes that represent input parameters for algorithms,
such as digest, signature, transform, and canonicalization. The corresponding interfaces
are namely, DigestMethodParameterSpec, SignatureMethodParameterSpec,
TransformParameterSpec,andc14NMethodParameterSpec.
-+ javax.xml.crypto.dsig.keyinfo
This package contains classes and interfaces for parsing and processing elements in <Keylnfo>
structures in digitally-signed XMLdocuments. The packageinciudesKeylnfo, KeyName, KeyValue,
XS09Data, and RetrievalMethod interfaces. The abstract factory KeylnfoFactory class is
used to create objects that implement these interfaces.
This package contains classesthat represent the core classesand interfaces that can validate XML
digital signatures. The XMLSignature class allows signing and validating XML signatures. The
XMLSignature structure is represented by a corresponding Java interfaces of XMLSignature
elements, suchas<signedln f 0>, <Signat ureMethod>, and soon. The XMLSigna tureFactory
class is an abstract factory that creates objects for implementing these interfaces.
-+ javax.xml.crypto.dsig
This package consists of classes that can perform XML cryptographic operations, such as
creating an XML signature or encrypting XML data. Two major classes are KeySelector and
URIDereferencer. The KeySelector classallows locating and validating keyswithin a Keylnfo
object, and the URIDereferencer classallows creating and specifying specific URI dereferencing
implementations.
-+ javax.xml.crypto
The Java XML Digital Signature APls are the standard Java 7.0 APls for creating and verifying XML
Signatures. XML Signatures can be applied to either XML or binary data types.
The XML Digital Signature APls consists of the following packages:
6.3.3 Java XML Digital Signature APls
Unleashyour potential
Handling XML Data
TM
Apfech ::~
COMPUTEREDUCATION
- 17. TM
V 1.0 © Aptech Limited
Class Description
XMLSignatureFactory A factory classfor creating the XMLSignature
objects. Its getInstance () method returns the
XMLSignatureFactoryobject.
Reference An interface that represents the <Reference>
element in an XML document with digital
signature. The newReference () method of
XMLSignatureFactory creates Reference objects for
resources, such as image files, XML documents.
SignedInfo An interface that represents the <SignedInfo>
element in an XML document with digital
signature. The newSignedInfo () method of
XMLSignatureFactory creates SignedInfo object.
KeyPairGenerator The class generates pairs of public and private keys. Its
get Instance () factory method creates an instance
of KeyPairGenerator using algorithms, such as
DSA.Its ini tialize () method initializes the key pair
generator with specified parameter set.
KeyPair The class stores public and private key pair.
KeyInfoFactory The factory classthat creates KeyInfo objects using its
newKeyInfo () factory method. Its newKeyValue ()
method returns a KeyValue object from a public key.
Its newKeyInfo () method returns a KeyInfo object
for a public key.
KeyValue The interface represents <KeyVal ue> element in an
XML document with digital signature. It contains a
public key that is required for validating a signature.
KeyInfo The interface represents <KeyInfo> element in an
XML document with digital signature.
XMLSignature The interface represents <Signature> element in an
XML document with digital signature. Its instance can
be created using the newXMLSignature () method of
XMLSignatureFactory factory class.
DocumentBuilderFactory The factory classthat allows applications to create a
DOM tree representation of an XML document.
Document The interface represents an entire HTML or XML
document. It allows accessto the data in a document.
DOMSignContext This classcontains methods to specify the location of
an XMLSignature object in a DOM tree.
TransformerFactory An instance of the class is used to create
Transformer objects.
Unleash your potential
Handling XML Data
Apfech ::~
COMPUTER EDUCATION
- 18. TM
V 1.0 © Aptech Limited
Document document = dbf.newDocumentBuilder() .newDocument();
DOMSignContext digitalSignContext = new DOMSignContext(kp.getPrivate(),
document);
OutputStream osStream = System.out;
signature.sign(digitalSignContext);
KeyInfoFactory kif = fac.getKeyInfoFactory();
KeyValue kv = kif.newKeyValue(kp.getPublic());
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
XMLSignature signature = fac.newXMLSignature(si, ki);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true) ;
KeyPairGenerator.getInstance("DSA");KeyPairGenerator kpg
kpg.initialize(5l2) ;
KeyPair kp = kpg.generateKeyPair();
SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(
CanonicalizationMethod.INCLUSIVE_WITH COMMENTS, (C14NMethodParameterSpec)
null), fac.newSignatureMethod (SignatureMethod. DSA_SHAl, null), Collections.
singletonList(ref)) ;
Reference ref = fac.newReference(''http://java.sun.com/javase/6/docs/api/
javax/xml/crypto/dsig/Reference.html", fac.newDigestMethod(DigestMethod
.SHAl, null));
public class XMLDigitalSignature
public static void main(String[] args) throws Exception {
XMLSignatureFactory fac = XMLSignatureFactory. getInstance ("DOM");
Code Snippet 10:
Table 6.3: Java XML Signature APls
Code Snippet 10 shows how Java XM Ldigital signatures APls can be used to create an XML digital signature
for an XML document.
An instance of the abstract class transforms a source
DOM tree into a result DOM tree.
Unleash your potential
Handling XML Data
Apfech ::~
COMPUTER EDUCATION
- 19. TM
V 1.0 © Aptech Limited
The first step in the code is to create an instance of the XMLSignatureFactory class by using the
get Instance () method. The method creates a DOM tree representation of the XM Ldigital signature. In
other words, the method looks for a service provider that supports DOM. The XMLSignatureFactory
class is used to assemble the different components of the XML signature.
Next, the code block creates a Reference object. This object identifies the data that will be digested
and signed. The newReference () method of the XMLSignatureFactory class is used for creating
the instance. This is done by passing as parameters each of its components, that is URI,DigestMethod,
and a list of Transforms. In this case, the URIof Reference.html is passed as the URI,and SHAl algorithm
isthe DigestMethod that is used.
Next, the SignedInfo object is created using the newSignedInfo () method of the
XMLSignatureFactory class. This method is used for calculating the signature. The object is
created by passing as parameters each of its components such as the Canonical i zat ionMetho d,
SignatureMethod, and a list of References. The newCanonicalizationMethod () method of the
XMLSignatureFactory classisusedto canonicalize the XMLdocument. The newSigna t ureMethod ()
method of the XMLSignatureFactory class is invoked to create a new <Signa tureMethod> element
using the DSA_SHAl algorithm.
Forcreating a digital signature, a public and private key pair isgenerated using the generateKeyPair ( )
method of KeyPairGenerator class using the DSAalgorithm. The public and private key generated
is stored in the KeyPair class instance. The public key value is obtained using the newKeyValue ()
method and stored in an instance of KeyValue class. The <KeyInfo> element is created using the
newKeyInfo () method and the key value is added to it. The <KeyInfo> element stores the details
of a digital certificate. The newXMLSignature () method of the XMLSignatureFactory class is
used for creating the digital signature by passing the SignedInfo and KeyInfo objects, si and ki
respectively.
Next, you instantiate the document to be signed, create the XMLSignature object, and generate the
signature. For doing this, an XML document object is created using the DocumentBuilderFactory
class.The Document interface stores the XML signature. It is inserted into the XML document using the
DOMSignContext object named digi talSignContext. Next, the XML document is signed using the
sign () method of the XMLSignature interface.
Finally, the signed XML document is created using the trans form () method and displayed on the
command prompt using the standard output object, System. out as shown in figure 6.7.
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
trans.transform(new DOMSource (document), new StreamResult(osStream));
Unleash your potential
Handling XML Data
Apfech ::~
COMPUTER EDUCATION
- 20. V 1.0 © Aptech Limited
Figure 6.7: Digitally Signed XML Document
p:'xlIIldsig>javac -d • XMLDigitalSignatm·e.java ~I
p:'xmldsig>java javaapplication1.XMLDigitalSignatu~e
~?xml vel'S ion ="1. 0" encoding="UTF-8" standalone ="no "? ><Signatu~e xmIns =''http://.,-
'10, • ·,3.0 l'g /2000/09 /xm Ids ig#" ><Sign e din f 0 ><Can0n ic a 1iz at io nMet ho d A19o l' it hm =''ht t P :
V/.1.,.,. ·,3. 01'g/TR/2001/REC-xml-c14n-20010315#lhthComments" /><S ignatu~eMethod AlgOl'
ithlll=''http://·I·I·,. ·,3. 01'g/2000/09/XlIIlds ig#dsa-sha1 "/><Refel'ence URI=''http://java.s
un ,co 111/javase/6/docs/api/ javax/xlIIl/Cl·ypto/d sig/Refel·ence. ht m],"><Dige stMethod A19
~l' it hili=''http://'I'I'' •·,3•0l'g /2000/09 /xlIIlds igits ha1 .,/ ><Dige stU a lue >en s B6'It FJ?C91'A 2Q?X
~~.'ilkGAk=</DigestUalue ></Refel'ence ></S ignedl nf 0 ><Signatm'eUalue >iTNScUNT?tCES9 +
9-X9y4U6tFJi8plllf s iHfkMJQAC10x2cqHMEBOPs.,==(/S ignatm'eUalue ><](eyl nf 0 ><](eyUa lue ><DS
~](eyUalue ><P>/](aCz04S Yl'01ll?8z3EQ5SbbB4sF?ey80et](1 I 8641~F64B81uRpH5t9 jQTxeEu01 IIIbzRM
fl~UDZkUG9
~D7nHIkuF·,==</P)< Q) 1i 7dz Dac uo 67J g7mt qEIII2I RuOMU=</Q)< G)Z4Rxs nqc '1E7pGkn FFH2xq al' yRP
,.,aQ01khpMdLRQnG541 A·,tx/X PaF5 Bps y4pNUMOHCBiNU0Nogps
~!.!5Qvn IMpA==</G ><'I>y I k5 05 +x'i vGO.,P0qfQnP9Ell, E0C981111'11-sc+goZex?6 ?CB/3 J f 10f iLNz hf z
~~bh iZ9 c a](Cf y21·!
PEN4He]( iGg ==</'1 ></DS A](eyUa lue ></](e yUa lue >(/](e yin f 0 ></S ign at ur-e >
p:'xlllldsig>_
==================================================-= ---
..:J.gJ~Ii!C:Viinclowssystem32cmd.exe
Unleashyour potential
Handling XML Data
TM
Apfech ::~
COMPUTEREDUCATION
- 21. TM
V 1.0 © Aptech Limited
(A) DOMSignContext (C) Transformer
(B) KeylnfoFactory (D) XMLSignature
7. classspecifies the location of an XMLSignature in a DOM tree.
(A) javax.xml.crypto (C) javax.xml.crypto.dsig.spec
(B) javax.xml.crypto.dsig.keyinfo (D) javax.xml.crypto.dsig
6. Which of the following packages of Java XML Signature APls provides classes and interfaces for
handling digest algorithm?
(A) <Signedlnfo> (C) <SignatureMethod>
(B) <Keylnfo> (D) <CanonicalizationMethod>
5. Which of the following elements are optional?
(A) Canonicalization (C) Signing
(B) Calculating digest value (D) X.509 certification
4. is an optional step in the XML digital signature process.
(A) Canonicalization (C) Encryption
(B) Digest (D) X.509 certificate
3. The method ensures that an XML document will always have the same signature.
(A) Authentication (C) Repudiation
(B) Falsification (D) Encryption
2. A digital signature is used for of a message or a document.
(A) SQLXML (C) SQUava
(B) XMLSQL (D) SQL
1. maps Javawith XML data type in a database.
6.4 Check Your Progress
Unleash your potential
Handling XML Data
Apfech ::~
COMPUTER EDUCATION
- 22. V 1.0 © Aptech Limited
1. A
2. A
3. A
4. D
5. B
6. C
7. A
6.4.1 Answers
Unleash your pot ential
TM
Apfech ::~
COMPUTEREDUCATION
Handling XML Data
- 23. TM
V 1.0 © Aptech Limited
-+ A new data type, called SQLXML that maps XML columns in a database has been introduced in
JDBCversion 4.0. The SQLXMLinterface implements methods for handling XML data types.
-+ XML Digital signatures provide authentication of source data and data integrity that are frequently
used in XML transactions. XML digital signatures can be applied to both XML and non-XML data
types.
-+ JavaXML Digital Signatures APls allow creating and verifying XML digital signatures.
-+ The JavaXML Digital Signature APls are the standard Java 7.0 APls for creating and verifying XML
Signatures.
-+ For creating a digital signature, a public and private key pair is generated using the
generateKeyPair() method of KeyPairGenerator class using the DSAalgorithm.
Summar
Unleash your potential
Handling XML Data
Apfech ::~
COMPUTER EDUCATION