Movatterモバイル変換


[0]ホーム

URL:


Java SE 25 & JDK 25

JAR File Specification

Introduction

JAR file is a file format based on the popular ZIP file format and isused for aggregating many files into one. A JAR file is essentially azip file that contains an optional META-INF directory. A JAR file can becreated by the command-line jar tool, or by using thejava.util.jarAPI in the Java platform. There is no restriction on the name of a JARfile, it can be any legal file name on a particular platform.

Modular JAR files

A modular JAR file is a JAR file that has a module descriptor,module-info.class, in the top-level directory (or root)directory. The module descriptor is the binary form of a moduledeclaration. (Note the section onmulti-release JAR files furtherrefines the definition of modular JAR files.)

A modular JAR file deployed on the module path, as opposed to theclass path, is anexplicit module. Dependences and serviceproviders are declared in the module descriptor. If the modular JAR fileis deployed on the class path then it behaves as if a non-modular JARfile.

A non-modular JAR file deployed on the module path is anautomatic module. If the JAR file has a main attributeAutomatic-Module-Name (seeMainAttributes) then the attribute's value is the module name, otherwisethe module name is derived from the name of the JAR file as specified inModuleFinder.of(Path...).

Multi-release JAR files

A multi-release JAR file allows for a single JAR file to supportmultiple major versions of Java platform releases. For example, amulti-release JAR file can depend on both the Java 8 and Java 9 majorplatform releases, where some class files depend on APIs in Java 8 andother class files depend on APIs in Java 9. This enables library andframework developers to decouple the use of APIs in a specific majorversion of a Java platform release from the requirement that all theirusers migrate to that major version. Library and framework developerscan gradually migrate to and support new Java features while stillsupporting the old features.

A multi-release JAR file is identified by the main attribute:

Multi-Release: true

declared in the main section of theJARManifest.

Classes and resource files dependent on a major version, 9 orgreater, of a Java platform release may be located under aversioneddirectory instead of under the top-level (or root) directory. Theversioned directory is located under thethe META-INF directory and is of theform:

META-INF/versions/N

where N is the string representation of the major version number of aJava platform release. SpecificallyN must conform to thespecification:

N:{1-9}{0-9}*

Any versioned directory whose value ofN is less than9 is ignored as is a string representation ofN that does not conform to the above specification.

A class file under a versioned directory, of versionNsay, in a multi-release JAR must have a class file version less than orequal to the class file version associated withNth majorversion of a Java platform release. If the class of the class file ispublic or protected then that class mustpreside over a classof the same fully qualified name and access modifier whose class file ispresent under the top-level directory. By logical extension this appliesto a class of a class file, if present, under a versioned directorywhose version is less thanN.

If a multi-release JAR file is deployed on the class path or modulepath (as an automatic module or an explicitmulti-release module) ofmajor versionN of a Java platform release runtime, then aclass loader loading classes from that JAR file will first search forclass files under theNth versioned directory, then priorversioned directories in descending order (if present), down to a lowermajor version bound of9, and finally under the top-leveldirectory.

The public API exported by the classes in a multi-release JAR filemust beexactly the same across versions, hence at a minimumwhy versioned public or protected classes for class files under aversioned directory must preside over classes for class files under thetop-level directory. It is difficult and costly to perform extensive APIverification checks as such tooling, such as thejar tool,is not required to perform extensive verification and a Java runtime isnot required to perform any verification. A future release of thisspecification may relax the exact same API constraint to support carefulevolution.

Resources under theMETA-INF directory cannot beversioned (such as for service configuration).

A multi-release JAR file can be signed.

Multi-release JAR files are not supported by the boot class loader ofa Java runtime. If a multi-release JAR file is appended to the bootclass path (with the-Xbootclasspath/a option) then the JARis treated as if it is an ordinary JAR file.

Modular multi-release JARfiles

A modular multi-release JAR file is a multi-release JAR file that hasa module descriptor,module-info.class, in the top-leveldirectory (as for amodular JAR file),or directly in a versioned directory.

A public or protected class in a non-exported package (that is notdeclared as exported in the module descriptor) need not preside over aclass of the same fully qualified name and access modifier whose classfile is present under the top-level directory.

A module descriptor is generally treated no differently to any otherclass or resource file. A module descriptor may be present under aversioned area but not present under the top-level directory. Thisensures, for example, only Java 8 versioned classes can be present underthe top-level directory while Java 9 versioned classes (including, orperhaps only, the module descriptor) can be present under the9 versioned directory.

Any versioned module descriptor that presides over a lesser versionedmodule descriptor or that at the top-level,M say, must beidentical toM, with two exceptions:

  1. the presiding versioned descriptor can have differentnon-transitiverequires clauses ofjava.* andjdk.* modules; and
  2. the presiding versioned descriptor can have differentuses clauses, even of service types defined outside ofjava.* andjdk.* modules.

Tooling, such as thejar tool, should perform suchverification of versioned module descriptors but a Java runtime is notrequired to perform any verification.

The META-INF directory

The following files/directories in the META-INF directory arerecognized and interpreted by the Java Platform to configureapplications, class loaders and services:

The manifest file that is used to define package related data.

The signature file for the JAR file. 'x' stands for the base filename.

The signature block file associated with the signature file with thesame base file name. This file stores the digital signature of thecorresponding signature file in a PKCS #7 structure.

This directory stores all the service provider configuration filesfor JAR files deployed on the class path or JAR files deployed asautomatic modules on the module path. See the specification ofserviceprovider development for more details.

This directory contains underneath it versioned class and resourcefiles for amulti-release JARfile.

Name-Value pairs andSections

Before we go to the details of the contents of the individualconfiguration files, some format convention needs to be defined. In mostcases, information contained within the manifest file and signaturefiles is represented as so-called "name: value" pairs inspired by theRFC822 standard. We also call these pairs headers or attributes.

Groups of name-value pairs are known as a "section". Sections areseparated from other sections by empty lines.

Binary data of any form is represented as base64. Continuations arerequired for binary data which causes line length to exceed 72 bytes.Examples of binary data are digests and signatures.

Implementations shall support header values of up to 65535 bytes.

All the specifications in this document use the same grammar in whichterminal symbols are shown in fixed width font and non-terminal symbolsare shown in italic type face.

Specification:

section:*header +newline
nonempty-section:+header +newline
newline:CR LF | LF | CR (notfollowed byLF)
header:name:value
name:alphanum *headerchar
value:SPACE *otherchar newline*continuation
continuation:SPACE*otherchar newline
alphanum:{A-Z} | {a-z} |{0-9}
headerchar:alphanum |- |_
otherchar:any UTF-8 character exceptNUL, CRandLF

Non-terminal symbols defined in the above specification will bereferenced in the following specifications.

JAR Manifest

Overview

A JAR file manifest consists of a main section followed by a list ofsections for individual JAR file entries, each separated by a newline.Both the main section and individual sections follow the section syntaxspecified above. They each have their own specific restrictions andrules.

Manifest Specification:

manifest-file:main-section newline*individual-section
main-section:version-info newline*main-attribute
version-info:Manifest-Version :version-number
version-number:digit+{.digit+}*
main-attribute:(any legitimate main attribute)newline
individual-section:Name :valuenewline *perentry-attribute
perentry-attribute:(any legitimate perentry attribute)newline
newline:CR LF | LF | CR (notfollowed byLF)
digit:{0-9}

In the above specification, attributes that can appear in the mainsection are referred to as main attributes, whereas attributes that canappear in individual sections are referred to as per-entry attributes.Certain attributes can appear both in the main section and theindividual sections, in which case the per-entry attribute valueoverrides the main attribute value for the specified entry. The twotypes of attributes are defined as follows.

Main Attributes

Main attributes are the attributes that are present in the mainsection of the manifest. They fall into the following differentgroups:

In addition to the above Main attributes defined by the JavaPlatform, the JDK Reference Implementation also supports the followingattributes for stand-alone applications that are bundled into executableJAR files. These attributes are ignored for JAR files that are not runwith "java -jar x.jar".

Per-Entry Attributes

Per-entry attributes apply only to the individual JAR file entry towhich the manifest entry is associated with. If the same attribute alsoappeared in the main section, then the value of the per-entry attributeoverwrites the main attribute's value. For example, if JAR file a.jarhas the following manifest content:

        Manifest-Version: 1.0        Created-By: 1.8 (Oracle Inc.)        Sealed: true        Name: foo/bar/        Sealed: false

It means that all the packages archived in a.jar are sealed, exceptthat package foo.bar is not.

The per-entry attributes fall into the following groups:

Signed JAR File

Overview

A JAR file can be signed by using the command line jarsigner tool ordirectly through thejava.security API. Every file entry,including non-signature related files in theMETA-INFdirectory, will be signed if the JAR file is signed by the jarsignertool. The signature related files are:

Note that if such files are located inMETA-INFsubdirectories, they are not considered signature-related.Case-insensitive versions of these filenames are reserved and will alsonot be signed.

Subsets of a JAR file can be signed by using thejava.security API. A signed JAR file is exactly the same asthe original JAR file, except that its manifest is updated and twoadditional files are added to theMETA-INF directory: asignature file and a signature block file. When jarsigner is not used,the signing program has to construct both the signature file and thesignature block file.

For every file entry signed in the signed JAR file, an individualmanifest entry is created for it as long as it does not already exist inthe manifest. Each manifest entry lists one or more digest attributesand an optionalMagic attribute.

Signature File

Each signer is represented by a signature file with extension.SF. The major part of the file is similar to the manifestfile. It consists of a main section which includes information suppliedby the signer but not specific to any particular jar file entry. Inaddition to theSignature-Version andCreated-By attributes (seeMainAttributes), the main section can also include the followingsecurity attributes:

The main section is followed by a list of individual entries whosenames must also be present in the manifest file. Each individual entrymust contain at least the digest of its corresponding entry in themanifest file.

Paths or URLs appearing in the manifest file but not in the signaturefile are not used in the calculation.

Signature Validation

A successful JAR file verification occurs if the signature(s) arevalid, and none of the files that were in the JAR file when thesignatures were generated have been changed since then. JAR fileverification involves the following steps:

  1. Verify the signature over the signature file when the manifest isfirst parsed. For efficiency, this verification can be remembered. Notethat this verification only validates the signature directionsthemselves, not the actual archive files.

  2. If anx-Digest-Manifest attribute exists in thesignature file, verify the value against a digest calculated over theentire manifest. If more than onex-Digest-Manifestattribute exists in the signature file, verify that at least one of themmatches the calculated digest value.

  3. If anx-Digest-Manifest attribute does not exist inthe signature file or none of the digest values calculated in theprevious step match, then a less optimized verification isperformed:

    1. If anx-Digest-Manifest-Main-Attributes entry existsin the signature file, verify the value against a digest calculated overthe main attributes in the manifest file. If this calculation fails,then JAR file verification fails. This decision can be remembered forefficiency. If anx-Digest-Manifest-Main-Attributes entrydoes not exist in the signature file, its nonexistence does not affectJAR file verification and the manifest main attributes are notverified.

    2. Verify the digest value in each source file information sectionin the signature file against a digest value calculated against thecorresponding entry in the manifest file. If any of the digest valuesdon't match, then JAR file verification fails.

    One reason the digest value of the manifest file that is stored inthex-Digest-Manifest attribute may not equal the digestvalue of the current manifest file is that it might contain sections fornewly added files after the file was signed. For example, suppose one ormore files were added to the JAR file (using the jar tool) after thesignature (and thus the signature file) was generated. If the JAR fileis signed again by a different signer, then the manifest file is changed(sections are added to it for the new files by the jarsigner tool) and anew signature file is created, but the original signature file isunchanged. A verification on the original signature is still consideredsuccessful if none of the files that were in the JAR file when thesignature was generated have been changed since then, which is the caseif the digest values in the non-header sections of the signature fileequal the digest values of the corresponding sections in the manifestfile.

  4. For each entry in the manifest, verify the digest value in themanifest file against a digest calculated over the actual datareferenced in the "Name:" attribute, which specifies either a relativefile path or URL. If any of the digest values don't match, then JAR fileverification fails.

Example manifest file:

    Manifest-Version: 1.0    Created-By: 1.8.0 (Oracle Inc.)    Name: common/class1.class    SHA-256-Digest: (base64 representation of SHA-256 digest)    Name: common/class2.class    SHA1-Digest: (base64 representation of SHA1 digest)    SHA-256-Digest: (base64 representation of SHA-256 digest)

The corresponding signature file would be:

    Signature-Version: 1.0    SHA-256-Digest-Manifest: (base64 representation of SHA-256 digest)    SHA-256-Digest-Manifest-Main-Attributes: (base64 representation of SHA-256 digest)    Name: common/class1.class    SHA-256-Digest: (base64 representation of SHA-256 digest)    Name: common/class2.class    SHA-256-Digest: (base64 representation of SHA-256 digest)

The Magic Attribute

Another requirement to validate the signature on a given manifestentry is that the verifier understand the value or values of the Magickey-pair value in that entry's manifest entry.

The Magic attribute is optional but it is required that a parserunderstand the value of an entry's Magic key if it is verifying thatentry's signature.

The value or values of the Magic attribute are a set ofcomma-separated context-specific strings. The spaces before and afterthe commas are ignored. Case is ignored. The exact meaning of the magicattributes is application specific. These values indicate how to computethe hash value contained in the manifest entry, and are thereforecrucial to the proper verification of the signature. The keywords may beused for dynamic or embedded content, multiple hashes for multilingualdocuments, etc.

Here are two examples of the potential use of Magic attribute in themanifest file:

        Name: http://www.example-scripts.com/index#script1        SHA-256-Digest: (base64 representation of SHA-256 hash)        Magic: JavaScript, Dynamic        Name: http://www.example-tourist.com/guide.html        SHA-256-Digest: (base64 representation of SHA-256 hash)        SHA-256-Digest-French: (base64 representation of SHA-256 hash)        SHA-256-Digest-German: (base64 representation of SHA-256 hash)        Magic: Multilingual

In the first example, these Magic values may indicate that the resultof an http query is the script embedded in the document, as opposed tothe document itself, and also that the script is generated dynamically.These two pieces of information indicate how to compute the hash valueagainst which to compare the manifest's digest value, thus comparing avalid signature.

In the second example, the Magic value indicates that the documentretrieved may have been content-negotiated for a specific language, andthat the digest to verify against is dependent on which language thedocument retrieved is written in.

Digital Signatures

A digital signature is a signed version of the.SFsignature file. These are binary files not intended to be interpreted byhumans.

Digital signature files have the same filenames as the .SF files butdifferent extensions. The extension varies depending on the algorithm ofthe signer's private key.

Digital signature files not using the PKCS #7 format must reside intheMETA-INF directory and have the prefix"SIG-". The corresponding signature file (.SFfile) must also have the same prefix.`For those formats that do not support external signed data, the file shall consist of a signed copy of the.SF`file. Thus some data may be duplicated and a verifier should compare thetwo files.

Formats that support external data either reference the.SF file, or perform calculations on it with implicitreference.

Each.SF file may have multiple digital signatures, butthose signatures should be generated by the same legal entity.

File name extensions may be 1 to 3alphanum characters.Unrecognized extensions are ignored.

Notes on Manifest andSignature Files

Following is a list of additional restrictions and rules that applyto manifest and signature files.

Class-Path Attribute

The manifest for an application can specify one or more relative URLsreferring to the JAR files and directories for other libraries that itneeds. These relative URLs will be treated relative to the code basethat the containing application was loaded from (the "contextJAR").

An application (or, more generally, JAR file) specifies the relativeURLs of the libraries that it needs via the manifest attributeClass-Path. This attribute lists the URLs to search forimplementations of other libraries if they cannot be found on the hostJava Virtual Machine. These relative URLs may include JAR files anddirectories for any libraries or resources needed by the application.Relative URLs not ending with '/' are assumed to refer to JAR files. Forexample,

Class-Path: servlet.jar infobus.jar acme/beans.jar images/

At most oneClass-Path header may be specified in a JARfile's manifest.

AClass-Path entry is valid if the following conditionsare true:

Invalid entries are ignored. Valid entries are resolved against thecontext JAR. If the resulting URL is invalid or refers to a resourcethat cannot be found, then it is ignored. Duplicate URLs areignored.

The resulting URLs are inserted into the class path, immediatelyfollowing the URL of the context JAR. For example, given the followingclass path:

a.jar b.jar

Ifb.jar contained the followingClass-Pathmanifest attribute:

Class-Path: lib/x.jar a.jar

Then the effective search path of such aURLClassLoaderinstance would be:

a.jar b.jar lib/x.jar

Of course, ifx.jar had dependencies of its own thenthese would be added according to the same rules and so on for eachsubsequent URL. In the actual implementation, JAR file dependencies areprocessed lazily so that the JAR files are not actually opened untilneeded.

Package Sealing

JAR files and packages can be optionallysealed, so that anpackage can enforce consistency within a version.

A package sealed within a JAR specifies that all classes defined inthat package must originate from the same JAR. Otherwise, aSecurityException is thrown.

A sealed JAR specifies that all packages defined by that JAR aresealed unless overridden specifically for a package.

A sealed package is specified via the manifest attribute,Sealed, whose value istrue orfalse (case irrelevant). For example,

    Name: javax/servlet/internal/    Sealed: true

specifies that thejavax.servlet.internal package issealed, and that all classes in that package must be loaded from thesame JAR file.

If this attribute is missing, the package sealing attribute is thatof the containing JAR file.

A sealed JAR is specified via the same manifest header,Sealed, with the value again of eithertrue orfalse. For example,

    Sealed: true

specifies that all packages in this archive are sealed unlessexplicitly overridden for a particular package with theSealed attribute in a manifest entry.

If this attribute is missing, the JAR file is assumed tonotbe sealed, for backwards compatibility. The system then defaults toexamining package headers for sealing information.

Package sealing is also important for security, because it restrictsaccess to package-protected members to only those classes defined in thepackage that originated from the same JAR file.

The unnamed package is not sealable, so classes that are to be sealedmust be placed in their own packages.

API Details

Packagejava.util.jar

See Also

Packagejava.security
Packagejava.util.zip


[8]ページ先頭

©2009-2025 Movatter.jp