Vous êtes sur la page 1sur 32

Porting Java Public Key Hash to C# .

Net




By Shaheryar Chaudhry (shaheryar@hotmail.com)


Table of Contents

Abstract ..........................................................................................................1
Section 1: Introduction .....................................................................................2
1 Who should read? ..................................................................................2
Section 2: Signing the Data...............................................................................3
1 Public and Private Key Generation ............................................................4
2 Public and Private Key initialization from stored files...................................7
3 Signing the Data .................................................................................. 10
4 Verify data and Signature...................................................................... 12
Section 3: Generating .Net compatible Public Key .............................................. 14
1 Net RSA Public Key XML........................................................................ 14
2 Generating .Net XML Public Key from Java .............................................. 15
Section 4: Reading Public Key and verifying the Data in .Net ............................... 18
1 Initialization ........................................................................................ 18
2 Reading Key ........................................................................................ 18
3 Verifying the Signature ......................................................................... 19
Glossary........................................................................................................ 22
References .................................................................................................... 29
About Author ................................................................................................. 30
Section 1: Introduction
1
Article content copyright Shaheryar Ch., 2004
Abstract
There is perhaps no software engineering topic of more timely importance than data
security and integrity. Attacks are costly, whether the attack comes from inside or
out, and some attacks can expose a software company to liability for damages.
Staying on top of the most up-to-date techniques and tools is one key to application
security and integrity. Developing cross platform applications to ensure security is a
big problem which has been encountered by number of developers.

This document is an effort to overcome such problems faced by the developers who
want to sign the data on one platform and want to verify it on another, using popular
public-key digital signature known as RSA.

Starting with a Java program to illustrate how to generate the keys, sign and verify
the data using the generated keys both by breaking down the functions of the
application and by viewing the final execution result. Next, a document discusses
how to export the public key, generated by Java, to be used later by .Net framework
to verify the data in.Net Applications. Finally, this document discusses how to read
the Public Key in .Net (using C#) generated by Java program and verify the data
using this Public Key. In the end of the document, different definitions of terms are
also provided to equip the beginners as well.
Section 1: Introduction
2
Article content copyright Shaheryar Ch., 2004
Section 1: Introduction
1 Who should read?
The main ideas behind this tutorial revolve around signing a data in Java and then
verifying it in .Net using C#. However, readers who are interested to start learning
the signing & verifying the data using Java Cryptographic APIs and language can
also use this tutorial. This tutorial assumes that reader knows how to read and write
basic Java & C# .Net applications.

Before going through this tutorial, it is highly recommended that you should have
basic knowledge of terms for Cryptography and Security packages defined in Java
and .Net framework. For interested readers the definitions of terms is provided in
Glossary at the end of the tutorial. Even if you know the terms just go through them
to refresh your memory.

Section 2: Signing the Data in Java
3
Article content copyright Shaheryar Ch., 2004
Section 2: Signing the Data

The zip file includes the SecurityManager.java. This
Java class is responsible for signing the data and
verifying the data using private and public keys
respectively. It also generates the XML Public key for
.Net framework. This class has following
responsibilities.
Initialize Signature Parameters
Generate Public and Private Keys
Store/Read generated Public and Private keys
Sign the input data
Verify the input data
Store the Public key in .Net compatible
(XML)format

Although it is not fair to keep all the things in one
class; but just to keep it simple, everything has been
kept in one class. Reader may alter the code and
may eliminate functions such as storing/reading the
keys on/from HDD to some other class.

The code has been well documented with comments
and hopefully the reader will not find it difficult to
understand.


Section 2: Signing the Data in Java
4
Article content copyright Shaheryar Ch., 2004
1 Public and Private Key Generation
Private Key is mandatory for digital signature generation. When you generate the
Private Key the corresponding Public key is automatically generated. For
performance Private / Public Keys are generated only once and stored at physical
location of the HDD. The methodology adopted in the current code is to store the
public key at some application path. However for web applications key may be
streamed along with data.

The following function generates the Public and Private Keys and stores them at the
specified location. This function also invokes functions to generate the compatible
.Net Public Key. It takes the size of the hash algorithm as a parameter and generates
the corresponding key.

Section 2: Signing the Data in Java
5
Article content copyright Shaheryar Ch., 2004

Now lets look at the corresponding code.
/**
* Generates the keys for given size.
* @param size - Key Size [512|1024]
*/
public void generateKeys(int size) {
try {
System.out.println("Generating Keys");
keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(size);
keypair = keyGen.genKeyPair(); //Get the KeyPair for given algorithm and size.
privateKey = keypair.getPrivate(); //Extract Private Key
publicKey = keypair.getPublic(); // Extract Public Key

// Get bytes of the public and private keys
byte[] privateKeyBytes = privateKey.getEncoded(); //Get the key bytes
byte[] publicKeyBytes = publicKey.getEncoded(); // Get the key bytes

//write bytes to corresponding files after encoding them to Base 64 using Base64Encoder Class.
writeKeyBytesToFile(new BASE64Encoder().encode(privateKeyBytes).
getBytes(), PRIVATE_KEY_FILE);
String encodedValue = new BASE64Encoder().encode(publicKeyBytes);
writeKeyBytesToFile(encodedValue.getBytes(), PUBLIC_KEY_FILE);

//Generate the Private Key, Public Key and Public Key in XML format.
PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(new
PKCS8EncodedKeySpec(privateKeyBytes));
PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new
X509EncodedKeySpec(publicKeyBytes));

//Create and Instance of RSAPublicKey class with X509 encoding
RSAPublicKey rsaPublicKey = (RSAPublicKey) KeyFactory.getInstance("RSA").
generatePublic(new X509EncodedKeySpec(publicKeyBytes));

//Get the RSAPublicKey as XML store the public key in XML string to make compatible .Net public
key file. See getRSAPublicKeyAsXMLString() for details

String xml = getRSAPublicKeyAsXMLString(rsaPublicKey);


Section 2: Signing the Data in Java
6
Article content copyright Shaheryar Ch., 2004
//Store the XML (Generated .Net public key file) in file
writeKeyBytesToFile(xml.getBytes(), DOT_NET_PUBLIC_KEY_FILE);
}
catch (java.security.NoSuchAlgorithmException e) {
System.out.println("No such algorithm. Please check the JDK version."+e.getCause());
}
catch (java.security.spec.InvalidKeySpecException ik) {
System.out.println("Invalid Key Specs. Not valid Key files."+ ik.getCause());
}
catch (UnsupportedEncodingException ex) {
System.out.println(ex);
}
catch (ParserConfigurationException ex) {
System.out.println(ex);
}
catch (TransformerException ex) {
System.out.println(ex);
}
catch (IOException ioe) {
System.out.println("Files not found on specified path. "+ioe.getCause());
}
}
Once the keys are generated they can be stored at specific path in a simple file to
avoid re-generation of Private and Public keys. It increases the performance. There
may be a requirement to generate new keys each time for each request. If you want
to generate the keys each time then invoke this function each time in main function
or in your application before signing the data.
Section 2: Signing the Data in Java
7
Article content copyright Shaheryar Ch., 2004
2 Public and Private Key initialization from stored files
Following two functions read the public and private keys. Whenever you have to sign
the data you only require a private key. Therefore I have provided an additional
function to initialize only the private key. The basic work flow of this function is
described in the figure.

Section 2: Signing the Data in Java
8
Article content copyright Shaheryar Ch., 2004
Lets look at the code now. As by name it is clear the initializePrivateKey only
initializes the private key but if you wish to initialize both private and public key
invoke the other function named as initializeKeys.

/**
* Initialize only the private key.
*/
private void initializePrivateKey() {
try {
//Read key files back and decode them from BASE64
BASE64Decoder decoder = new BASE64Decoder();
byte[] privateKeyBytes = decoder.decodeBuffer(new String(
readPrivateKeyFile()));

// Convert back to public and private key objects
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
privateKey = keyFactory.generatePrivate(privateKeySpec);
}
catch (IOException io) {
System.out.println("Private Key File Not found."+io.getCause());
}
catch (InvalidKeySpecException e) {
System.out.println("Invalid Key Specs. Not valid Key files."+ e.getCause());
}
catch (NoSuchAlgorithmException e) {
System.out.println("There is no such algorithm. Please check the JDK ver."+ e.getCause());
}
}
/**
* Initializes the public and private keys.
*/
private void initializeKeys() {
try {
//Read key files back and decode them from BASE64
BASE64Decoder decoder = new BASE64Decoder();
byte[] privateKeyBytes = decoder.decodeBuffer(new String(
readPrivateKeyFile()));
byte[] publicKeyBytes = decoder.decodeBuffer(new String(readPublicKeyFile()));

// Convert back to public and private key objects
Section 2: Signing the Data in Java
9
Article content copyright Shaheryar Ch., 2004
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
privateKey = keyFactory.generatePrivate(privateKeySpec);
EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
publicKey = keyFactory.generatePublic(publicKeySpec);
}
catch (IOException io) {
System.out.println("Public/ Private Key File Not found."+ io.getCause());
}
catch (InvalidKeySpecException e) {
System.out.println("Invalid Key Specs. Not valid Key files."+ e.getCause());
}
catch (NoSuchAlgorithmException e) {
System.out.println("There is no such algorithm. Please check the JDK ver."+ e.getCause());
}
}

Section 2: Signing the Data in Java
10
Article content copyright Shaheryar Ch., 2004
3 Signing the Data
As it is evident from the function name that function is responsible for signing the
data sent as bytes. Prior to this function invocation the private key initialization is
must. Either read the existing private key or generate new private key.



Section 2: Signing the Data in Java
11
Article content copyright Shaheryar Ch., 2004
/**
* Signs the data and return the signature for a given data.
* @param toBeSigned Data to be signed
* @return byte[] Signature
*/
public byte[] signData(byte[] toBeSigned)
{
if (privateKey == null) {
initializePrivateKey();
}
try {
Signature rsa = Signature.getInstance("SHA1withRSA");
rsa.initSign(privateKey); //initialize the signature with provided key
rsa.update(toBeSigned); //sign the data
return rsa.sign(); //return the signature in bytes
}
catch (NoSuchAlgorithmException ex) {
System.out.println(ex);
}
catch (InvalidKeyException in) {
System.out.println("Invalid Key file.Please chekc the key file path"+ in.getCause());
}
catch (SignatureException se) {
System.out.println(se);
}
return null;
}

Section 2: Signing the Data in Java
12
Article content copyright Shaheryar Ch., 2004
4 Verify data and Signature
Verifying the data is fairly simple. The following function is responsible for verifying
the signature for corresponding data, sent as bytes. The signature is verified with the
Public Key.
/**
* Verifies the signature for the given bytes using the public key.
* @param signature Signature
* @param data Data that was signed
* @return boolean True if valid signature else false
*/
public boolean verifySignature(byte[] signature, byte[] data) {
try {
initializeKeys(); // Initialize the keys before verifying the signature
sign.initVerify(publicKey); //Initialize the signature engine instance with public key
sign.update(data); // load the data to be verified
return sign.verify(signature); // verify the data loaded in previous step with given signature and
return the
//result
}
catch (SignatureException e) {
e.printStackTrace();
}
catch (InvalidKeyException e) {
}
return false;
}


Section 2: Signing the Data in Java
13
Article content copyright Shaheryar Ch., 2004

Section 3: Generating .Net compatible Public key using Java
14
Article content copyright Shaheryar Ch., 2004
Section 3: Generating .Net compatible Public Key
1 Net RSA Public Key XML
.Net RSA Public Key contains Modulus and exponent which can be extracted from the
Java Public key. Before we look into the Java code details lets look at the XML which
can be transformed into the RSAParameters structure.
The Modulus represents the Modulus parameter for the RSA algorithm while
Exponent represents the Exponent parameter for the RSA Algorithm. The RSA
Algorithm class in .Net is available under the namespace
System.Security.Cryptography.RSA

The .Net RSA Public XML key structure is given below.
<?xml version="1.0" encoding="UTF-8"?>
<RSAKeyValue>
<Modulus>uKI+0wG6eILUPRNf6ImqRdez/nLxsV0LHGsuvYR0LDVrXz8Y7sYSlp
Akn1HpJI8US8Sx5bJzvBib&#13; vKv0pAa7UQ==
</Modulus>
<Exponent>AQAB</Exponent>
</RSAKeyValue>

Section 3: Generating .Net compatible Public key using Java
15
Article content copyright Shaheryar Ch., 2004
2 Generating .Net XML Public Key from Java
In this section we will discuss the methodology adopted to export the Java public key
class as .Net compatible public key. The exported XML key will be later loaded in our
.Net application and we will verify the signature by using this key.

Lets look at the code.
Recall from our Key Generation process that we invoked some functions to generate
the Public key in XML format.

//Create and Instance of RSAPublicKey class with X509 encoding key specs
RSAPublicKey rsaPublicKey = (RSAPublicKey) KeyFactory.getInstance("RSA").
generatePublic(new X509EncodedKeySpec(publicKeyBytes));

//Get the RSAPublicKey as XML store the public key in XML string to make compatible .Net public
key file. See getRSAPublicKeyAsXMLString() for details

String xml = getRSAPublicKeyAsXMLString(rsaPublicKey);

//Store the XML (Generated .Net public key file) in file
writeKeyBytesToFile(xml.getBytes(), DOT_NET_PUBLIC_KEY_FILE);

If you see the first line, X509EncodedKeySpec have been used. This class represents
the ASN.1 encoding of a public key, encoded according to the ASN.1 type
SubjectPublicKeyInfo. The SubjectPublicKeyInfo syntax is defined in the X.509
standard as follows:

SubjectPublicKeyInfo ::= SEQUENCE {
algorithm AlgorithmIdentifier,
subjectPublicKey BIT STRING }

Now look at the function named as getRSAPublicKeyAsXMLString
/**
* Gets the RSA Public key as XML string.
* @param key RSAPublicKey
* @return String XML representation of RSA Public Key.
* @throws UnsupportedEncodingException
* @throws ParserConfigurationException
Section 3: Generating .Net compatible Public key using Java
16
Article content copyright Shaheryar Ch., 2004
* @throws TransformerException
*/
private String getRSAPublicKeyAsXMLString(RSAPublicKey key) throws
UnsupportedEncodingException, ParserConfigurationException, TransformerException {

Document xml = getRSAPublicKeyAsXML(key);
Transformer transformer =
TransformerFactory.newInstance().newTransformer();
StringWriter sw = new StringWriter();
transformer.transform(new DOMSource(xml), new StreamResult(sw));
return sw.getBuffer().toString();
}

/**
* Gets the RSA Public Key as XML. The idea is to make the key readable for
* .Net platform. The generated key is compatible with .Net key structure.
* @param key RSAPublicKey
* @return Document XML document.
* @throws ParserConfigurationException
* @throws UnsupportedEncodingException
*/
private Document getRSAPublicKeyAsXML(RSAPublicKey key) throws
ParserConfigurationException, UnsupportedEncodingException {

Document result = DocumentBuilderFactory.newInstance().newDocumentBuilder().
newDocument();
Element rsaKeyValue = result.createElement("RSAKeyValue");
result.appendChild(rsaKeyValue);
Element modulus = result.createElement("Modulus");
rsaKeyValue.appendChild(modulus);
byte[] modulusBytes = key.getModulus().toByteArray();
modulusBytes = stripLeadingZeros(modulusBytes);

// KeyManager.write("c:\\mod.c",
// new sun.misc.BASE64Encoder().encode(modulusBytes)); //Stored it for testing purposes
modulus.appendChild(result.createTextNode(
new String(new sun.misc.BASE64Encoder().encode(modulusBytes))));
Element exponent = result.createElement("Exponent");
rsaKeyValue.appendChild(exponent);
byte[] exponentBytes = key.getPublicExponent().toByteArray();

Section 3: Generating .Net compatible Public key using Java
17
Article content copyright Shaheryar Ch., 2004
// KeyManager.write("C:\\exponenet.c",
// new sun.misc.BASE64Encoder().encode(exponentBytes)); //stored it for testing purposes
exponent.appendChild(result.createTextNode(
new String(new sun.misc.BASE64Encoder().encode(exponentBytes))));
return result;
}
The above mentioned functions allow us to generate the XML file which contains the
Public Key Information. We store this file on the Hard disk or stream it over the
network.

Section 4: Reading Public Key and verifying the Data in .Net
18
Article content copyright Shaheryar Ch., 2004
Section 4: Reading Public Key and verifying the Data in
.Net
In this section we will read the Public key which was generated in previous section by
the Java program.
1 Initialization
In the constructor, initialize RSAParameters class and RSACryptoServiceProvider.

PUBLIC_KEY="c:\\netpublic.key"; //Generated by Java Program
RSAKeyInfo = new RSAParameters();
RSA = new RSACryptoServiceProvider();

2 Reading Key
Following function reads the file from the specific path on HDD. One may use
network stream to read the XML file. Parse the modulus data and exponent data and
assign them to variables. Convert the strings from Base64 and assign them to
RSAParameters.Modulus and RSAParameters.Exponent. ImportParameters function
of RSACryptoServiceProvider is used to load the parameters for RSA algorithm.

private void readKey()
{
// read the XML formated public key
try
{
XmlTextReader reader = new XmlTextReader(PUBLIC_KEY);
while(reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if(reader.Name=="Modulus")
{
reader.Read();
modStr= reader.Value;
}
else if(reader.Name=="Exponent")
Section 4: Reading Public Key and verifying the Data in .Net
19
Article content copyright Shaheryar Ch., 2004
{
reader.Read();
expStr= reader.Value;
}
}
}
if(modStr.Equals("") ||expStr.Equals(""))
{
//throw exception
throw new Exception("Invalid public key");
}
RSAKeyInfo.Modulus = Convert.FromBase64String(modStr);
RSAKeyInfo.Exponent = Convert.FromBase64String(expStr);
RSA.ImportParameters(RSAKeyInfo);
}
catch(Exception e)
{
throw new Exception("Invalid Public Key.");
}
}
3 Verifying the Signature
The signature can be verified once the Modulus and Exponent have been parsed from
the XML and loaded in RSACryptoServiceProvider. verifySignature method is
invoked to verify the Signature for given data. It verifies the specified signature data
by comparing it to the signature computed for the specified data.

public bool verifySignature(byte[] signature , string signedData)
{
byte[] hash = Convert.FromBase64String(signedData);
try
{
if(RSA.VerifyData(hash,"SHA1",signature))
{
//Console.WriteLine("The signature is valid.");
return true;
}
else
{
//Console.WriteLine("The signature is not valid.");
Section 4: Reading Public Key and verifying the Data in .Net
20
Article content copyright Shaheryar Ch., 2004
return false;
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
return false;
}
}


Section 4: Reading Public Key and verifying the Data in .Net
21
Article content copyright Shaheryar Ch., 2004
References
22
Article content copyright Shaheryar Ch., 2004
Glossary
Digital Signature
A digital code that can be attached to an electronically transmitted message that
uniquely identifies the sender. Like a written signature, the purpose of a digital
signature is to guarantee that the individual sending the message really is who he or
she claims to be. Digital signatures are especially important for e-commerce
applications and are a key component of most authentication schemes. Like a
handwritten signature, a digital signature has many useful characteristics:

Its authenticity can be verified, via a computation that uses the public key
corresponding to the private key used to generate the signature.
It cannot be forged, assuming the private key is kept secret.
It is a function of the data signed and thus cant be claimed to be the
signature for other data as well.
The signed data cannot be changed; if its corresponding signature will no
longer verify as being authentic.

RSA Algorithm
It is a public-key encryption algorithm developed by RSA Data Security, Inc. The
acronym stands for Rivest, Shamir, and Adelman, the inventors of the technique.
The RSA algorithm is based on the fact that there is no efficient way to factor very
large numbers. Deducing an RSA key, therefore, requires an extraordinary amount of
computer processing power and time.

The RSA algorithm has become the de facto standard for industrial-strength
encryption, especially for data sent over the Internet.

Message Digest
The representation of text in the form of a single string of digits, created using a
formula called a one-way hash function. Encrypting a message digest with a private
key creates a digital signature, which is an electronic means of authentication.

Hashing
References
23
Article content copyright Shaheryar Ch., 2004
Producing hash values for accessing data or for security. A hash value (or simply
hash), also called a message digest, is a number generated from a string of text. The
hash is substantially smaller than the text itself, and is generated by a formula in
such a way that it is extremely unlikely that some other text will produce the same
hash value.

Hashes play a role in security systems where they're used to ensure that transmitted
messages have not been tampered with. The sender generates a hash of the
message, encrypts it, and sends it with the message itself. The recipient then
decrypts both the message and the hash, produces another hash from the received
message, and compares the two hashes. If they're the same, there is a very high
probability that the message was transmitted intact. Hashing is also a common
method of accessing data records. Consider, for example, a list of names:
John Smith
Sarah Jones
Roger Adams

To create an index, called a hash table, for these records, you would apply a formula
to each name to produce a unique numeric value. So you might get something like:
1345873 John smith
3097905 Sarah Jones
4060964 Roger Adams

Then to search for the record containing Sarah Jones, you just need to reapply the
formula, which directly yields the index key to the record. This is much more efficient
than searching through all the records till the matching record is found.

Public Key
A number associated with a particular entity (for example, an individual or an
organization). A public key is intended to be known to every one who needs to have
trusted interactions with that entity.

Private Key
References
24
Article content copyright Shaheryar Ch., 2004
A number that is supposed to be known only to a particular entity. That is, private
keys are always meant to be kept secret. A private key is always associated with a
single public key.

Cryptography Algorithm
An algorithm used to help ensure one or more of the following:
The confidentiality of data
Authentication of the data sender
Integrity of the data sent
Non repudiation; a sender cannot deny having sent a particular message

Encryption
The process of taking data (called cleartext) and a short string (a key) and producing
ciphertext, which is data meaningless to a third-party who does not know the key.

Decryption
The inverse of encryption; the process of taking ciphertext and a short key string,
and producing cleartext.

Certificate
A digitally signed statement from one entity, saying that the public key of some
other entity has some particular value. If you trust the entity that signed a
certificate, you trust that the association in the certificate between the specified
public key and another particular entity is authentic.

Message Digest Algorithm (or One-Way Hash Function)
A function that takes arbitrary-sized input data (referred to as a message) and
generates a fixed-size output, called a digest (or hash). A digest has the following
properties:

It should be computationally infeasible to find another input string that will
generate the same digest.
The digest does not reveal anything about the input that was used to
generate it.

References
25
Article content copyright Shaheryar Ch., 2004
Message digest algorithms are used to produce unique and reliable identifiers of
data. The digests are sometimes called the "digital fingerprints" of data.
Some digital signature algorithms use message digest algorithms for parts of their
computations.

Some digital signature systems compute the digest of a message and digitally sign
the digest rather than signing the message itself. This can save a lot of time, since
digitally signing a long message can be time-consuming.

Engine Class
The term engine class is used in the Java Security API to refer to a class that
provides the functionality of a type of cryptography algorithm. The Security API
defines a Java class for each engine class. For example, there is a MessageDigest
class, a Signature class, and a KeyPairGenerator class. Users of the API request and
utilize instances of these engine classes to carry out corresponding operations. A
Signature instance is used to sign and verify digital signatures, a MessageDigest
instance is used to calculate the message digest of specified data, and a
KeyPairGenerator is used to generate pairs of public and private keys suitable for a
specified algorithm.
An engine class provides the interface to the functionality of a specific type of
algorithm, while its actual implementations (from one or more providers) are those
for specific algorithms. The Signature engine class, for example, provides access to
the functionality of a digital signature algorithm. The actual implementation supplied
in a Signature subclass could be that for any kind of signature algorithm, such as
SHA-1 with DSA, SHA-1 with RSA, or MD5 with RSA. We have used SHA-1 with RSA.

Provider
Implementations for various algorithms in Java Security are provided by
Cryptography Package Providers. Providers are essentially packages that implement
one or more engine classes for specific algorithms. For example, the Java
Development Kit's default provider named "SUN"; supplies implementations of the
DSA signature algorithm and of the MD5 and SHA-1 message digest algorithms.
Other providers may define their own implementations of these algorithms or of
other algorithms, such as one of the RSA-based signature algorithms or the MD2
message digest algorithm.
References
26
Article content copyright Shaheryar Ch., 2004
What Does the Java Security API Provide?
The Java Security API is a new Java core API, built around the java.security package
(and its subpackages). The first release of the Java Security API, available in JDK
1.1, contains APIs for:
Digital Signatures
Digital signature algorithms, such as DSA (Digital Signature Algorithm). The
functionality includes generating public/private key pairs as well as signing and
verifying arbitrary digital data.

Message Digests
Cryptographically secure message digests, such as MD5 and SHA-1. These
algorithms, also called one-way hash algorithms, are useful for producing "digital
fingerprints" of data, which are frequently used in digital signatures and other
applications that need unique and unforgeable identifiers for digital data.

Key Management
A set of abstractions for managing principals (entities such as individual users or
groups), their keys, and their certificates. It allows applications to design their own
key management systems, and to interoperate with other systems at a high level.
Note that support for specific certificate formats is not available but will be part of a
future JDK release.

The cryptography framework in the Java Security API is designed so that a new
algorithm can be added later on without much difficulty and can be utilized in the
same fashion as existing algorithms. For example, although DSA is the only built-in
digital signature algorithm in this release, the framework can easily accommodate
another algorithm such as RSA. Vendors can develop their own algorithms and
integrate their resulting provider) packages into the Java Security API so that clients
can utilize them.

Core Classes
The Signature Class
The Signature class is an engine class designed to provide the functionality of a
digital signature algorithm such as DSA or RSA with MD5. A signature algorithm
takes arbitrary-sized input and a private key and generates a relatively short (often
References
27
Article content copyright Shaheryar Ch., 2004
fixed-size) string of bytes, called the signature, with the following properties:
Given the public key corresponding to the private key used to generate the
signature, it should be possible to verify the authenticity and integrity of the input.
The signature and the public key do not reveal anything about the private key. A
Signature object can be used to generate a digital signature for data. It can also be
used to verify whether or not an alleged signature is in fact the authentic signature
of the data associated with it.

The MessageDigest Class
The MessageDigest class is an engine class designed to provide the functionality of
cryptographically secure Message Digest. Message digests such as SHA-1 or MD5. It
takes arbitrary-sized input (a byte array), and generates a fixed-size output, called a
digest. A digest has the following properties:

It should be computationally infeasible to find another input string that will
generate the same digest.
The digest does not reveal anything about the input that was used to
generate it.

Message digests are used to produce unique and reliable identifiers of data. They are
sometimes called the "digital fingerprints" of data.

Key Interfaces
The Key interface is the top-level interface for all keys. It defines the functionality
shared by all key objects. All keys have three characteristics:
An Algorithm
An Encoded Form
This is an external encoded form for the key used when a standard
representation of the key is needed outside the Java Virtual Machine, as when
transmitting the key to some other party. The key is encoded according to a
standard format (such as X.509 or PKCS#8).
A Format
This is the name of the format of the encoded key.Keys are generally
obtained through key generators, certificates, or various Identity classes used
to manage keys.
References
28
Article content copyright Shaheryar Ch., 2004
The KeyPair Class
The KeyPair class is a simple holder for a key pair (a public key and a private key). It
has two public methods, one for returning the private key, and the other for
returning the public key.

The KeyPairGenerator Class
The KeyPairGenerator class is an engine class used to generate pairs of public and
private keys.
References
29
Article content copyright Shaheryar Ch., 2004
References

Special Thanks to Philip Ross [psr@warwickcompsoc.co.uk] & Mitch Gallant
[neutron@istar.ca]
http://pages.istar.ca/~neutron/feature/JKeyNet/

MSDN Library
http://msdn.microsoft.com/library/default.asp?url=/library/enus/dncapi/html/encryp
tdecrypt2a.asp

DotNet247
http://www.dotnet247.com/247reference/msgs/36/184491.aspx

About Author
30
Article content copyright Shaheryar Ch., 2004
About Author
Shaheryar Chaudhry specializes in architecture, design, development and
deployment of J2EE and .Net enterprise applications. He got hooked with enterprise
application development during his graduation and has been devoted to it ever since.
Shaheryar has Bachelors degree in Computer Science (Major in Software Engg.) from
Mohammed Ali Jinnah University, Islamabad-Pakistan.

Vous aimerez peut-être aussi