The JKS format has no published specification; it is defined by the code that writes
it, sun.security.provider.JavaKeyStore and
sun.security.provider.KeyProtector in the OpenJDK source, which this page
follows (the JCEKS section follows com.sun.crypto.provider.JceKeyStore and
com.sun.crypto.provider.KeyProtector). Numbers are big-endian (“high byte
first”), as Java’s DataOutputStream writes them; strings are written with
writeUTF: a 2-byte length then modified UTF-8 (java.io.DataOutputStream
documentation).
File
| Field | Type | Description |
|---|---|---|
| Magic | int | FE ED FE ED. |
| Version | int | 2 (engineStore always writes the latest version); 1 is still read. Version 1 has no certificate type strings, and engineLoad reads every certificate with an X.509 certificate factory. |
| Count | int | Number of entries. |
| Entries | – | See entries. |
| Integrity hash | 20 bytes | See integrity. |
JKS loader rules
What JavaKeyStore.engineLoad accepts and refuses (OpenJDK master, raw
JavaKeyStore.java; the key-protection rules are in
KeyProtector.java of the same package):
- the magic must be
FE ED FE EDand the version 1 or 2; anything else is refused as an invalid format. (The JCEKS loader accepts two magics; the JKS loader only this one.) - the existing entries are cleared, then the count and that many entries are read. The tag must be 1 or 2; any other tag refuses the file. A count of 0 or less reads no entries (the loop runs while i < count).
- every length-prefixed byte block (a protected key, a certificate) is read with
IOUtils.readExactlyNBytes: a negative length is refused (anIOException), and a length longer than the bytes left fails at the end of the stream (anEOFException). A UTF field (alias, certificate type) that runs past the end fails the same way. - in version 2, the certificate type string names a
CertificateFactory; a type the JDK has no factory for, or certificate bytes that factory cannot parse, refuses the file (aCertificateException). Version 1 reads every certificate as X.509. - a key entry’s chain count of 0 (or any value not above 0) means the entry has no chain; certificates are read only when the count is above 0.
- aliases are kept as read: the loader does not lower-case them (only the setters do), so an alias stored with capital letters is not found by a lookup through the
JKStype, which lower-cases the name it is asked for. - a duplicate alias is not rejected: entries are put in a table keyed by the alias, so the later entry replaces the earlier one, whichever kind each is. The result has fewer entries than the file’s count.
- with a password, the 20-byte closing hash is computed over everything read and compared with the 20 bytes that follow; a mismatch refuses the file, and the failure is marked as a wrong-password failure (an
IOExceptioncaused byUnrecoverableKeyException). With no password the integrity hash is not read and nothing is checked; bytes after the last entry are not looked at. - recovering a private key (
KeyProtector.recover): the EncryptedPrivateKeyInfo’s algorithm OID must be1.3.6.1.4.1.42.2.17.1.1, otherwise the key is refused; after decrypting, SHA-1(password ‖ plaintext key) must equal the 20-byte check at the end of the protected data, otherwise it is refused (“Cannot recover key”, anUnrecoverableKeyException; a wrong OID gives “Unsupported key protection algorithm”); then the plaintext must parse as a PKCS #8 key (PKCS8Key.parseKey), and a failure there is also anUnrecoverableKeyException; a null password is refused. Protected data shorter than 40 bytes (salt plus check) is not tested for, and fails with an unchecked array exception rather than a key exception.
Entries
Every entry starts:
| Field | Type | Description |
|---|---|---|
| Tag | int | 1 private key entry; 2 trusted certificate entry. |
| Alias | UTF | The entry’s name, unique in the keystore. The JKS keystore type lower-cases aliases (alias.toLowerCase(Locale.ENGLISH) in convertAlias), so they are stored in lower case; the CaseExactJKS variant in the same file keeps them as given. |
| Date | long | The entry creation date, in milliseconds since 1970 (Instant.toEpochMilli()). |
A private key entry (tag 1) continues:
| Field | Type | Description |
|---|---|---|
| Key length | int | – |
| Protected key | bytes | A DER EncryptedPrivateKeyInfo; see key protection. |
| Chain length | int | Certificates in the chain, 0 if none. |
| Certificates | – | For each: the type (UTF, such as X.509, which is what java.security.cert.X509Certificate reports; version 2 only), the length (int) and the encoded certificate (getEncoded(), DER for X.509). |
A trusted certificate entry (tag 2) continues with one certificate: type (version 2 only), length and bytes, with no chain count.
Key protection
The private key, encoded as PKCS #8, is protected by Sun’s own scheme
(KeyProtector.protect) and wrapped in an EncryptedPrivateKeyInfo whose
algorithm is the OID KnownOIDs.JAVASOFT_JDKKeyProtector,
1.3.6.1.4.1.42.2.17.1.1 (sun.security.util.KnownOIDs). The
encrypted data is:
| Part | Size | Description |
|---|---|---|
| Salt | 20 | Random. |
| Encrypted key | key length | The PKCS #8 key XORed with a key stream: SHA-1(password ‖ salt), then SHA-1(password ‖ previous digest), and so on, cut to the key’s length. |
| Check | 20 | SHA-1(password ‖ plaintext key); a wrong password gives a different value. |
The password is taken as its UTF-16 characters, each as two bytes, high byte first
(convertToBytes in JavaKeyStore). The scheme uses one SHA-1
per 20 bytes of key and no iteration count; JavaKeyStore itself warns that
“JKS uses outdated cryptographic algorithms”. Java changed its default keystore type
from JKS to PKCS #12 in Java 9 (JEP 229, Create PKCS12 Keystores by
Default).
Integrity
The last 20 bytes are SHA-1 of: the password (UTF-16 big-endian, as above), the
UTF-8 bytes of the text Mighty Aphrodite, then every byte of the file
before the hash (getPreKeyedHash and engineStore). When a
password is given, engineLoad checks it and fails with “Keystore was
tampered with, or password was incorrect”.
JCEKS
The related JCEKS keystore (com.sun.crypto.provider.JceKeyStore) uses
the magic CE CE CE CE and the same layout, and its loader also accepts the
JKS magic. Its setters lower-case aliases the same way (the loader keeps an alias as
it reads it). It adds a third entry type, tag 3, a secret key entry, described
below. Private keys are protected by
com.sun.crypto.provider.KeyProtector with Sun’s
PBEWithMD5AndTripleDES, an 8-byte random salt and an iteration count of
200,000 by default (set by jdk.jceks.iterationCount, read with
SecurityProperties.getOverridableProperty: the system property when it is
set, otherwise the security property of the same name; in jdk-11+28 the count is the
constant 200,000 and there is no property, while jdk8u, jdk-17-ga,
jdk-21-ga and master read it),
and wrapped in an EncryptedPrivateKeyInfo with the OID
1.3.6.1.4.1.42.2.19.1 (KnownOIDs.JAVASOFT_JCEKeyProtector).
The closing keyed SHA-1 hash is made the same way as in JKS. Sources for this and the
following sections are the raw OpenJDK files JceKeyStore.java,
KeyProtector.java, SealedObjectForKeyProtector.java,
PBEParameters.java, PBES1Core.java, PBEKey.java
(all com.sun.crypto.provider), DESKey.java, DESedeKey.java,
PBKDF2KeyImpl.java, javax/crypto/SealedObject.java,
java/security/KeyRep.java, java/io/ObjectStreamClass.java and
sun/security/util/PBEUtil.java (OpenJDK master), PBEKey.java of
the jdk8u, jdk11u and jdk17u branches and the tags
jdk-17-ga to jdk-25-ga, and the Java Object
Serialization Specification (docs.oracle.com, Java SE 21: chapters 4 “Class
Descriptors” and 6 “Object Serialization Stream Protocol”).
JCEKS loader rules
JceKeyStore.engineLoad reads the whole stream into memory first (its
length becomes fullLength), then:
- the magic must be
CE CE CE CEorFE ED FE EDand the version 1 or 2, otherwise it throws “Invalid keystore format”. Version 1 has no certificate type strings (an X509 factory reads every certificate); version 2 has a type UTF before each certificate.engineStorealways writes the JCEKS magic and version 2; - the existing entries are cleared, then the count and that many entries are read; a tag other than 1, 2 or 3 throws “Unrecognized keystore entry: tag”;
- tags 1 and 2 have the layout of JKS (the store writes a type UTF before every certificate, also in a chain), but the JCEKS loader of OpenJDK master, 17 and 21 has no “chain count above 0” test: it makes an array of the count, so a negative count fails with an unchecked
NegativeArraySizeException, and a count of 0 gives an empty chain where the JKS loader leaves the chain unset (jdk-11+28 still had the test); - when a password is given, the keyed hash is checked; with no password the integrity hash is not checked (and is not read). The checks of the plain JKS loader are listed under JKS loader rules;
- a tag 3 entry is read with a fresh
ObjectInputStreamover the same data stream, one per entry, and the stream filter described below. AClassNotFoundExceptionbecomes anIOExceptionwith its message, anInvalidClassExceptionbecomes “Invalid secret key format”; - filter (
JceKeyStore.DeserializationChecker): any array longer than the whole file is rejected; at depth 1 the class must beSealedObjectForKeyProtector; at depth 2 the class must be null,SealedObjectorbyte[]; deeper only null orObjectare allowed; the JVM-widejdk.serialFilteris then consulted. The key object inside the encrypted content is checked at unseal time bySealedObjectForKeyProtector.DeserializationChecker(array length at most the file length; a class of exactlyObjectis answered UNDECIDED at once, without consulting either filter; then thejceks.key.serialFilterproperty, thenjdk.serialFilter). The default ofjceks.key.serialFilterin thejava.securityfile (OpenJDK master, raw) isjava.base/java.lang.Enum;java.base/java.security.KeyRep;java.base/java.security.KeyRep$Type;java.base/javax.crypto.spec.SecretKeySpec;!*: onlyEnum,KeyRep,KeyRep$TypeandSecretKeySpecare allowed and every other class is rejected. A stock JDK therefore accepts, in a tag 3 entry, only aSecretKeySpecor aKeyRep(which is what the SunJCE key classes write); a key of any other class fails to load unless the filter is changed. The system property of the same name, when set, supersedes the security property. Release scope (rawJceKeyStore.javaandSealedObjectForKeyProtector.javaof each): the filters above are those ofjdk8u,jdk-17-ga,jdk-21-gaand master. Injdk-11+28the loader’s filter has no array-length test and no depth 2 rule: it rejects a class other thanSealedObjectForKeyProtectorat depth 1 and a class that is neither null norObjectat depth 3 and deeper, and nothing at depth 2, and then consultsjdk.serialFilter; and its key filter has no maximum length either: it answers UNDECIDED forObject, then appliesjceks.key.serialFilter, thenjdk.serialFilter; - not part of loading, but of fetching a key (
engineGetKey, inKeyProtector): private keys are recovered by OID:1.3.6.1.4.1.42.2.19.1usesPBEWithMD5AndTripleDES,1.3.6.1.4.1.42.2.17.1.1(the JKS scheme above,recover(byte[])) is also accepted, anything else gives “Unsupported encryption algorithm”. For the first OID, missing PBE parameters are an error (IOException“Missing PBE parameters”, which becomes anUnrecoverableKeyException) in OpenJDK master,jdk-21-gaandjdk8u;jdk-17-gaandjdk-11+28have no such test and pass the parameter bytes straight to the PBE parameters object. An iteration count above 5,000,000 (MAX_ITERATION_COUNT, in every release read) is refused (“PBE iteration count too large”). Unsealing a tag 3 secret key applies the same limit. A file whose counts are too large therefore loads, and fails only when that key is fetched. JCEKS has no check value: after decrypting, the plaintext is parsed as a PKCS #8PrivateKeyInfoand given to theKeyFactoryits algorithm names, so a wrong password shows up only as a padding failure or as plaintext that is not PKCS #8. Any of those errors becomes anUnrecoverableKeyException, except a missing key factory, which stays aNoSuchAlgorithmException; - fetching a key, the errors (
engineGetKey; the messages are in the files of every release read,jdk8u,jdk-11+28,jdk-17-ga,jdk-21-gaand master). Both stores return null for an alias that is missing or is not a key entry, before anything else. If the protected bytes of a private key do not parse as a DEREncryptedPrivateKeyInfo, both throwUnrecoverableKeyException“Private key not stored as PKCS #8 EncryptedPrivateKeyInfo”. A null password: the JKS store throwsUnrecoverableKeyException“Password must not be null”, for a key entry only; the JCEKS store makes itsKeyProtectorfor a private key entry and for a secret key entry alike, and that constructor throws an uncheckedIllegalArgumentException“password can't be null”. Unsealing a tag 3 entry (KeyProtector.unseal) fails, each time as anUnrecoverableKeyExceptioncarrying the message, with: “Cannot get algorithm parameters” (the sealed object has no encoded parameters); “Invalid PBE algorithm parameters” (the parameters are not PBE parameters); “PBE iteration count too large”; and, when a filter rejects a class while the key object is read, anIOException“Rejected by the jceks.key.serialFilter or jdk.serialFilter property”. ANoSuchAlgorithmExceptionis passed on as it is; - writing, in
engineStore(JKS and JCEKS alike): a password is required (“password can't be null”, anIllegalArgumentException); - writing, in
engineSetKeyEntry(not inengineStore), where the key is protected. JKS: a key that is not aPrivateKeyis refused withKeyStoreException“Cannot store non-PrivateKeys”; injdk-17-ga,jdk-21-gaand master a null password is aKeyStoreException“password can't be null” (injdk-11+28the JKSKeyProtectorconstructor throws an uncheckedIllegalArgumentExceptionwith that message instead; injdk8uconvertToBytesreadspassword.lengthfirst, so a null password is an uncheckedNullPointerException); and the JKS key protector (KeyProtector.protect) refuses a key whose format is not PKCS#8 withKeyStoreException“Cannot get key bytes, not PKCS#8 encoded”, and a key with no encoding with “Cannot get key bytes, encoding not supported”. JCEKS: any exception is wrapped asKeyStoreExceptionwith the same message, so a null password givesKeyStoreException“password can't be null”; the JCEKS protector has no PKCS #8 format test; - for writing,
jdk.jceks.iterationCount(system property, otherwise security property) counts only when it is a number from 10,000 to 5,000,000 (MIN_ITERATION_COUNTandMAX_ITERATION_COUNT); otherwise 200,000 is used.
PBEWithMD5AndTripleDES
The algorithm parameters, in the EncryptedPrivateKeyInfo and in a sealed object’s
encodedParams, are DER (PBEParameters.java):
PBEParameter ::= SEQUENCE {
salt OCTET STRING SIZE(8),
iterationCount INTEGER }
With the default count 200,000 (03 0D 40) that is the 17 bytes
30 0F 04 08 salt (8) 02 03 03 0D 40. The parser
rejects anything but a SEQUENCE and any trailing data, and refuses an
iterationCount that does not fit a 32-bit signed integer: it reads the
count with DerValue.getInteger, which throws an IOException
for a value above 231−1 or below −231. A negative count that
fits parses; the cipher then refuses a count of 0 or less (“IterationCount must be a
positive number”, PBES1Core.init), and KeyProtector refuses a
count above 5,000,000 when the key is fetched. The cipher
(PBES1Core, algorithm DESede) works as follows:
- The password bytes come from the
PBEKeythatKeyProtectormakes from the keystore password (new PBEKeySpec(password)), and the encoding depends on the JDK release that wrote the file (rawPBEKey.javaread for each release). Before JDK 25 (the files ofjdk8u,jdk11uandjdk17u, and the tagsjdk-17-ga,jdk-21-gaandjdk-24-gaall carry the same check): every character must be in the range U+0020 to U+007E, otherwise the key is refused withInvalidKeySpecException“Password is not ASCII”; each character becomes one byte,(byte)(c & 0x7f), which for that range is the ASCII code. The one exception is a password that is the single character U+0000, which is accepted and stays the one byte00(the source comment: “zero-length password with no terminator”). From JDK 25 (jdk-25-ga, also OpenJDK master):PBEUtil.encodePasswordencodes the characters as UTF-8 and the ASCII-only check is gone from the constructor (it remains inPBEKey.readObject, which aKeyRepnever reaches); a null password is an empty one. The two rules agree for every password of printable ASCII characters, so only a password with other characters differs: old releases cannot protect a key with it at all, JDK 25 and later write UTF-8 bytes. A keystore holding such a password therefore opens only on JDK 25 and later. Unlike the JKS scheme this is not UTF-16. The salt must be 8 bytes and the count above 0; when encrypting, a “weak” salt (first four bytes equal the last four, and byte 0 = byte 3 and byte 1 = byte 2) is refused with “Weak salts cannot be used for encryption” (PBES1Core.init; when the cipher makes its own salt it redraws until it is not weak). A weak salt is accepted when decrypting. - If the two 4-byte halves of the salt are identical, the first half is inverted: bytes 0 and 3 swap and bytes 1 and 2 swap.
- For each half i (0, then 1):
t = MD5(salt half i ‖ password), then count − 1 timest = MD5(t ‖ password). The two 16-byte results are joined in order: 32 bytes. - The first 24 bytes are the Triple DES (DESede) key and the last 8 bytes the CBC initialisation vector.
- The data is encrypted with DESede in CBC mode with PKCS #5 padding (the cipher’s fixed mode and padding), which adds 1 to 8 bytes, so the output is a multiple of 8 bytes.
(The single-DES variant PBEWithMD5AndDES in the same class hashes password ‖ salt for the whole count, but JCEKS does not use it.)
Tag 3: the secret key entry
After the date the writer creates a new ObjectOutputStream over the same
output (the comment in JceKeyStore warns not to create it earlier) and
calls writeObject with the entry’s sealed key. Each secret key entry
therefore carries its own complete Java serialisation stream, starting with its own
header, and the stream states no total length: the reader must parse the object to find
where it ends. The object is an instance of
com.sun.crypto.provider.SealedObjectForKeyProtector, which extends
javax.crypto.SealedObject and adds no fields. In the serialisation grammar
the stream is:
| Element | Bytes and meaning |
|---|---|
| magic, version | AC ED 00 05: STREAM_MAGIC, STREAM_VERSION 5. |
| object | 73 TC_OBJECT, then the class descriptor. |
| class descriptor of the object | 72 TC_CLASSDESC; class name as UTF: 00 33 + com.sun.crypto.provider.SealedObjectForKeyProtector (51 bytes); serialVersionUID CD 57 CA 59 E7 30 BB 53 (−3650226485480866989); flags 02 (SC_SERIALIZABLE, no SC_WRITE_METHOD); field count 00 00; class annotation 78 (TC_ENDBLOCKDATA); then the superclass descriptor. |
| superclass descriptor | 72; 00 19 + javax.crypto.SealedObject; serialVersionUID 3E 36 3D A6 C3 B7 54 70 (4482838265551344752); flags 02; field count 00 04; the four field descriptors below; class annotation 78; its own superclass 70 (TC_NULL: Object is not serialisable). |
| field descriptors | Object-typed fields sorted by name with String.compareTo (no primitive fields): [ encodedParams with type string [B; [ encryptedContent with type [B; L paramsAlg with type Ljava/lang/String;; L sealAlg with type Ljava/lang/String;. Each type is an object: the first use is 74 TC_STRING + UTF, a repeat is 71 TC_REFERENCE + a 4-byte handle. |
| class data | Superclass first. SealedObject’s values in descriptor order (it has no writeObject method, only readObject, so there is no end marker): encodedParams, encryptedContent, paramsAlg, sealAlg. SealedObjectForKeyProtector has no fields and writes nothing. |
Handles number every new object from 0x007E0000 (baseWireHandle) in order of appearance: the two class descriptors, the two type strings, the object itself, then the values. The field values are:
| Field | Type | Content in a JCEKS secret key |
|---|---|---|
encodedParams | byte[] | 75 TC_ARRAY, a class descriptor for [B (the first array in the stream writes it in full: 72 00 02 5B 42 ([B), the serialVersionUID AC F3 17 F8 06 08 54 E0 (see the array UID), flags 02, 00 00, 78, 70), a 4-byte length and the bytes: the DER PBEParameter above (Cipher.getParameters().getEncoded()). |
encryptedContent | byte[] | 75, a 71 back-reference to the [B descriptor, a 4-byte length and the bytes: see below. |
paramsAlg | String | 74 + UTF PBEWithMD5AndTripleDES (PBES1Core.getParameters names its parameters that way); null (70) if the cipher had no parameters. |
sealAlg | String | PBEWithMD5AndTripleDES, the cipher’s transformation name; 74 + UTF, or 71 + handle if it is the same String object as paramsAlg. |
The encrypted content is made by the SealedObject constructor: the key
object is serialised with a fresh ObjectOutputStream (so the plaintext is a
second, complete stream: AC ED 00 05 then an object), and the bytes are
encrypted with PBEWithMD5AndTripleDES as above, with a new random 8-byte
salt and the iteration count, for each key. The decrypted object must be a
java.security.Key (SealedObjectForKeyProtector.getKey casts
the result); for example, a javax.crypto.spec.SecretKeySpec serialises its
algorithm String and key byte array (SecretKeySpec.java,
which declares serialVersionUID 6577238317307289933 and a
readObject check). The keys the SunJCE provider makes itself
(DESKey, DESedeKey, PBEKey,
PBKDF2KeyImpl) are not serialised as themselves: each has a
writeReplace that returns a java.security.KeyRep, so the stream
holds a KeyRep, as tabulated below. Unsealing
creates the cipher from sealAlg and encodedParams and checks
the iteration count against the 5,000,000 limit.
The key object inside the encrypted content
The plaintext of encryptedContent is one Java serialisation stream
(AC ED 00 05, then one object; handles start again at
0x007E0000) whose object is a java.security.Key. Two forms
occur. The class descriptors below follow the rules summarised under
Java serialisation facts used here.
javax.crypto.spec.SecretKeySpec
Serialised as itself (SecretKeySpec.java: implements KeySpec,
SecretKey; fields private byte[] key and private final String
algorithm; serialVersionUID 6577238317307289933 =
5B 47 0B 66 E2 30 61 4D; a private readObject and no
writeObject, so flags 02). Sorted by name, the object-typed
fields are algorithm then key:
| Element | Bytes and meaning |
|---|---|
| object, class descriptor | 73 72 00 1F + javax.crypto.spec.SecretKeySpec (31 bytes), UID 5B 47 0B 66 E2 30 61 4D, flags 02, field count 00 02. |
| field descriptors | 4C 00 09 algorithm 74 00 12 Ljava/lang/String;; 5B 00 03 key 74 00 02 [B. Then 78 (annotation end) and 70 (its superclass Object: none). |
| values | algorithm: 74 + UTF, the algorithm name (for example AES). key: 75 + the [B descriptor in full (72 00 02 5B 42, UID, 02 00 00 78 70) + 4-byte length + the raw key bytes. |
java.security.KeyRep
Source: KeyRep.java (OpenJDK master). KeyRep implements
Serializable, has serialVersionUID −4757683898830641853
(BD F9 4F B3 88 9A A5 43), declares no writeObject (flags
02) and has four private final fields, all object-typed:
| Field (descriptor order) | Type | Meaning |
|---|---|---|
algorithm | String (L) | The key’s getAlgorithm(): DES (DESKey), DESede (DESedeKey), the PBE algorithm name given when the key was made (PBEKey, for example PBEWithMD5AndTripleDES) or PBKDF2With + the MAC name (PBKDF2KeyImpl, for example PBKDF2WithHmacSHA1). |
encoded | byte[] ([) | The key’s getEncoded() bytes: 8 bytes for DES, 24 for DESede (DESKeySpec.DES_KEY_LEN, DESedeKeySpec.DES_EDE_KEY_LEN); for a PBEKey the encoded password (the rule under PBE, step 1), not a derived key; for PBKDF2KeyImpl the derived key. |
format | String (L) | The key’s getFormat(), upper-cased with Locale.ENGLISH by the constructor: RAW for all four classes. |
type | KeyRep.Type (L) | An enum: SECRET, PUBLIC or PRIVATE; the four classes above write SECRET. |
The stream of a KeyRep (the plaintext inside the sealed object):
| Element | Bytes and meaning |
|---|---|
| header | AC ED 00 05. |
| object and descriptor | 73 72 00 14 + java.security.KeyRep (20 bytes), UID BD F9 4F B3 88 9A A5 43, flags 02, field count 00 04. Handle 0x007E0000. |
| field descriptors | 4C 00 09 algorithm 74 00 12 Ljava/lang/String; (handle +1); 5B 00 07 encoded 74 00 02 [B (+2); 4C 00 06 format 71 00 7E 00 01 (a back reference to the same type string); 4C 00 04 type 74 00 1B Ljava/security/KeyRep$Type; (+3). Then 78 and 70. The object itself takes the next handle (0x007E0004). |
value algorithm | 74 + UTF (handle 0x007E0005). |
value encoded | 75 + the [B descriptor in full (72 00 02 5B 42, AC F3 17 F8 06 08 54 E0, 02 00 00 78 70; 0x007E0006), the array (0x007E0007), 4-byte length, bytes. |
value format | 74 00 03 RAW (0x007E0008). |
value type | An enum constant (7E TC_ENUM): the class descriptor of java.security.KeyRep$Type (72 00 19 + the name, UID 00 00 00 00 00 00 00 00, flags 12 = SC_SERIALIZABLE + SC_ENUM, field count 00 00, 78), then its superclass descriptor, java.lang.Enum (72 00 0E + the name, UID 0, flags 12, 00 00, 78, 70); then the constant’s handle and its name as a String object: 74 00 06 SECRET. Handles: the two descriptors 0x007E0009, 0x007E000A, the constant 0x007E000B, its name 0x007E000C. |
Reading it back (KeyRep.readResolve): SECRET with format
RAW gives a SecretKeySpec(encoded, algorithm);
PUBLIC with X.509 and PRIVATE with
PKCS#8 make a KeyFactory for the algorithm and decode the
bytes; any other combination is a NotSerializableException
(“unrecognized type/format combination”). The constructor refuses null arguments.
The four SunJCE classes always write SECRET/RAW, so a
JCEKS secret key entry for them resolves to a SecretKeySpec.
Sources for the facts above: writeReplace in DESKey.java,
DESedeKey.java, PBEKey.java and
PBKDF2KeyImpl.java (all return new KeyRep(KeyRep.Type.SECRET,
getAlgorithm(), getFormat(), key)), and their getAlgorithm and
getFormat methods; in JDK 8, 11 and 17 the same writeReplace
passes getEncoded() of PBEKey.
The array UID
The class descriptor of byte[] (class name [B) always has
serialVersionUID AC F3 17 F8 06 08 54 E0
(0xACF317F8060854E0). An array class declares no UID, so the default is computed
(ObjectStreamClass.computeDefaultSUID, raw source read): SHA-1 over the
UTF name 00 02 5B 42 and the 4-byte class modifiers (public, final and
abstract: 00 00 04 11); for an array the interface names are left out,
and an array has no fields, constructors or methods. The first eight bytes of the
digest (E0 54 08 06 F8 17 F3 AC, computed here with
shasum over those eight input bytes) are assembled least significant byte
first, as in the specification’s formula (chapter 4, “Stream Unique Identifiers”),
which gives the value above.
Java serialisation facts used here
Source: the Java Object Serialization Specification, Java SE 21, saved raw from
docs.oracle.com: chapter 6 (Object Serialization Stream Protocol, grammar and
constants), chapter 4 (Class Descriptors), chapter 1 (section 1.12, enum
constants) and chapter 2 (the order of work in writeObject), with
ObjectStreamClass.writeNonProxy from OpenJDK for the flags written.
- Stream.
magic version contents:AC ED, version00 05. - Type codes (
ObjectStreamConstants):70TC_NULL,71TC_REFERENCE,72TC_CLASSDESC,73TC_OBJECT,74TC_STRING,75TC_ARRAY,76TC_CLASS,77TC_BLOCKDATA,78TC_ENDBLOCKDATA,79TC_RESET,7ATC_BLOCKDATALONG,7BTC_EXCEPTION,7CTC_LONGSTRING,7DTC_PROXYCLASSDESC,7ETC_ENUM;baseWireHandleis0x7E0000. - Class descriptor.
TC_CLASSDESC className(utf) serialVersionUID(long) newHandle classDescInfo, whereclassDescInfoisclassDescFlags(byte) fields classAnnotation superClassDesc;fieldsis a short count then the field descriptors;classAnnotationisTC_ENDBLOCKDATAwhen nothing was annotated; the superclass descriptor is a class descriptor,TC_NULLor a back reference. - Flags (
classDescFlags):01SC_WRITE_METHOD(a Serializable class has awriteObjectmethod, so its data is followed byTC_ENDBLOCKDATA);02SC_SERIALIZABLE;04SC_EXTERNALIZABLE;08SC_BLOCK_DATA(Externalizable, protocol 2);10SC_ENUM. A serialisable non-enum class withoutwriteObjecthas02; an enum type12, with UID 0 and no fields. - Field descriptors. Primitive fields first (type code
B C D F I J S Z+ name), sorted by name; then object fields ([orL+ name + the type as a String object in field-descriptor form, such asLjava/lang/String;), sorted by name; the names are compared withString.compareTo. The type string is a normal String object:TC_STRINGthe first time,TC_REFERENCEafterwards. - Handles. The next number in sequence goes to each new object as it is written: to a class descriptor right after its UID (before its fields), to a type string, array, object or string as it is met, and to an enum constant after its class descriptor and before its name. A
TC_REFERENCEholds the 4-byte handle. A superclass descriptor is written inside its subclass’s descriptor, so it is numbered after the subclass’s own field type strings (the subclass’s fields are written before its annotation and superclass), and before the superclass’s. - Object data.
TC_OBJECT classDesc newHandle classdata[], with the data of the highest serialisable superclass first, each as the field values in descriptor order (primitives, then objects); for a class withSC_WRITE_METHODfollowed by an annotation ending inTC_ENDBLOCKDATA. Arrays:TC_ARRAY classDesc newHandle size(int) values. Enums:TC_ENUM classDesc newHandle name(String object); only the constant’s name is written, andObjectInputStreamfinds it withEnum.valueOf. A class whosewriteReplacereturns another object has that object written in its place (this is how aDESedeKeybecomes aKeyRep).
PKCS #12 inside a .jks file
The keystore type JKS is, in the JDK, the class
sun.security.provider.JavaKeyStore.DualFormatJKS, a delegator over
JKS and PKCS12 (JavaKeyStore.java, raw), whose
loading is done by KeyStoreDelegator.engineLoad:
- With no stream, a new empty keystore is created in the primary format, JKS.
- Otherwise the JKS loader is tried first on the whole file (the stream is buffered and marked so that it can be rewound).
- If it fails and the failure is an
IOExceptioncaused by anUnrecoverableKeyException, that is, a wrong password (the closing hash did not match), the error is thrown and nothing else is tried. - For any other failure (bad magic, a bad tag, truncated data, a certificate that does not parse, and so on), the stream is rewound to its start and loaded as PKCS #12. If that also fails, a wrong-password failure from the PKCS #12 loader is thrown; otherwise the error from the JKS attempt is thrown. That error is rethrown as itself when it is an
IOException,CertificateExceptionorNoSuchAlgorithmException, and also when it is aRuntimeException(jdk8u,jdk-17-ga,jdk-21-gaand master have this branch; its source comment is only “rethrow the outer exception”): a runtime exception from the first loader is not replaced by a different error. Thejdk-11+28delegator has noRuntimeExceptionbranch, so no statement there rethrows it. A runtime exception raised by the second loader is not caught by the delegator at all and also propagates as it is, and with the fallback off the first loader’s runtime exception propagates directly. For a keystore opened asPKCS12the roles are swapped, so it is the PKCS #12 loader’s runtime exception that propagates. - The fallback happens only while the security property
keystore.type.compatistrue; its default injava.securityistrue. The test is"true".equalsIgnoreCase(property), made once when the keystore object is constructed, so any other value, and a missing property, turn the fallback off: theJKStype then loads JKS files only and the JKS error is thrown. - A later store writes the format that was loaded (a new keystore: JKS).
The magic is therefore not what decides. The test of the first four bytes for
FE ED FE ED (DualFormatJKS.engineProbe, which reads one
int and compares it with the JKS magic) is a separate method and is not part
of engineLoad. Versions checked in the source read this session:
KeyStoreDelegator.java of the tags jdk-11+28,
jdk-17-ga and jdk-21-ga and of OpenJDK master all contain this
load sequence and the keystore.type.compat switch, and so does the one in
the jdk8u branch (sun/security/provider/KeyStoreDelegator.java),
which has no engineProbe and, with the property not true,
goes straight to the JKS loader without a fallback. java.security of
master and of the jdk8u Linux file sets the property to true.
In the jdk-11+28, jdk-17-ga and jdk-21-ga files
the same sequence applies (the first two keep the flag as a non-final field).
The reverse also holds. The keystore type PKCS12 is
sun.security.pkcs12.PKCS12KeyStore.DualFormatPKCS12, the same delegator
with PKCS #12 as the primary format and JKS as the secondary
(super("PKCS12", PKCS12KeyStore.class, "JKS", JKS.class),
PKCS12KeyStore.java, master, raw). While keystore.type.compat
is true, a JKS file opened as PKCS12 therefore loads too, by
the same steps with the roles swapped.
A file named .jks is therefore either a JKS keystore (described above)
or a PKCS #12 file (the PFX structure of RFC 7292, a DER SEQUENCE), for
example one made by keytool on a current JDK, which makes PKCS #12 by
default. The explorer tells them apart by the start of the file, which is not what the JDK
does: FE ED FE ED is a JKS keystore, CE CE CE CE a JCEKS one, and a
file that is a PFX (a SEQUENCE of the version 3 and an authSafe
ContentInfo of type data or signedData) is read by the
PKCS #12 viewer; anything else keeps the neutral name. The JCEKS type
has a separate loader, JceKeyStore, that accepts CE CE CE CE
and FE ED FE ED only.
Example
00000000 FE ED FE ED 00 00 00 02 00 00 00 01 00 00 00 02 ................
00000010 00 06 6D 79 63 65 72 74 00 00 01 8B CF E5 68 7B ..mycert......h{
00000020 00 05 58 2E 35 30 39 00 00 03 5A 30 82 03 56 … ..X.509...Z0..V
Reading it: magic, version 2, one entry; tag 2, a trusted certificate; alias
mycert; date 0x18BCFE5687B, 1,700,000,000,123 ms, which is
14 November 2023 22:13:20.123 UTC; type X.509; length 858; then the DER
certificate, starting 30 82 03 56.