Class Prng
- All Implemented Interfaces:
AutoCloseable
Generate random bytes, encoded values, passwords, and application identifiers.
Use Chilkat.Prng when an application needs random bytes or
random text values for cryptographic or application-level purposes. The class
can seed itself automatically from the system entropy source, accept
additional entropy from the application, and produce random data as raw
bytes, encoded strings, passwords, integers, booleans, GUID-style values, or
higher-level identifiers such as Firebase Push IDs.
Random bytes
Generate random byte data for keys, IVs, nonces, salts, tokens, test data, or protocol-specific binary values.
Encoded random strings
Produce random values encoded as Base64, hex, URL-safe text, or other supported encodings when binary data must be represented as text.
Password generation
Create random passwords using configurable character sets and length requirements.
Entropy input
Allow the PRNG to seed from the system entropy source and optionally add application-provided entropy.
Random application values
Generate random integers, booleans, GUID-style values, and other convenient random outputs for application logic.
Firebase Push IDs
Create Firebase-style push IDs for applications that need sortable, client-generated identifiers.
Common pattern:
Use Prng to create random material in the form required by the
caller: bytes for cryptographic inputs, encoded strings for tokens or API
values, passwords for user-facing credentials, or Firebase Push IDs for
sortable identifiers. For cryptographic workflows, generate enough random
bytes for the algorithm or protocol and avoid reducing randomness by
truncating or reformatting values incorrectly.
For an extended overview, see Prng Class Overview.
</section>
Instances hold a native Chilkat object: close them with ChilkatObject.close() (try-with-resources) when
done; an unclosed instance is freed when it becomes unreachable.
- See Also:
- Online reference
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidaddEntropy(String entropy, String encoding)Adds caller-supplied seed material to the PRNG.Exports a Base64-encoded value derived from the PRNG's accumulated entropy pools.Generates a Firebase-compatible push ID.Generatesrandom bytes and returns those bytes as text using the encoding named bynumBytes, such asencodinghex,base64, orbase64url.voidgenRandomBd(int numBytes, BinData bd)Generatesrandom bytes and appends them to the existing contents of thenumBytesBinDataobject passed in.bdgetEntropy(int numBytes, String encoding)Requestsbytes from the platform's cryptographic system entropy source and returns them using the text encoding named bynumBytes.encodingSelects the pseudo-random number generator used by this object.voidimportEntropy(String entropy)Imports the Base64-encoded entropy value previously returned byExportEntropy.intrandomInt(int low, int high)Returns a pseudorandom integer in the inclusive range fromthroughlow.highrandomPassword(int length, boolean mustIncludeDigit, boolean upperAndLowercase, String mustHaveOneOf, String excludeChars)Generates a password of exactlycharacters while applying the requested composition rules:lengthrandomString(int length, boolean bDigits, boolean bLower, boolean bUpper)Generates a string of exactlycharacters.lengthvoidsetPrngName(String value)Sets thePrngNameproperty; seegetPrngName().Methods inherited from class com.chilkatsoft.chilkat2.ChilkatObject
close, getDebugLogFilePath, getLastErrorHtml, getLastErrorText, getLastErrorXml, getLastMethodSuccess, getVerboseLogging, getVersion, isClosed, setDebugLogFilePath, setLastMethodSuccess, setVerboseLogging, toString
-
Constructor Details
-
Prng
public Prng()Creates a newPrngobject.
-
-
Method Details
-
getPrngName
Selects the pseudo-random number generator used by this object. The only supported value isfortuna, which is also the default. Chilkat's Fortuna implementation uses AES-256 for generation and SHA-256 in its entropy-processing and reseeding design.Compatibility note: Assigning any value other than
fortunais ignored. Applications should normally leave this property unchanged.- Returns:
- the value of the
PrngNameproperty
-
setPrngName
Sets thePrngNameproperty; seegetPrngName().- Parameters:
value- the new value (notnull)
-
addEntropy
Adds caller-supplied seed material to the PRNG.contains the bytes in the text encoding named byentropy, such asencodinghex,base64, orascii. For Fortuna, the decoded bytes are incorporated into the internal entropy pools and become available to later reseeding.This method is optional and is not the normal way an application obtains entropy for the PRNG. It may be called more than once and at any point during the lifetime of the object. It returns
truewhen the input is decoded and accepted, orfalseif the encoding is invalid or another error occurs.Automatic system seeding: If no entropy has been added before the first request for random output, Chilkat automatically obtains 32 bytes from the platform's cryptographic system entropy source to seed the PRNG. This is the normal and recommended mode of operation. Call
AddEntropyonly when the application has additional trustworthy entropy to contribute or deliberately needs deterministic seeding for testing.Repeatable tests: A freshPrngobject can be seeded with the same deterministic values to reproduce the same output sequence, provided the same entropy calls and random-generation calls occur in the same order. Predictable seed material is appropriate only for tests and debugging. Do not use it for real keys, nonces, passwords, or tokens.- Parameters:
entropy- theentropyargument (notnull)encoding- theencodingargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
exportEntropy
Exports a Base64-encoded value derived from the PRNG's accumulated entropy pools. The internal pools are rehashed for export so the returned value is not a direct disclosure of the generator state.The returned value can be persisted and supplied to
ImportEntropywhen a later process starts. For language bindings in which this method directly returns a string, checkLastMethodSuccessbefore using the result.Seed-file guidance: Imported entropy can improve startup behavior, but it should not be the only seed used indefinitely. After importing, also allow Chilkat to obtain fresh operating-system entropy. Protect persisted entropy from unauthorized modification and accidental reuse across cloned systems.
- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
firebasePushId
Generates a Firebase-compatible push ID. A push ID is a 20-character identifier built from a 48-bit millisecond timestamp followed by 72 bits of randomness, encoded with Firebase's ordered 64-character alphabet.The timestamp prefix makes push IDs sort approximately by creation time, while the random portion makes collisions highly unlikely across independent clients. For language bindings in which this method directly returns a string, check
LastMethodSuccessbefore using the result.Not a secret: A push ID is an identifier, not an authentication token. Its prefix reveals approximate creation time, and uniqueness is probabilistic rather than an absolute guarantee.
- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
genRandom
Generatesrandom bytes and returns those bytes as text using the encoding named bynumBytes, such asencodinghex,base64, orbase64url.is the number of binary bytes before text encoding; it is not the number of output characters.numBytesIf no entropy has been added before the first request for random output, Chilkat automatically obtains 32 bytes from the platform's cryptographic system entropy source to seed the PRNG.
For language bindings in which this method directly returns a string, check
LastMethodSuccessbefore using the result.Encoding does not add entropy: Hex, Base64, and other encodings represent the same random bytes in different textual forms. Choose
numBytesfrom the security requirement of the key, nonce, salt, or token—not from the desired text length.- Parameters:
numBytes- thenumBytesargumentencoding- theencodingargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
genRandomBd
Generatesrandom bytes and appends them to the existing contents of thenumBytesBinDataobject passed in. The destination is not cleared before the bytes are added.bdIf no entropy has been added before the first request for random output, Chilkat automatically obtains 32 bytes from the platform's cryptographic system entropy source to seed the PRNG.
Returns
trueon success orfalseon failure.Appending behavior: Call
BinData.Clearfirst when the destination should contain only the newly generated bytes.- Parameters:
numBytes- thenumBytesargumentbd- thebdargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getEntropy
Requestsbytes from the platform's cryptographic system entropy source and returns them using the text encoding named bynumBytes. This obtains system-provided random seed material directly; it is different from asking the Fortuna generator to expand its current state withencodingGenRandom.For seeding this PRNG, 32 bytes normally provide the full 256-bit seed input expected by the implementation. Applications may request another amount when a protocol specifically requires raw bytes from the system source.
For language bindings in which this method directly returns a string, check
LastMethodSuccessbefore using the result.Usually unnecessary: The simplest secure use is to call a random-generation method directly. If no entropy was added explicitly, Chilkat automatically obtains 32 bytes of system entropy on the first generation request.
- Parameters:
numBytes- thenumBytesargumentencoding- theencodingargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
importEntropy
Imports the Base64-encoded entropy value previously returned byExportEntropy. The imported material is supplied to the PRNG for use in its entropy and reseeding process.Returns
trueif the value is valid and imported successfully. Returnsfalseif it cannot be decoded or imported; checkLastErrorTextfor details.Recommended startup sequence: Import persisted entropy before the first random-generation call, then mix in fresh system entropy or allow the first generation call to perform Chilkat's automatic system seeding.
- Parameters:
entropy- theentropyargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
randomInt
public int randomInt(int low, int high)Returns a pseudorandom integer in the inclusive range fromthroughlow. For example,highRandomInt(4, 8)can return 4, 5, 6, 7, or 8.The caller should ensure that
is less than or equal tolow.highCryptographic material: Use
GenRandom,GenRandomBytes, orGenRandomBdwhen a protocol requires an exact number of random bytes. Do not assemble keys or nonces from decimal random integers unless the protocol explicitly defines that representation.- Parameters:
low- thelowargumenthigh- thehighargument- Returns:
- the result (see
ChilkatObject.getLastMethodSuccess()where the description mentions failure)
-
randomPassword
public String randomPassword(int length, boolean mustIncludeDigit, boolean upperAndLowercase, String mustHaveOneOf, String excludeChars)Generates a password of exactlycharacters while applying the requested composition rules:lengthArgument Effect
WhenmustIncludeDigittrue, require at least one digit from0-9.WhenupperAndLowercasetrue, require at least one lowercase and at least one uppercase US-ASCII letter.When nonempty, require at least one character from this supplied set, such asmustHaveOneOf!@#$%.Exclude every listed character from the generated password. This is useful for ambiguous characters such asexcludeCharsiIlL1oO0.The requested length must be large enough to satisfy all enabled requirements, and exclusions must not remove every usable character from a required category. For language bindings in which this method directly returns a string, check
LastMethodSuccessbefore using the result.Password policy note: Longer randomly generated passwords generally provide more security than short passwords with many composition rules. Also ensure the receiving system accepts every character that may be generated.
- Parameters:
length- thelengthargumentmustIncludeDigit- themustIncludeDigitargumentupperAndLowercase- theupperAndLowercaseargumentmustHaveOneOf- themustHaveOneOfargument (notnull)excludeChars- theexcludeCharsargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
randomString
Generates a string of exactlycharacters. The remaining arguments select the character categories placed in the source alphabet:lengthArgument When
trueInclude digitsbDigits0-9.Include lowercase ASCII lettersbLowera-z.Include uppercase ASCII lettersbUpperA-Z.At least one character category must be enabled. The flags define the pool from which each character is chosen; they do not guarantee that every enabled category appears in a particular result.
Requirement-aware passwords: Use
RandomPasswordinstead when the result must contain at least one digit, both uppercase and lowercase letters, or a required special character.- Parameters:
length- thelengthargumentbDigits- thebDigitsargumentbLower- thebLowerargumentbUpper- thebUpperargument- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-