Class Pkcs12

java.lang.Object
com.codename1.backend.security.pki.Pkcs12

public final class Pkcs12 extends Object

A PKCS#12 key store (.p12, .pfx) holding one private key and its certificate chain, or only certificates.

Pkcs12 store = Pkcs12.decode(Files.readAllBytes(path), password);
byte[] key = store.getPrivateKey();           // PKCS#8, for Crypto.sign
List<Certificate> chain = store.getCertificates();

byte[] p12 = Pkcs12.encode(key, chain, "api", password);

The profile is the one OpenSSL 3 and current JDKs write by default: PBES2 with PBKDF2-HMAC-SHA-256 (or SHA-1) and AES-128/192/256-CBC for the encrypted parts, and an HMAC-SHA-256, -384, -512 or -SHA-1 integrity MAC. The legacy RC2 and 3DES schemes (openssl pkcs12 -legacy, very old keytool) are refused with a message saying how to re-export the file. What encode(byte[], List, String, String) writes is PBES2/PBKDF2-HMAC-SHA-256/AES-256-CBC with an HMAC-SHA-256 MAC, which openssl pkcs12 and keytool both read.

A store with more than one private key is read for its first one.

  • Method Details

    • getPrivateKey

      public byte[] getPrivateKey()
      The private key as PKCS#8 DER, or null for a store of certificates only.
    • getCertificates

      public List<Certificate> getCertificates()
      The certificates. When there is a private key, its certificate is first and the rest follow in issuing order as far as they chain; any others come last.
    • getAlias

      public String getAlias()
      The friendly name of the key, or of the first certificate when there is no key; null when the file gives none.
    • decode

      public static Pkcs12 decode(byte[] pfx, String password) throws IOException
      Reads a store, checking its MAC with password.
      Throws:
      CertificateException - when the password is wrong (the MAC does not match), the file is not PKCS#12, or it uses a scheme outside the profile
      IOException
    • encode

      public static byte[] encode(byte[] privateKey, List<Certificate> chain, String alias, String password) throws IOException
      Writes a store holding privateKey and chain.
      Parameters:
      privateKey - the PKCS#8 key, or null for a store of certificates only (a trust store)
      chain - the key's certificate first, then its issuers
      alias - the friendly name keytool lists the entry under; null for none
      password - protects both the key and the MAC
      Throws:
      IOException