PrivateKey React Native Reference Documentation

PrivateKey

Current Version: 11.6.1

PrivateKey

Load, inspect, export, save, and convert one private key.

PrivateKey is a key-container class. It holds one current RSA, DSA, EC, or Ed25519 private key and provides format conversion, persistence, JWK/XML access, raw EC and Ed25519 access, and public-key extraction. Cryptographic operations such as signing, decryption, TLS authentication, and SSH authentication are performed by other Chilkat classes that receive the loaded PrivateKey.

Content-based loading

Named load methods inspect the content and recognize supported unencrypted formats. Password-taking loaders also recognize encrypted PKCS #8 and unencrypted input.

Standard export choices

Use PKCS #8 for modern algorithm-independent interchange, encrypted PKCS #8 for password-protected storage, JWK for JOSE, and traditional PEM only when required by a legacy consumer.

One-key state

A successful load replaces the current key. A failed load leaves the object empty. Check KeyType and BitLength after loading when the expected algorithm matters.

Independent public key

ToPublicKey creates an independent PublicKey that is unaffected when this object is reloaded with another key.

Key generation

Generate new keys with Rsa, Ecc, or EdDSA, which can place the generated key into a PrivateKey.

Certificates are separate

A private key does not contain a certificate or chain. Use Cert or Pfx when certificate association is required.

Recommended format selection: Prefer unencrypted PKCS #8 for transient interchange, encrypted PKCS #8 with aes256 and a strong password for stored key files, JWK for JWT/JWS/JWE workflows, and traditional RSA or EC PEM only when the receiving software requires it.
Protect private material: Base64, hexadecimal, PEM, JWK, and XML are encodings or containers, not encryption. Avoid exporting a private key unless necessary, and protect every unencrypted representation as sensitive data.

Object Creation

// npm install @chilkat/react-native react-native-nitro-modules
// (React Native 0.76+ with the New Architecture; then `pod install` for iOS.  The Chilkat
//  native library is downloaded and verified during the native build -- see the package README.)

import { Chilkat, PrivateKey } from '@chilkat/react-native'

// Once per app start, before any other Chilkat call:
Chilkat.unlockBundle('Anything for 30-day trial')   // shorthand for new Global().unlockBundle(..)

const privateKey = new PrivateKey()
// ... the native object is released when `privateKey` is garbage collected, or now with privateKey.dispose()
new PrivateKey()

Creates the underlying native Chilkat object. PrivateKey is a Nitro Module HybridObject: use it from the JavaScript thread only (it cannot be passed to a Worklet or another runtime). Every member is synchronous and blocks the JavaScript thread until Chilkat returns; a method that can take a while also exists as a ...Async twin returning a Promise, which runs the same call on a native worker thread so the UI keeps rendering. While such a call is pending, every other call on this object throws, except abort() and assigning onPercentDone / onProgressInfo.

dispose(): void

Releases the native object immediately instead of waiting for garbage collection (useful for a large BinData or an open socket). Calling it more than once is harmless; any other use of the object afterwards throws. An object with a pending ...Async call cannot be disposed until the promise settles.

Errors

A method that can fail throws a plain Error: a method whose only outcome is success or failure returns void and throws on failure; a method producing a string or an object returns it and throws where Chilkat would have returned null. The error's message is "Class.method(...): reason", where the reason is the last informative line of the object's lastErrorText, which holds the full Chilkat log of the failed call. A ...Async twin rejects its promise with the same Error instead of throwing. Properties never throw, and methods that answer a question (has..., is..., ...) return a plain boolean.

try {
  privateKey.someMethod(...)
} catch (e) {
  console.log((e as Error).message)   // PrivateKey.someMethod(...): <reason>
  console.log(privateKey.lastErrorText)   // the full Chilkat log of the failed call
}

// The same call without blocking the JavaScript thread:
try {
  await privateKey.someMethodAsync(...)
} catch (e) {
  console.log((e as Error).message)   // PrivateKey.someMethodAsync: <reason>
}

Properties

BitLength
// read-only
readonly bitLength: number
Introduced in version 9.5.0.49

Returns the nominal size of the loaded private key, in bits. The value is 0 when the object is empty. For RSA it is the modulus size; for DSA it is the size of p; for EC it is the named-curve field size; and for Ed25519 it is 256.

Comparing strength: Bit lengths are meaningful only within the context of the algorithm. A 256-bit EC key and a 256-bit RSA key do not provide comparable security.

top
DebugLogFilePath
// read/write
debugLogFilePath: string

If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.

Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.

Possible causes of hangs include:

  • A timeout property set to 0, indicating an infinite timeout.
  • A hang occurring within an event callback in the application code.
  • An internal bug in the Chilkat code causing the hang.

More Information and Examples
top
KeyType
// read-only
readonly keyType: string
Introduced in version 9.5.0.52

Identifies the algorithm of the currently loaded key. The value is one of empty, rsa, dsa, ecc, or ed25519. empty means that no usable private key is loaded.

One-key state model: A PrivateKey object holds one current key. Loading another key replaces it; a failed load leaves the object empty.

top
LastErrorHtml
// read-only
readonly lastErrorHtml: string

Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastErrorText
// read-only
readonly lastErrorText: string

Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastErrorXml
// read-only
readonly lastErrorXml: string

Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastMethodSuccess
// read/write
lastMethodSuccess: boolean

Indicates the success or failure of the most recent method call: true means success, false means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.

top
Pkcs8EncryptAlg
// read/write
pkcs8EncryptAlg: string
Introduced in version 9.5.0.49

Controls the block cipher used by encrypted PKCS #8 export methods. Supported values are 3des, aes128, aes192, and aes256. Values are case-insensitive and are normalized to lowercase. The default is 3des. Assigning an empty or unrecognized value resets the property to 3des. All choices use CBC mode.

Encrypted PKCS #8 output uses PBES2 with PBKDF2. The generated parameters use an 8-byte salt, 2048 PBKDF2 iterations, and the default PBKDF2 PRF (HMAC-SHA-1). The selected cipher uses CBC mode with a newly generated IV.

Recommended setting: Prefer aes256 for new output unless an older consumer requires 3DES. This property selects encryption parameters only; password quality remains essential.

top
UncommonOptions
// read/write
uncommonOptions: string
Introduced in version 9.5.0.96

Provides a catch-all string for specialized compatibility options that are not exposed as ordinary properties. The default is the empty string, which is appropriate for normal use.

Leave empty unless instructed: Set this property only when a Chilkat example, release note, or support response documents a specific option needed for an unusual interoperability case.

top
VerboseLogging
// read/write
verboseLogging: boolean

If set to true, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is false. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.

top
Version
// read-only
readonly version: string

Version of the component/library, such as "10.1.0"

More Information and Examples
top

Methods

GetJwk
getJwk(): string
Introduced in version 9.5.0.66

Exports the key as a compact JWK (JSON Web Key). Binary integers and byte strings use Base64url without padding.

Key typeMembers emitted
RSAkty, n, e, d, p, q, dp, dq, qi
ECkty, crv, x, y, d
Ed25519kty=OKP, crv=Ed25519, x, d, and use=sig
Key material only: Optional JOSE metadata loaded from a JWK, such as kid, alg, key_ops, or a caller-supplied use, is not retained for re-export. The Ed25519 use=sig member is emitted by Chilkat.
Private output: The returned JSON contains private key material and must be protected accordingly.

Throws an Error on failure (where the description says null is returned, the method throws instead).

top
GetJwkThumbprint
getJwkThumbprint(hashAlg: string): string
Introduced in version 9.5.0.66

Computes the RFC 7638 thumbprint of the public portion of the loaded key using the hash algorithm named by hashAlg. Supported values include md5, sha1, sha256, sha384, and sha512. An unsupported name causes the method to fail. The returned digest is Base64url-encoded without padding.

Public-key identity: The canonical thumbprint input contains only the required public JWK members. Private members and optional metadata such as kid, use, and alg are excluded, so the result matches the thumbprint of the corresponding PublicKey.
Recommended hash: Use sha256 for normal RFC 7638 interoperability. MD5 and SHA-1 are available for compatibility but should not be chosen for new security-sensitive identifiers.

Throws an Error on failure (where the description says null is returned, the method throws instead).

top
GetPkcs1ENC
getPkcs1ENC(encoding: string): string
Introduced in version 9.5.0.52

Exports the key as the traditional or preferred unencrypted DER representation and encodes the DER as text using the binary encoding named by encoding. The binary bytes are the same as returned by GetPkcs1.

Historical method name: PKCS #1 is specifically an RSA standard. For non-RSA key types, this method returns the applicable traditional structure or a PKCS #8 fallback.
Key typeReturned representation
RSARSAPrivateKey DER from PKCS #1.
DSAThe traditional six-integer DSA private-key structure.
ECECPrivateKey DER from RFC 5915.
Ed25519PKCS #8 PrivateKeyInfo DER using the Ed25519 OID 1.3.101.112, because Ed25519 has no traditional PKCS #1 form.

For RSA, the DER contains:

RSAPrivateKey ::= SEQUENCE {
    version           Version,
    modulus           INTEGER,  -- n
    publicExponent    INTEGER,  -- e
    privateExponent   INTEGER,  -- d
    prime1            INTEGER,  -- p
    prime2            INTEGER,  -- q
    exponent1         INTEGER,  -- d mod (p-1)
    exponent2         INTEGER,  -- d mod (q-1)
    coefficient       INTEGER,  -- (inverse of q) mod p
    otherPrimeInfos   OtherPrimeInfos OPTIONAL
}

For EC, the traditional structure is:

ECPrivateKey ::= SEQUENCE {
    version        INTEGER { ecPrivkeyVer1(1) },
    privateKey     OCTET STRING,
    parameters [0] ECParameters OPTIONAL,
    publicKey  [1] BIT STRING OPTIONAL
}
Encoding validation: An unsupported encoding encoding name causes the method to fail; it does not silently select another encoding.

Throws an Error on failure (where the description says null is returned, the method throws instead).

top
GetPkcs1Pem
getPkcs1Pem(): string
Introduced in version 9.5.0.58

Exports the key as unencrypted PEM, preferring the traditional algorithm-specific representation when one exists.

Key typePEM labelBody
RSARSA PRIVATE KEYPKCS #1 DER
DSADSA PRIVATE KEYTraditional DSA DER
ECEC PRIVATE KEYRFC 5915 DER
Ed25519PRIVATE KEYPKCS #8 DER
Generated PEM formatting: PEM output uses CRLF line endings, Base64 lines of at most 64 characters, and a final CRLF.
Security note: The returned private key is not encrypted.

Throws an Error on failure (where the description says null is returned, the method throws instead).

More Information and Examples
top
GetPkcs8ENC
getPkcs8ENC(encoding: string): string
Introduced in version 9.5.0.52

Exports the key as unencrypted PKCS #8 DER and encodes the DER as text using the binary encoding named by encoding. PKCS #8 is an algorithm-independent private-key container. Chilkat emits the classic version-0 PrivateKeyInfo structure, with the algorithm-specific private-key DER in an OCTET STRING.

PrivateKeyInfo ::= SEQUENCE {
    version                   Version,
    privateKeyAlgorithm       AlgorithmIdentifier,
    privateKey                OCTET STRING,
    attributes           [0]  IMPLICIT Attributes OPTIONAL
}
Encoding validation: An unsupported encoding encoding name causes the method to fail; it does not silently select another encoding.
Encoding is not encryption: Base64, hexadecimal, and similar encodings only represent the DER bytes as text. They do not protect the private key.

Throws an Error on failure (where the description says null is returned, the method throws instead).

top
GetPkcs8EncryptedENC
getPkcs8EncryptedENC(encoding: string, password: string): string
Introduced in version 9.5.0.52

Exports the key as password-protected PKCS #8 DER, then encodes the encrypted DER as text. encoding names the binary encoding and password supplies the password. The cipher is selected by Pkcs8EncryptAlg.

Encrypted PKCS #8 output uses PBES2 with PBKDF2. The generated parameters use an 8-byte salt, 2048 PBKDF2 iterations, and the default PBKDF2 PRF (HMAC-SHA-1). The selected cipher uses CBC mode with a newly generated IV.

Encoding validation: An unsupported encoding encoding name causes the method to fail.
Empty passwords: A nonempty, strong password should be used. An empty password is accepted but provides no meaningful password protection.

Throws an Error on failure (where the description says null is returned, the method throws instead).

top
GetPkcs8EncryptedPem
getPkcs8EncryptedPem(password: string): string

Exports the key as password-protected PKCS #8 PEM using password as the password. The cipher is selected by Pkcs8EncryptAlg. The output uses:

-----BEGIN ENCRYPTED PRIVATE KEY-----
...
-----END ENCRYPTED PRIVATE KEY-----

Encrypted PKCS #8 output uses PBES2 with PBKDF2. The generated parameters use an 8-byte salt, 2048 PBKDF2 iterations, and the default PBKDF2 PRF (HMAC-SHA-1). The selected cipher uses CBC mode with a newly generated IV.

Generated PEM formatting: PEM output uses CRLF line endings, Base64 lines of at most 64 characters, and a final CRLF.
Empty passwords: An empty password is accepted and still produces encrypted PKCS #8, but it provides no meaningful password protection.

Throws an Error on failure (where the description says null is returned, the method throws instead).

top
GetPkcs8Pem
getPkcs8Pem(): string

Exports the key as unencrypted PKCS #8 PEM. For RSA, EC, and Ed25519, the PEM armor is:

-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----
PKCS #8 is an algorithm-independent private-key container. Chilkat emits the classic version-0 PrivateKeyInfo structure, with the algorithm-specific private-key DER in an OCTET STRING.
PrivateKeyInfo ::= SEQUENCE {
    version                   Version,
    privateKeyAlgorithm       AlgorithmIdentifier,
    privateKey                OCTET STRING,
    attributes           [0]  IMPLICIT Attributes OPTIONAL
}
Generated PEM formatting: PEM output uses CRLF line endings, Base64 lines of at most 64 characters, and a final CRLF.
Security note: This output is not password-protected.

Throws an Error on failure (where the description says null is returned, the method throws instead).

More Information and Examples
top
GetPkcsBd
getPkcsBd(pkcs1: boolean, password: string, bd: BinData): void
Introduced in version 11.0.0

Exports the key as DER and replaces the contents of the BinData in bd.

pkcs1passwordOutput
trueIgnored for encryption.RSA PKCS #1, traditional DSA, RFC 5915 EC, or PKCS #8 for Ed25519.
falseEmpty string.Unencrypted PKCS #8 DER.
falseNonempty password.Encrypted PKCS #8 DER using Pkcs8EncryptAlg.
Output state: A successful call replaces any existing bd content. If the call fails, bd is cleared.
Password behavior: When pkcs1 is true, password does not encrypt the output. To obtain encrypted output, set pkcs1 to false and provide a nonempty password.

Returns normally on success; throws an Error on failure.

More Information and Examples
top
GetRawHex
getRawHex(pubKey: StringBuilder): string
Introduced in version 9.5.0.83

Exports the raw private value as lowercase hexadecimal and replaces the contents of the StringBuilder in pubKey with the corresponding raw public key.

Key typeReturned private valuePublic value in pubKey
Ed25519The 32-byte seed accepted by LoadEd25519, as 64 hex characters.The 32-byte public key, as 64 hex characters.
ECThe private scalar, padded to the curve size as needed.The uncompressed point 04 || HEX(x) || HEX(y).
Applicable key types: This method supports Ed25519 and ordinary EC keys. RSA and DSA keys do not have a single simple raw representation and cause the method to fail.
Output on failure: If the method fails, pubKey is cleared.

Throws an Error on failure (where the description says null is returned, the method throws instead).

top
GetXml
getXml(): string

Exports the key in Chilkat-compatible XML. The XML is not encrypted. RSA and DSA components use ordinary Base64.

RSA keys use:

<RSAKeyValue>
  <Modulus>...</Modulus>
  <Exponent>...</Exponent>
  <D>...</D>
  <P>...</P>
  <Q>...</Q>
  <DP>...</DP>
  <DQ>...</DQ>
  <InverseQ>...</InverseQ>
</RSAKeyValue>

DSA keys use:

<DSAKeyValue>
  <P>...</P>
  <Q>...</Q>
  <G>...</G>
  <Y>...</Y>
  <X>...</X>
</DSAKeyValue>

EC keys place the named curve in the curve attribute and Base64-encode the RFC 5915 ECPrivateKey DER in the element content:

<ECCKeyValue curve="secp256r1">...</ECCKeyValue>

Ed25519 keys Base64-encode 64 bytes consisting of the 32-byte private seed followed by the 32-byte public key:

<Ed25519KeyValue>...</Ed25519KeyValue>
Round-trip support: XML produced by this method can be loaded by LoadXml, LoadXmlFile, or the general format-detection methods.
Interoperability note: These XML forms are Chilkat-compatible representations. Prefer PKCS #8, PEM, or JWK when interoperating with systems that expect standard key containers.

Throws an Error on failure (where the description says null is returned, the method throws instead).

top
LoadAnyFormat
loadAnyFormat(privKeyData: BinData, password: string): void
Introduced in version 9.5.0.75

Loads a private key from the data in privKeyData by inspecting its contents. Recognized representations include RSA PKCS #1 DER, traditional DSA and EC DER, PKCS #8 DER, encrypted PKCS #8, PEM, JWK, Chilkat-compatible XML, Microsoft PVK, and supported Ed25519 representations. password supplies the password when the detected representation is encrypted; otherwise it may be empty.

Text and binary input: privKeyData contains the exact bytes to inspect. Textual PEM, JWK, and XML are detected from those bytes; a filename extension is not involved.
Trailing DER data: If the input begins with one complete supported DER key followed by extra bytes or another DER object, the first key is loaded and trailing data is ignored.
Object state: A successful load replaces any key already held by this object. If loading fails, this object is left empty.

Returns normally on success; throws an Error on failure.

top
LoadAnyFormatFile
loadAnyFormatFile(path: string, password: string): void
Introduced in version 9.5.0.83

Loads a private key from the file at path by inspecting its contents. Recognized representations include RSA PKCS #1 DER, traditional DSA and EC DER, PKCS #8 DER, encrypted PKCS #8, PEM, JWK, Chilkat-compatible XML, Microsoft PVK, and supported Ed25519 representations. password supplies the password when needed.

Filename extensions are advisory: The file content determines the format; a nonstandard or misleading extension does not prevent recognition.
Object state: A successful load replaces any key already held by this object. If loading fails, this object is left empty.

Returns normally on success; throws an Error on failure.

More Information and Examples
top
LoadEd25519
loadEd25519(privKey: string, pubKey: string): void
Introduced in version 9.5.0.83

Loads an Ed25519 key pair from raw hexadecimal values. privKey is the 32-byte Ed25519 private seed. pubKey is the 32-byte public key. Each nonempty value must contain exactly 64 hexadecimal digits. Uppercase hexadecimal and an optional 0x prefix are accepted; embedded whitespace is not accepted. pubKey may be empty, in which case Chilkat derives the public key from the seed.

Supplied public key is not verified: When pubKey is nonempty, Chilkat stores the supplied public value without checking that it corresponds to privKey. Pass an empty pubKey when the public key should be derived and guaranteed to match the private seed.
Object state: A successful load replaces any key already held by this object. If loading fails, this object is left empty.

Returns normally on success; throws an Error on failure.

top
LoadEncryptedPem
loadEncryptedPem(pemStr: string, password: string): void

Loads a private key from the PEM text in pemStr. password supplies the password when the PEM is encrypted. The method accepts encrypted PKCS #8 PEM and also loads supported unencrypted PEM.

-----BEGIN ENCRYPTED PRIVATE KEY-----
...
-----END ENCRYPTED PRIVATE KEY-----
Content auto-detection: Chilkat examines the content rather than relying on the method name or filename extension. This password-taking method can load both encrypted and unencrypted supported private-key representations.
Object state: A successful load replaces any key already held by this object. If loading fails, this object is left empty.
Password failure: An incorrect password causes loading to fail and leaves this object empty.

Returns normally on success; throws an Error on failure.

top
LoadEncryptedPemFile
loadEncryptedPemFile(path: string, password: string): void

Loads a private key from the file at path, using password when the detected key is encrypted. The file may contain encrypted PKCS #8 PEM or another supported encrypted or unencrypted representation.

Content auto-detection: Chilkat examines the content rather than relying on the method name or filename extension. This password-taking method can load both encrypted and unencrypted supported private-key representations.
Object state: A successful load replaces any key already held by this object. If loading fails, this object is left empty.

Returns normally on success; throws an Error on failure.

top
LoadJwk
loadJwk(jsonStr: string): void
Introduced in version 9.5.0.66

Loads a private key from the JWK JSON in jsonStr. Supported private JWK key types are RSA (kty=RSA), EC (kty=EC), and Ed25519 (kty=OKP, crv=Ed25519). An unsupported kty causes the method to fail.

Private key material required: A JWK containing only public members belongs in a PublicKey. This method is for JWKs that contain private key material.
Metadata handling: Optional JOSE metadata such as kid, use, alg, and key_ops may be present but is not retained by PrivateKey.
Object state: A successful load replaces any key already held by this object. If loading fails, this object is left empty.

Returns normally on success; throws an Error on failure.

top
LoadPem
loadPem(str: string): void

Loads a private key from the PEM text in str. This method has no password argument and therefore cannot load password-protected PEM. Use LoadEncryptedPem for encrypted input.

Content auto-detection: The method name identifies the expected or traditional use, but Chilkat examines the content and can load other supported unencrypted private-key representations. Encrypted input requires a load method that accepts a password.
PEM block selection: If the text contains multiple PEM blocks, Chilkat selects the first supported private-key block. It skips preceding public-key or unrelated PEM blocks.
Accepted surrounding content: Leading and trailing whitespace, a UTF-8 BOM, and trailing non-PEM text are accepted.
Object state: A successful load replaces any key already held by this object. If loading fails, this object is left empty.

Returns normally on success; throws an Error on failure.

top
LoadPemFile
loadPemFile(path: string): void

Loads a private key from the file at path. This method has no password argument and therefore cannot load a password-protected key. Use LoadEncryptedPemFile or LoadAnyFormatFile when a password may be required.

Content auto-detection: The method name identifies the expected or traditional use, but Chilkat examines the content and can load other supported unencrypted private-key representations. Encrypted input requires a load method that accepts a password.
PEM block selection: For a file containing multiple PEM blocks, Chilkat selects the first supported private-key block and skips preceding public-key or unrelated blocks.
Object state: A successful load replaces any key already held by this object. If loading fails, this object is left empty.

Returns normally on success; throws an Error on failure.

top
LoadPkcs1File
loadPkcs1File(path: string): void
Introduced in version 9.5.0.58

Loads a private key from the file at path. Despite the historical PKCS #1 name, the method examines the content and accepts supported unencrypted private-key representations.

Content auto-detection: The method name identifies the expected or traditional use, but Chilkat examines the content and can load other supported unencrypted private-key representations. Encrypted input requires a load method that accepts a password.
Object state: A successful load replaces any key already held by this object. If loading fails, this object is left empty.

Returns normally on success; throws an Error on failure.

More Information and Examples
top
LoadPkcs8EncryptedFile
loadPkcs8EncryptedFile(path: string, password: string): void

Loads a private key from the file at path, using password when the detected key is encrypted. The method can load encrypted PKCS #8 DER or PEM and also supported unencrypted representations.

Content auto-detection: Chilkat examines the content rather than relying on the method name or filename extension. This password-taking method can load both encrypted and unencrypted supported private-key representations.
Object state: A successful load replaces any key already held by this object. If loading fails, this object is left empty.

Returns normally on success; throws an Error on failure.

top
LoadPkcs8File
loadPkcs8File(path: string): void

Loads a private key from the file at path. Although named for unencrypted PKCS #8, the method examines the file content and accepts other supported unencrypted private-key representations.

Content auto-detection: The method name identifies the expected or traditional use, but Chilkat examines the content and can load other supported unencrypted private-key representations. Encrypted input requires a load method that accepts a password.
Trailing DER data: When the file begins with a complete supported DER private-key object, trailing bytes or a second concatenated DER object are ignored; the first key is loaded.
Object state: A successful load replaces any key already held by this object. If loading fails, this object is left empty.

Returns normally on success; throws an Error on failure.

More Information and Examples
top
LoadPvkFile
loadPvkFile(path: string, password: string): void

Loads a private key from the file at path, using password if the detected representation is encrypted. This Windows-only method supports Microsoft PVK and also participates in Chilkat private-key content auto-detection.

Content auto-detection: Chilkat examines the content rather than relying on the method name or filename extension. This password-taking method can load both encrypted and unencrypted supported private-key representations.
Object state: A successful load replaces any key already held by this object. If loading fails, this object is left empty.

Returns normally on success; throws an Error on failure.

top
LoadXml
loadXml(xml: string): void

Loads a private key from the XML text in xml. Supported Chilkat-compatible XML roots include RSAKeyValue, DSAKeyValue, ECCKeyValue, and Ed25519KeyValue.

Content auto-detection: The method name identifies the expected or traditional use, but Chilkat examines the content and can load other supported unencrypted private-key representations. Encrypted input requires a load method that accepts a password.
Ed25519 XML: The Ed25519KeyValue content is ordinary Base64 for the 32-byte private seed followed by the 32-byte public key.
Object state: A successful load replaces any key already held by this object. If loading fails, this object is left empty.

Returns normally on success; throws an Error on failure.

More Information and Examples
top
LoadXmlFile
loadXmlFile(path: string): void

Loads a private key from the file at path. Chilkat recognizes RSA, DSA, EC, and Ed25519 XML produced by GetXml, and also auto-detects other supported unencrypted private-key representations.

Content auto-detection: The method name identifies the expected or traditional use, but Chilkat examines the content and can load other supported unencrypted private-key representations. Encrypted input requires a load method that accepts a password.
Object state: A successful load replaces any key already held by this object. If loading fails, this object is left empty.

Returns normally on success; throws an Error on failure.

More Information and Examples
top
SavePemFile
savePemFile(path: string): void
Introduced in version 9.5.0.58

Saves the key at path as unencrypted PEM, preferring a traditional algorithm-specific representation when one exists. RSA uses RSA PRIVATE KEY, DSA uses DSA PRIVATE KEY, EC uses EC PRIVATE KEY, and Ed25519 uses the PKCS #8 PRIVATE KEY form.

Generated PEM formatting: PEM output uses CRLF line endings, Base64 lines of at most 64 characters, and a final CRLF.
File behavior: An existing destination file is replaced. Parent directories are not created; the parent directory must already exist.
PKCS #8 alternative: Use SavePkcs8PemFile to always request the algorithm-independent PKCS #8 PRIVATE KEY form.
Security note: The file is not password-protected.

Returns normally on success; throws an Error on failure.

More Information and Examples
top
SavePkcs1File
savePkcs1File(path: string): void
Introduced in version 9.5.0.58

Saves the key at path using the traditional or preferred unencrypted DER representation.

Historical method name: RSA is saved as PKCS #1, EC as RFC 5915, DSA in its traditional structure, and Ed25519 as PKCS #8 because no traditional PKCS #1 form exists.
File behavior: An existing destination file is replaced. Parent directories are not created; the parent directory must already exist.
Security note: The file contains cleartext private-key material.

Returns normally on success; throws an Error on failure.

More Information and Examples
top
SavePkcs8EncryptedFile
savePkcs8EncryptedFile(password: string, path: string): void

Saves the key as password-protected PKCS #8 DER. password supplies the password and path is the destination path. The cipher is selected by Pkcs8EncryptAlg.

Encrypted PKCS #8 output uses PBES2 with PBKDF2. The generated parameters use an 8-byte salt, 2048 PBKDF2 iterations, and the default PBKDF2 PRF (HMAC-SHA-1). The selected cipher uses CBC mode with a newly generated IV.

File behavior: An existing destination file is replaced. Parent directories are not created; the parent directory must already exist.
Empty passwords: An empty password is accepted but provides no meaningful password protection.

Returns normally on success; throws an Error on failure.

top
SavePkcs8EncryptedPemFile
savePkcs8EncryptedPemFile(password: string, path: string): void

Saves the key as password-protected PKCS #8 PEM. password supplies the password and path is the destination path. The file uses the ENCRYPTED PRIVATE KEY PEM label, and the cipher is selected by Pkcs8EncryptAlg.

Encrypted PKCS #8 output uses PBES2 with PBKDF2. The generated parameters use an 8-byte salt, 2048 PBKDF2 iterations, and the default PBKDF2 PRF (HMAC-SHA-1). The selected cipher uses CBC mode with a newly generated IV.

Generated PEM formatting: PEM output uses CRLF line endings, Base64 lines of at most 64 characters, and a final CRLF.
File behavior: An existing destination file is replaced. Parent directories are not created; the parent directory must already exist.
Empty passwords: An empty password is accepted but provides no meaningful password protection.

Returns normally on success; throws an Error on failure.

top
SavePkcs8File
savePkcs8File(path: string): void

Saves the key as unencrypted PKCS #8 DER at path. PKCS #8 is an algorithm-independent private-key container. Chilkat emits the classic version-0 PrivateKeyInfo structure, with the algorithm-specific private-key DER in an OCTET STRING.

PrivateKeyInfo ::= SEQUENCE {
    version                   Version,
    privateKeyAlgorithm       AlgorithmIdentifier,
    privateKey                OCTET STRING,
    attributes           [0]  IMPLICIT Attributes OPTIONAL
}
File behavior: An existing destination file is replaced. Parent directories are not created; the parent directory must already exist.
macOS Keychain: Starting in Chilkat v10.0.0, path may be formatted as keychain:<label> to save the private key to the Apple Keychain.
Security note: The file contains cleartext private-key material.

Returns normally on success; throws an Error on failure.

top
SavePkcs8PemFile
savePkcs8PemFile(path: string): void

Saves the key as unencrypted PKCS #8 PEM at path. The PEM label is PRIVATE KEY for RSA, EC, Ed25519, and other supported PKCS #8 key types.PKCS #8 is an algorithm-independent private-key container. Chilkat emits the classic version-0 PrivateKeyInfo structure, with the algorithm-specific private-key DER in an OCTET STRING.

PrivateKeyInfo ::= SEQUENCE {
    version                   Version,
    privateKeyAlgorithm       AlgorithmIdentifier,
    privateKey                OCTET STRING,
    attributes           [0]  IMPLICIT Attributes OPTIONAL
}
Generated PEM formatting: PEM output uses CRLF line endings, Base64 lines of at most 64 characters, and a final CRLF.
File behavior: An existing destination file is replaced. Parent directories are not created; the parent directory must already exist.
Security note: The file is not password-protected.

Returns normally on success; throws an Error on failure.

More Information and Examples
top
SaveXmlFile
saveXmlFile(path: string): void

Saves the key as unencrypted Chilkat-compatible XML at path. The XML representation is the same as returned by GetXml.

File behavior: An existing destination file is replaced. Parent directories are not created; the parent directory must already exist.
Security note: The XML contains cleartext private-key material.

Returns normally on success; throws an Error on failure.

More Information and Examples
top
ToPublicKey
toPublicKey(pubKey: PublicKey): void
Introduced in version 11.0.0

Extracts the public portion of the loaded private key and stores an independent copy in the PublicKey supplied in pubKey. The resulting public key is unaffected if this PrivateKey is later reloaded with a different key.

Target state on failure: If extraction fails, an existing key already held by pubKey is preserved.

Returns normally on success; throws an Error on failure.

More Information and Examples
top
UploadToCloud
uploadToCloud(jsonIn: JsonObject, jsonOut: JsonObject): void
Introduced in version 9.5.0.96

Uploads or imports the private key to a supported cloud key-management service. jsonIn supplies service-specific input parameters as a JsonObject, and jsonOut receives service-specific result information.

Open-ended interface: The required JSON members and returned JSON depend on the target service and operation. Follow the corresponding Chilkat example for AWS KMS, Azure Key Vault, or another supported provider rather than assuming one common schema.
Security note: Cloud import operations may transmit private-key material. Use only the provider endpoint, authentication, and transport settings documented for the intended service.

Returns normally on success; throws an Error on failure.

top
UploadToCloudAsync
uploadToCloudAsync(jsonIn: JsonObject, jsonOut: JsonObject): Promise<void>
Introduced in version 9.5.0.96

Asynchronous form of UploadToCloud: the same call on a native worker thread, so the JavaScript thread (and the UI) stays responsive. Takes the same arguments and resolves with the same result. While the returned Promise is pending, every other call on this object throws (the object is busy), except abort(), which cancels the call, and assigning the onPercentDone / onProgressInfo callbacks, which report its progress.

Note: the onPercentDone and onProgressInfo callbacks run on the JavaScript thread while the promise is pending, so they can update the UI directly. A rejection's message is "Class.methodAsync: reason"; the full log is in lastErrorText.

Returns a Promise that resolves with the synchronous method's result (undefined for a void method) and rejects with an Error where the synchronous method would throw.

top

Events

While a method runs, PrivateKey reports progress through two optional callback properties. Assign a function to receive the event, or undefined to stop receiving it. The callbacks are delivered on the JavaScript thread, so they are useful with the ...Async methods: during a synchronous call the JavaScript thread is busy inside Chilkat, and the events can only arrive after it returns.

const privateKey = new PrivateKey()
privateKey.onPercentDone = (pct) => setProgress(pct)          // pct is 0..100
privateKey.onProgressInfo = (name, value) => console.log(`${name}: ${value}`)
privateKey.heartbeatMs = 250   // let abort() take effect within a quarter second

const pending = privateKey.someMethodAsync(...)
cancelButton.onPress = () => privateKey.abort()   // the promise then rejects
await pending

PercentDone fires when an operation's completion percentage is known; ProgressInfo delivers named progress values (what is reported depends on the class and method). There is no AbortCheck callback: to cancel a pending ...Async call, call abort() on the object. Chilkat notices the request at its next progress check, which happens at least every heartbeatMs milliseconds on the classes that have that property (0, the default, disables the heartbeat, so set it for a responsive cancel), and the promise rejects with Chilkat's abort error. abort() is harmless when nothing is pending.

PercentDone
// callback property; assign undefined to remove
onPercentDone?: (pctDone: number) => void

This provides the percentage completion for any method involving network communications or time-consuming processing, assuming the progress can be measured as a percentage. This event is triggered only when it's possible and logical to express the operation's progress as a percentage. The pctDone argument will range from 1 to 100. For methods that finish quickly, the number of PercentDone callbacks may vary, but the final callback will have pctDone equal to 100. For longer operations, callbacks will not exceed one per percentage point (e.g., 1, 2, 3, ..., 98, 99, 100).

The PercentDone callback also acts as an AbortCheck event. For fast methods where PercentDone fires, an AbortCheck event may not trigger since the PercentDone callback already provides an opportunity to abort. For longer operations, where time between PercentDone callbacks is extended, AbortCheck callbacks enable more responsive operation termination.

To abort the operation, set the abort output argument to true. This will cause the method to terminate and return a failure status or corresponding failure value.

More Information and Examples

Example:

privateKey.onPercentDone = (pct) => {
  // pct ranges from 0 to 100.
  setProgress(pct)   // runs on the JavaScript thread: React state may be updated directly
}
await privateKey.someMethodAsync(...)
// To stop an operation from within the callback, call privateKey.abort()
top
ProgressInfo
// callback property; assign undefined to remove
onProgressInfo?: (name: string, value: string) => void

This event callback provides tag name/value pairs that detail what occurs during a method call. To discover existing tag names, create code to handle the event, emit the pairs, and review them. Most tag names are self-explanatory.

Note: Some Chilkat methods don't fire any ProgressInfo events.

More Information and Examples

Example:

privateKey.onProgressInfo = (name, value) => console.log(`${name}: ${value}`)
await privateKey.someMethodAsync(...)
top