- Special Edition Using Java, 2nd Edition -

Chapter 37

Java Security in Depth


by David Baker

In any bulleted list description of the features of the Java execution environment, a phrase such as Java is secure will be found. Security can mean a lot of different things, and when developing Java applets, it is critical to understand the implications of Java security. Your applets are restricted to functioning within the Java security framework, which affects your design while enabling the safe execution of network-loaded code.

To ensure an uncompromised environment, the Java security model errs on the side of caution. All applets loaded over the network are assumed to be potentially hostile and are treated with appropriate caution. This fact will greatly restrict your design. To enable Java applets to expand beyond these limitations, the Java Security API has been developed.

What Necessitates Java Security?

In order to appreciate the intent and rationale behind the framework on which Java is based, we must investigate what makes security an issue at all. Java provides many solutions to matters of security, many of which will have ramifications on how you approach the installation and authoring of Java applications in your Internet network solutions.

The Internet forms a vast shared medium, allowing machines throughout the world to communicate freely. Trusted and untrusted computers, allowing access to millions of individuals with unknown intentions, are linked together. One computer may send information to almost any other on the Internet. Furthermore, Internet applications and protocols are not foolproof; at various levels, the identities can be concealed through a variety of techniques.

Adding Java to this scene opens up tremendous potential for abuse. Java's strengths present the most problematic issues. Specifically:

Given these characteristics, it is easy to see why Java code should be treated with great care. Without a tightly controlled environment, one could envision a number of problematic scenarios:

With these problems in mind, the overall problem can be seen. In order to be practical, Java must provide a controlled environment in which applications are executed. Avenues for abuse or unintended damage must be anticipated and blocked. System resources must be protected. To be safe, Java must assume code that is loaded over the network comes from an untrusted source; only those capabilities known to be secure should be permitted. However, Java should not be so restricted that its value goes unrealized.

For those who are familiar with Internet security systems, the issues Java faces are not new. This situation presents the old paradox where computers must have access to capabilities and resources in order to be useful. However, in an inverse relationship, the more power we provide to such systems, the greater the potential for abuse. In such a situation, a paranoid stance will render the system useless. A permissive stance will eventually spell doom. A prudent stance strikes to find an intelligent middle ground.

The Java Security Framework

True to what the word means, Java provides a clear framework, which creates a secure execution environment. Java is much more than a programming language. It consists of many different layers that create the Java execution environment:

At critical points within this structure, specific features ensure a safe execution environment. In isolation, each portion may provide little or no benefit to the system. In concert, these features work to create the solid and secure framework that makes Java a practical solution to executable content.

Part One: The Safety Provided by the Language

The Java language itself provides the first layer of network security. This security provides the features that are necessary to protect data structures and limit the likelihood of unintentionally flawed programs.

Java Enforced Adherence to the Object-Oriented Paradigm

Private data structures and methods are encapsulated within Java classes. Access to these resources is provided only through a public interface that is furnished by the class. Object-oriented code often proves to be more maintainable and follows a clear design.

No Pointer Arithmetic

Java references cannot be incremented or reset to point to specific portions of the Java Virtual Machine's memory. Furthermore, every object that isn't waiting for garbage collection must have a reference defined to it.

It is often said that Java does not contain pointers. In the abstract sense, pointers are merely variables that don't contain data but, rather, identify the location of program data, data structures, or functions. References fit this definition.
 
However, Java does not permit various operations that usually accompany pointers. Pointer arithmetic allows a program to reference and manipulate directly specific portions of machine memory that may not belong to the pointer's data structures. References may not do this.
 

Array-Bounds Checking

Many security problems in flawed applications created with other programming languages were because of the lack of array-bounds checking. A program could be induced to iterate beyond the end of an array, referring to outside data not belonging to the array. Java prevents this. An attempt to index an element before the beginning or after the end of an array will throw an exception.

Java's Typecasting System

Java ensures that any cast of one object to another is actually a legal operation. An object cannot be arbitrarily cast to another type.

Language Support for Thread-Safe Programming

Multi-threaded programming is an intrinsic part of the Java language, and special semantics ensure that different threads of execution modify critical data structures in a sequential, controlled fashion.

Final Classes and Methods

Many classes and methods within the Java API are declared final, preventing programs from further subclassing or overriding specific code.

Part Two: The Java Compiler

The Java compiler converts Java code to a specific bytecode for the Java Virtual Machine. The compiler ensures that all of the security features of the language are imposed. A trustworthy compiler establishes that the code is safe and establishes that a programmer has appropriated used typecasting.

Part Three: The Verifier

Java bytecode is the essence of what is transmitted over the network. It is machine code for the Java Virtual Machine. Java's security would be easy to subvert if only the policies defined previously were assumed to have been enforced. A hostile compiler could be easily written to create bytecode that would perform dangerous acts which the well-behaved Java compiler would prevent.

Thus, security checks on the browser-side are critical to maintaining a safe execution environment. Bytecode cannot be assumed to be created from a benevolent compiler, such as javac, within the JDK. Instead, a fail-safe stance assumes that class files are hostile unless clearly proven otherwise.

In order to prove such an assertion, when Java bytecode is loaded, it first enters into a system known as the verifier. The verifier performs a number of checks upon all class files loaded into the Java execution environment. The verifier goes through a number of steps before approving of any loaded code:

The first pass-over ensures that the class file is of the proper general format.

The second check ensures that a number of Java conventions are upheld, such as checking that every class has a superclass (except the Object class) and that final classes and methods are not overridden.

The third step is the most detailed inspection of the class file. Within this step, the bytecodes themselves are examined to ensure their validity. This mechanism within the verifier is generally referred to as the bytecode verifier.

The last step performs some additional checks, such as ensuring the existence of class fields and the signature of methods.

For more detailed information on the verifier, read the paper by Frank Yellin entitled “Low Level Security,” available at URL:http://java.sun.com/sfaq/verifier.html.
 

Part Four: The ClassLoader

Bytecode that has reached this stage has been determined to be valid and then enters the ClassLoader, an object that subclasses the abstract class java.lang.ClassLoader. The ClassLoader loads applets incoming from the Net and subjects them to the restrictions of the Applet Security Manager, described in “Part Five: Establishing a Security Policy.” It strictly allocates namespaces for classes that are loaded into the runtime system. A namespace is conceptual real estate in which an object’s data structures can reside.

The ClassLoader ensures that objects don’t intrude into each other’s namespaces in unauthorized fashions. Public fields and methods may be accessed, but unless such an interface is defined, another object has no visibility to the variables. This point is important because system resources are accessed through specific classes—ones that are trusted to behave well and are installed within the JDK. If untrusted code was able to manipulate the data of the core Java API, disastrous results would ensue.

The ClassLoader also provides a strategic gateway for controlling which class code can be accessed. For example, applets are prevented from overriding any of the built-in Java classes, such as those that are provided within the Java API. Imported classes are prevented from impersonating built-in classes that are allowed to perform important system-related tasks. When a reference to an object is accessed, the namespace of built-in classes is checked first, thwarting any spoofing by network loaded classes.

Part Five: Establishing a Security Policy

The previous pieces of the Java security framework ensure that the Java system is not subverted by invalid code or a hostile compiler. Basically, they ensure that Java code plays by the rules. Given such an assurance, you are now able to establish a higher-level security policy. This security policy exists at the application level, allowing you to dictate what resources a Java program can access and manipulate.

The Java API provides the java.lang.SecurityManager class as a means of creating a clearly defined set of tasks an application can and cannot perform, such as access files or network resources. Java applications don’t start out with a SecurityManager, meaning that all resources it could restrict are freely available. However, by implementing a SecurityManager, you can add a significant measure of protection.

Java-enabled browsers use the SecurityManager to establish a security policy that greatly distinguishes what Java applets and Java applications can do. Later in the section “The SecurityManager Class,” such special restrictions are described in detail.

Putting It All Together

Figure 37.1 illustrates how these separate pieces of the framework interlock so as to provide a safe, secure environment. This careful structure establishes an intelligent, fail-safe stance for the execution of Java programs:


FIG. 37.1

A safe environment is created by different pieces working in a smooth fashion.

Applet Restrictions

Java applets are programs that extend the java.applet.Applet class. They can be seamlessly downloaded and executed by a Java-enabled browser, such as HotJava or Netscape. Prior to the JDK 1.1, there was no mechanism for establishing proof of ownership and trust of authorship. Thus, all applets must be assumed to be from an untrustworthy source.

Applets Versus Applications

An important point to realize when investigating Java security is the distinction between Java applets and Java applications. Applets are special programs that extend the Applet class. They can be dynamically executed within a browser merely by loading an HTML page that contains an APPLET element.

Applications, on the other hand, are executed directly by the Java interpreter. They must be manually installed on the local system and consciously executed by the user on that system. A Java browser does not execute these programs.

See "Developing an Application," Chapter 20 for more information.
 

Because of the differences between applets and applications, the two are allowed to execute under different security policies. It is assumed that during the manual installation process, the user has approved of the applications potential access to system resources. The application is trusted to the degree that it can open and write files, connect to various network resources, and execute a variety of programs on the local system. Such a policy is consistent with just about any other application that you would install on your personal computer.

Applets, on the other hand, are assumed to come from an untrusted source and could potentially perform harmful acts unless run within a carefully controlled execution environment.

The SecurityManager Class

Most of the security features that are added to Java applets are imposed by the class java.lang.SecurityManager, although (as previously mentioned), the use of a ClassLoader instance plays a significant role as well. The SecurityManager class allows you to establish a specific security policy that is appropriate to the level of trust given to a particular program. This abstract class provides the ability to create an object that determines whether an operation that a program intends to perform is permitted.

The SecurityManager has methods for performing the following acts to enforce a security policy:

The Security Policy of Java Browsers

Within the HotJava and Netscape browsers, a specific policy has been identified for the loading of untrusted applets. The SecurityManager performs a number of checks on a program's allowed actions, while the ClassLoader, which loads Java classes over the network, ensures that classes loaded from external systems do not subvert this security stance.

File readFile = new File("/etc/passwd");
FileInputStream readIn = new FileInputStream(readFile);

File writeData = new File("write.txt"); // Can't create files.
FileOutputStream out = new FileOutputStream(writeData);
out.write(1);
File oldName = new File("one.txt"); // Can't modify files, such as
File newName = new File("two.txt"); // by changing their names
oldName.renameTo(newName); // within directories.
File removeFile = new File("import.dat"); // Can't delete files.
removeFile.delete();

File isHere = new File("grades.dbm");
isHere.exists();

File createDir = new File("mydir");
createDir.mkdir();

String[] fileNames;
File lookAtDir = new File("/users/hisdir");
fileNames = lookAtDir.list();

File checkFile = new File("this.dat");
long checkSize;
boolean checkType;
long checkModTime;
checkSize = checkFile.length();
checkType = checkFile.isFile();
checkModTime = checkFile.lastModified();

// Can't open TCP socket.
Socket mailSocket = new Socket("mail.untrusted.org",25);
// The URL objects are similarly restricted.
URL untrustedWeb = new URL("http://www.untrusted.org/");
URLConnection agent = untrustedWeb.openConnection();
agent.connect();
// As are UDP datagrams.
InetAddress thatSite = new InetAddress("www.untrusted.org");
int thatPort = 7;
byte[] data = new byte[100];
DatagramPacket sendPacket =
new DatagramPacket(data,data.length,thatSite,thatPort);
DatagramSocket sendSocket = new DatagramSocket();
sendSocket.send(sendPacket);

As described later, however, it will be shown that this network connection restriction was not implemented completely. This deficiency has since been corrected.
 

 

See "Known Flaws," Chapter 37 for more information.
 

ServerSocket listener = new ServerSocket(8000);
listener.accept();

String command = "DEL \AUTOEXEC.BAT";
Runtime systemCommands = Runtime.getRuntime();
systemCommands.exec(command);

Runtime systemCommands = Runtime.getRuntime();
systemCommands.loadLibrary("local.dll");

// This mechanism fails.
Runtime systemCommands = Runtime.getRuntime();
systemCommands.exit(0);
// As does this mechanism.
System.exit(0);

Table 37.1 System Properties and Java Applets

Key Purpose Accessible to Applets?
file.separator The token used to separate files and directories on the filesystem (for example, "/" on UNIX and "\" on Windows NT/95). yes
java.class.path The CLASSPATH value used to search for classes to load. no
java.class.version The version of the Java API used. yes
java.home The directory in which the Java environment is installed. no
java.vendor A vendor-specific string used for identification purposes. yes
java.vendor.url URL of a resource identifying the vendor yes
java.version Version number of the Java interpreter. yes
line.separator The character(s) that separate lines on the system (for example, the linefeed character on UNIX, or a linefeed, carriage-return pair on Windows NT/95). yes
os.arch The operating system’s hardware architecture. yes
os.name The name of the operating system. yes
os.version Operating system version. yes
path.separator The token used to separate directories in a search-path specification (for example, ":" on UNIX and ";" on Windows NT/95) yes
user.dir The current working directory. no
user.home The user's home directory. no
user.name The account name of the user. no

As you might imagine, this policy presents a number of severe limitations that affect what your applets can and cannot do. One particular problem is that the Internet, by its very nature, is a distributed system. However, Java applets are prevented from accessing this web of computers—they can only connect to the machine from which they were downloaded.

Furthermore, because data cannot be written to the local system, applets cannot maintain a persistent state across executions on the client. As a work-around, applets must connect to a server to store state information, reloading that information from the original server when executed at a later time.

HotJava has a properties file that allows for certain of the previous restrictions to be relaxed for all applets. The HotJava User’s Guide provides more information on this process. More importantly, the new Java API provides the framework for creating specialized security policies for trusted applets loaded from known sources. This latter solution is described later within this chapter.

Java Security Problems

Despite its success and significant attention, Java is still a very immature system. Since the release of the 1.0 JDK, a number of practical flaws have been identified. Understanding these flaws will provide you with a feel for the medium into which your are immersing yourself.

An important point to note in this regard is the degree of openness that has been encouraged within the Java development arena. Obviously, companies such as Sun and others that have a significant stake in promoting Java suffer when a bug or flaw is revealed. Nevertheless, public scrutiny and critiques have been encouraged and generally well-received.

Based on the experience of most security professionals, such public review is an essential component of the development of a secure system. In most cases, it is impossible to prove a system is secure. A safe stance is to assume that a system with no known flaws is merely one with flaws that are waiting to be exposed and exploited. Peer review allows for various experts to search for these hidden flaws—a process that is very much familiar within the Internet community.

The opposing argument is that exposing the implementation of the system to the public allows untrusted and malicious individuals to identify and act on flaws before others can rectify the situation; by keeping a system secret, it is less likely that abusive hackers will discover these problems. Many experienced with Internet security disagree, believing that the obscuring the implementation is unwise: secrecy in design creates a system that is ultimately poorer while providing more opportunity for malevolence. Java's evolution has followed this philosophy, and from most practical observations, it appears that we have benefited.

A word to the wise: always treat with caution any supposedly secure system whose designer claims that the system’s security would be subverted by revealing the details of its implementation.
 

Known Flaws

During the first few months after the release of the Java Development Kit, a number of problematic issues were revealed. The following list is an overview of some of the flaws discovered in Java since its release:

Of the three mentioned flaws, the DNS attack identified first has received perhaps the most public attention. The basic problem lies within the enforcement of the security policy by the SecurityManager.

The applet policy enforced by Netscape and HotJava dictates that a network connection can only be opened by the applet to the machine from which it was downloaded. As indicated within Chapter 22, network computers identify each other on the Internet with IP addresses. The Domain Name System allows IP addresses to be associated in various ways, primarily enabling the use of human-understandable host names.

See "Internet Protocol (IP)," Chapter 22 for more information.
 

In the flawed SecurityManager, the IP address of the incoming applet would be used to look up the host name of the remote machine. Then, this host name would be used to look up the set of IP addresses to which it is mapped. Such a lookup should return at least the original IP address, but it may contain other IP addresses; such IP addresses may correspond to the same physical machine or completely separate machines.

Such a system might allow some flexibility in designing applets, allowing machines that share the same host name to spread out the responsibility for handling connections initiated from downloaded applets. However, such a system subtly violates the original security policy in a very significant way.

The DNS is a distributed resource. Various systems throughout the Internet are responsible for maintaining the integrity of specific parts. You have no ability to guarantee that a specific DNS server will not be broken into by hackers, and malicious individuals could easily set up their own DNS servers providing information that could exploit this leniency in the SecurityManager.

By design, the DNS is insecure. One could claim that Java should not be to blame for the limitations of such a commonly used system. However, this nature of the DNS is well-known to Internet security specialists, and it should have been anticipated.

One final point should be made about the problems found with the Java security system. The design of the system appears inherently sound. Rather, it is the implementation of that design which is not completely flawless, and such is to be expected of any technology as new as Java.

Denial-of-Service Attacks

The term denial-of-service is a standard way of describing a particular type of security attack. Such attacks are aimed at preventing you or anyone else from using your own computer, rather than attempting to obtain sensitive data from your systems. These attacks often utilize “brute force” to overload a system.

Denial-of-service attacks in areas other than Java include such factors as:

Most of these attacks exploit a resource’s own usefulness to make the system effectively useless. Because of this, it’s not completely practical or possible to completely prevent such attacks. Only by removing the features that make the system useful can it be protected.

Denial-of-service attacks are quite possible with Java applets. These attacks don’t require much imagination:

Currently, these types of attacks are identified as out of the scope of the Java security model. Java must continue to be useful. If applets have interesting and powerful capabilities, they could potentially exhaust the practical limitations of your computer. However, Sun continues to investigate the feasibility of controlling more closely the amount of system resources an applet can use.

To see what a denial-of-service attack through Java might look like, check out the following resource that collects such hostile applets for demonstrations:
 
<URL:http://www.math.gatech.edu/~mladue/HostileApplets.html>
 

The Java Security API: Expanding the Boundaries for Applets

By now, you have come to realize the significant, though prudent, limitations to which Java applets are held. These policies create a safe but restricted environment. When designing an applet to accomplish certain tasks, cumbersome work-arounds must be created, while other goals just can 2't be accomplished through applets.

This situation is necessary because all applets are treated as hostile—a fail-safe stance. However, in many situations, you are able to assert that certain programs are not hostile. For instance, applets distributed by a faithful vendor or provided from within your firewall may be reasonably expected to have greater access to system resources than a random applet loaded from someone’s Web page.

One of the key capabilities missing from the initial Java implementations was the ability to establish trust relationships. With Java 1.1 and the formation of the Java Security API, you have the ability to create these relationships and verify that code from these sources is not altered by an outside party.

The features of the Java Security API are based on computer cryptography designs and algorithms. A quick investigation of these concepts can help you understand how the Security API works.

Symmetric Cryptography

The cryptographic scheme that is most familiar to many is symmetric cryptography, or private-key encryption. The concept is that a special formula or process takes a piece of data and uses a special key, such as a password, to produce an encrypted block of data.

Given only the encrypted data, or ciphertext, it is difficult or impossible to reproduce the original copy. However, with the key, you can decrypt the ciphertext into the original message.

Thus, anyone with access to the key can easily decrypt the data. Because the security of this system depends on the secrecy of this key, this scheme is referred to as private key encryption. It is symmetrical in nature because the same key that is used to encrypt the data is required to decrypt the message. Figure 37.2 illustrates the private key encryption scheme.


FIG. 37.2

Private key cryptography uses the same key for encryption and decryption. To be secure, the key must be kept secret.

A number of cryptographic systems use private key cryptography. Data Encryption Standard (DES) is a widely used system; however, cracking it is practical with today’s technology. IDEA is a much newer algorithm and is believed to be much more secure than DES, although it has not been as thoroughly tested as DES. RC2 and RC4 are propriety algorithms distributed by RSA Data Security.

One of the problems with using private key encryption to protect communications is that both parties must have the same key. However, this exchange of private keys must be protected. Thus, in order to securely transmit documents, a secure mechanism of exchanging information must already exist.

Public Key Cryptography

Public key cryptography is a phenomenal idea. It is a radical system that is based on breakthroughs made during the 1970s. The concept is based on special mathematical algorithms.

A special formula is used to create two keys that are mathematically related, but neither can be induced from the other. One key is used to encrypt a particular message to produce a ciphertext. The other key is used to decrypt the message; however, the original key cannot be used to decrypt the ciphertext. Thus, this type of cryptography is referred to as asymmetric.

This system solves the problem of key distribution that limits private key cryptography. An individual who expects to receive protected documents can advertise one of the keys, generally referred to as the public key. Anyone who wishes to send an encrypted message to this person merely picks up the public key and creates the ciphertext. This encrypted message can be safely transmitted because only the other key can decrypt it. The recipient keeps the corresponding, or secret, key hidden from others because it is the only key that can be used to read messages encrypted by the public key. Figure 37.3 shows this mechanism.


FIG. 37.3

Public key cryptography provides a solution to key distribution.

Perhaps of more usefulness to Java applets, however, is the converse operation that is known as signing. Given a message, the secret key is used to create an encrypted signature. The unencoded message is transmitted along with the signature, and if the message is altered, the signature cannot be decrypted. Anyone who receives the message can obtain the freely available public key to ensure two things:

The process of signing messages through public key cryptography is shown in figure 37.4.


FIG. 37.4

Digital signatures can establish identity and data integrity.

Certification Authorities

One of the limitations in the public key system is verifying that a public key truly belongs to the individual you believe it does. It is conceivable that a hostile individual could send you a message signed with a secret key, claiming to be from another party. This attacker then advertises a public key as belonging to the impersonated person. You retrieve this key and decrypt the signature. Believing that you have verified the author, you now trust information that, unbeknownst to you, is written by a hostile source.

Secure transmission systems on the Web have turned to a system known as Certification Authorities (CA) to overcome this limitation. Basically, a CA is an organization or company that is very well-known and goes to great lengths to ensure that its public key is properly advertised. The CA then signs the key of other agencies that conclusively prove their identity. When you receive the public key of this agency, you can use the CA’s public key to verify it. If successful, you know that the CA believes this agency is what it claims to be. Thus, the CA certifies the agency.

If your Web browser implements a mechanism of secure communications such as SSL, you can see a list of some certificate authorities. Netscape is SSL-enabled—if you choose Options, Security Preferences, Site Certificates, you can see the certificates of the CAs distributed with the browser.

What Is Accomplished

After this lengthy discussion, you might be wondering why encryption can expand the capabilities of applets. As mentioned before, applets are assumed to be untrusted and potentially hostile. However, if an applet was digitally signed with public key cryptography, you could identify the company that created the applet and ensure that a hacker has not somehow altered what the company claims to have written.

Now you can establish trust relationships. You can assign specific roles to applets from known agents. For instance, you may purchase a stock quote service from a company. To use that service, you download an applet. Because you already have a relationship with that company and you want to trust the information it provides, you can feel comfortable in allowing the applet greater access to your local system:

It is important to note that other parts of the Java security framework are still in place. The bytecode is still verified to ensure validity. Furthermore, this isn’t an all-or-nothing proposition. Applets from trusted sources may be given incrementally greater access to your computer. (Review the various checks the SecurityManager class has available to get a feel for the gradations of increased access that could be allowed.) Finally, unsigned applets are still untrusted; they will still be subject to the same limitations that were in place prior to the release of the Java Security API.

Examples of Use

As of this writing, the Java Security API specification has yet to be released. All of these functions belong to the java.security package. Examples of use are found in listings 37.1 and 37.2. By the time this book is published, however, the released API may prove to be significantly different.

The Security API provides support for symmetric encryption systems. For example, Listing 37.1 demonstrates the use of it for loading and encrypting a file with DES.

Listing 37.1 An example of DES encryption.

File plaintext; // The plaintext file.
SymmetricCypher desEncrypt; // An object for encryption.
FileInputStream readFile; // To read in the file.
int nextChar; // Read chars into this.
StringBuffer inputBuffer; // Place chars into buffer.
byte[] documentBytes; // Byte array for data.
String fileAsString;
CryptoRandom rand;
byte[] cryptoKey; // Session key.
byte[] ciphertext; // Encrypted data
// Load in the plaintext file.
plaintext = new File(“plain.txt”);
readFile = new FileInputStream(plaintext);
inputBuffer = new StringBuffer();
// Read it into our buffer.
while((nextChar = readFile.read()) != -1) {
inputBuffer.append((char)nextChar);
}
// Place the data into a byte array.
fileAsString = inputBuffer.toString;
documentBytes = new byte[fileAsString.length()];
fileAsString.getBytes(0,fileAsString.length(),documentBytes,0);
// Set up our encryption system. Use DES.
desEncrypt = new SymmetricCipher(“DES”);
rand = new CryptoRandom();
cryptoKey = desEncrypt.initialize(rand);
// Encrypt the data.
ciphertext = desEncrypt.encrypt(documentBytes);

Listing 37.2 shows an example of signing a document with public key cryptography.

Listing 37.2 An example of signing with public key cryptography.

File specialFile; // The file to sign.
Signature dsaSignature; // Use to sign file.
FileInputStream readFile; // To read in the file.
int nextChar; // Read chars into this.
StringBuffer inputBuffer; // Place chars into buffer.
byte[] documentBytes; // Byte array for data.
String fileAsString;
byte[] digiSignature; // The digital signature.
// Load in the plaintext file.
specialFile = new File(“my.data”);
readFile = new FileInputStream(specialFile);
inputBuffer = new StringBuffer();
// Read it into our buffer.
while((nextChar = readFile.read()) != -1) {
inputBuffer.append((char)nextChar);
}
// Place the data into a byte array.
fileAsString = inputBuffer.toString;
documentBytes = new byte[fileAsString.length()];
fileAsString.getBytes(0,fileAsString.length(),documentBytes,0);
dsaSignature = new Signature(“dsa”);
// thisKey is an instance of java.security.Entity loaded
// from the local key database.
dsa.initialize(thisKey);
digitalSingature = dsaSignature.sign(documentBytes);


Previous Page TOC Next Page

| Previous Chapter | Next Chapter |

|Table of Contents | Book Home Page |

| Que Home Page | Digital Bookshelf | Disclaimer |


To order books from QUE, call us at 800-716-0044 or 317-361-5400.

For comments or technical support for our books and software, select Talk to Us.

© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company