JAR file revealed

Source: Internet
Author: User
Tags sha1

Explore the powerful features of the JAR file format

Most Java programmers are familiar with the basic operation of the JAR file. But only a handful of programmers understand the powerful features of the JAR file format. In this article, the author explores many of the features and benefits of the jar format, including packaging, executable jar files, security, and indexes.

What is a JAR file?

The JAR file format is based on a popular ZIP file format that aggregates many files into one file. Unlike ZIP files, JAR files are not only used for compression and publishing, but are also used to deploy and encapsulate libraries, components, and plug-ins, and can be used directly by tools such as compilers and JVMs. The jar contains special files, such as manifests and deployment descriptors, to indicate how the tool handles a particular JAR.

A JAR file can be used to:

    • For publishing and using class libraries
    • As an application and an extended build unit
    • As a deployment unit for a component, applet, or plug-in program
    • Used to package the secondary resources associated with a component

The JAR file format offers many advantages and functionality, many of which are traditional compression formats such as ZIP or TAR that are not available. They include:

    • security. You can digitally sign the contents of a JAR file. This way, a signature-aware tool can selectively grant you software security privileges, which cannot be done by other files, and it can also detect if the code has been tampered with.
    • reduce download time. If an applet is bundled into a JAR file, the browser can download the applet's class file and related resources in an HTTP transaction instead of opening a new connection to each file.
    • compression. The JAR format allows you to compress files to improve storage efficiency.
    • Transport platform Extensions. the Java Extension Framework (Java Extensions Framework) provides a way to add functionality to the Java core platform, which is packaged with JAR files (Java and JavaMail are examples of extensions developed by Sun).
    • Package seal. packages stored in JAR files can optionally be sealed to enhance version consistency and security. Sealing a package means that all classes in the package must be found in the same JAR file.
    • Package version control. A JAR file can contain data about the files it contains, such as vendor and version information.
    • portability. the mechanism for working with JAR files is a standard part of the Java platform core API.
Compressed and uncompressed jars

jarTools (see Tools for details jar ) compress files by default. Uncompressed jar files can generally be loaded faster than compressed jar files because the files are uncompressed during the load, but uncompressed files may take longer to download on the network.

Meta-inf Directory

Most JAR files contain a meta-inf directory, which is used to store package and extended configuration data, such as security and version information. The Java 2 platform identifies and interprets the following files and directories in the Meta-inf directory in order to configure applications, extensions, and class loaders:

    • MANIFEST. Mf. This manifest file defines the data associated with the extension and the package.
    • INDEX. LIST. This file is jar generated by a new option for the tool that -i contains the location information for the package defined in the application or extension. It is part of the Jarindex implementation and is used by the class loader to speed up the class loading process.
    • xxx. SF. This is the signature file for the JAR file. Placeholder xxx identifies the signer.
    • xxx. Dsa. the signature block file associated with the signature file, which stores the public signature used to sign the JAR file.
Jar Tool

To perform basic tasks with JAR files, use the Java Archive Tool (tools) provided as part of the Java development Kit jar . Invoke the tool with a jar command jar . Table 1 shows some of the most common applications:

Table 1. of common jarTool usage
function Command
Create a JAR file with a separate file Jar CF Jar-file Input-file ...
Create a JAR file with a directory Jar CF Jar-file Dir-name
Create an uncompressed JAR file Jar Cf0 Jar-file Dir-name
Update a JAR file Jar UF jar-file input-file ...
View the contents of a JAR file Jar TF Jar-file
Extracting the contents of a JAR file Jar XF Jar-file
Extracting a specific file from a JAR file Jar XF Jar-file archived-file ...
Run an application packaged as an executable JAR file Java-jar App.jar
The executable JAR

An executable jar file is a self-contained Java application that is stored in a specially configured jar file that can be executed directly by the JVM without having to extract the files beforehand or set the classpath. To run an application stored in a non-executable JAR, you must add it to your classpath and invoke the application's main class by name. But with an executable JAR file, we can run an application without extracting it or knowing the main entry point. Executable jars facilitate the publishing and execution of Java applications.

Creating an executable JAR

Creating an executable JAR is easy. First put all the application code in a directory. Suppose the main class in the application is com.mycompany.myapp.Sample . You want to create a JAR file that contains the application code and identify the main class. To do this, create a file named in a location (not in the application directory) manifest and include the following line in it:

Main-class:com.mycompany.myapp.sample

Then, create the JAR file like this:

Jar CMF Manifest Executablejar.jar application-dir

That's all you have to do--now you can java -jar execute the JAR file Executablejar.jar.

An executable jar must refer to all other dependent jars it requires through the header of the Menifest file. If an option is used -jar , the environment variable CLASSPATH and any classpath specified on the command line are ignored by the JVM.

Start the executable JAR

Now that we have packaged our application in an executable jar called Executablejar.jar, we can start the application directly from the file using the following command:

Java-jar Executablejar.jar

Package Seal

Sealing a package In a jar file means that all classes defined in the package must be found in the same jar file. This enables the author of the package to enhance version consistency between packaged classes. The seal also provides a means of preventing code tampering.

To seal a package, you need to add a header to the package in the JAR's manifest file and a header with a Name value of "true" Sealed . As with an executable jar, you can seal a jar by specifying a manifest file with the appropriate header element when creating the jar, as follows:

name:com/samplepackage/  Sealed:true

NameThe header identifies the relative path name of the package. It ends with a "/" to distinguish it from the file name. Nameall headers before the first empty line behind the header are used for the Name file or package specified in the header. In the above example, the header is Sealed Name Sealed interpreted as only applied to the package because the header appears behind the head and there is no blank line in the middle com/samplePackage .

If you attempt to load a class in a sealed package from somewhere other than the JAR file where the sealed package resides, the JVM throws one SecurityException .

Extended packaging
Extensions add functionality to the Java platform, and extension mechanisms have been added to the JAR file format. The extension mechanism allows the jar file to Class-Path specify additional jar files as required by the headers in the manifest file.

Assuming that Extension1.jar and Extension2.jar are two jar files in the same directory, Extension1.jar's manifest file contains the following head:

Class-path:extension2.jar

This header indicates that the class in Extension2.jar is an extended class of classes in Extension1.jar. Classes in Extension1.jar can call classes in Extension2.jar and do not require Extension2.jar to be in the classpath.

When loading jars that use the extension mechanism, the JVM effectively and automatically Class-Path adds the jar referenced in the header to the classpath. However, the extended jar path is interpreted as a relative path, so in general, the extension jar must be stored in the same directory as the jar that references it.

For example, suppose a class ExtensionClient refers ExtensionDemo to a class that is bundled in a jar file named Extensionclient.jar, and the class ExtensionDemo is bundled in Extensiondemo.jar. In order for the Extensiondemo.jar to be an extension, Extensiondemo.jar must be listed in the manifest header of Extensionclient.jar Class-Path , as follows:

1.0   Class-path:extensiondemo.jar

The value of the header in this manifest Class-Path is extensiondemo.jar with no path specified, indicating that Extensiondemo.jar is in the same directory as the Extensionclient jar file.

Security in the JAR file

JAR files can be jarsigner signed with tools or directly through the java.security API. A signed jar file is identical to the original jar file, just updates its manifest and adds two files, a signature file, and a signature block file to the Meta-inf directory.

The JAR file is signed with a certificate stored in the Keystore database. The certificate stored in KeyStore is password protected and must be provided to the jarsigner tool to sign the JAR file.

Figure 1. Keystore Database

Each signer of the jar is made up of one of the meta-inf directories in the jar file. A signature file representation of the SF extension. The format of this file is similar to the manifest file-a set of RFC-822 headers. As shown below, its composition includes a major part that includes information provided by the signer, but not specifically for any particular JAR file entry, and a series of separate items that must also be included in the Menifest file. When validating a signed jar, the digest value of the signature file is compared to the digest value computed for the corresponding item in the JAR file.

Listing 1. Manifest and signature files in the signature JAR
Contents of signature file meta-inf/manifest. MF  manifest-version:1.0  created-by:1.3.0 (Sun Microsystems Inc.)  Name:Sample.java  sha1-digest:3+ddyw8inictyg8zarhlfxx0w6g=  Name:Sample.class  sha1-digest: yj5yqhbzbj3sstnchjfqukfwemi=  Contents of signature file meta-inf/james. SF  signature-version:1.0  sha1-digest-manifest:hbstzojbuutj6qmidb90t8sjaom=  created-by:1.3.0 (Sun Microsystems INC)  Name:Sample.java  sha1-digest:qipmdrkurqckwnyili3jtrnia8q=  Name:Sample.class  sha1-digest: pt2dyby8qxpcczv2nwplxd8p4g4=

Digital signatures

A digital signature is. The signed version of the SF signature file. The digital signature file is a binary file and is associated with the. SF files have the same file name but different extension names. There are different extensions depending on the type of digital signature-RSA, DSA, or PGP-and the type of certificate used to sign the JAR.

Keystore

To sign a JAR file, you must first have a private key. The private key and its associated public key certificate are stored in a keystores password-protected database named. The JDK contains tools for creating and modifying Keystores. Each key in the KeyStore can be identified by an alias, which is usually the name of the signer who owns the key.

All KeyStore entries (keys and trusted certificate entries) are accessed with a unique alias. Aliases are keytool -genkey specified when generating a key pair (public and private) with a command and adding an item in KeyStore. Subsequent keytool commands must use the same alias to refer to this item.

For example, to generate a new public/private key pair with the alias "James" and wrap the public key into a self-signed certificate, use the following command:

Keytool-genkey-alias james-keypass jamespass         -validity 80-keystore jameskeystore         -storepass Jameskeystorepass

This command sequence specifies an initial password of "Jamespass", which is required for subsequent commands to access the private key associated with the alias "James" in KeyStore "Jameskeystore". If KeyStore "Jameskeystore" does not exist, keytool it is created automatically.

Jarsigner Tools

jarsignerThe tool uses KeyStore to generate or verify the digital signature of the JAR file.

Assuming that KeyStore "Jameskeystore" is created as in the example above, and that it contains a key with an alias of "James", you can sign a JAR file with the following command:

Jarsigner-keystore jameskeystore-storepass jameskeystorepass           -keypass Jamespass-signedjar SSample.jar Sample.jar James

This command uses the password "Jameskeystorepass" from the name "Jameskeystore" in the KeyStore named "James", the password is "Jamespass" key, and the Sample.jar file signature, create a signed JAR--Ssample.jar.

jarsignerThe tool can also validate a signed Jar file, which is much simpler than signing the jar file by simply executing the following command:

Jarsigner-verify Ssample.jar

If the signed JAR file has not been tampered with, then the jarsigner tool will tell you that the jar is validated. Otherwise, it throws one SecurityException that indicates which files did not pass the validation.

You can also use the java.util.jar and java.security API to programmatically sign jars (see Resources for details). You can also use tools such as the Netscape Object Signing tool.

JAR Index

If an application or applet is bundled into multiple jar files, the class loader uses a simple linear search algorithm to search for each element in the Classpath, which allows the class loader to download and open many jar files until the desired class or resource is found. If the class loader tries to find a resource that does not exist, all the JAR files in the application or applet are downloaded. For large network applications and applets, this can lead to slow startup, slow response, and wasted bandwidth.

Since JDK 1.3, the JAR file format began to support indexing to optimize the search process for classes in network applications, especially applets. The Jarindex mechanism collects the contents of all JAR files defined in an applet or application and stores that information in an index file in the first JAR file. When the first jar file is downloaded, the Applet class loader uses the collected content information to efficiently load the jar file. This directory information is stored in the Meta-inf directory of the root JAR file named INDEX. List in a simple text file.

Create a Jarindex
You can jar create a jarindex by specifying options in the command -i . Let's say our directory structure looks like this:

Figure 2. Jarindex

You will create an index file for Jarindex_main.jar, Jarindex_test.jar, and Jarindex_test1.jar using the following command:

Jar-i Jarindex_main.jar Jarindex_test.jar Sampledir/jarindex_test1.jar

INDEX. The format of the LIST file is simple, containing the name of the package or class contained in each indexed JAR file, as shown in Listing 2:

Listing 2. Jarindex INDEX. LIST File Example
jarindex-version:1.0  Jarindex_main.jar  sp  jarindex_test.jar  Sample  sampledir/jarindex_ Test1.jar  org  org/apache  org/apache/xerces  org/apache/xerces/framework  org/apache/xerces/ Framework/xml4j
Conclusion

The JAR format is far beyond a compressed format and has many features that improve efficiency, security, and organization of Java applications. Because these features are already built into the core platform-including compilers and class loaders-developers can leverage the ability of the JAR file format to simplify and improve the development and deployment process.

JAR file revealed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.