Crypt2 Chilkat2 Java Reference Documentation

Crypt2

Current Version: 11.7.0

Markdown version of this page for AI tools (v 11.7.0) · all AI docs

Chilkat.Crypt2

Encrypt, decrypt, hash, sign, verify, encode, and authenticate data.

Chilkat.Crypt2 is a broad cryptographic utility class for applications that need symmetric encryption, decryption, hashing, HMACs, key derivation, random data generation, one-time passwords, binary encoding, PKCS#7/CMS signatures, CAdES options, and certificate-based public-key encryption and decryption. It works with strings, files, byte data, BinData, and StringBuilder objects, making it useful for both small in-memory operations and file-based cryptographic workflows.

Encryption and decryption

Encrypt and decrypt strings, files, byte arrays, and Chilkat buffer objects using configurable algorithms, modes, keys, IVs, padding, and encodings.

Hashes and HMACs

Compute message digests and keyed message authentication codes for text, files, byte data, and in-memory buffers.

PKCS#7 / CMS signatures

Create and verify signed data, detached signatures, opaque signatures, and certificate-based signature formats used in many security workflows.

CAdES support

Use CAdES-related options when advanced CMS signature profiles are required for compliance or interoperability.

Key and random utilities

Derive keys, generate random bytes, create one-time passwords, and prepare keying material for cryptographic operations.

Encoding and data conversion

Encode and decode binary data using formats such as Base64, hex, URL encoding, and other supported binary encodings.

Common pattern: Choose the cryptographic operation, set the algorithm and related options, provide keys, certificates, passwords, IVs, or encoding settings as needed, then call the method matching the data form: string, file, bytes, BinData, or StringBuilder. Check LastErrorText when diagnosing algorithm, key, certificate, signature, or encoding issues.

Object Creation

import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Crypt2;

try (Crypt2 crypt2 = new Crypt2()) {
    // ... use crypt2 ...
} catch (ChilkatException e) {
    System.out.println(e.getMessage());          // "Crypt2.someMethod failed: <reason>"
    System.out.println(e.getLastErrorText());    // the full log of the failed call
}
public Crypt2()

Creates the underlying native Chilkat object. The native library (chilkat2java) is loaded the first time any Chilkat2 object is created; see the README in the download for where it is looked for (-Dchilkat2.library.path, a classpath resource, or java.library.path).

public void close()

Releases the native object (Crypt2 is AutoCloseable, so try-with-resources calls it). Calling it again does nothing; any other method or property accessor called afterwards throws IllegalStateException. An object that is never closed is freed by a background cleaner once it becomes unreachable, but the garbage collector does not see native memory, so closing is the normal path. Objects returned by methods are owned by the caller too.

public boolean isClosed()

Returns true once close() has been called.

Errors

A method that fails throws ChilkatException, an unchecked exception carrying getClassName(), getMethodName(), getReason() (one line, also in the message) and getLastErrorText() (the full log, captured at the moment of the failure). The object remains usable. Methods that look something up and find nothing return null instead of throwing (each such method says so), and methods that answer a question (hasMember, isUnlocked, ...) return a plain boolean. Property accessors do not throw for Chilkat reasons.

A null string or object argument throws NullPointerException naming the parameter (except where a method documents that null is accepted), and a string containing U+0000 throws IllegalArgumentException.

Use an object from one thread at a time; it may be handed from one thread to another. The one cross-thread operation is setting setAbortCurrent(true) on an object that is busy in another thread (on the classes that have AbortCurrent). Unlocking: call new Global().unlockBundle("...") once at startup.

Properties

AbortCurrent
// read/write
boolean getAbortCurrent()
void setAbortCurrent(boolean value)
Introduced in version 9.5.0.58

Setting this property to true will abort the current method, but only for those methods having an Async alternative. The property automatically resets to false at the start of each method and after an abort. Both synchronous and asynchronous methods can be aborted; synchronous methods require setting this property from another thread.

top
BCryptWorkFactor
// read/write
int getBCryptWorkFactor()
void setBCryptWorkFactor(int value)
Introduced in version 9.5.0.65

The BCrypt work factor determines the computational cost of BCryptHash and BCryptVerify . It represents the base-2 logarithm of the number of hashing rounds. For instance, a work factor of 12 corresponds to 2^12 hashing rounds. This cost factor is designed to make computations challenging enough to deter brute-force attacks. The work factor must be set between 4 and 31, inclusive, with a default value of 10.

top
BlockSize
// read-only
int getBlockSize()

This property indicates the block size in bytes for the chosen encryption algorithm. For instance, if the CryptAlgorithm is set to AES, the BlockSize is automatically set to 16 bytes. In contrast, the block size for the ChaCha20 streaming algorithm is 1 byte.

top
CadesEnabled
// read/write
boolean getCadesEnabled()
void setCadesEnabled(boolean value)

This property applies to all PKCS7 signature creation methods. When set to true, it ensures the inclusion of required attributes (such as content-type, message-digest, and signing-certificate-v2) to qualify the signature as at least a CAdES-BES signature. By default, this property is set to false.

top
CadesSigPolicyHash
// read/write
String getCadesSigPolicyHash()
void setCadesSigPolicyHash(String value)

This property is for PKCS7 CMS signatures that wish to include CAdES signature policy attributes. Set it to the base64-encoded hash of the policy document at the CadesSigPolicyUri using either SHA256 or SHA1.

top
CadesSigPolicyId
// read/write
String getCadesSigPolicyId()
void setCadesSigPolicyId(String value)

This property is for PKCS7 CMS signatures that wish to include CAdES signature policy attributes. The CAdES Signature Policy ID is an object identifier (OID) included in a CAdES signature that specifies the exact signature policy the signer followed. It is the OID associated with the policy URL. An example OID would look like this: 2.16.840.1.101.3.2.1.48.1

An application that wishes to include signature policy attributes should set all three properties: CadesSigPolicyHash , CadesSigPolicyUri , and CadesSigPolicyId .

More Information and Examples
top
CadesSigPolicyUri
// read/write
String getCadesSigPolicyUri()
void setCadesSigPolicyUri(String value)

This property is for PKCS7 CMS signatures that wish to include CAdES signature policy attributes. The signature policy URI in a CAdES digital signature is a link that points to a document describing the rules and conditions under which the signature was created. Typically the Signature Policy URI in a CAdES signature points to a .der file, not a PDF or human-readable document. For example: http://example.com/policies/my-policy.der

More Information and Examples
top
Charset
// read/write
String getCharset()
void setCharset(String value)

This property specifies the character encoding used to represent text as bytes for encryption and hashing. By default, it uses the computer's ANSI charset, such as Windows-1252 for locales like the United States, United Kingdom, Western Europe, Australia, and New Zealand.

Most applications are advised to set this property to UTF-8. Chilkat plans to change its default to UTF-8 in a future major version to align with current standards. The current default of ANSI stems from a time when UTF-8 was not widely adopted.

top
CipherMode
// read/write
String getCipherMode()
void setCipherMode(String value)

Sets the cipher mode for block encryption algorithms (AES, Blowfish,TwoFish, DES, 3DES, RC2). Possible values are CBC (the default) , ECB, CTR, OFB, GCM, and CFB. These acronyms have the following meanings:

  • CBC: Cipher Block Chaining,
  • ECB: Electronic CookBook
  • CTR: Counter Mode
  • CFB: Cipher Feedback
  • OFB: Output Feedback
  • GCM: Galois/Counter Mode
  • XTS: AES-XTS (starting in Chilkat v9.5.0.91, only works with AES encryption)

The GCM (Galois/Counter Mode) is available with any cipher having a 16-byte block size, such as AES. The CFB, OFB, CTR, and GCM modes convert block ciphers into stream ciphers. In these modes of operation, the PaddingScheme property is unused because no padding occurs.

Starting in v9.5.0.91 Chilkat supports AES-XTS mode. XTS mode additionally uses a tweak key and tweak value, which are set via the XtsSetEncodedTweakKey, XtsSetEncodedTweakValue, and XtsSetDataUnitNumber. (The latter two functions provide alternative means of setting the tweak value.) Chilkat fully supports AES-XTS mode with ciphertext-stealing, which means it will correctly encrypt/decrypt data with size not divisible by the block size (i.e. divisible by 16 bytes).

top
CmsOptions
// read/write
String getCmsOptions()
void setCmsOptions(String value)
Introduced in version 9.5.0.78

A JSON string to manage additional CMS (PKCS7) signature and validation options. Possible options are:

  • boolean OmitAlgorithmIdNull: Set this JSON member to true to omit the explicit NULL within an AlgorithmIdentifier ASN.1 within the PKCS7. This should almost never be used, but helps for rare cases where a validator dislikes the explicit NULL being present.
  • boolean ValidateTimestampTokens: Tells Chilkat to also validate the timestamp tokens when validating a signature that includes a timestamp.
  • boolean ConstructedOctets: When set to true, tells Chilkat to use the ASN.1 constructed octets format for the data contained in the CMS (PKCS7) signed-data.
  • boolean CanonicalizeITIDA: This applies to Egypt ITIDA, which requires signed documents in a CAdES-BES CMS format, using ITIDA’s JSON canonicalization (for JSON payloads), with only the Base64‑encoded signature attached - not the original data itself. When set to true, Chilkat will automatically do the special ITIDA JSON canonicalization.

top
CryptAlgorithm
// read/write
String getCryptAlgorithm()
void setCryptAlgorithm(String value)

Selects the encryption algorithm for encrypting and decrypting. Possible values are:

Algorithm Type Symmetric? Key Size(s) Block/Stream Mode of Operation Notes
aes Block cipher ✔ Yes 128, 192, 256 bits Block (128-bit) CBC, CTR, GCM, etc. Widely used, FIPS-approved
pki (Public-Key Encryption) Asymmetric ✗ No 1024–4096+ bits N/A N/A Used for key exchange, not bulk data
chacha20 Stream cipher ✔ Yes 256 bits Stream N/A High speed, secure, designed for simplicity
des Block cipher ✔ Yes 56 bits Block (64-bit) ECB, CBC, etc. Deprecated, insecure
3des Block cipher ✔ Yes 112 or 168 bits Block (64-bit) ECB, CBC, etc. Legacy use, weak by modern standards
rc2 Block cipher ✔ Yes 40–128 bits (variable) Block (64-bit) ECB, CBC, etc. Obsolete, variable strength
blowfish2 (Blowfish) Block cipher ✔ Yes 32–448 bits (variable) Block (64-bit) ECB, CBC, etc. Fast, but 64-bit block size is a limitation
twofish Block cipher ✔ Yes Up to 256 bits Block (128-bit) ECB, CBC, etc. AES finalist, secure and flexible
pbes1 Key derivation ✔ Yes Based on underlying cipher Block (varies) PKCS#5 v1.5 Obsolete, uses DES/RC2
pbes2 Key derivation ✔ Yes Based on underlying cipher Block (varies) PKCS#5 v2.0 Modern, supports AES, SHA, etc.
arc4 (RC4) Stream cipher ✔ Yes 40–2048 bits (variable) Stream N/A Deprecated, insecure due to biases

top
DebugLogFilePath
// read/write
String getDebugLogFilePath()
void setDebugLogFilePath(String value)

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
EncodingMode
// read/write
String getEncodingMode()
void setEncodingMode(String value)

The EncodingMode property specifies the binary encoding format (e.g., base64, hex, base58, base64url) used by functions ending in "ENC", like EncryptStringENC and DecryptStringENC. For encryption functions, EncodingMode determines the encoding of the output. For decryption functions, it specifies the encoding of the input data.

A list of supported binary encodings is available at the link below.

The default value is base64

More Information and Examples
top
FirstChunk
// read/write
boolean getFirstChunk()
void setFirstChunk(boolean value)

Using the FirstChunk and LastChunk properties is the way to do streaming encryption or decryption with Chilkat.

By default, both FirstChunk and LastChunk are set to true, indicating that the data passed to the encryption or decryption method is the full amount. To process data in multiple chunks, adjust these settings as follows:

1. For the first chunk, set FirstChunk = true and LastChunk = false.
2. For intermediate chunks, set both FirstChunk = false and LastChunk = false.
3. For the final chunk, set FirstChunk = false and LastChunk = true.

You can feed data chunks of any size, regardless of the encryption algorithm's block size (e.g., 16 bytes for AES). Chilkat will handle buffering and, upon receiving the final chunk, pad the output to the appropriate block size according to the selected PaddingScheme.

top
HashAlgorithm
// read/write
String getHashAlgorithm()
void setHashAlgorithm(String value)

Selects the hash algorithm used by methods that create hashes. The valid choices are sha256, sha384, sha512, sha3-224, sha3-256, sha3-384, sha3-512, sha1, md2, md5, haval, ripemd128, ripemd160,ripemd256, or ripemd320.

(Chilkat supports SHA-2 because it includes the SHA-256, SHA-384, and SHA-512 hash functions.)

The default value is sha256.

Note: The HAVAL hash algorithm is affected by two other properties: HavalRounds and KeyLength .

  • The HavalRounds may have values of 3, 4, or 5.
  • For HAVAL hashing, the KeyLength can be 128, 160, 192, 224, or 256.

More Information and Examples
top
HavalRounds
// read/write
int getHavalRounds()
void setHavalRounds(int value)

Applies to the HAVAL hash algorithm only and must be set to the integer value 3, 4, or 5. The default value is 3.

top
HeartbeatMs
// read/write
int getHeartbeatMs()
void setHeartbeatMs(int value)

The interval in milliseconds between each AbortCheck event callback, which enables an application to abort certain method calls before they complete. By default, HeartbeatMs is set to 0, meaning no AbortCheck event callbacks will trigger. Methods with event callbacks include: CkDecryptFile , CkEncryptFile , HashFile , and HashFileENC .

More Information and Examples
top
IncludeCertChain
// read/write
boolean getIncludeCertChain()
void setIncludeCertChain(boolean value)

This applies only to creating digital signatures. By default (true), any additional certificates in the authentication chain are included in the PKCS7 digital signature.

top
InitialCount
// read/write
int getInitialCount()
void setInitialCount(int value)
Introduced in version 9.5.0.55

The initial counter for the ChaCha20 encryption algorithm, which has a default value of 0, is pre-agreed by both the encryptor and decryptor.

top
IterationCount
// read/write
int getIterationCount()
void setIterationCount(int value)

The iteration count in password-based encryption (PBE) establishes the computational difficulty for encryption and decryption, thereby enhancing resistance to exhaustive search attacks. The default iteration count is 1024, which is considered low, so it is recommended that applications increase this number when using pbes2 encryption.

PBES2 Iteration Count Recommendations

Aim for a 100–200 ms derive time on your target hardware.

  • Server/Desktop: 100000 – 1000000+
  • Mobile/Embedded: 50000 - 100000

Benchmark annually and increase iterations as hardware improves.

top
KeyLength
// read/write
int getKeyLength()
void setKeyLength(int value)

The key length in bits for symmetric encryption algorithms. The default value is 256.

top
LastChunk
// read/write
boolean getLastChunk()
void setLastChunk(boolean value)

See the documentation for the FirstChunk property.

top
LastErrorHtml
// read-only
String getLastErrorHtml()

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
String getLastErrorText()

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
String getLastErrorXml()

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
boolean getLastMethodSuccess()
void setLastMethodSuccess(boolean value)

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
MacAlgorithm
// read/write
String getMacAlgorithm()
void setMacAlgorithm(String value)
Introduced in version 9.5.0.55

Selects the MAC algorithm to be used for any of the Mac methods, such as MacStringENC, MacBytes, etc. The default value is hmac. Possible values are hmac and poly1305.

More Information and Examples
top
NumSignerCerts
// read-only
int getNumSignerCerts()

This property is set upon verifying a digital signature and indicates the number of signer certificates. You can retrieve each signing certificate using the LastSignerCert method with an index ranging from 0 to NumSignerCerts-1.

top
OaepHash
// read/write
String getOaepHash()
void setOaepHash(String value)
Introduced in version 9.5.0.67

Selects the hash algorithm for use within OAEP padding when encrypting using pki with RSAES-OAEP. The valid choices are sha1, sha256, sha384, sha512,

The default value is sha256

top
OaepMgfHash
// read/write
String getOaepMgfHash()
void setOaepMgfHash(String value)
Introduced in version 9.5.0.71

Selects the MGF hash algorithm for use within OAEP padding when encrypting using pki with RSAES-OAEP. The valid choices are sha1, sha256, sha384, sha512, The default is sha256.

top
OaepPadding
// read/write
boolean getOaepPadding()
void setOaepPadding(boolean value)
Introduced in version 9.5.0.67

Selects the RSA encryption scheme when encrypting using pki (with a certificate and private key). The default value is false, which selects RSAES_PKCS1-V1_5. If set to true, then RSAES_OAEP is used.

top
PaddingScheme
// read/write
int getPaddingScheme()
void setPaddingScheme(int value)

This property defines the padding scheme Chilkat uses for adding padding to input data during encryption and removing it during decryption. It is applicable only to symmetric block ciphers, such as AES, Blowfish, and Twofish, which require input sizes matching their exact block size. Padding ensures the last block is completely filled.

The possible values are:

  1. PKCS#5/PKCS#7 (RFC 1423) default
    Each pad byte = number of padding bytes.
    Block size: 8
    Data: "HELLO" (5 bytes)
    Padding: 0x03 0x03 0x03
  2. FIPS 81
    Last byte = count; others = random.
    Block size: 8
    Data: "HELLO"
    Padding: 0xA4 0x2F 0x9C 0x03
  3. Random
    All pad bytes random; decryptor must know original length.
    Block size: 8
    Data: "HELLO"
    Padding: 0x7D 0x20 0xCB 0x81
  4. Null (0x00)
    Pad with zeros; no padding if already exact.
    Block size: 8
    Data: "HEL" (3 bytes)
    Padding: 0x00 0x00 0x00 0x00 0x00
  5. Space (0x20)
    Pad with spaces; no padding if already exact.
    Block size: 8
    Data: "HEL" (3 bytes)
    Padding: 0x20 0x20 0x20 0x20 0x20

More Information and Examples
top
PbesAlgorithm
// read/write
String getPbesAlgorithm()
void setPbesAlgorithm(String value)

If the CryptAlgorithm property is set to pbes1 or pbes2, this property defines the symmetric encryption algorithm to be used for password-based encryption (PBE). The default is "des". Applications should set this property equal to "aes".

More Information and Examples
top
PbesPassword
// read/write
String getPbesPassword()
void setPbesPassword(String value)

The password to be used when the CryptAlgorithm is "pbes1" or "pbes2".

More Information and Examples
top
Pkcs7CryptAlg
// read/write
String getPkcs7CryptAlg()
void setPkcs7CryptAlg(String value)

This property determines the underlying symmetric encryption algorithm when the CryptAlgorithm property is set to pki for selecting PKCS7 public-key encryption.

The default is aes.

top
Rc2EffectiveKeyLength
// read/write
int getRc2EffectiveKeyLength()
void setRc2EffectiveKeyLength(int value)

The effective key length (in bits) for the RC2 encryption algorithm. When using RC2, set both the KeyLength and Rc2EffectiveKeyLength properties to values between 8 and 1024, inclusive. The default setting for both is 128.

The default value is 128

RC2 is an old symmetric encryption algorithm, now considered insecure due to its small key size and vulnerability to cryptanalysis. Modern algorithms like AES are recommended instead.

top
SigningAlg
// read/write
String getSigningAlg()
void setSigningAlg(String value)
Introduced in version 9.5.0.67

This property applies when creating RSA signatures.

It defines the RSA signature scheme. The default is PKCS1-v1_5. You can change it to RSASSA-PSS (or pss) to use the RSASSA-PSS signature scheme.

  1. PKCS#1 v1.5
    Older, deterministic scheme.
    - Simple padding.
    - Vulnerable to certain attacks if not used carefully.
    - Still widely used for compatibility.
  2. RSASSA-PSS
    Newer, probabilistic scheme (recommended by modern standards).
    - Adds random salt for each signature.
    - More secure against chosen-plaintext and padding oracle attacks.
    - Recommended by modern standards like PKCS#1 v2.1 and FIPS.

top
SigningAttributes
// read/write
String getSigningAttributes()
void setSigningAttributes(String value)
Introduced in version 9.5.0.75

Contains JSON to specify the authenticated (signed) attributes or unauthenticated (unsigned) attributes that are to be included in CMS signatures. The default value is:

{
    "contentType": true,
    "signingTime": true,
    "messageDigest": true
}

More Information and Examples
top
UncommonOptions
// read/write
String getUncommonOptions()
void setUncommonOptions(String value)
Introduced in version 9.5.0.83

This is a catch-all property to be used for uncommon needs. This property defaults to the empty string and should typically remain empty.

Can be set to a list of the following comma separated keywords:

  • UseConstructedOctets - Introduced in v9.5.0.83. When creating opaque CMS signatures (signatures that embed the data being signed), will use the constructed octets form of the ASN.1 that holds the data. This is to satify some validators that are brittle/fragile/picky and require a particular format, such as for the ICP-Brazil Digital Signature Standard.

top
UuFilename
// read/write
String getUuFilename()
void setUuFilename(String value)

When UU encoding, this is the filename to be embedded in UU encoded output. The default is file.dat. When UU decoding, this is the filename found in the UU encoded input.

More Information and Examples
top
UuMode
// read/write
String getUuMode()
void setUuMode(String value)

When UU encoding, this is the file permissions mode to be embedded in UU encoded output. The default is 644. When UU decoding, this property is set to the mode found in the UU encoded input.

top
VerboseLogging
// read/write
boolean getVerboseLogging()
void setVerboseLogging(boolean value)

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
String getVersion()

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

More Information and Examples
top

Methods

AddEncryptCert
void addEncryptCert(Cert cert)

Adds a certificate for public-key encryption. To enable public-key encryption with digital certificates, set the CryptAlgorithm property to pki. Call AddEncryptCert separately for each certificate you wish to use for encryption.

Any of the Encrypt* methods will do RSA public-key encryption when the CryptAlgorithm is set to the keyword pki. The output is a PKCS#7 enveloped-data secure container.

top
AddPfxSourceBd
void addPfxSourceBd(BinData bd, String password)
Introduced in version 11.0.0

Adds a PFX file to the object's list of sources for locating certificates and private keys during public-key decryption or signing. To add multiple PFX sources, call this method multiple times. bd should contain the bytes of a PFX file (also known as PKCS12 or .p12).

Note: Information about the certificate(s) needed for public-key decryption are included in the PKCS#7 enveloped-data. Chilkat will automatically find a usable certificate and private key from sources like Windows certificate stores, the Apple keychain, or other sources provided by the application.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
AddPfxSourceFile
void addPfxSourceFile(String pfxFilePath, String pfxPassword)

Adds a PFX file to the object's list of sources for locating certificates and private keys during public-key decryption or signing. To add multiple PFX sources, call this method multiple times.

Note: Information about the certificate(s) needed for public-key decryption are included in the PKCS#7 enveloped-data. Chilkat will automatically find a usable certificate and private key from sources like Windows certificate stores, the Apple keychain, or other sources provided by the application.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
AddSigningCert
void addSigningCert(Cert cert)
Introduced in version 9.5.0.83

Call this method once per certificate to add multiple certificates for signing. If signing with a single certificate, then the SetSigningCert or SetSigningCert2 methods can be used instead.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
AesKeyUnwrap
String aesKeyUnwrap(String kek, String wrappedKeyData, String encoding)
Introduced in version 9.5.0.66

Implements the AES Key Wrap Algorithm (RFC 3394) for unwrapping. The kek is the Key Encryption Key (the AES key used to unwrap the wrappedKeyData). The arguments and return value are binary encoded strings using the encoding specified by encoding (which can be base64, hex, base64url, etc.) The full list of supported encodings is available at the link below.

The kek should be an AES key of 16 bytes, 24 bytes, or 32 bytes (i.e. 128-bits, 192- bits, or 256-bits). For example, if passed as a hex string, then the kek should be 32 chars in length, 48 chars, or 64 chars (because each byte is represented as 2 chars in hex).

The wrappedKeyData contains the data to be unwrapped. The result, if decoded, is 8 bytes less than the wrapped key data. For example, if a 256-bit AES key (32 bytes) is wrapped, the size of the wrapped key data is 40 bytes. Unwrapping restores it to the original 32 bytes.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
AesKeyUnwrapWithPadding
String aesKeyUnwrapWithPadding(String kek, String wrappedKeyData, String encoding)
Introduced in version 9.5.0.96

Implements the AES Key Wrap with Padding Algorithm (RFC 5649) for unwrapping. The kek is the Key Encryption Key (the AES key used to unwrap the wrappedKeyData). The arguments and return value are binary encoded strings using the encoding specified by encoding (which can be base64, hex, base64url, etc.)

The kek should be an AES key of 16 bytes, 24 bytes, or 32 bytes (i.e. 128-bits, 192- bits, or 256-bits). For example, if passed as a hex string, then the kek should be 32 chars in length, 48 chars, or 64 chars (because each byte is represented as 2 chars in hex).

The wrappedKeyData contains the data to be unwrapped.

The unwrapped key is returned as an encoded string (using the encoding specified in encoding).

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
AesKeyWrap
String aesKeyWrap(String kek, String keyData, String encoding)
Introduced in version 9.5.0.66

Implements the AES Key Wrap Algorithm (RFC 3394). The kek is the Key Encryption Key (the AES key used to encrypt the keyData). The arguments and return value are binary encoded strings using the encoding specified by encoding (which can be base64, hex, base64url, etc.) The full list of supported encodings is available at the link below.

The kek should be an AES key of 16 bytes, 24 bytes, or 32 bytes (i.e. 128-bits, 192- bits, or 256-bits). For example, if passed as a hex string, then the kek should be 32 chars in length, 48 chars, or 64 chars (because each byte is represented as 2 chars in hex).

The keyData contains the data to be key wrapped. It must be a multiple of 64-bits in length. In other words, if the keyData is decoded to binary, it should be a number of bytes that is a multiple of 8.

The return string, if decoded to binary bytes, is equal to the size of the key data + 8 additional bytes.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
AesKeyWrapWithPadding
String aesKeyWrapWithPadding(String kek, String keyData, String encoding)
Introduced in version 9.5.0.96

Implements the AES Key Wrap with Padding Algorithm (RFC 5649). The kek is the Key Encryption Key (the AES key used to encrypt the keyData). The arguments and return value are binary encoded strings using the encoding specified by encoding (which can be base64, hex, base64url, etc.)

The kek should be an AES key of 16 bytes, 24 bytes, or 32 bytes (i.e. 128-bits, 192- bits, or 256-bits). For example, if passed as a hex string, then the kek should be 32 chars in length, 48 chars, or 64 chars (because each byte is represented as 2 chars in hex).

The keyData contains the data to be key wrapped.

Returns the wrapped key using the encoding specified in encoding.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
Argon2DeriveKey
void argon2DeriveKey(String password, String json, BinData bdKey)
Introduced in version 11.6.0

Derives a key from a password using Argon2, the memory-hard key derivation function specified in RFC 9106. Argon2 is deliberately expensive in both CPU time and memory, which is what makes a brute-force search of the password space costly.

password is the password. json is a JSON string containing the Argon2 options (described below). The derived key is returned in bdKey, which is cleared before the derived key is stored in it.

A salt member is required in json. There is no default, because a key derivation salt is chosen and stored by the application. Use GenRandomBytesENC to generate one.

Every other member is optional. Passing an empty string for json is the same as passing {} and would fail only because no salt was given.

The JSON is validated strictly before it is used, so malformed JSON is rejected rather than partially applied. It must be a single JSON object, and every member value must be a simple value (string, number, true, false or null) -- no Argon2 member takes an object or an array. Member names are matched exactly, and any member not listed below is an error rather than something ignored. A member given twice, or a member given together with its short alias, is also an error, because which one would win is ambiguous. All of this is deliberate. A misspelled name such as iteration, a miscapitalized one such as memoryCostKB, or a single missing comma would otherwise be discarded in silence and the default used in its place. For a cost parameter that is a silent downgrade, and it produces a hash that looks perfectly valid, so nothing downstream would catch it. The specific problem is reported in the LastErrorText.

  • variant - argon2id (the default), argon2i, or argon2d. Use argon2id unless there is a specific reason not to: it combines Argon2i's resistance to side-channel attacks with Argon2d's resistance to time-memory tradeoff attacks.
  • version - 19 (the default, 0x13) or 16 (0x10). Only set 16 to reproduce a hash made by an old implementation.
  • iterations - the number of passes over memory, called t in RFC 9106. Must be at least 1. Defaults to 3.
  • memoryCostKb - the amount of memory used, in KB, called m in RFC 9106. Must be at least 8 times parallelism. Defaults to 65536 (64 MB). This is the parameter that does the most to make an attack expensive.
  • parallelism - the number of lanes, called p in RFC 9106. Defaults to 1. Changing it changes the derived key. Chilkat computes all lanes on the calling thread, so raising it does not make the computation faster.
  • keyLen - the length of the derived key in bytes. Must be between 4 and 1048576. Defaults to 32.
  • salt - the salt, which must be at least 8 bytes. 16 random bytes is the usual choice.
  • secret - the optional secret value K of RFC 9106, often called a pepper: a key held by the application and not stored alongside the hash, so that a stolen database of hashes cannot be attacked without it.
  • ad - the optional associated data X of RFC 9106: additional non-secret data bound into the derivation.
  • encoding - how the salt, secret and ad members are encoded. Defaults to base64. May be any encoding Chilkat supports, such as hex, or utf-8 to use the characters of the member itself as the bytes.
  • saltEncoding, secretEncoding, adEncoding - override encoding for one member.
  • passwordCharset - the character encoding the password is converted to before use. Defaults to utf-8. If set to hex or base64, password is instead treated as encoded binary and decoded, exactly as for the charset argument of Pbkdf2.
  • maxMemoryKb - refuses to allocate more than this many KB. This is not an Argon2 parameter; it is a guard so that an unreasonable memoryCostKb cannot exhaust memory. Defaults to 2097152 (2 GB).

The short names used in RFC 9106 and in PHC hash strings are accepted as aliases: t for iterations, m for memoryCostKb, p for parallelism, and v for version. This means the parameters of an existing hash string such as $argon2id$v=19$m=65536,t=3,p=1$... can be transcribed directly.

For example, to derive a 32-byte key:

{ "iterations": 3, "memoryCostKb": 65536, "parallelism": 1, "keyLen": 32, "salt": "cmFuZG9tc2FsdDEyMzQ=" }

To hash a password for storage, use Argon2HashPassword instead, which generates a random salt and returns a self-describing string.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
Argon2HashPassword
String argon2HashPassword(String password, String json)
Introduced in version 11.6.0

Hashes a password using Argon2 (RFC 9106) and returns the result as a PHC format string, such as

$argon2id$v=19$m=65536,t=3,p=1$c29tZXJhbmRvbXNhbHQ$3fJ7v1qKcVJ0lHqXjBQZ8mYm3sNTfSPRt0bqDl9kEyM

The string records the variant, version, memory cost, iterations, parallelism, salt and hash, so it is everything needed to verify the password later with Argon2VerifyPassword. Store the whole string.

password is the password. json is a JSON string containing the Argon2 options, which are the same members documented for Argon2DeriveKey, with one difference: the salt is optional here. As with all of the Argon2 methods, an unrecognized member name is an error. When no salt member is present, a cryptographically random salt is generated for this hash, which is what should normally happen. A saltLen member (default 16, allowed range 8 to 1024) sets how many random bytes to generate.

Passing an empty string for json uses all defaults: Argon2id, version 19, 3 iterations, 64 MB of memory, 1 lane, a 32-byte hash and a 16-byte random salt.

Note that if a secret (pepper) or ad is used, it is not stored in the returned string. The same value must be supplied to Argon2VerifyPassword for the password to verify.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
Argon2VerifyPassword
int argon2VerifyPassword(String password, String json, String phcHash)
Introduced in version 11.6.0

Verifies password against a PHC format Argon2 hash string previously produced by Argon2HashPassword (or by any other RFC 9106 implementation).

Returns one of three values:

  • 1 - the password matched.
  • 0 - the password did not match.
  • -1 - the verification could not be performed at all: phcHash was not a valid Argon2 hash string, its parameters were out of range, or an internal failure occurred. The reason is written to the LastErrorText.
Test for a match with == 1, never for != 0, so that an unusable hash string is not mistaken for a successful login.

The variant, version, memory cost, iterations, parallelism, salt and hash length are all read from phcHash, so none of the Argon2 cost options need to be supplied. Pass an empty string for json unless the hash was created with a secret (pepper) or ad, in which case json must contain the same values that were used to create it. Only the secret, ad, encoding, passwordCharset and maxMemoryKb members of json are used; everything else is ignored. The other documented members are still accepted here, so that one JSON string can be shared between hashing and verifying, but an unrecognized member name is an error.

A return of 0 and a return of -1 call for different handling. 0 is a normal failed login attempt. -1 means the stored hash itself is unusable, which is a data or configuration problem rather than a bad password, and is worth logging or alerting on separately.

The maxMemoryKb member is worth setting when the hash strings come from an untrusted source. The memory cost is taken from phcHash, so a hash claiming an enormous m would otherwise cause a very large allocation. It defaults to 2 GB and is checked before any memory is allocated.

top
BCryptHash
String bCryptHash(String password)
Introduced in version 9.5.0.65

Computes and returns a bcrypt hash of the password. The number of rounds of hashing is determined by the BCryptWorkFactor property.

Starting in v9.5.0.76, if the password is prefixed with $2b$ then the output will use the $2b version of bcrypt. For example, to create a $2b$ bcrypt has for the password secret, pass in the string $2b$secret for password.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
BCryptVerify
void bCryptVerify(String password, String bcryptHash)
Introduced in version 9.5.0.65

Verifies the password against a previously computed BCrypt hash. Returns true if the password matches the bcryptHash. Returns false if the password does not match.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
CkDecryptFile
void ckDecryptFile(String srcFile, String destFile)

File-to-file decryption that supports files of any size by using internal streaming mode.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
CkEncryptFile
void ckEncryptFile(String srcFile, String destFile)

Encrypts a file to another file using streaming mode, allowing files of virtually any size to be processed without loading the entire file into memory. The exception is when the CryptAlgorithm property is set to "pki", in which case the entire input file must reside in memory because public-key encryption is performed in-memory rather than as a streaming operation.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
ClearEncryptCerts
void clearEncryptCerts()

Clears the internal list of digital certificates to be used for public-key encryption.

More Information and Examples
top
ClearSigningCerts
void clearSigningCerts()
Introduced in version 9.5.0.83

Clears the set of certificates to be used in signing.

More Information and Examples
top
CoSign
void coSign(BinData bdIn, Cert cert, BinData bdOut)
Introduced in version 9.5.0.89

Co-sign's an existing CMS signature. bdIn contains the existing CMS signature. If successful, cert is the output co-signed CMS signature.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
CrcBd
long crcBd(String crcAlg, BinData bd)
Introduced in version 11.0.0

Computes a CRC for data contained in crcAlg, which can be either crc-32 used in the Zip file format, or crc8 for the CRC8 algorithm.

More Information and Examples
top
CrcFile
long crcFile(String crcAlg, String path)
Introduced in version 9.5.0.38

Calculates the CRC for a file's contents using the CRC algorithm specified by crcAlg. Possible algorithms are:

  • crc-32 - This is the CRC used in the Zip file format.
  • crc8

More Information and Examples
top
CreateP7M
void createP7M(String inFilename, String p7mPath)

Signs the contents of inFilename and writes the enveloping (i.e. opaque) PKCS7 signature (.p7m) to p7mPath.

In a PKCS#7/CMS signature, the signer computes a cryptographic hash (e.g. SHA-256) of the data, then uses their private key to sign that hash.

The signature = Sign( Hash(data) )

This signed hash is what gets stored in the signature file. For enveloping/opaque signatures, the signed data is also stored in the signature file.

Set the HashAlgorithm property to specify the hash algorithmg. The valid options are sha256, sha1, sha384, and sha512.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
CreateP7S
void createP7S(String inFilename, String p7sPath)

Signs the contents of inFilename and writes the detached PKCS7 signature (.p7s) to p7sPath.

In a PKCS#7/CMS detached signature, the signer computes a cryptographic hash (e.g. SHA-256) of the data, then uses their private key to sign that hash.

The signature = Sign( Hash(data) )

This signed hash is what gets stored in the signature file.

Set the HashAlgorithm property to specify the hash algorithmg. The valid options are sha256, sha1, sha384, and sha512.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
DecodeString
String decodeString(String inStr, String charset, String encoding)

Decodes from an encoding back to the original string. The encoding can be set to any of the following strings: base64, hex, quoted-printable, url, base32, Q, B, url_rc1738, url_rfc2396, url_rfc3986, url_oauth, uu, modBase64, or html (for HTML entity encoding).

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
DecryptBd
void decryptBd(BinData bd)
Introduced in version 9.5.0.67

Decrypts the contents of bd. This method can do either symmetric key decryption or CMS public key decryption (e.g., PKCS#7 EnvelopedData).

Before calling this method for symmetric key decryption (e.g., AES, ChaCha20, Blowfish, etc.), ensure the following setup:

  1. Define the encryption algorithm using the CryptAlgorithm property.
  2. Specify the encryption key length with the KeyLength property.
  3. Establish the cipher mode through the CipherMode property.
  4. Use the SetEncodedIV method to set the IV, if needed by the cipher mode.
  5. Set the encryption key with the SetEncodedKey method.
  6. Ensure the PaddingScheme property matches the encryptor's value.

When calling this method for public key decryption (i.e. decrypting a PKCS7 CMS message), the following setup is required:

  1. The CryptAlgorithm property should be set to the string "pki".
  2. Optionally specify the certificate to be used for decryption by calling SetDecryptCert. If SetDecryptCert is not called, then Chilkat will automatically search certificate sources (Windows certificate stores, Apple keychain, etc.) for the required certificate.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
DecryptEncoded
String decryptEncoded(String encodedEncryptedData)

Decrypts encoded encrypted data, and returns the decrypted data as a binary encoded string. For example:

Input → Decode EncodingMode → Decrypt → Encode EncodingMode → Output

The encoding (e.g. base64, hex, etc.) is determined by the EncodingMode property.

This method supports symmetric key and public key decryption. For more information on properties that affect decryption, such as CryptAlgorithm, CipherMode, etc., refer to the DecryptBd method documentation.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
DecryptSb
void decryptSb(BinData bdIn, StringBuilder sbOut)
Introduced in version 9.5.0.67

This function is intended for use when the expected decrypted output is text. It decrypts the contents of bdIn and appends the resulting string to sbOut. Ensure that the Charset property, such as utf-8, matches the one used during encryption to interpret the decrypted bytes correctly as characters.

Input → Decrypt → Interpret Bytes according to Charset → Append to StringBuilder

This method supports symmetric key and public key decryption. For more information on properties that affect decryption, such as CryptAlgorithm, CipherMode, etc., refer to the DecryptBd method documentation.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
DecryptSecureENC
void decryptSecureENC(String cipherText, SecureString secureStr)
Introduced in version 9.5.0.71

This function is intended for use when the expected decrypted output is text. It decrypts binary encoded encrypted bytes passed in cipherText and appends the resulting string to secureStr. Ensure that the Charset property, such as utf-8, matches the one used during encryption to interpret the decrypted bytes correctly as characters.

Input → Decode using EncodingMode → Decrypt → Interpret Bytes according to Charset → Append to Secure String

The encoding (e.g. base64, hex, etc.) is determined by the EncodingMode property.

This method supports symmetric key and public key decryption. For more information on properties that affect decryption, such as CryptAlgorithm, CipherMode, etc., refer to the DecryptBd method documentation.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
DecryptStringENC
String decryptStringENC(String str)

This function is intended for use when the expected decrypted output is text. It decrypts binary encoded encrypted bytes passed in str and appends the resulting string to ARG2. Ensure that the Charset property, such as utf-8, matches the one used during encryption to interpret the decrypted bytes correctly as characters.

Input → Decode using EncodingMode → Decrypt → Interpret Bytes according to Charset → Output

The encoding (e.g. base64, hex, etc.) is determined by the EncodingMode property.

This method supports symmetric key and public key decryption. For more information on properties that affect decryption, such as CryptAlgorithm, CipherMode, etc., refer to the DecryptBd method documentation.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
EncodeInt
String encodeInt(int value, int numBytes, boolean littleEndian, String encoding)
Introduced in version 9.5.0.77

Encodes an integer to N bytes and returns in the specified encoding. If littleEndian is true, then little-endian byte ordering is used. Otherwise big-endian byte order is used.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
EncodeString
String encodeString(String strToEncode, String charsetName, String toEncodingName)

Binary encodes a string. The toEncodingName can be set to any of the binary encodings supported by Chilkat, such as base64, hex, etc. (see the link below for the full list of encodings). The charsetName, such as "utf-8", determines the bytes that are encoded.

The toEncodingName can also be set to the value html for HTML entity encoding.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
EncryptBd
void encryptBd(BinData bd)
Introduced in version 9.5.0.67

Encrypts the contents of bd. This method can do either symmetric key encryption or CMS public key encryption (e.g., PKCS#7 EnvelopedData).

Before calling this method for symmetric key encryption (e.g., AES, ChaCha20, Blowfish, etc.), ensure the following setup:

  1. Define the encryption algorithm using the CryptAlgorithm property.
  2. Specify the encryption key length with the KeyLength property.
  3. Establish the cipher mode through the CipherMode property.
  4. Use the SetEncodedIV method to set the IV, if needed by the cipher mode.
  5. Set the encryption key with the SetEncodedKey method.
  6. Set the PaddingScheme property if needing something different than the default.

When calling this method for public key encryption (i.e. creating a PKCS7 CMS message), the following setup is required:

  1. The CryptAlgorithm property should be set to the string "pki".
  2. To specify the encryption certificate, use SetEncryptCert. For multiple certificates, call AddEncryptCert for each one.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
EncryptEncoded
String encryptEncoded(String str)

Encrypts binary-encoded data and returns it as a binary-encoded string. For example:

Input → Decode EncodingMode → Encrypt → Encode EncodingMode → Output

The encoding (e.g. base64, hex, etc.) is determined by the EncodingMode property.

This method supports symmetric key and public key decryption. For more information on properties that affect decryption, such as CryptAlgorithm, CipherMode, etc., refer to the method documentation.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
EncryptSb
void encryptSb(StringBuilder sbIn, BinData bdOut)
Introduced in version 9.5.0.67

Encrypts text and appends the encrypted bytes in bdOut. The Charset property, such as utf-8, determines the actual bytes that are encrypted.

StringBuilder → Get bytes according to Charset → Encrypt → Append to BinData

This method supports symmetric key and public key encryption. For more information on properties that affect encryption, such as CryptAlgorithm, CipherMode, etc., refer to the EncryptBd method documentation.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
EncryptSecureENC
String encryptSecureENC(SecureString secureStr)
Introduced in version 9.5.0.71

Encrypts the secure string and returns the encrypted bytes as a binary encoded string. The Charset property determines the actual bytes that are encrypted.

SecureString → Get bytes according to Charset → Encrypt → Encode using EncodingMode → Output

The encoding (e.g. base64, hex, etc.) is determined by the EncodingMode property.

This method supports symmetric key and public key encryption. For more information on properties that affect encryption, such as CryptAlgorithm, CipherMode, etc., refer to the EncryptBd method documentation.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
EncryptStringENC
String encryptStringENC(String str)

Encrypts the str and returns the encrypted bytes as a binary encoded string. The Charset property determines the actual bytes that are encrypted.

Input → Get bytes according to Charset → Encrypt → Encode using EncodingMode → Output

The encoding (e.g. base64, hex, etc.) is determined by the EncodingMode property.

This method supports symmetric key and public key encryption. For more information on properties that affect encryption, such as CryptAlgorithm, CipherMode, etc., refer to the EncryptBd method documentation.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
GenerateUuid
String generateUuid()
Introduced in version 9.5.0.55

Generates a random UUID string having standard UUID format, such as de305d54-75b4-431b-adb2-eb6b9e546014.

Note: This generates a version 4 UUID using random byte values. See RFC 4122.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
GenRandomBytesENC
String genRandomBytesENC(int numBytes)

Generates numBytes random bytes and returns them as an encoded string. The encoding format (e.g., base64, hex) is determined by the EncodingMode property. It utilizes the Fortuna cryptographically secure random number generator, auto-seeded by an OS-dependent secure entropy source.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
GetEncodedAuthTag
String getEncodedAuthTag(String encoding)
Introduced in version 9.5.0.55

When encrypting in GCM mode, Chilkat generates the GCM authentication tag. The application can then use this method to retrieve the tag, which should be sent to the decrypting party along with the encrypted data. For further details on GCM authenticated encryption, please refer to the web pages linked below.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
GetEncodedIV
String getEncodedIV(String encoding)

This method retrieves the IV set by the application during the last call to SetEncodedIV or RandomizeIV.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
GetLastJsonData
void getLastJsonData(JsonObject json)
Introduced in version 11.0.0

Offers details on the last method executed. While many methods provide no information, some do through GetLastJsonData. For instance, after invoking a signature verification method, GetLastJsonData will return JSON detailing the algorithms used.

More Information and Examples
top
GetSignatureSigningTimeStr
String getSignatureSigningTimeStr(int index)

This method retrieves the signing time of the Nth certificate in a digital signature after verification. The signing time for the first certificate is at index 0. The NumSignerCerts property indicates the total number of signing certificates, although typically only one is used. Note: Before accessing the signing time, use the HasSignatureSigningTime method to verify its availability, and skip indices lacking a signing time. The signing time is returned in RFC822 string format.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
GetSignedAttributes
boolean getSignedAttributes(int signerIndex, BinData pkcs7Der, StringBuilder sbJson)
Introduced in version 9.5.0.75

Extracts the signed (authenticated) attributes for the Nth signer, where signerIndex is typically 0, as most signatures have only one signer. Provide the binary PKCS7 in pkcs7Der. If successful, sbJson will hold the signed attributes in JSON format.

Sample JSON output:

{
  "signedAttributes": [
    {
      "oid": "1.2.840.113549.1.9.3",
      "name": "Content Type"
    },
    {
      "oid": "1.2.840.113549.1.9.5",
      "name": "Signing Time"
    },
    {
      "oid": "1.2.840.113549.1.9.4"
      "name": "Message Digest"
    },
    {
      "oid": "1.2.840.113549.1.9.16.2.47",
      "name": "Signing Certificate V2"
    }
  ]
}

Never throws: false is an answer, not a failure.

More Information and Examples
top
HashBdENC
String hashBdENC(BinData bd)
Introduced in version 9.5.0.66

Hashes the bytes in bd and returns the hash as a binary-encoded string. The hash algorithm is determined by the HashAlgorithm property, while the encoding is specified by the EncodingMode property. Encoding options include base64, hex, base64url, or others listed at the link below.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
HashBeginString
void hashBeginString(String strData)

To hash a large amount of text, start by processing the first chunk using this method. For subsequent chunks, use the HashMoreString method as needed. Conclude by calling HashFinalENC to obtain the final result. The hash algorithm is determined by the HashAlgorithm property setting.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
HashChunkBd
void hashChunkBd(boolean firstChunk, BinData bd)
Introduced in version 11.1.0

Start or continue hashing data in chunks. Set firstChunk to true for the first chunk, and false for subsequent chunks. Finish by calling HashFinalENC to obtain the result. The hash algorithm used is determined by the HashAlgorithm property.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
HashFileENC
String hashFileENC(String path)

Hashes a file and returns the hash as an encoded string.

The hash algorithm is specified by the HashAlgorithm property, The encoding is controlled by the EncodingMode property, which can be set to base64, hex, base64url, or any of the encodings listed at the link below.

Any size file is supported because the file is hashed internally in streaming mode (keeping memory usage low and constant).

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
HashFinalENC
String hashFinalENC()

Finalizes a multi-step hash computation and returns the hash bytes encoded according to the EncodingMode property setting.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
HashMoreString
void hashMoreString(String strData)

Adds more text to the hash currently under computation. (See HashBeginString)

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
HashStringENC
String hashStringENC(String str)

Hashes the str and returns the hash as a binary encoded string. The Charset property determines the actual bytes that are hashed.

Input → Get bytes according to Charset → Hash → Encode using EncodingMode → Output

The encoding (e.g. base64, hex, etc.) is determined by the EncodingMode property.

The hash algorithm is determined by the HashAlgorithm property.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
HasSignatureSigningTime
boolean hasSignatureSigningTime(int index)

After verifying a digital signature with a signature verification method, you can call this method. It returns true if the signing time for the Nth certificate is available and can be accessed using the GetSignatureSigningTimeStr method.

Never throws: false is an answer, not a failure.

More Information and Examples
top
Hotp
String hotp(String secret, String secretEnc, String counterHex, int numDigits, int truncOffset, String hashAlg)
Introduced in version 9.5.0.77

Implements RFC 4226: HOTP: An HMAC-Based One-Time Password Algorithm. The arguments to this method are:

  • secret: The shared secret in an enocded representation such as base64, hex, ascii, etc.
  • secretEnc: The encoding of the shared secret, such as base64
  • counterHex: The 8-byte counter in hexidecimal format.
  • numDigits: The number of decimal digits to return.
  • truncOffset: Normally set this to -1 for dynamic truncation. Otherwise can be set in the range 0..15.
  • hashAlg: Normally set to sha1. Can be set to other hash algorithms such as sha256, sha512, etc.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
LastDecryptCert
void lastDecryptCert(Cert cert)
Introduced in version 11.0.0

Returns in cert the last certificate used for public-key decryption.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
LastSignerCert
void lastSignerCert(int index, Cert cert)
Introduced in version 11.0.0

Retrieves the Nth certificate used for signing in cert, where the first certificate is at index 0. Use this method after verifying a digital signature to access the signer certificates. The NumSignerCerts property indicates the total number of signing certificates. Usually, only one certificate is used when creating a digital signature.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
MacBdENC
String macBdENC(BinData bd)
Introduced in version 9.5.0.66

Generates a Message Authentication Code (MAC) for the bytes in bd using the algorithm defined by the MacAlgorithm property. The resulting MAC is encoded into a string based on the EncodingMode property (e.g., base64 or hex). The HashAlgorithm property determines the internal hash function. Before generating the MAC, specify the secret key using SetMacKeyEncoded .

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
MacStringENC
String macStringENC(String inText)
Introduced in version 9.5.0.55

Computes a Message Authentication Code (MAC) and returns it as a binary encoded string. The MAC algorithm is defined by the MacAlgorithm property. The Charset property determines the actual bytes that are hashed.

Input → Get bytes according to Charset → MAC → Encode using EncodingMode → Output

The encoding (e.g. base64, hex, etc.) is determined by the EncodingMode property.

The hash algorithm is determined by the HashAlgorithm property. The secret key must be set beforehand by calling SetMacKeyEncoded .

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
MySqlAesDecrypt
String mySqlAesDecrypt(String strEncryptedHex, String strPassword)

Matches MySQL's AES_DECRYPT function. strEncryptedHex is a hex-encoded AES-encrypted string, and the return value is the original unencrypted string.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
MySqlAesEncrypt
String mySqlAesEncrypt(String strData, String strPassword)

This function replicates MySQL's AES_ENCRYPT, returning the encrypted data as a hex-encoded string. In MySQL, this is done using: HEX(AES_ENCRYPT('The quick brown fox jumps over the lazy dog', 'password')).

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
OpaqueSignBd
void opaqueSignBd(BinData bd)
Introduced in version 9.5.0.67

Digitally signs the contents of bd. If successful, the contents of bd are replaced with the PKCS#7 signed-data, which embeds the original data within the signature. Ensure a certificate is set using SetSigningCert before invoking this method. The HashAlgorithm property specifies the hash algorithm for creating the data's hash during signing.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
OpaqueSignStringENC
String opaqueSignStringENC(String str)

Digitally signs a string and returns PKCS#7 signed-data as a binary encoded string. The EncodingMode property determines the binary encoding, such as base64, hex, hex_lower, base64_mime, etc. The Charset property determines the actual bytes that are hashed and signed. The HashAlgorithm property specifies the hash algorithm for creating the data's hash during signing.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
OpaqueVerifyBd
void opaqueVerifyBd(BinData bd)
Introduced in version 9.5.0.67

The method performs in-place verification of the PKCS#7 signed-data content of bd. If the signature is successfully verified, the content of bd is replaced with the original data, and the method returns true. If verification fails, bd remains unchanged, and the method returns false. Afterwards, you can retrieve signer certificates by using the NumSignerCerts property and the LastSignerCert method.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
OpaqueVerifyStringENC
String opaqueVerifyStringENC(String p7m)

This function verifies a PKCS#7 signed-data binary-encoded signature and returns the original text data. The EncodingMode property determines how p7m is decoded to bytes. If the signature does not verify successfully, it returns an empty string. The Charset property specifies how the original data bytes are converted to characters. You can obtain signer certificates using the NumSignerCerts property and the LastSignerCert method.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
Pbkdf1
String pbkdf1(String password, String charset, String hashAlg, String salt, int iterationCount, int outputKeyBitLen, String encoding)

This function implements the PBKDF1 (Password-Based Key Derivation Function #1) algorithm. Follow these guidelines to use it:

  1. password (the password) is first converted using the character encoding specified by charset before being processed by the key derivation function.
  2. hashAlg specifies the hash function to use, such as md5, sha1, or md2.
  3. salt represents the salt, which should be random data of at least 8 bytes (64 bits). You can use the GenRandomBytesENC method to generate this.
  4. iterationCount sets the iteration count, which must be a minimum of 1000.
  5. outputKeyBitLen determines the length (in bits) of the derived key.
  6. encoding defines the output encoding format, such as base64 or hex, and also the expected encoding of salt (the salt).

The function returns the derived key.

Note: If charset is specified as hex or base64, the password (password) will be treated as binary data encoded in that format. It will be decoded into binary form and used directly as such.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
Pbkdf2
String pbkdf2(String password, String charset, String hashAlg, String salt, int iterationCount, int outputKeyBitLen, String encoding)

Implements the PBKDF2 algorithm as follows:

  1. Convert password to the character encoding specified by charset before using it in the key derivation function.
  2. hashAlg specifies the hash algorithm. Options include sha256, sha384, sha512, md5, sha1, md2, or any algorithm listed in the HashAlgorithm property.
  3. Provide a random salt value that is at least 8 bytes (64 bits) long. Use methods like GenRandomBytesENC to generate this salt value.
  4. Ensure iterationCount is 1000 or greater.
  5. Control the length of the derived key output using outputKeyBitLen.
  6. Set encoding to specify the encoding format for the output and the expected encoding for salt. Options include base64 and hex.

The derived key is the output of this process. Internally, PBKDF2 uses a pseudorandom function (PRF), specifically a keyed HMAC. The hash algorithm chosen with hashAlg dictates this PRF; for example, SHA256 uses HMAC-SHA256, while SHA1 uses HMAC-SHA1.

Note: If charset is hex or base64, password is treated as binary data. It will be decoded and used directly as a binary password. SHA256 uses HMAC-SHA256, while SHA1 uses HMAC-SHA1.

PBKDF1 and PBKDF2 are both key derivation functions used to strengthen passwords for cryptographic purposes, but PBKDF2 is the improved version.

  • PBKDF1: Older and limited - it can only generate small keys (up to the hash function’s output size), making it less flexible and secure.
  • PBKDF2: More advanced - it can generate longer keys, is more resistant to attacks, and is widely recommended for modern security needs.

In short, PBKDF2 is stronger and more versatile than PBKDF1.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
RandomizeIV
void randomizeIV()

Sets the initialization vector (IV) to a random value. The CryptAlgorithm property should be set prior to calling this method.

A random IV is used in symmetric encryption (like AES-CBC or AES-GCM) to ensure that encrypting the same plaintext with the same key produces different ciphertext each time. This prevents attackers from recognizing patterns in encrypted data and strengthens security.

Why use a random IV?

  • It ensures semantic security (i.e. same plaintext never results in same ciphertext).
  • Prevents replay and pattern attacks.
  • Especially important in modes like CBC and GCM.

How is the IV sent to the decrypting party?

The IV is not secret, but it must be available for decryption. Common methods:

  • Prepended to the ciphertext (e.g., IV || ciphertext)
  • Sent in a separate field (e.g., JSON field, HTTP header)
  • Concatenated and encoded (e.g., base64 of IV + ciphertext)

At the receiving side, the decryptor extracts the IV and uses it with the shared key to decrypt the ciphertext correctly.

top
ReEncode
String reEncode(String encodedData, String fromEncoding, String toEncoding)

This method converts between different encodings, such as from base64 to hex. Each argument can be any binary encoding supported by Chilkat.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
SetDecryptCert
void setDecryptCert(Cert cert)

Sets the digital certificate for decryption when the CryptAlgorithm property is set to "pki". This method requires that the certificate has a private key.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
SetDecryptCert2
void setDecryptCert2(Cert cert, PrivateKey key)

Sets the digital certificate and associated private key for decryption when the CryptAlgorithm property is set to "pki". The private key must be the one that matches the certificate's public key.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
SetEncodedAad
void setEncodedAad(String aadStr, String encoding)
Introduced in version 9.5.0.55

Sets the optional authenticated additional data (AAD) for AES encryption in GCM mode. The data is provided as a binary-encoded string using the specified encoding, and any binary encoding supported by Chilkat can be used.

In GCM (Galois/Counter Mode) encryption, AAD (Additional Authenticated Data) is optional input that is not encrypted but is authenticated along with the ciphertext. It's used to verify integrity of associated data like headers or metadata. If AAD is modified, decryption will fail due to authentication tag mismatch.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
SetEncodedAuthTag
void setEncodedAuthTag(String authTagStr, String encoding)
Introduced in version 9.5.0.55

In GCM mode, the authentication tag is a short value (e.g. 16 bytes) generated during encryption that ensures the integrity and authenticity of both the ciphertext and any AAD. It must be verified during decryption to confirm the data hasn't been altered.

When decrypting AES-GCM, applications must call this method to provide the expected authentication tag.

To prevent Chilkat from checking the authentication tag after decryption, you can set the authentication tag to the special hex value FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF (16 bytes of 0xFF).

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
SetEncodedIV
void setEncodedIV(String ivStr, String encoding)

Sets the initialization vector used in symmetric encrpytion (AES, Blowfish, etc.) from a binary-encoded string using any Chilkat-supported encoding method (e.g., base64, hex).

An Initialization Vector (IV) is a random or unique value used in symmetric encryption to ensure that encrypting the same plaintext multiple times produces different ciphertexts. It prevents pattern leakage.

Cipher Modes That Require an IV:

  • CBC (Cipher Block Chaining)
  • CFB (Cipher Feedback)
  • OFB (Output Feedback)
  • CTR (Counter Mode)
  • GCM (Galois/Counter Mode)

ECB (Electronic Codebook) does *not* use an IV, which makes it less secure.

top
SetEncodedKey
void setEncodedKey(String keyStr, String encoding)

Sets the encryption key used in symmetric encryption (AES, Blowfish, etc.) from a binary-encoded string using any Chilkat-supported encoding method (e.g., base64, hex).

The key must have a byte size equal to the KeyLength property. For instance, a KeyLength of 128 bits requires a 16-byte key, and a KeyLength of 256 bits requires a 32-byte key.

top
SetEncodedSalt
void setEncodedSalt(String saltStr, String encoding)

Sets the pbes2 or pbes1 salt bytes from a binary-encoded string using any Chilkat-supported encoding method (e.g., base64, hex).

This salt is used for encryption and decryption when the CryptAlgorithm property is set to pbes1 or pbes2. Note: This does not apply to the Pbkdf1 or Pbkdf2 methods, where the salt is provided as a function argument.

top
SetEncryptCert
void setEncryptCert(Cert cert)

Instructs the encryption library to use a specified digital certificate for public-key encryption. To encrypt using multiple certificates, call AddEncryptCert for each one. This action is equivalent to calling ClearEncryptCerts before AddEncryptCert .

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
SetMacKeyEncoded
void setMacKeyEncoded(String key, String encoding)
Introduced in version 9.5.0.55

Sets the MAC key from a binary-encoded string using any Chilkat-supported encoding method (e.g., base64, hex).

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
SetMacKeyString
void setMacKeyString(String key)
Introduced in version 9.5.0.55

Sets the MAC key from a string. The Charset property determines the actual bytes used for the MAC key.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
SetSigningCert
void setSigningCert(Cert cert)

Sets the digital certificate to be used for signing. Signing requires that the certificate has a private key.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
SetSigningCert2
void setSigningCert2(Cert cert, PrivateKey privateKey)

Sets the digital certificate and associated private key for signing. The private key must be the one that matches the certificate's public key.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
SetTsaHttpObj
void setTsaHttpObj(Http http)

If timestamp server communications are needed for signing and special Internet settings like a proxy server are necessary, this method can provide an Http object configured with these settings.

top
SetVerifyCert
void setVerifyCert(Cert cert)

Assigns the digital certificate for signature verification. Typically, a PKCS7 (CMS) signature includes the signing certificate information, making it unnecessary to call this method explicitly. This is only required in rare instances.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
SignBdENC
String signBdENC(BinData dataToSign)
Introduced in version 9.5.0.67

Digitally signs the content in dataToSign and returns a detached signature (PKCS#7 signed-data) as a binary-encoded string. The EncodingMode property determines the binary-encoding. Possible encodings include base64, base64_mime, hex, and hex_lower. The HashAlgorithm property specifies the hash algorithm for creating the data's hash during signing.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
SignHashENC
String signHashENC(String encodedHash, String hashAlg, String hashEncoding)
Introduced in version 9.5.0.90

Digitally signs a pre-computed hash and returns a detached signature (PKCS#7 signed-data) as a binary-encoded string. The EncodingMode property determines the binary-encoding. Possible encodings include base64, base64_mime, hex, and hex_lower

encodedHash is a binary-encoded hash to be signed, with its encoding format specified by hashEncoding (e.g., base64, hex). hashAlg specifies the hash algorithm (e.g., sha256, sha1, sha512) used for encodedHash.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
SignSbENC
String signSbENC(StringBuilder sb)
Introduced in version 9.5.0.67

Digitally signs the text contained in sb and returns a detached signature (PKCS#7 signed-data) as a binary-encoded string. The EncodingMode property determines the binary-encoding. Possible encodings include base64, base64_mime, hex, and hex_lower. The HashAlgorithm property specifies the hash algorithm for creating the data's hash during signing. The Charset property determines the actual bytes that are hashed and signed.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
SignStringENC
String signStringENC(String str)

Digitally signs a string and returns a detached signature (PKCS#7 signed-data) as a binary-encoded string. The EncodingMode property determines the binary-encoding. Possible encodings include base64, base64_mime, hex, and hex_lower. The HashAlgorithm property specifies the hash algorithm for creating the data's hash during signing. The Charset property determines the actual bytes that are hashed and signed.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
Totp
String totp(String secret, String secretEnc, String t0, String tNow, int tStep, int numDigits, int truncOffset, String hashAlg)
Introduced in version 9.5.0.77

Implements RFC 6238: TOTP: Time-Based One-Time Password Algorithm. The arguments to this method are:

  • secret: The shared secret in an enocded representation such as base64, hex, ascii, etc.
  • secretEnc: The encoding of the shared secret, such as base64
  • t0: The Unix time to start counting time steps. It is a number in decimal string form. A Unix time is the number of seconds elapsed since midnight UTC of January 1, 1970. 0 is a typical value used for this argument.
  • tNow: The current Unix time in decimal string form. To use the current system date/time, pass an empty string for this argument.
  • tStep: The time step in seconds. A typical value is 30. Note: Both client and server must pre-agree on the secret, the t0, and the tStep.
  • numDigits: The number of decimal digits to return.
  • truncOffset: Normally set this to -1 for dynamic truncation. Otherwise can be set in the range 0..15.
  • hashAlg: Normally set to sha1. Can be set to other hash algorithms such as sha256, sha512, etc.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
UseCertVault
void useCertVault(XmlCertVault vault)
Introduced in version 9.5.0.40

Adds an XML certificate vault to the object's internal list of sources to be searched for certificates and private keys when encrypting/decrypting or signing/verifying. Unlike the AddPfxSourceData and AddPfxSourceFile methods, only a single XML certificate vault can be used. If UseCertVault is called multiple times, only the last certificate vault will be used, as each call to UseCertVault will replace the certificate vault provided in previous calls.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
VerifyBdENC
void verifyBdENC(BinData data, String encodedSig)
Introduced in version 9.5.0.67

Verifies a detached digital signature against the original data contained in data. Returns true if the signature is verified. The encodedSig holds a binary-encoded PKCS#7 signed-data detached signature. The type of binary encoding, such as base64, hex, or base64_mime, is determined by the EncodingMode property.

Afterwards, you can retrieve signer certificates by using the NumSignerCerts property and the LastSignerCert method.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
VerifyP7M
void verifyP7M(String p7mPath, String destPath)

Verifies an opaque digital signature contained in a .p7m file and extracts the original data to destPath. Returns true if the .p7m is validated and the original data was extracted. Otherwise returns false.

Afterwards, you can retrieve signer certificates by using the NumSignerCerts property and the LastSignerCert method.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
VerifyP7S
void verifyP7S(String originalDataPath, String p7sPath)

Verifies a detached digital signature contained in a .p7s file against the original data contained in originalDataPath. Returns true if the signature is verified.

Afterwards, you can retrieve signer certificates by using the NumSignerCerts property and the LastSignerCert method.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
VerifySbENC
void verifySbENC(StringBuilder sb, String encodedSig)
Introduced in version 9.5.0.67

Verifies a detached digital signature against the original text contained in sb. Returns true if the signature is verified. The encodedSig holds a binary-encoded PKCS#7 signed-data detached signature. The type of binary encoding, such as base64, hex, or base64_mime, is determined by the EncodingMode property. The Charset property determines how the text in sb is converted to bytes for signature validation.

Afterwards, you can retrieve signer certificates by using the NumSignerCerts property and the LastSignerCert method.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
VerifyStringENC
void verifyStringENC(String str, String encodedSig)

Verifies a detached digital signature against the original text in str. Returns true if the signature is verified. The encodedSig holds a binary-encoded PKCS#7 signed-data detached signature. The type of binary encoding, such as base64, hex, or base64_mime, is determined by the EncodingMode property. The Charset property determines how the text in str is converted to bytes for signature validation.

Afterwards, you can retrieve signer certificates by using the NumSignerCerts property and the LastSignerCert method.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
XtsSetDataUnitNumber
void xtsSetDataUnitNumber(long loUint32, long hiUint32)
Introduced in version 9.5.0.91

Sets the XTS-AES mode data unit number. The data unit number is a 64-bit unsigned integer. It is passed in as two 32-bit unsigned integers representing the high and low 32-bits.

Setting the data unit number is one way of setting the tweak value. The tweak value is 16 bytes in length and can alternatively be set by calling XtsSetEncodedTweakValue.

This method sets the tweak value such that the first 8 bytes are composed of the little-endian 64-bit data unit number, followed by 8 zero bytes.

(Unfortunately, Chilkat cannot use 64-bit integers in method arguments because many older programming environments, such as ActiveX, do not support it. Chilkat must present an identical and uniform API across all programming languages.)

top
XtsSetEncodedTweakKey
void xtsSetEncodedTweakKey(String key, String encoding)
Introduced in version 9.5.0.91

Sets the XTS-AES mode tweak key from an encoded string. The encoding argument can be set to any of the following strings: base64, hex, quoted-printable, ascii, or url. The tweak key should be equal in size to the encryption key. For example, to do 256-bit AES-XTS, the encryption key is 256-bits, and the tweak key is also 256-bits.

More Information and Examples
top
XtsSetEncodedTweakValue
void xtsSetEncodedTweakValue(String tweak, String encoding)
Introduced in version 9.5.0.91

Sets the XTS-AES mode tweak value from an encoded string. The encoding argument can be set to any of the following strings: base64, hex, quoted-printable, ascii, or url.

The tweak value must be 16 bytes in length. An application can set the initial tweak value by calling this method, or by calling XtsSetDataUnitNumber (but not both).

More Information and Examples
top

Events

All Chilkat methods are synchronous: the call returns when the work is done. During a long-running call, Crypt2 reports progress through a ProgressListener, an interface with three methods, each with a default, so you override only what you need:

import com.chilkatsoft.chilkat2.ProgressListener;

crypt2.setProgressListener(new ProgressListener() {
    @Override public boolean percentDone(int pctDone) {
        System.out.println(pctDone + "%");
        return false;           // return true to abort the method in progress
    }
    @Override public void progressInfo(String name, String value) {
        System.out.println(name + ": " + value);
    }
});
crypt2.setHeartbeatMs(250);   // abortCheck 4 times per second

For a single callback, a lambda is shorter:

crypt2.onPercentDone(pct -> { System.out.println(pct + "%"); return false; });
public void setProgressListener(ProgressListener listener)

Installs listener as the receiver of this object's events, replacing any listener or lambda installed before; null removes it.

public ProgressListener getProgressListener()

Returns the installed listener, or null.

public void onAbortCheck(BooleanSupplier callback)
public void onPercentDone(IntPredicate callback)
public void onProgressInfo(BiConsumer<String, String> callback)

Each installs a listener whose only callback is the given lambda (from java.util.function). Like setProgressListener, each replaces the listener installed before, so to handle more than one event, implement ProgressListener. null removes the listener.

abortCheck is called at the interval set by the HeartbeatMs property (0, the default, disables it); percentDone is called when an operation's completion percentage is known; progressInfo delivers named progress values. Returning true from abortCheck or percentDone aborts the running method, which then throws ChilkatException.

Callbacks run on the thread that called the method, before it returns. Inside a callback, property accessors of the object (such as setAbortCurrent(true)) and other objects may be used, but calling a method of the same object throws IllegalStateException. An exception thrown by a callback aborts the running method and is rethrown from it; the object remains usable.

AbortCheck
// ProgressListener method (default returns false), or onAbortCheck(BooleanSupplier)
boolean abortCheck()

Enables a method call to be aborted by triggering the AbortCheck event at intervals defined by the HeartbeatMs property. If HeartbeatMs is set to its default value of 0, no events will occur. For instance, set HeartbeatMs to 200 to trigger 5 AbortCheck events per second.

More Information and Examples

Example

import java.util.concurrent.atomic.AtomicBoolean;

final AtomicBoolean stop = new AtomicBoolean(false);   // another thread may call stop.set(true)
crypt2.setHeartbeatMs(250);                     // call abortCheck 4 times per second
crypt2.onAbortCheck(() -> stop.get());
top
PercentDone
// ProgressListener method (default returns false), or onPercentDone(IntPredicate)
boolean percentDone(int pctDone)

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

crypt2.onPercentDone(pct -> {
    // pct ranges from 0 to 100.
    System.out.println("Percent done: " + pct);
    return false;   // return true to abort the method in progress
});
top
ProgressInfo
// ProgressListener method (default does nothing), or onProgressInfo(BiConsumer<String, String>)
void progressInfo(String name, String value)

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

crypt2.onProgressInfo((name, value) -> System.out.println(name + ": " + value));
top