PyJKS

20.0.0 · active · verified Sun Apr 12

PyJKS is a pure-Python library for reading and writing Java KeyStore (JKS) files. It provides programmatic access to key entries, certificate entries, and trusted certificate entries within a JKS file. The current version is 20.0.0, and it is actively maintained with releases tied to significant updates and improvements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load a Java KeyStore (JKS) file, authenticate with a password, and iterate through its entries. It uses `os.environ.get` for `KEYSTORE_PATH` and `KEYSTORE_PASSWORD` to allow easy configuration via environment variables or fall back to default placeholders. Error handling for `FileNotFoundError` and `jks.util.KeystoreException` is included for common issues like incorrect paths or passwords.

import jks
import os

# --- Configuration ---
# Replace 'path/to/your/keystore.jks' with the actual path to your JKS file.
# For a runnable example, ensure this file exists or temporarily create an empty one.
keystore_path = os.environ.get('PYJKS_KEYSTORE_PATH', 'my_keystore.jks')

# Replace 'your_keystore_password' with the actual password for your JKS file.
# For security, avoid hardcoding passwords in production; use environment variables or a secret management system.
keystore_password = os.environ.get('PYJKS_KEYSTORE_PASSWORD', 'changeit')

# --- Quickstart Code ---
try:
    # Attempt to load the keystore from the specified path and password
    with open(keystore_path, "rb") as f:
        ks = jks.KeyStore.load(f, keystore_password)

    print(f"Successfully loaded keystore from: {keystore_path}")
    print(f"Keystore type: {ks.ks_type}")
    print(f"Number of entries: {len(ks.entries)}")

    if not ks.entries:
        print("No entries found in the keystore.")
    else:
        print("\nKeystore Entries:")
        for alias, entry in ks.entries.items():
            print(f"  Alias: {alias}")
            print(f"    Type: {entry.entry_type}")
            if entry.entry_type == 'key':
                print(f"    Key Algorithm: {entry.algorithm}")
                # Further details like certificate chain can be accessed via entry.cert_chain
            elif entry.entry_type == 'cert':
                print(f"    Certificate Subject: {entry.cert.subject.human_friendly}")
                # Further details like issuer, validity, etc., are available on entry.cert

except FileNotFoundError:
    print(f"Error: Keystore file not found at '{keystore_path}'.")
    print("Please replace 'my_keystore.jks' with an actual path or create a dummy JKS file for testing.")
except jks.util.KeystoreException as e:
    print(f"Error loading keystore: {e}")
    print("This often indicates an incorrect password or a corrupted/unsupported JKS format.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →