Generate Tokens in Delphi

is an object-oriented programming language developed by Embarcadero Technologies. In Delphi, you can use the TRandomNumberGenerator class from the System.Security.Cryptography unit to generate a secure random number. The following is an example of a Delphi function that emulates the functionality of the JavaScript function you provided:

uses
  System.SysUtils,
  System.Generics.Collections,
  System.Security.Cryptography;

function GenerateToken(const Length: Integer; UpperCase, LowerCase, Numbers: Boolean): string;
var
  CharSet: string;
  Token: string;
  I: Integer;
  RandomIndex: Integer;
  RNG: TRandomNumberGenerator;
begin
  // Define character sets
  CharSet := '';
  if UpperCase then
    CharSet := CharSet + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  if LowerCase then
    CharSet := CharSet + 'abcdefghijklmnopqrstuvwxyz';
  if Numbers then
    CharSet := CharSet + '0123456789';

  // Check if at least one character set is selected
  if CharSet = '' then
    raise Exception.Create('At least one character set must be selected.');

  Token := '';
  RNG := TRandomNumberGenerator.Create;
  try
    for I := 1 to Length do
    begin
      // Generate a random byte
      RNG.GetBytes(TBytes.Create(RandomIndex));
      // Append a random character from the character set to the token
      RandomIndex := RandomIndex mod Length(CharSet) + 1;
      Token := Token + CharSet[RandomIndex];
    end;
  finally
    RNG.Free;
  end;

  Result := Token;
end;

// Example usage:
// var Token: string;
// Token := GenerateToken(16, True, True, True);
// ShowMessage(Token);

In this Delphi function, GenerateToken accepts four parameters: Length (the length of the token), and three boolean parameters UpperCase, LowerCase, and Numbers, which respectively indicate whether to include uppercase letters, lowercase letters, and numbers. Inside the function, a character set CharSet is constructed, and then the TRandomNumberGenerator class is used to generate random numbers. For each character of the token, a random byte is generated and used to select a character from CharSet.

Please note that TRandomNumberGenerator is a cryptographically secure random number generator suitable for scenarios requiring high security. If your application does not require such a high level of security, you can use the Random function from the System.Math unit, but please be aware that Random is not cryptographically secure and may not be suitable for all purposes.

Before using this code, ensure that your Delphi version supports the System.Security.Cryptography unit and the TRandomNumberGenerator class. If you are using an older version of Delphi, you may need to look for alternative cryptographic libraries or use the Random function (but remember that these are not cryptographically secure).