Class Pfx
- All Implemented Interfaces:
AutoCloseable
Load, inspect, build, export, convert, and import PFX / PKCS#12 containers.
Chilkat.Pfx is the Chilkat class for working with
PFX / PKCS#12 containers, which commonly hold certificates together with
their associated private keys and certificate chains. It can load
certificate/private-key bundles from files, memory, encoded data,
BinData, or PEM; add certificates and private keys; inspect
contained certificates and keys; manage safe-bag attributes; export to PFX,
PEM, encoded strings, binary data, files, or Java KeyStore format; and import
contents into Windows or macOS/iOS key stores.
Load PFX / PKCS#12 data
Load password-protected certificate and private-key bundles from files,
memory, encoded strings, BinData, or PEM input.
Inspect certificates and keys
Enumerate contained certificates, private keys, and certificate chains to locate the identity or trust material needed by the application.
Build PFX containers
Add certificates and private keys to create a PKCS#12 bundle for TLS, S/MIME, signing, authentication, or platform import workflows.
Safe-bag attributes
Read and manage PKCS#12 safe-bag attributes such as friendly names or local key identifiers when interoperability requires them.
Export and convert
Export PFX content as binary data, encoded text, files, PEM, or Java KeyStore format depending on the target system.
Import to key stores
Import certificates and private keys into Windows certificate stores or macOS/iOS keychains when platform-backed access is required.
Common pattern:
Use Pfx when certificate material includes private keys packaged
in a PKCS#12 container. Load the PFX with its password, inspect or retrieve
the needed certificate and private key, then export, convert, or import the
contents into the format or platform store required by the application. Use
Chilkat.Cert and PrivateKey when working directly
with individual certificate or key objects.
For an extended overview, see Pfx Class Overview.
</section>
Instances hold a native Chilkat object: close them with ChilkatObject.close() (try-with-resources) when
done; an unclosed instance is freed when it becomes unreachable.
- See Also:
- Online reference
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidAddscertto this PFX as an identity.voidaddPrivateKey(PrivateKey privKey, CertChain certChain)AddsprivKeyand the certificate chain incertChainto this PFX object.voidCopies the certificate at the zero-based indexindexintocert.voidcertByLocalKeyId(String localKeyId, String encoding, Cert cert)Searches for a certificate whose certificate-baglocalKeyIdattribute matcheslocalKeyIdand copies it intocert.Gets or sets the password-based encryption scheme used for PKCS#8 shrouded private-key bags when writing a PFX.voidgetLastJsonData(JsonObject json)Replaces the entire contents ofjsonwith structured JSON information from the most recent operation.intReturns the number of certificates currently contained in this PFX object.intReturns the number of private keys currently contained in this PFX object.Gets or sets the content-encryption cipher used whenisgetAlgorithmId()pbes2.Gets or sets the HMAC algorithm used by PBKDF2 whenisgetAlgorithmId()pbes2.getSafeBagAttr(boolean forPrivateKey, int index, String attrName)Reads a recognized safe-bag attribute from a private key or certificate contained in this PFX.Provides specialized compatibility options for unusual PFX interoperability requirements.voidimportToKeychain(JsonObject opts)Imports all certificates and private keys currently held by thisPfxobject into the application's default keychain.voidimportToWindows(boolean exportable, boolean userProtected, boolean machineKeyset, boolean allowOverwriteKey, boolean allowExport, String leafStore, String intermediateStore, String rootStore, String extraOptions)Imports the certificates and private keys in this PFX into Windows certificate stores and Windows key storage.voidLoads one or more certificate/private-key identities from the PEM-formatted text inpemStrand builds the contents of thisPfxobject.voidLoads a PFX / PKCS#12 container from the bytes currently held inbd.voidloadPfxEncoded(String encodedData, String encoding, String password)Decodes the text inencodedDatausing the binary encoding named byencoding, then loads the resulting bytes as a PFX / PKCS#12 container.voidloadPfxFile(String path, String password)Loads a PFX / PKCS#12 container from the file path inpath.voidprivateKeyAt(int index, PrivateKey privKey)Copies the private key at the zero-based indexindexintoprivKey.voidsetAlgorithmId(String value)Sets theAlgorithmIdproperty; seegetAlgorithmId().voidsetPbes2CryptAlg(String value)Sets thePbes2CryptAlgproperty; seegetPbes2CryptAlg().voidsetPbes2HmacAlg(String value)Sets thePbes2HmacAlgproperty; seegetPbes2HmacAlg().voidsetSafeBagAttr(boolean forPrivateKey, int index, String name, String value, String encoding)Sets a safe-bag attribute on a private key or certificate contained in this PFX.voidsetUncommonOptions(String value)Sets theUncommonOptionsproperty; seegetUncommonOptions().voidSerializes the current PFX contents as PKCS#12 data and writes the bytes tobd, usingpasswordas the output password.toEncodedString(String password, String encoding)Serializes the current PFX contents usingpasswordas the output password, then returns the PKCS#12 bytes encoded as text usingencoding.voidSerializes the current PFX contents and writes the resulting PKCS#12 data topath, usingpasswordas the output password.voidtoJksObj(String aliasName, String password, JavaKeyStore jksObj)PopulatesjksObjwith a Java KeyStore (JKS) representation of this PFX.toPem()Exports all private keys and certificates currently held by this object as PEM-formatted text.toPemEx(boolean extendedAttrs, boolean noKeys, boolean noCerts, boolean noCaCerts, String encryptAlg, String password)Exports selected PFX contents as PEM-formatted text.voiduseCertVault(XmlCertVault vault)Adds the certificates currently contained invaultto the set of certificate sources available for later chain-building operations, such as.addCert(Cert, boolean)Methods inherited from class com.chilkatsoft.chilkat2.ChilkatObject
close, getDebugLogFilePath, getLastErrorHtml, getLastErrorText, getLastErrorXml, getLastMethodSuccess, getVerboseLogging, getVersion, isClosed, setDebugLogFilePath, setLastMethodSuccess, setVerboseLogging, toString
-
Constructor Details
-
Pfx
public Pfx()Creates a newPfxobject.
-
-
Method Details
-
getAlgorithmId
Gets or sets the password-based encryption scheme used for PKCS#8 shrouded private-key bags when writing a PFX. After a PFX is loaded, this property reports the scheme found for the loaded shrouded key bag.The default is
pbeWithSHAAnd3_KeyTripleDES_CBCfor backward compatibility. Set this property topbes2to use the cipher and PBKDF2 HMAC choices specified byandgetPbes2CryptAlg().getPbes2HmacAlg()Scope: This property selects protection for private-key bags. It does not select the certificate's public-key algorithm, the private key's algorithm, or the signature algorithm used by a certificate. Compatibility versus modern encryption: The Triple-DES default supports older consumers. For new PFX output, prefer
pbes2with AES when every target platform supports it.- Returns:
- the value of the
AlgorithmIdproperty
-
setAlgorithmId
Sets theAlgorithmIdproperty; seegetAlgorithmId().- Parameters:
value- the new value (notnull)
-
getNumCerts
public int getNumCerts()Returns the number of certificates currently contained in this PFX object. This count includes end-entity certificates and any available intermediate or root CA certificates.Certificate indexes range from
0throughNumCerts - 1for use with.certAt(int, Cert)Indexes are independent: Certificates and private keys are stored in separate collections. Certificate index
ihas no positional relationship to private-key indexi. In particular,CertAt(i)must not be assumed to return the certificate for. Do not infer meaning from order: No end-entity-first, CA-last, or load/export/reload ordering guarantee is documented. Use certificate properties to determine each certificate's role, and useprivateKeyAt(int, PrivateKey)localKeyIdto associate a private key with its certificate when that attribute is present.- Returns:
- the value of the
NumCertsproperty (read-only)
-
getNumPrivateKeys
public int getNumPrivateKeys()Returns the number of private keys currently contained in this PFX object.Private-key indexes range from
0throughNumPrivateKeys - 1for use with.privateKeyAt(int, PrivateKey)Indexes are independent: Private keys and certificates are stored in separate collections. Private-key index
ihas no positional relationship to certificate indexi. A PFX commonly has more certificates than private keys because intermediate and root CA certificates are also included. Finding the matching certificate: When the private key has alocalKeyId, retrieve it withand pass the value togetSafeBagAttr(boolean, int, String). Do not pair a key and certificate by using the same index. Secret material: A nonzero value means the object contains private keys in memory. Handle the object and any exported form accordingly.certByLocalKeyId(String, String, Cert)- Returns:
- the value of the
NumPrivateKeysproperty (read-only)
-
getPbes2CryptAlg
Gets or sets the content-encryption cipher used whenisgetAlgorithmId()pbes2. After loading a PBES2-protected PFX, this property reports the cipher used by the loaded shrouded key bag.Value Cipher
aes256-cbcAES-256 in CBC mode; the default for new PBES2 output.aes192-cbcAES-192 in CBC mode.aes128-cbcAES-128 in CBC mode.3des-cbcTriple DES in CBC mode for compatibility.PBES2 components: This property chooses the cipher.
chooses the HMAC-based PBKDF2 pseudorandom function used to derive the encryption key from the password.getPbes2HmacAlg()- Returns:
- the value of the
Pbes2CryptAlgproperty
-
setPbes2CryptAlg
Sets thePbes2CryptAlgproperty; seegetPbes2CryptAlg().- Parameters:
value- the new value (notnull)
-
getPbes2HmacAlg
Gets or sets the HMAC algorithm used by PBKDF2 whenisgetAlgorithmId()pbes2. After loading a PBES2-protected PFX, this property reports the HMAC choice found in the loaded shrouded key bag.hmacWithSha256— default for new PBES2 output.hmacWithSha384hmacWithSha512hmacWithSha1— primarily for compatibility with older consumers.
Not the container-integrity MAC: This setting is part of PBES2 key derivation for private-key encryption. It should not be confused with the separate integrity protection that a PKCS#12 container may use.
- Returns:
- the value of the
Pbes2HmacAlgproperty
-
setPbes2HmacAlg
Sets thePbes2HmacAlgproperty; seegetPbes2HmacAlg().- Parameters:
value- the new value (notnull)
-
getUncommonOptions
Provides specialized compatibility options for unusual PFX interoperability requirements. The default is an empty string, which is appropriate for normal use. Multiple options are separated by commas.Option Effect
LegacyOrderWrites internal PKCS#12ContentInfoobjects in the ordering traditionally used by older Chilkat versions.NoTruncatePfxPassword64Prevents Chilkat's default compatibility behavior of truncating an extremely long PFX password to 64 characters.Leave empty unless required: These options can reduce interoperability with software that expects the default behavior. Enable one only for a documented compatibility case.
- Returns:
- the value of the
UncommonOptionsproperty
-
setUncommonOptions
Sets theUncommonOptionsproperty; seegetUncommonOptions().- Parameters:
value- the new value (notnull)
-
addCert
Addscertto this PFX as an identity. The certificate must have an associated private key that Chilkat can obtain and copy. This requirement applies whetherincludeChainistrueorfalse;AddCertdoes not provide a certificate-only mode.includeChaincontrols only whether Chilkat also attempts to add the certificate chain:Certificate/private-key state
includeChainResultNo private key
falseortrueFails. A certificate cannot be added by this method without its private key.Private key exists but cannot be obtained or exported
falseortrueFails. Chilkat does not fall back to adding the certificate without the key.Usable private key
falseAdds the private key andcertonly. Intermediate and root certificates are not added.Usable private key; complete chain locatable
trueAdds the private key,cert, and the locatable intermediate and root certificates.Usable private key; chain incomplete
trueSucceeds with a partial chain. Missing intermediate or root certificates do not cause failure.Chain construction: When
includeChainistrue, Chilkat searches the certificates already associated withcertand certificates made available for chain building, principally through. Each intermediate or root certificate is included when it can be located. The chain does not need to terminate at a root, and trust is not evaluated by this operation. Snapshot semantics: The certificate, associated private key, and any locatable chain certificates are copied at the time of the call. Chilkat does not retain a live reference touseCertVault(XmlCertVault)cert. After this method returns, modifying, reloading, or destroying the sourceCertdoes not affect the material already stored in the PFX, and later changes to the PFX do not affect the source object. Duplicate handling: A private key already present in the object is not added again. The primary certificate and any certificate that has a private key are always inserted, even if an equivalent certificate is already present. Other intermediate or CA certificates are skipped when they are duplicates. Not atomic: After the certificate and key have passed the initial requirements, certificates are merged first and the private key is added afterward. If the key-add step fails, the method returnsfalsebut certificates already merged remain in the object. Treat failure as a possible partial modification. A missing or unobtainable private key is rejected before this merge begins. Automatic association: If the private key does not already have alocalKeyId, Chilkat generates one and assigns the same value to the key's primary certificate. This identifier associates the key and leaf certificate without relying on collection indexes. Intermediate and root CA certificates may be shared across multiple identities and are not paired by position.- Parameters:
cert- thecertargument (notnull)includeChain- theincludeChainargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
addPrivateKey
AddsprivKeyand the certificate chain incertChainto this PFX object. The chain must contain at least one certificate. The certificate at index0is treated as the end-entity certificate associated withprivKey; the remaining entries are additional certificates to include with the identity. The chain does not need to contain a root certificate and may consist only of the end-entity certificate.Caller responsibility: Chilkat does not verify that
privKeymathematically matches the public key in the certificate at index0. The association is positional. A mismatch is not rejected and can produce a PFX identity that later fails during signing, decryption, or client authentication. Copy and lifetime behavior: Chilkat immediately copies the private key and every certificate in the supplied chain. It retains neither source object. Modifying, reloading, or destroying the sourcePrivateKeyorCertChainafter this method returns does not affect the PFX. Duplicates and automatic association: A private key already present in the PFX is not added again, and duplicate certificates are skipped. If the private key does not already have alocalKeyId, Chilkat generates one. The same identifier is assigned to the certificate at index0, linking that certificate to the key. Other safe-bag attributes are not generated automatically. Failure and partial modification: An empty certificate chain is rejected before anything is added. For later failures, the operation is not atomic: certificates are merged before the private key is added, so the method can returnfalseafter leaving some certificates in the PFX.- Parameters:
privKey- theprivKeyargument (notnull)certChain- thecertChainargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
certAt
Copies the certificate at the zero-based indexindexintocert. The first certificate is at index0; valid indexes are less than.getNumCerts()On success,
certis replaced with an independent, detached copy of the selected certificate. The method does not merge with or append to any certificate already held bycert. The returned copy does not remain linked to the PFX: changing either object later does not affect the other, and the copied certificate remains usable even if the PFX is subsequently modified or destroyed.Failure leaves the destination unchanged: If
indexis out of range or the certificate cannot be returned, the method returnsfalsewithout modifyingcert. When reusing aCertobject in a loop, always use its contents only after this method returnstrue; otherwisecertmay still contain the certificate from an earlier successful call. Do not pair by index: Certificate indexes and private-key indexes are independent.CertAt(i)is not necessarily the certificate associated with. To associate a key with its certificate, obtain the key'sprivateKeyAt(int, PrivateKey)localKeyIdwithand usegetSafeBagAttr(boolean, int, String).certByLocalKeyId(String, String, Cert)- Parameters:
index- theindexargumentcert- thecertargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
certByLocalKeyId
Searches for a certificate whose certificate-baglocalKeyIdattribute matcheslocalKeyIdand copies it intocert.encodingnames the binary representation used forlocalKeyId, such asdecimal,base64, orhex.On success,
certis replaced with the matching certificate. The method does not merge with any certificate already held bycert.Failure leaves the destination unchanged: If
encodingis invalid,localKeyIdcannot be decoded, or no matching certificate is found, the method returnsfalsewithout modifyingcert. Always usecertonly after atruereturn, because a reused destination may still contain a certificate from an earlier call. Recommended association workflow: For a private key at indexi, callwithgetSafeBagAttr(boolean, int, String)localKeyId=true,encoding=i, andcert=localKeyId. That method returns the identifier in decimal representation, so pass the returned value aslocalKeyIdanddecimalasencodinghere. Do not use matching indexes: Certificates and private keys are stored in independent collections.CertAt(i)is not the certificate forPrivateKeyAt(i)unless that happens coincidentally. Scope: This method returns the matching primary certificate. It does not return an associated certificate chain as a separate object.- Parameters:
localKeyId- thelocalKeyIdargument (notnull)encoding- theencodingargument (notnull)cert- thecertargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getLastJsonData
Replaces the entire contents ofjsonwith structured JSON information from the most recent operation. The data is copied as a complete replacement; it is never merged with members already present injson.The exact members depend on the preceding method. After loading a PFX, the JSON may describe authenticated-safe content, safe bags, encryption information, and bag attributes. If no JSON data is available,
jsonis cleared to an empty JSON object.Destination behavior: The previous contents of
jsonare never preserved by this call. Reusing aJsonObjectis safe without clearing it first, but do not expect older members to remain. Diagnostics: Call this method immediately after the operation being inspected. Not every method produces JSON detail, and this information supplements rather than replacesLastErrorText.- Parameters:
json- thejsonargument (notnull)
-
getSafeBagAttr
Reads a recognized safe-bag attribute from a private key or certificate contained in this PFX.forPrivateKeyistruefor a private key andfalsefor a certificate.indexis the zero-based index within the selected collection.attrNameis the attribute name and is matched case-insensitively.Empty values are treated as failure: The method succeeds only when the requested attribute is recognized, readable, set, and nonempty. If the attribute is unset or its stored value is an empty string, the method reports failure. An empty string is therefore never a successful attribute result.
Logical attribute Accepted
attrNamenames Read behaviorFriendly name
friendlyName,keyContainerName, orkeyNameAll three names read the same underlying text attribute. The read succeeds only when the attribute contains a nonempty value; an unset or empty value causes failure.Storage provider
storageProviderormsStorageProviderBoth names read the same underlying text attribute. The read succeeds only when the attribute contains a nonempty value; an unset or empty value causes failure.Local key ID
localKeyIdThe read succeeds only when a nonempty local key ID is present. The value is always returned in decimal encoding as one big-endian integer, regardless of the encoding used when it was set.Enhanced key usage
enhancedKeyUsageNot readable through this method. The operation reports failure even if the attribute was previously set with.setSafeBagAttr(boolean, int, String, String, String)An unrecognized
attrNamename, an invalid index, an unreadable attribute, or any recognized attribute whose value is unset or empty causes the read to fail.Decimal localKeyId representation: The raw bytes are interpreted as one unsigned big-endian integer. For example, bytes
01 02 03 04 05 06 07 08are returned as72623859790382856. Leading zero bytes are not preserved by a set-read-set round trip because00 01 02 03and01 02 03represent the same integer. Pairing a key with its certificate: For private-key indexi, readlocalKeyIdwithforPrivateKey=trueandindex=i. If a nonempty value is returned successfully, pass it tousing the encodingcertByLocalKeyId(String, String, Cert)decimal. Never assume that certificate indeximatches private-key indexi.- Parameters:
forPrivateKey- theforPrivateKeyargumentindex- theindexargumentattrName- theattrNameargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
importToKeychain
Imports all certificates and private keys currently held by thisPfxobject into the application's default keychain. This method is available only on macOS and iOS. On other platforms it returnsfalseand reports that the method is macOS/iOS only.The method does not accept a password. Any required password must already have been supplied when loading the PFX or PEM data; the objects presently contained in the
Pfxare what this method imports.optsis reserved for future use: TheJsonObjectcurrently has no defined members and does not affect the import. Pass an emptyJsonObject. Any JSON members supplied today are ignored. The destination keychain, access group, key accessibility, iCloud synchronization, and replacement behavior are not configurable through this method.The certificates and private keys are imported into the application's platform-default keychain without assigning special access-group, accessibility, or synchronization attributes. Normal macOS or iOS keychain-access rules and application entitlements still apply.
Duplicates and atomicity: An item already present in the keychain does not cause failure and is not added again or replaced, so re-importing the same identity is safe. The import is all-or-nothing: if the method fails, it does not leave only a subset of the PFX contents imported.
The calling sequence is the same on macOS and iOS: load or build the
Pfx, create an emptyJsonObject, and pass it asopts.- Parameters:
opts- theoptsargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
importToWindows
public void importToWindows(boolean exportable, boolean userProtected, boolean machineKeyset, boolean allowOverwriteKey, boolean allowExport, String leafStore, String intermediateStore, String rootStore, String extraOptions)Imports the certificates and private keys in this PFX into Windows certificate stores and Windows key storage. This method is available only on Microsoft Windows.Argument Name Meaning
exportableexportableControls the legacy CryptoAPI exportability setting. This is the companion setting for the older certificate-import path; it is not the setting that determines exportability of the CNG-persisted key.userProtecteduserProtectedWhentrue, enables Windows strong key protection, which can display an interactive prompt when the key is imported or used. Whenfalse, key import and use are silent.machineKeysetmachineKeysetSelects the scope for both private-key storage and certificate stores.trueuses Local Machine;falseuses Current User. Local Machine imports generally require elevation.allowOverwriteKeyallowOverwriteKeyWhentrue, an existing private key having the same key-container name may be overwritten. Whenfalse, the import fails if that key already exists.allowExportallowExportControls the private key as persisted by the CNG Microsoft Software Key Storage Provider. Whentrue, the key is marked plaintext-exportable and can later be exported, including as raw private-key material. This is the effective exportability control for the key installed by this method.leafStoreleafStoreDestination store for end-entity (leaf) certificates.intermediateStoreintermediateStoreDestination store for intermediate CA certificates.rootStorerootStoreDestination store for root or self-signed certificates.extraOptionsextraOptionsCurrently unused. It has no effect for any value. Pass an empty string.Two different exportability settings:
exportableapplies to the legacy CryptoAPI path.allowExportapplies to the CNG Key Storage Provider used to persist the private key and determines whether that installed key can actually be exported later. SetallowExporttotrueonly when later private-key export is required, because it permits plaintext export.Store names are case-insensitive. Standard names include
Myfor leaf certificates,CAorCertificationAuthorityfor intermediate certificates, andRootfor trusted roots. For any certificate class, passNone,Nothing, or an empty string to skip importing that class. Other Windows store names, such asAddressBook,AuthRoot,TrustedPeople, andTrustedPublisher, may also be used when appropriate.If a certificate already exists, it is updated or replaced rather than causing an error. Existing private keys are handled separately: when a key having the same key-container name exists,
allowOverwriteKeydetermines whether it is overwritten or causes the import to fail. The key-container name comes from the private key's friendly name; if no friendly name exists, Chilkat generates a unique name.Overwrite risk: Enabling
allowOverwriteKeycan replace an unrelated existing key when its container name matches the imported key's friendly name. Enable overwrite only when that name is known to identify the key that should be replaced. Not atomic: Keys are imported one at a time, followed by certificates one at a time. Items imported before a later failure remain installed. A private-key failure stops key processing, while a certificate failure does not necessarily prevent later certificates from being attempted. Afalsereturn can therefore leave partial results in Windows; applications requiring all-or-nothing behavior must inspect and clean up the target stores themselves. Interactive protection: Do not setuserProtectedtotruein a Windows service or another noninteractive process. The required protection prompt cannot be displayed and the operation may fail or hang. Usefalsefor silent service and server operation. Trust-store impact: Importing a root certificate into the WindowsRootstore makes it a trust anchor for the selected Current User or Local Machine scope. Import only roots that the application or administrator intentionally trusts. UseNoneforrootStorewhen root installation is not required.Common configurations:
Scenario Typical settings
Per-user, silent import
exportable=false,userProtected=false,machineKeyset=false,allowOverwriteKey=false,allowExport=false, leafMy, intermediateCA, rootNone.Machine-wide service/server Use the silent settings above with
machineKeyset=trueand run elevated.Key must be exportable later Set
allowExport=true. Also setexportable=truewhen legacy CryptoAPI exportability is wanted.Leaf certificate only Use a real leaf store such as
Myand passNonefor both intermediate and root stores.Replace an existing key Set
allowOverwriteKey=trueonly after confirming that the key-container name cannot collide with an unrelated key.- Parameters:
exportable- theexportableargumentuserProtected- theuserProtectedargumentmachineKeyset- themachineKeysetargumentallowOverwriteKey- theallowOverwriteKeyargumentallowExport- theallowExportargumentleafStore- theleafStoreargument (notnull)intermediateStore- theintermediateStoreargument (notnull)rootStore- therootStoreargument (notnull)extraOptions- theextraOptionsargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
loadPem
Loads one or more certificate/private-key identities from the PEM-formatted text inpemStrand builds the contents of thisPfxobject.passwordsupplies the password when the PEM contains encrypted private keys.The supported PEM block types are:
PEM block Meaning
BEGIN CERTIFICATEAn X.509 certificate.BEGIN PRIVATE KEYAn unencrypted PKCS #8 private key.BEGIN ENCRYPTED PRIVATE KEYA password-encrypted PKCS #8 private key.BEGIN RSA PRIVATE KEYA traditional RSA private key, either unencrypted or password-encrypted.Multiple independent identities are supported. Each private key is paired with the certificate whose public key cryptographically matches it, and its chain is assembled from the other certificates in the PEM. Block order is therefore irrelevant; keys and certificates are not paired by position.
Required content: The PEM must contain at least one private key, and every private key must have a matching certificate. The method fails if any key lacks its certificate or if the PEM contains certificates but no private key. Certificates that do not belong to any loaded key's certificate chain are not carried into the PFX. Duplicates: Repeated private-key or certificate blocks are accepted and de-duplicated. They do not cause an error and do not create duplicate entries in the resulting PFX. Replacement and failure behavior: A successful call replaces all existing contents. If the PEM cannot be parsed, the previous contents are preserved because replacement has not begun. If parsing succeeds but conversion fails while the parsed items are being added, the object has already been cleared and may contain only the items processed before the failure. Therefore, a failed call can mean either unchanged or partially replaced state, depending on where the failure occurred.
- Parameters:
pemStr- thepemStrargument (notnull)password- thepasswordargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
loadPfxBd
Loads a PFX / PKCS#12 container from the bytes currently held inbd.passwordis the password argument.Password and JSON options:
passwordaccepts either a literal password, which is used for both integrity verification and all private-key bags, or a JSON object that can separately provideintegrity,privKeys, andskipPrivateKeys. Seefor the exact JSON-detection rules, member types, defaults, and edge cases.Destructive replacement: This method always replaces the current contents. The object is cleared before the import is attempted, so a failed load leaves theloadPfxFile(String, String)Pfxobject empty; previously loaded certificates and keys are not preserved.- Parameters:
bd- thebdargument (notnull)password- thepasswordargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
loadPfxEncoded
Decodes the text inencodedDatausing the binary encoding named byencoding, then loads the resulting bytes as a PFX / PKCS#12 container. Common encodings includebase64andhex.passwordis the password argument.Password and JSON options:
passwordaccepts either a literal password, which is used for both integrity verification and all private-key bags, or a JSON object that can separately provideintegrity,privKeys, andskipPrivateKeys. Seefor the exact JSON-detection rules, member types, defaults, and edge cases.Binary encoding is not a charset:loadPfxFile(String, String)encodingdescribes how binary PFX bytes were represented as text. It does not control certificate-name character encoding or password interpretation.Destructive replacement: This method always replaces the current contents. The object is cleared before the import is attempted, so a decoding error, bad password, or malformed PFX leaves thePfxobject empty; previously loaded certificates and keys are not preserved.- Parameters:
encodedData- theencodedDataargument (notnull)encoding- theencodingargument (notnull)password- thepasswordargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
loadPfxFile
Loads a PFX / PKCS#12 container from the file path inpath.passwordfollows the password contract below. The same contract is used by,LoadPfxBytes, andloadPfxBd(BinData, String); it does not apply toloadPfxEncoded(String, String, String).loadPem(String, String)The password argument has two modes:
- Plain password: For any non-JSON value
P, Chilkat usesPfor both integrity verification and all private-key bags.skipPrivateKeysisfalse. - JSON options: After trimming leading and trailing whitespace, JSON mode is used
only when the value begins with
{, ends with}, and parses as valid JSON. All three recognized members are optional and case-sensitive.
{ "integrity": "integrity-password", "privKeys": "private-key-password", "skipPrivateKeys": false }Member Accepted value Default when omitted
integrityString Integrity verification is skipped.privKeysString The empty string is used as the password for every private-key bag.skipPrivateKeysJSON Booleantrue, or a string equal totruewithout regard to casefalseUnknown JSON members are silently ignored. A misspelled member such as
privkeystherefore does not produce a JSON error; the documented default is used instead. The singleprivKeyspassword applies to every private-key bag. Per-bag passwords are not supported.Certificate-only loading: When
skipPrivateKeysis true, private-key bags are not processed and theprivKeyspassword is irrelevant. Integrity verification is still performed when anintegritymember is supplied.Empty versus omitted integrity password: A plain empty string requests integrity verification using an empty password. To intentionally skip integrity verification, use JSON and omitintegrity, for example{"skipPrivateKeys":true}or{}.Literal-password collision: A real password that, after trimming, is a valid JSON object text is interpreted as options, and there is no force-literal escape. Text enclosed in braces that is not valid JSON falls back to literal-password handling.Independent protection roles: PKCS#12 can use one password for the container integrity MAC and another for encrypted private-key bags. A correctintegritypassword does not validate theprivKeyspassword. If integrity verification succeeds but private-key decryption fails, the load still fails unless private keys were skipped.Destructive replacement: This method always replaces the current contents. The object is cleared before opening and importing the file, so any failure—including a missing file, invalid password, or malformed PFX—leaves thePfxobject empty. Load into a new object when the previously loaded contents must be preserved on failure.- Parameters:
path- thepathargument (notnull)password- thepasswordargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
- Plain password: For any non-JSON value
-
privateKeyAt
Copies the private key at the zero-based indexindexintoprivKey. The first private key is at index0; valid indexes are less than.getNumPrivateKeys()On success,
privKeyis replaced with an independent, detached copy of the selected private key. The method does not merge with or append to any key already held byprivKey. The returned copy does not remain linked to the PFX: changing either object later does not affect the other, and the copied key remains usable even if the PFX is subsequently modified or destroyed.Failure leaves the destination unchanged: If
indexis out of range or the private key cannot be returned, the method returnsfalsewithout modifyingprivKey. When reusing aPrivateKeyobject, use its contents only after this method returnstrue; otherwiseprivKeymay still contain a key from an earlier successful call. Do not pair by index: Private-key indexes and certificate indexes are independent.PrivateKeyAt(i)is not necessarily associated with. Finding the matching certificate: CallcertAt(int, Cert)withgetSafeBagAttr(boolean, int, String)indexset totrue,privKeyset to this private-key index, and ARG3 set tolocalKeyId. If the attribute is present, pass the returned value tousingcertByLocalKeyId(String, String, Cert)decimalas the encoding. Sensitive material: TreatprivKeyas secret key material. Avoid unnecessary serialization, logging, or long-lived copies.- Parameters:
index- theindexargumentprivKey- theprivKeyargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setSafeBagAttr
public void setSafeBagAttr(boolean forPrivateKey, int index, String name, String value, String encoding)Sets a safe-bag attribute on a private key or certificate contained in this PFX. A safe-bag attribute is metadata attached to an item inside a PKCS#12/PFX container; it does not change the certificate or private-key material itself.forPrivateKeyistrueto address a private key andfalseto address a certificate.indexis the zero-based index within the selected collection.nameis the attribute name. Attribute names are matched case-insensitively.valueis the value to set.encodingspecifies howvalueis decoded only when settinglocalKeyId. It is ignored for all text-valued attributes.
Setting a recognized attribute replaces its existing value; it never creates a duplicate attribute. The method returns
falseand makes no change ifnameis not one of the recognized names listed below.Logical attribute Accepted
namenames Value and behaviorFriendly name
friendlyName,keyContainerName, orkeyNameThese names refer to the same underlying text attribute.valueis stored as text, andencodingis ignored. Setting through any alias replaces the value visible through every alias.Storage provider
storageProviderormsStorageProviderThe two names refer to the same underlying text attribute.valueis stored as text, andencodingis ignored.Local key ID
localKeyIdA binary identifier commonly used to associate a private-key bag with its certificate bag.encodingspecifies the encoding ofvalue, such ashex,base64, ordecimal. An emptyvalueremoves the attribute.Enhanced key usage
enhancedKeyUsagevalueis a comma-separated text list. Each item may be a recognized usage name, such asserverAuth,clientAuth,codeSigning, oremailProtection, or a dotted OID such as1.3.6.1.5.5.7.3.1. Unrecognized items that are not valid OIDs are silently skipped.encodingis ignored. An emptyvalueremoves the attribute. This attribute is write-only through the safe-bag attribute API.Encoding applies only to localKeyId: Friendly name, storage provider, and enhanced key usage are text values. Supplying
hex,base64, or another encoding for those attributes has no effect.- Parameters:
forPrivateKey- theforPrivateKeyargumentindex- theindexargumentname- thenameargument (notnull)value- thevalueargument (notnull)encoding- theencodingargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
toBd
Serializes the current PFX contents as PKCS#12 data and writes the bytes tobd, usingpasswordas the output password.bdis cleared before serialization begins. On success, it contains only the newly generated PFX data; the method replaces the previousBinDatacontents and never appends to them.Clear-first failure behavior: If the method returns
false, the contents thatbdheld before the call are not restored.bdmay be empty or may contain partially generated data. Use the destination only after atruereturn when complete output is required.The private-key encryption scheme is controlled by
and, for PBES2, the related algorithm properties.getAlgorithmId()Sensitive output:
bdmay contain encrypted private-key material. Keep the password and resulting bytes protected even though they are stored only in memory.- Parameters:
password- thepasswordargument (notnull)bd- thebdargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
toEncodedString
Serializes the current PFX contents usingpasswordas the output password, then returns the PKCS#12 bytes encoded as text usingencoding. Common choices forencodingarebase64andhex.The PFX encryption settings are controlled by
and the PBES2 properties.getAlgorithmId()Encoding does not add protection: Base64, hexadecimal, and similar encodings only represent binary bytes as text. The confidentiality of private keys depends on the PFX password and encryption settings.
- Parameters:
password- thepasswordargument (notnull)encoding- theencodingargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
toFile
Serializes the current PFX contents and writes the resulting PKCS#12 data topath, usingpasswordas the output password..pfxand.p12are the conventional filename extensions for PKCS#12 containers. The private-key protection scheme is controlled byand the PBES2 properties.getAlgorithmId()File security: A PFX commonly contains private keys. In addition to choosing a strong password, protect the file with appropriate filesystem permissions and avoid leaving unnecessary backup copies.
- Parameters:
password- thepasswordargument (notnull)path- thepathargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
toJksObj
PopulatesjksObjwith a Java KeyStore (JKS) representation of this PFX. One private-key entry is created for each private key, and certificates in the PFX are used to construct the corresponding certificate chains.passwordprotects the generated private-key entries.jksObjis cleared before conversion begins. On success, it contains only the newly converted key store; the method replaces the destination's previous entries rather than merging with them.Clear-first failure behavior: If conversion returns
false, the key store thatjksObjheld before the call is not restored.jksObjmay be empty or partially populated. Use the destination only after atruereturn when a complete conversion is required.If
aliasNameis nonempty, it becomes the alias for the first private key. Otherwise, the alias is selected in this order:- Certificate subject common name.
- Certificate subject email address.
- PKCS#9 friendly-name attribute.
- Certificate serial number.
Aliases for additional private keys are selected automatically using the same preference order.
Container conversion: PKCS#12 and JKS are different keystore formats. Conversion preserves available key-and-certificate relationships, but provider-specific PKCS#12 attributes may not have an equivalent JKS representation.
- Parameters:
aliasName- thealiasNameargument (notnull)password- thepasswordargument (notnull)jksObj- thejksObjargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
toPem
Exports all private keys and certificates currently held by this object as PEM-formatted text. Certificates are written as standardBEGIN CERTIFICATEblocks.Every private key is exported as unencrypted PKCS #8 in a
BEGIN PRIVATE KEYblock. This method does not emit PKCS #1 RSA, SEC 1 EC, traditional DSA, or legacy OpenSSL encrypted-private-key blocks.Private keys are unencrypted: The returned text contains cleartext private-key material. Use
to produce encrypted PKCS #8 private-key blocks or to omit selected categories of objects.toPemEx(boolean, boolean, boolean, boolean, String, String)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
toPemEx
public String toPemEx(boolean extendedAttrs, boolean noKeys, boolean noCerts, boolean noCaCerts, String encryptAlg, String password)Exports selected PFX contents as PEM-formatted text. Certificates are written as standardBEGIN CERTIFICATEblocks. Private keys are always written in PKCS #8 form:BEGIN PRIVATE KEYwhen unencrypted, orBEGIN ENCRYPTED PRIVATE KEYwhen encrypted. Traditional PKCS #1 RSA, SEC 1 EC, DSA, and legacy OpenSSL encrypted-key PEM formats are not produced.The arguments control the output as follows:
Argument Effect
extendedAttrsWhentrue, emits OpenSSL-style bag and key attribute text in addition to the PEM blocks.noKeysWhentrue, omits private-key blocks.noCertsWhentrue, omits all certificate blocks.noCaCertsWhentrue, omits intermediate and root CA certificates while retaining applicable end-entity certificates.encryptAlgSelects private-key encryption. Recognized keywords areaes128,aes192,aes256,des3, and3des. Leave empty for unencrypted private keys. An unrecognized nonempty value falls back to triple-DES rather than silently producing unencrypted output.passwordThe password for encrypted private-key output. Encryption is applied only when bothencryptAlgandpasswordare nonempty.Encryption format: AES choices use CBC mode with a 16-byte IV.
des3and3desuse triple-DES in CBC mode with an 8-byte IV. The result is an encrypted PKCS #8BEGIN ENCRYPTED PRIVATE KEYblock. Security note: If private keys are included and eitherencryptAlgorpasswordis empty, the output contains unencrypted PKCS #8 private-key material. Preferaes256for new encrypted output unless the receiving system requires another supported choice.- Parameters:
extendedAttrs- theextendedAttrsargumentnoKeys- thenoKeysargumentnoCerts- thenoCertsargumentnoCaCerts- thenoCaCertsargumentencryptAlg- theencryptAlgargument (notnull)password- thepasswordargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
useCertVault
Adds the certificates currently contained invaultto the set of certificate sources available for later chain-building operations, such as.addCert(Cert, boolean)The call captures a point-in-time snapshot of the vault's certificates. Chilkat retains its own lifetime-safe references to those individual certificates and does not retain a reference to the
XmlCertVaultobject itself. After this method returns,vaultmay be released, destroyed, or allowed to go out of scope; its contributed certificates remain available to thisPfxobject.Snapshot, not live synchronization: Certificates added to or removed from
vaultafter this call are not automatically reflected here. CallUseCertVaultagain to capture certificates added later. Additive behavior: Repeated calls accumulate certificate sources; a later call does not replace or clear certificates contributed by earlier vaults. The vault certificates are made available for chain construction and are not, merely by this call, added to the PFX's exported certificate collection.- Parameters:
vault- thevaultargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-