CapeSoft.Com
Clarion Accessories
Cryptonite
Documentation
Cryptonite Logo

CapeSoft Cryptonite
Documentation

Download Latest Version JumpStart FAQ History
Installed Version Latest Version

Introduction

Cryptonite requires StringTheory.

Cryptonite provides encryption and decryption in your applications for security, safe data transfer etc. Cryptonite completely removes the complexity of implementing cryptography. Cryptonite aims to make using encryption as simple as possible, and handles all the complexity for you.
Cryptonite will easily help you:
We strongly recommend starting with the example applications, which are described below in the Example section.

Basic Terminology

Cryptography is a field that has a wide variety of specific terminology, much of which can be confusing without a background in the subject.

Cipher

A cipher is simply a method of encrypting (transforming or changing) data from one form into another. A simple cipher would be substituting letters with numbers, for example "ABC" would become "123". The different methods for encrypting data are known as ciphers. Ciphers typically preserve the data, so that what is encrypted can then be decrypted at a later stage. Most ciphers use a "key" to lock and unlock (encrypt and decrypt) the data.

Encryption and Decryption

The process of using a cipher to transform plain data into encrypted data and vice versa.

Symmetric and Asymmetric keys

When encrypting and decrypting there are two basic types of keys used:
Symmetric keys use the same key to encrypt and decrypt the data. An example would be providing a password to encrypt a file, and then using the same password to decrypt the file. In order to decrypt the data, you need to know the key (password), and hence the data is only as a secure as your mechanism for transferring the key is.

Asymmetric keys use a two parts of the the key, anything encrypted with one part can only be decrypted with the other. These are know as the Public and Private keys and form the Public/Private key pair. The public key is distributed, allowing anyone to encrypted data using it. The private key is kept securely, allowing the owner to decrypt data that is encrypted with the matching public key. Or vice versa, the data can be encrypted by the owner with the private key, and decrypted by anyone else using the public key. In this scenario the data is not kept secret, but the very fact that it can be decrypted using the public key, validates that the data was created by the owner of the private key.

Asymmetric keys tend to be far larger than symmetric keys are, and asymmetric encryption is far slower. For this reason it is usually used as a key exchange mechanism. The session key (which is a symmetric key) is used to encrypt the data. The session key is then encrypted using the Public key, which means that only the person with the Private key can decrypt it. This is known as a key transport mechanism.

Hashing and Digest creation

Hashing is a method of creating a unique number from a given set of data. This provides a way to uniquely identify particular data, and to ensure that it has not been changed (if the data is not identical, the hash will change). Hashing is used to ensure the integrity of encrypted data, and to validate that the data has not been altered. Both plain (unencrypted) and cipher (encrypted) data can be hashed. A hash is also known as a digest. Common methods of creating digests are MD5, SHA-1 and SHA-2. SHA-1 is the most commonly used hash, although SHA-2 corrects a potential mathematical weakness that SHA-1 might possess and is hence technically more secure. MD5 is no longer recommended as a result of demonstrated attacks resulting in collisions (two sets of data with the same hash).

MD5 hashes are 128 bits (16 bytes) long, SHA-1 hashes are 160 bits (20 bytes) long, and SHA-2 (SHA-256 and SHA-512) hashes can be 256 or 512 bits (32 and 64 bytes respectively) long.

Using Cryptonite

The only requirement to using Cryptonite in your application is to add the global extension to the app. See the Jump Starts for common uses of Cryptonite that you may want to apply to your app.

Add the global extension

  1. Add the StringTheory Global Extension
    Global -> Extensions -> Insert -> Activate StringTheory
  2. Add the Global Extension:
    Global -> Extensions -> Insert -> Activate CapeSoft Cryptonite.

Using Cryptonite in a Hand-Coded Project

To add Cryptonite to a hand-coded project (with no APP and hence no Global Extension template) do the following;
  1. Add StringTheory to the app as per StringTheory Documentation.
  2. Add
    include('Crytonite.Inc'),Once
    to your main module
  3. Add the CryptoniteLinkMode and CryptoniteDllMode project defines to your project. Set
    CryptoniteLinkMode=>1
    if the class should be linked into the project and
    CryptoniteDllMode=>1
    if the class is exported from another DLL.
  4. Add the _ABCLinkMode_ and _ABCDllMode_ project defines to your project. Assuming this is not an ABC app you will almost certainly want to use
    _ABCLinkMode_=>1
    _ABCDLLMode_=>0
  5. Add the crypt32.lib to your solution. (There is no crypt32.DLL - just the Lib is included.)

Jump Starts

Hashing

Hashing is the process of converting one string into another string, in an irreversible way. Thus if two strings are hashed, and the hashes are compared, and the hashes are equal, then the two original strings are equal as well. However the two original strings are not known, nor are they derivable from the hash. Hashing can be performed on text or binary data.

Consider a login system. The password for a user is hashed, and the hash (not the password) is stored. When the user logs in, the password they use is hashed, and compared to the stored hash. If they are the same then the user entered the correct password. However because only the hash of the password is stored, even if the database is compromised, the password is not exposed.

Cryptonite supports several common forms of hashing including (but not limited to) MD-5, SHA-1, SHA-256 and SHA-512. The hash itself is usually stored as a string of hexadecimal values (plain text), rather than the raw binary data.

Cryptonite provides a MakeHash method that handles all the tasks associated with hashing automatically. This is demonstrated in the SimpleHashing example application that ships with Cryptonite.
Crypto               Cryptonite
st                   StringTheory
hashString           string(128)
  code
  st.SetValue(encData, true)            ! Store data in the StringTheory object to be hashed
  Crypto.MakeHash(st, cs:CALG_SHA_256)  ! Create a SHA256 hash
  hashString = st.GetValue()            ! Retrieve the hash value (hex encoded)

Some Background Information on Hashing and Hash Algorithms

The hashing algorithm defaults to cs:CALG_SHA1 for SHA-1 hashing. Other algorithms available are:

Common Hashing Algorithms
cs:CALG_MD5: MD5 hashing algorithm
cs:CALG_SHA1: SHA-1 hashing algorithm
cs:CALG_SHA_256: 256 bit SHA256 hashing algorithm. Requires Windows XP SP3 or later

Additional Algorithms
cs:CALG_HUGHES_MD5: Hughes MD5 hashing algorithm
cs:CALG_HASH_REPLACE_OWF: One way function hashing algorithm (not supported under Windows 2000 or NT)
cs:CALG_HMAC: HMAC keyed hash algorithm.
cs:CALG_MAC: MAC keyed hash algorithm. A keyed hashing algorithm that uses a symmetric session key to help ensure that a block of data has retained its integrity from the time it was sent until the time it was received. When using this type of algorithm, the receiving application must also possess the session key to recompute the hash value so it can verify that the base data has not changed.

cs:CALG_MD2: MD2 hashing algorithm
cs:CALG_MD4: MD4 hashing algorithm
cs:CALG_SHA: SHA hashing algorithm

cs:CALG_SHA_384: 384 bit SHA384 hashing algorithm. Requires Windows XP SP3 or later
cs:CALG_SHA_512: 512 bit SHA512 hashing algorithm. Requires Windows XP SP3 or later

In practice you are likely to only encounter for few of the supported algorithms. MD5 is a common hash in use and you can use this for inter-operation with systems that require MD5 hashes. However MD5 hashes are weak, and are not recommended. SHA1 is also widespread, but also has potential flaws. SHA2 (cs:CALG_SHA_256, cs:CALG_SHA_384, cs:CALG_SHA_512) is the most secure hash currently available. The three options presented here require strings of length 32 bytes, 48 bytes or 64 bytes. Using the Hex-String approach this means a string of length 128 bytes is sufficient to hold cs:CALG_SHA_512 (or weaker) hashes.

Note that SHA256, SHA384 and SHA512 hashing is only supported on newer version of Windows (Windows XP SP3 and above), so you should not assume that the Cryptographic Service Provider on a particular machine is capable of newer hashing algorithms. The MakeHash method used in the example above will returned Crypto:NotOK and set the .lastErrorCode property of the class to Crypto:NoProvider if a suitable provider is not available.

Symmetrically Encrypting a String

Symmetric Encryption is where the same key is used to encrypt and decrypt the password. Cryptonite includes two methods that make encrypting, and decrypting strings easy; EncryptString and DecryptString. These methods work with either a string, or a StringTheory object. Using these functions you can easily encrypt, or decrypt a string using a minimal amount of code.

Example of encrypting the contents of a StringTheory object.
Crypto               Cryptonite
st                   StringTheory
  code
  Crypto.EncryptString(st,'password')       ! now the StringTheory string contains the encrypted value of the string
Example of Decrypting the contents of a StringTheory object
Crypto               Cryptonite
st                   StringTheory
  code
  Crypto.DecryptString(st,'password') ! now the StringTheory string contains the decrypted value of the string
Example of Encrypting a normal String variable
Crypto               Cryptonite
somedata             String(255)
password             string(255)
datalen              Long
  code
  somedata = 'some string goes here'
  datalen = len(clip(somedata))
  password = 'capesoft rocks'
  Crypto.EncryptString(somedata,datalen,password)  		
Example of Decrypting a normal String variable
Crypto               Cryptonite
somedata             String(255)
password             string(255)
datalen              Long
  code
  password = 'capesoft rocks'
  Crypto.DecryptString(somedata,datalen,password)  		
At this point you are probably wondering what algorithm was used to encrypt the string, and indeed how you control which algorithm is used. The EncryptString and DecryptString methods take three additional parameters which allow you to control the ProviderType, ProviderName and Algorithm Id. The default provider type is RSA FULL, provided by the Microsoft Enhanced Cryptographic Provider using the RC4 algorithm.

Crypto.EncryptString(st,password,cs:PROV_RSA_FULL,cs:MS_ENHANCED_PROV,cs:CALG_RC4)

By changing these parameters you can select the provider, and algorithm that you prefer.

Symmetrically Encrypting a File

The easiest way to symmetrically encrypt, or decrypt a file is simply to apply the same technique as for encrypting and decrypting a StringTheory object, making use of the StringTheory loadfile and savefile methods.

Example of Encrypting a File
Crypto               Cryptonite
st                   StringTheory
  code	
  st.LoadFile(filename)
  crypto.EncryptString(st,password)
  st.SaveFile(filename)  
Example of Decrypting a File
Crypto               Cryptonite
st                   StringTheory
  code	
  st.LoadFile(filename)
  crypto.DecryptString(st,password)
  st.SaveFile(filename)  

Asymmetric Encryption and Decryption

Up to now the encryption and decryption has been done symmetrically. This means that the key used to encrypt the data is the same key as the one used to decrypt the data. This is sometimes called a "shared secret" approach in the sense that both parties share the same secret (the key) and it's important that the key itself remain a secret. Keeping the key a secret can be hard, because the key itself needs to be transferred between the encrypter and the decrypter, and thus can be vulnerable.

Asymmetric encryption is different. In this situation there are two keys, which work as a pair. The one key encrypts, and the other decrypts (and vice versa). In this situation only one of the keys is a secret, and the other can be freely shared. The secret one is the Private Key and it is never shared. The un-secret one is the public key, and it can be shared with everyone.

So if something is encrypted with a Public key, then only the holder of the Private key can decipher it. Since the public key can be shared, you can ask the receiver for their public key, and they can share that with you, without compromising the message.

It should be noted that asymmetric encryption and decryption is very slow compared to symmetric encryption. For this reason messages which are asymmetrically encrypted tend to be very short. In fact the most useful thing to pass in an asymmetric encrypted message is a symmetric key for decrypting another, longer, message.

Using Generated Keys

Example: An Example of this technique is in the \examples\cryptonite\demo\crypto.app program, in the AsymmetricEncryption procedure.

Recording: Following the steps below in the example can be tricky because 2 instances of the program are involved. A recording of the example is available at DemoAsymmetricEncryption.wmv.

In many cases there is no need to use a pre-existing public/private key pair. As long as the pair can be created (or already exist), and the public part can be transferred, that may suffice. This is sometimes called a "session key" approach, and it can be used where the message, in encrypted format, does not need to be stored. For example, say a small message is being passed from program A to program B. To accomplish this B will generate a public/private key pair and pass the public part to A. A will then encrypt the message using the public key, and send the message back to B. At this point A can discard the public key. Once B has decrypted the message using the Private part of the key, then it too can discard the key completely.

Note: The Demo example, AsymmetricEncryption procedure, contains all of the steps below. Using two instances of this demo program, perhaps on two different computers, helps to understand the process.

Also Note, that somewhat counter-intuitively, it is the receiver which starts the process.

The whole process can be broken down into the following steps;
  1. The procedure needs to get a container - this is usually done as the procedure opens. Both the sender and receiver need to do this step first.

    Crypto  CryptoNite

    if Crypto.GetContainer('MyCrypto', true) <> Crypto:OK
      Stop('Get Container Failed')
    End

  2. The receiver needs to get a Public/Private Key

    If Crypto.GetUserKey(cs:AT_KEYEXCHANGE, true,2048) <> Crypto:OK
      stop('GetUserKey failed')
    End

  3. The receiver needs to export the key, so it can be transferred to the sender.

    PublicKey     String(2048)
    PublicKeyLen  Long

    PublicKeyLen = len(PublicKey)
    If Crypto.ExportKey(Crypto.hExchangeKey, cs:PUBLICKEYBLOB, PublicKey, PublicKeyLen) <> Crypto:OK
      Stop('Export Key failed')
    End


    As a pure convenience this binary string can be converted to Base64 using StringTheory if you wish;

    str   StringTheory
    PublicKey64   String(2048)

    str.SetValue(sub(PublicKey,1,PublicKeyLen))
    str.Base64Encode()
    PublicKey64 = str.GetValue()

  4. The PublicKey (or PublicKey64) is then passed to the sender. The mechanism for this depends on your situation, but could be over the network using NetTalk, or via the clipboard, or whatever. The mechanism you use is not important to the encryption / decryption process.
  5. The sender now has the public key. If it is in base64 format it needs to be converted back to binary;

    str.SetValue(PublicKey64,st:clip)
    str.Base64Decode()
    PublicKeyLen = str.Length()
    PublicKey = str.GetValue()

    Then the public key has to be imported

    If Crypto.ImportKey(PublicKey, PublicKeyLen, Crypto.hExchangeKey) <> Crypto:OK
      stop('Import Failed')
    End
  6. Now the sender is ready to encrypt the message. Note that the message cannot be longer than the key. A 1024 bit key (the default length) means the message is limited to 128 characters. In step 2 above the length was set to 2048 bits (not 2048 bytes.) Because the encrypted text may be longer than the plain text, the encdata string may need to be longer than the PlainData string. If this is the case an error will occur at runtime telling you the length you will need.

    encData = PlainData
    dataLen = Len(Clip(encData))
    if Crypto.Encrypt(Crypto.hExchangeKey, encData, dataLen) <> Crypto:OK
      stop('Encryption Failed')
    End


    Again for convenience this can be encoded as Base64 for easier maneuverability if desired;

    str.SetValue(sub(encData,1,dataLen))
    str.Base64Encode()
    encData64 = str.GetValue()

  7. The encrypted data (encData or encData64) can now be transferred to the receiver.
  8. The receiver receives the message. If it is base64 encoded it needs to be decoded;

    str.SetValue(encData64)
    str.Base64Decode()
    decData = str.GetValue()
    dataLen = str.Length()


    then it needs to be decrypted;

    if Crypto.Decrypt(Crypto.hExchangeKey, decData, dataLen) <> Crypto:OK
      stop('Decryption Failed')
    end


    At this point the receiver now has the decrypted message
The most likely contents of the message is the secret key to some symmetric encryption. Because of the speed, and size limits of Asymmetric encryption, larger message should be symmetrically encrypted. To do that safely the secret key for that encryption needs to be safely passed from the sender to the receiver, and this asymmetric method makes that possible.

Generated keys are great if the sender and receiver are connected together and the public key can be fetched from the receiver in real-time. In some situations though the receiver needs to publish the public key in advance, and thus must use a "fixed" public/private key pair in order to work. The next section discusses this approach.

Using Keys from the KeyStore

Example: An Example of this technique is in the \examples\cryptonite\demo\crypto.app program, in the AsymmetricEncryptionFromCertificate procedure.

Instead of using a generated key pair, the two programs could accomplish the same thing by making use of a key pair stored in the windows certificate store. In this scenario one program encrypts (using either the public, or private, key) and the other program decrypts using the reciprocal key.

For the purpose of this discussion it will be assumed that the keys to use have already been imported into the Windows Certificate Store. You can find instructions on importing a certificate in the section Importing a Certificate below.
  1. As before the process starts by getting a container;

    Crypto  CryptoNite

    if Crypto.GetContainer('MyCrypto', true) <> Crypto:OK
      Stop('Get Container Failed')
    End

  2. Next the certificate needs to be retrieved from the certificate store. In this example the certificate is in the MY store - see xxx for a list of possible stores.
    The Certificate name is the SUBJECT property of the certificate in that store.

    Store       HCERTSTORE
    CertContext PCCERT_CONTEXT
    Provider    HCRYPTPROV
    FreeKey     Long
    Result      Long

      Store = Crypto.CertOpenSystemStore ('MY')
      If Store
        CertContext = Crypto.CertFind (Store,'Safe Update Test')
    ! certificate name
        If CertContext
          Provider = Crypto.CertGetPrivateKey(CertContext, FreeKey)
          If Provider
            self.hProvider = Provider
            Result = Crypto.GetUserKey()
          End
        End
      End

  3. To Encrypt data;
      encData = PlainData
      dataLen = Len(Clip(encData))
      if Crypto.Encrypt(Crypto.hExchangeKey, encData, dataLen) <> Crypto:OK
        stop('Encryption Failed')
      End


    This can be Base64 encoded if necessary;
      str.SetValue(sub(encData,1,dataLen))
      str.Base64Encode()
      encData64 = str.GetValue()

  4. To Decrypt the data (from raw binary);
      if Crypto.Decrypt(Crypto.hExchangeKey, decData, dataLen) <> Crypto:OK
        stop('Decryption Failed')
      end


    Or to decrypt it from Base64 encoded, inside a StringTheory object;
      str.SetValue(encData64)
      str.Base64Decode()
      decData = str.GetValue()
      dataLen = str.Length()
      if Crypto.Decrypt(Crypto.hExchangeKey, decData, dataLen) <> Crypto:OK
        stop('Decryption Failed')
      end

Interoperability

This section deals with things to consider, and take note of, when encrypting and decrypting between different languages and operating systems. Some of the common differences between systems are discussed here.

Hashed Passwords

By taking a HASH of the password and then using the Hash as the key to the encryption you ensure that the full strength of the encryption algorithm is used. The hash should be long enough, and also uses all possible bits, so the result is as strong as it can be.

This is the default approach taken by the EncryptString and DecryptString methods. A Windows Crypto API method called CryptDeriveKey is used to convert the user-password into a strong password for the encryption. As this is done for both encryption and decryption it is transparent to you as long as you are using Cryptonite (or the Windows API) to generate the password.

The default hash algorithm used by the EncryptString and DecryptString methods is SHA-1. However this is an optional parameter of the methods so you can use a different hash algorithm if you prefer. See the documentation of EncryptString and DecryptString for more information.

If you are dealing with a .NET program, then you can read about the .NET equivalent method here.

If you are dealing with data from other languages or platforms (Java, PHP and so on) then you need to use the plain passwords approach.

Plain Passwords

A plain password is, as the name suggests, just the plain text of the password itself. This approach relies on the inherent strength of the password itself for security.

The length of the password matters in that the password should be as long as the encryption block size, but if the password is longer than that then the extra information is not used. Also passwords tend to consist of typeable characters which means that many possible password combinations are not used and thus the password is weaker than it should be.

That said, if you are dealing with data that has been encrypted on non-Windows platforms, or needs to be decrypted on non-Windows platforms, then you need to use the plain password approach. Choosing this approach is simple enough by passing cs:CALG_NOHASH as the hashing algorithm to EncryptString and DecryptString. See the documentation of EncryptString and DecryptString for more information.

Padding

When you are encrypting a string then "chuncks" of the string are encrypted at a time. The size of this chuck is known as the Block Length. Since the string you are encrypting may not be exactly the right length, the various algorithms use Padding to manage the end of the string. And not surprisingly there are many possible padding algorithms in use.

The only padding algorithm supported by the Microsoft supplied providers is called PKCS5.

As with passwords, padding is important when you are moving data between systems or environments. Both sides need to be using the same padding.

Many systems (including PHP) default to an alternative approach called ZERO Padding. Choosing this approach is done by passing the cs:NO_PADDING equate as the  Padding parameter of  EncryptString and DecryptString. See the documentation of EncryptString and DecryptString for more information.

Chaining

Chaining is a technique that many algorithms use to make for a stronger result. The default chaining setting is usually determined by that specific algorithm. You can set the Ciphermode parameter  of  EncryptString and DecryptString if you need to override this.

The most common default is cs:CRYPT_MODE_CBC (Cipher-Block-Chaining) but another common one is cs:CRYPT_MODE_ECB (Electronic Code book).

Initialization Vector

When using the Cipher-Block-Chaining (CBC) method, it is sometimes necessary to specify an initalization vector. This can be done by setting the IV parameter of  EncryptString and DecryptString. See the documentation of EncryptString and DecryptString for more information.

Byte Ordering

Different systems can order the bytes in different ways. In at least one case it was necessary to reverse the string before decrypting it. For example;

Str.SetValue(clip(InValue))
Str.Base64Decode()
Str.Reverse()
decData = Str.GetValue()
dataLen = Str.Length()
If Crypto.Decrypt(Crypto.hExchangeKey, decData, dataLen, , cs:CRYPT_OAEP) <> Crypto:OK
 
! etc

 

Importing a Certificate

Certificates are required by a number of the Cryptonite functions, especially with regard to asymmetric encryption and message signing.

There is much to say on the topic of acquiring of a certificate from a certificate authority. However at this point we'll assume that you have one. A test certificate (called safetester.pfx) is included in the \examples\cryptonite\demo folder and that one will be sufficient for the purposes of this JumpStart. Or you can just make your own.

The safetester.pfx file uses a password, and you will need this password when importing it - the password is capesoft.

In order for the Windows Crypto API to use the certificate it must be imported into the Windows Certificate Store. This can be done manually using the Windows Certificate Manager (which you can run by going to the Start menu, Run, and then entering CERTMGR.MSC. It can also be done programmatically using the method call PFXImport.

Example of importing a certificate

crypto     Cryptonite
  code
  crypto.PFXImport('safetester.pfx',Password,'Personal')


If the PFX file contains a Private Key then you will need the password to the PFX file in order to install it.

Once you have installed the certificate, you can view it using the Certificate Manager. By default the certificate is added to the Personal \ Certificates store.



For a more in-depth discussion about certificates see the Certificate section in this document.

Signing Data

Note : This is not the same as code signing an EXE, or DLL - that is explained elsewhere.

The concept behind signing data is fairly simple. The idea is that while you don't want to encrypt the data, you want to be sure that the data is "correct", where correct in this situation means that it is unchanged between the creator and the recipient.

The data that is signed is usually a Hash of the data being sent. Once a hash is created it is encrypted using the Private key. This is then sent with the message. The recipient checks that the hash decrypts using the public key, and then creates a hash of the sent data. If the two hashes match then the data has not been tampered with, and the sender who signed the message can be validated.

It's possible of course to generate a signature for any kind of data; a file on the disk, a block of xml data, an email and so on. It doesn't matter what the data contains.  Of course how you attach the signature to some data will vary depending on the file format. For example for email the signature is attached as a Mime attachment, for xml the signature is often included in the xml itself as an extra data node and so on.

We've already seen that we can determine the correctness of data by making a Hash of it. If you have the data, and you know what the hash of the data should be, then you can verify that the hash of what you actually got matches what the hash should be. At this point you just have to determine the validity of the Hash itself that you have received. Clearly the Hash cannot be given to you unencrypted because then an interceptor could change the data and the hash at the same time. So the Hash needs to be encrypted.

Signing is just the idea that you take a hash of the data, and encrypt that hash, and then that becomes the Signature of the data. In order to validate the data at the receivers end, the signature is decrypted to get the hash, and then a hash of the received data is compared with it.

Cryptonite provides a couple of easy-to-use methods to create (SignMessage), and verify (VerifySignature) a signature.

Simple Example of generating a signature.
Crypto               Cryptonite
mess                 StringTheory
Signature            StringTheory
  code	
  mess.LoadFile(filename)
  crypto.SignMessage(mess,cs:CALG_SHA_256,'Safe Update Test', signature)    
The mess parameter contains the data to be used, and the second parameter sets the hashing algorithm that will be used. The third parameter identifies the certificate which will be used to encrypt the result. The signature itself is returned in another StringTheory object (Signature) after it has been hex-encoded. You can specify base 64 encoding by setting the fourth parameter;

crypto.SignMessage(mess,cs:CALG_SHA_256,'Safe Update Test', signature, Crypto:EncBase64)

By default the certificate is included in the signature. If you wish to exclude it then you can add a fifth parameter, set to false. For Example;

crypto.SignMessage(mess,cs:CALG_SHA_256,'Safe Update Test', signature, Crypto:EncHex ,false)

Also, by default, the data itself is not included in the signature. However you can include the data as well if you add a sixth parameter, and set that to false. For example;

crypto.SignMessage(mess,cs:CALG_SHA_256,'Safe Update Test', signature, Crypto:EncNone ,true, false)

The opposite of creating a signature is verifying that the signature is valid.

Simple Example of verifying a signature

Crypto               Cryptonite
mess                 StringTheory
Signature            StringTheory
Signer               String(255)
CertInfo             String(255)
Result               Long
Verified             Long

  code
  mess.LoadFile(filename)
  result = crypto.VerifySignature(mess,signature,Crypto:EncHex,Signer,CertInfo,,Verified)

In this example, once the call is completed, the Signer and CertInfo variables will contain information about the certificate used. If you care about who signed the message (and you probably do) then you should check these values. Indeed if the Signer variable is set to something other than blank when you make the call, and it does not match the certificate in the signature, then the VerifySignature method will return Crypto:NotOk.

If the signature contains the message as well as the signature (in other words, if SignMessage was called with the 7th parameter set to false) then you will need to use a slightly different call to verify the signature. As with SignMessage another parameter is needed;

   result = crypto.VerifySignature(mess,signature,Crypto:EncHex,Signer,CertInfo,,Verified,false)

If the method returns Crypto:NotOk then the Verified parameter contains specific reason for why the signature was not verified. See the method documentation for more information on the possible values in this field.

Both the SignMessage and VerifySignature methods take additional optional parameters. These allow you more control over how the signature is created (what encoding type is used, whether the certificate is included or not) and also a lot more information about the signature when it is verified (and more detail on why it failed, if it fails.) Refer to the method documentation for more information on the methods themselves.

You may want to access more information about the certificates used when doing a SignMessage, to do that see the section Get the Certificate Chain.

Get the Certificate Chain

It may be necessary to check a certificate in the Windows certificate store. This can be done using the GetCertificateChain method. This loads the certificate, and all the parent certificates in the chain into the Certificates queue.

This method is called automatically when calling SignMessage. If you call SignMessage then you do not need to call GetCertificateChain, the Certificates queue will automatically be loaded.

Certificates Queue

The certificates property is a queue is loaded by a call to GetCertificateChain. The components of the queue are as follows;
Field Description
Version
Long
The version number of the certificate. At the time of writing the possible versions are 1, 2 or 3. the most likely value is 3.
CertEncodingType
Long
One of cs:X509_ASN_ENCODING (1), or cs:PKCS_7_ASN_ENCODING (10000h/4096)
CertEncoded
String
The encoding of the certificate, as per the encoding type above. Note that this field is already Hex Encoded using the ToHex method. this makes it displayable on the screen. To return it to binary form use the FromHex method.
SignatureAlgorithm
String
A text description of the algorithm used.
SerialNumber
String
The serial number of the certificate. Note that this field is already Hex Encoded using the ToHex method. this makes it displayable on the screen. To return it to binary form use the FromHex method.
Subject
String
A comma separated list, containing attribute=value,attribute=value. For example;
CommonName=Safe Update Test,emailAddress=safeupdate@capesoft.com
Issuer
String
A comma separated list, containing attribute=value,attribute=value. For example;
Country=IL,Organization=StartCom Ltd.,OrganizationalUnit=StartCom Certification Authority,CommonName=StartCom Class 1 Client CA
NotBeforeDate
Long
A Clarion date marking the start of the validity period for the certificate.
NotBeforeTime
Long
A Clarion time marking the start of the validity period for the certificate. This time is in the UTC time zone.
NotAfterDate
Long
A Clarion date marking the end of the validity period for the certificate.
NotAfterTime
Long
A Clarion time marking the end of the validity period for the certificate. This time is in the UTC time zone.
PublicKeyAlgorithm
String
The algorithm used to generate the public key
PublicKey
String
The public key for the certificate. Note that this field is already Hex Encoded using the ToHex method. this makes it displayable on the screen. To return it to binary form use the FromHex method.
PublicKeyLength
Long
The length of the public key in bits.
You can inspect the certificate, and the parents of the certificate, by looping through the Certificates queue. For example;

crypto  Cryptonite
x            Long
CertData   String(32000)

  code

  crypto.GetCertificateChain('Safe Update Test')
  CertData = ''
  loop x = 1 to records(crypto.certificates)
    get(crypto.certificates,x)
    CertData = clip(certData) & '=== CERTIFICATE ===<13,10>'
    CertData = clip(certData) & ' Version = ' & crypto.certificates.Version & '<13,10>'
    CertData = clip(certData) & ' CertEncodingType = ' & crypto.certificates.CertEncodingType & '<13,10>'
    CertData = clip(certData) & ' CertEncoded = ' & clip(crypto.certificates.CertEncoded) & '<13,10>'
    CertData = clip(certData) & ' SignatureAlgorithm = ' & clip(crypto.certificates.SignatureAlgorithm) & '<13,10>'
    CertData = clip(certData) & ' SerialNumber = ' & clip(crypto.certificates.SerialNumber) & '<13,10>'
    CertData = clip(certData) & ' Subject = ' & clip(crypto.certificates.Subject) & '<13,10>'
    CertData = clip(certData) & ' Issuer = ' & clip(crypto.certificates.Issuer) & '<13,10>'
    CertData = clip(certData) & ' NotBeforeDate = ' & format(crypto.certificates.NotBeforeDate ,@d1) & '<13,10>'
    CertData = clip(certData) & ' NotBeforeTime = ' & format(crypto.certificates.NotBeforeTime ,@t4) & ' UTC<13,10>'
    CertData = clip(certData) & ' NotAfterDate = ' & format(crypto.certificates.NotAfterDate ,@d1) & '<13,10>'
    CertData = clip(certData) & ' NotAfterTime = ' & format(crypto.certificates.NotAfterTime ,@t4) & ' UTC<13,10>'
    CertData = clip(certData) & ' PublicKeyAlgorithm = ' & clip(crypto.certificates.PublicKeyAlgorithm) & '<13,10>'
    CertData = clip(certData) & ' PublicKeyLength = ' & crypto.certificates.PublicKeyLength & ' bits<13,10>'
    CertData = clip(certData) & ' PublicKey = ' & clip(crypto.certificates.PublicKey) & '<13,10>'
    CertData = clip(certData) & '=== =========== ===<13,10>'
  end




Codesigning an Exe or DLL

Work in Progress.

Asymmetrically Encrypting a File

If you symmetrically encrypt a file then the same password is used to encrypt, and decrypt the file. This is fine if the file will be created, and used by the same program. However if your goal is to move the file between two systems then asymmetric encryption can be useful.

With asymmetric encryption one key is used to encrypt the file, and another is used to decrypt the file. One of the keys is a secret (the so called Private Key) and one of the keys is not a secret (the Public Key).

For example, say the file is encrypted with the non-secret key. Since the key is freely available anyone can encrypt a file using this key. Once encrypted though the file can only be decrypted by the person who holds the private key.

The reverse is also true, files encrypted with the private key can only be decrypted with the public key. This is not useful in protecting the contents of the file, however it is useful to validate the origin of the file. If a file can be decrypted using a public key, then one can be sure that the file was encrypted by the owner of that public key (since he is the only one who has access to his private key.)

Template Level Encryption

Cryptonite includes a global extension template which allows fields in a table to be separately encrypted. You can use the Global Extension template to set up field and file level encryption for specific fields of data tables.

The primary goal for encrypting fields is to enhance the security for fields which must not be accessible to other users of the database, even if they have access to database, and that specific table. The goal is not to replace database-level security, and this should be used in addition to that for best results.

Some caveats for using encryption for your data files:
  1. You must not lose your Password or Initialization Vector

    If you do, throw away your data, and any backups, as they will be useless.

    In other word, make sure that you have backups of the password and vector. Encryption protects the data from anyone who does not have the key, and that potentially includes you. There is no backdoor to the data without this key.
  2. Don't encrypt fields where the order is used in a view or key, as the order will be meaningless. the key will be the order of the encrypted values, not the unencrypted values.
  3. Any EXE accessing the data, must also have Cryptonite added with the same password and initialization vector to access that table (in order to decrypt the field).
  4. You cannot encrypt CSTRING values. CSTRINGs cannot hold binary values, since they cannot hold the Chr(0), and so are not suitable for encryption. Use a STRING field instead.
  5. There is no way to tell if a field has already been encrypted, or not. Thus changing fields in existing records from unencrypted, to encrypted is tricky, and would need to be done with a separate utility. Therefore fields that need encrypting should be added to the templates before data is added to the table.
  6. For the same reason changing the password for a field is tricky, and con only be done using an external utility.

Samples

Encrypting an INI value

str Stringtheory
Crypto Cryptonite
  code
  str.SetValue(System:EmailPassword,st:clip)
  Crypto.EncryptString(str,'vwlur' & 12*13.23 & 'u45,.<13,10>')
  str.Base64Encode(true)
  PutIni('Email','EmailPassword',str.GetValue(),inifile)

Decrypting an INI value

str Stringtheory
Crypto Cryptonite
  code
  System:EmailPassword = GetIni('Email','EmailPassword','',inifile)
  str.SetValue(System:EmailPassword,st:clip)
  str.Base64Decode()
  Crypto.DecryptString(str,'vwlur' & 12*13.23 & 'u45,.<13,10>')
  System:EmailPassword = str.GetValue()

Encrypting a field inside a group when saving to XML using xFiles

crypto    Cryptonite
str       StringTheory
xml                     class(xFileXml)
SaveCurrentFieldToXML     PROCEDURE (Long p_x,Long p_DimCounter,String p_name),Virtual
                        end
  code
  xml.Save(System:Email,clip(FileName:Directory) & 'settings.xml','','settings')
 
xml.SaveCurrentFieldToXML PROCEDURE (Long p_x,Long p_DimCounter,String p_name)
  CODE
  if instring('password',lower(p_name),1,1) > 0
    str.SetValue(self.currentfield,st:clip)
    Crypto.EncryptString(str,'somepassword')
    str.Base64Encode(st:NoWrap)
    self.currentfield &= str.GetValuePtr()
  end
  PARENT.SaveCurrentFieldToXML (p_x,p_DimCounter,p_name)

Decrypting a field inside a group when loading from XML using xFiles

crypto    Cryptonite
str       StringTheory
xml                     class(xFileXml)
AssignField               Procedure (String pString),Virtual
                        end
 
  code
  xml.Load(System:Email,'settings.xml','','settings')
 
xml.AssignField Procedure (String pString)
  code
  if instring('password',lower(self.CurrentTag),1,1)   
    str.SetValue(pString,st:clip)
    str.Base64Decode()
    Crypto.DecryptString(str,'somepassword') 
    self.CurrentField = str.GetValue()
    return ! this is important to avoid the call to PARENT
  end
  parent.AssignField(pString)

Examples

Demo\Crypto.app

This is the main Cryptonite example application. It demonstrates a variety of common and useful tasks using the Cryptonite class, including:

Provider



The Cryptonite Templates

The Global Extension

DataTables Tab

For a background on this topic see Template Level Encryption.
Tables To Encrypt
A list containing the tables which contain encrypted fields.
Fields To Encrypt
Fields in the table which will be encrypted. Note that encrypting fields which are used in Keys can lead to problems. Since keys are used to sort data in the table, if you encrypt key fields then the key is sorted by encrypted value, not actual value. This means that you cannot do a SET/NEXT loop through a table using a encrypted field, and Browses cannot use column-sorting on encrypted fields. You can still do a GET on encrypted keys.
Password
The password for the encryption. This is symmetric encryption, meaning that the same password is used to encrypt, and decryprt the fields. Be sure to look after this password - if you lose it then the data in the table becomes irretrivable. There is no back-ddor way to unencrypt the data.
Initialization Vector
The initialization vection for the fields. This can be thought of as a way of extending the password. Again this should be very carefully looked after, if you lose this vector then the data will be irretrivable.

The Local Extension

Add this extension to populate an instance of the Cryptonite class for you.

You do not need to use the extension template. It is also possible to declare the class in code like this;
Crypto                  Cryptonite

Cryptographic Service Providers

The Windows CryptoAPI exposes functionality using Cryptographic Service Providers (CSP). Each provider implements a specific set of algorithms for encryption, hashing, signing etc.

Before using any of the functionality provider by Cryptonite which uses the CryptoApi a provider and cryptographic context is required. Cryptonite simplifies this process using the GetContainer method. This method will acquire a cryptographic context using the default provider (or the provider specified) and get or create the specified container. A Container is used to store key sets within a provider, and is accessed using a string to identify it.

Note that the container name should include the Windows User Name (or other unique string) so that each user on the machine has their own container. Failing to do this will result in an error;

"Could not acquire a context and create a new keyset for the container"
The "Providers" example demonstrates how to list the providers available on the system and acquire a specific provider.

Examples

Use the default CSP and get a container called 'CryptoProvs'. Create it if it does not exist. The parameters specify the container name (a name that your application uses to identify a container), the second parameter allows the container to be created if it is set to True and the container doesn't exist.
Crypto.GetContainer('CryptoProvs', true)
Here's another example. Use a specific CSP and get a container called 'CryptoProvs'. Create it if it does not exist. The third parameter specifies the Type of the provider (see Provider Types below for a list of provider types and the functionality each type supports). The fourth parameter specifies which Provider should be used (See Available Providers below for a list of providers).
Crypto.GetContainer('CryptoProvs', true, cs:PROV_RSA_AES, cs:MS_ENH_RSA_AES_PROV

Available Providers

The following CSPs (Cryptographic Service Providers) are available as a part of Windows (note that older version of Windows do not provide all of the below CSPs).

You can "inspect" the providers installed on a machine by going to the following place in the Windows registry;
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\Defaults\Provider Types
Each type is listed under a number, and the Name attribute of each type matches the names below.
 

Microsoft Base Cryptographic Provider

The Microsoft Base Cryptographic Provider is the initial cryptographic service provider (CSP) provider, and is distributed with CryptoAPI versions 1.0 and 2.0. It is a general-purpose provider that supports digital signatures and data encryption.

The RSA public key algorithm is used for all public key operations.
Provider type cs:PROV_RSA_FULL
Provider name cs:MS_DEF_PROV
Hash Algorithms cs:CALG_MD2, cs:CALG_MD5, cs:CALG_SHA, cs:CALG_SHA1, cs:CALG_MAC, cs:CALG_HMAC, cs:CALG_SSL3_SHAMD5 
Asymmetric Algorithms cs:CALG_RSA_SIGN, cs:CALG_RSA_KEYX 
Symmetric Algorithms cs:CALG_RC2, cs:CALG_RC4, cs:CALG_DES
For more information on this provider see http://msdn.microsoft.com/en-us/library/windows/desktop/aa386980(v=vs.85).aspx

Microsoft Strong Cryptographic Provider

The Microsoft Strong Cryptographic Provider is used as the default RSA Full cryptographic service provider (CSP). It supports all of the algorithms of the Microsoft Base Cryptographic Provider plus the .
Provider type cs:PROV_RSA_FULL
Provider name cs:MS_STRONG_PROV
Hash Algorithms cs:CALG_MD2, cs:CALG_MD5, cs:CALG_SHA, cs:CALG_SHA1, cs:CALG_MAC, cs:CALG_HMAC, cs:CALG_SSL3_SHAMD5 
Asymmetric Algorithms cs:CALG_RSA_SIGN, cs:CALG_RSA_KEYX 
Symmetric Algorithms cs:CALG_RC2, cs:CALG_RC4, cs:CALG_DES
For more information on this provider see http://msdn.microsoft.com/en-us/library/windows/desktop/aa386989(v=vs.85).aspx

Microsoft Enhanced Cryptographic Provider

This is the default CSP used by Cryptonite. The Microsoft Enhanced Cryptographic Provider, called the Enhanced Provider, supports the same capabilities as the Microsoft Base Cryptographic Provider, called the Base Provider. The Enhanced Provider supports stronger security through longer keys and additional algorithms. It can be used with all versions of CryptoAPI.
Provider type cs:PROV_RSA_FULL
Provider name cs:MS_ENHANCED_PROV
Hash Algorithms cs:CALG_MD2, cs:CALG_MD5, cs:CALG_SHA, cs:CALG_SHA1, cs:CALG_MAC, cs:CALG_HMAC, cs:CALG_SSL3_SHAMD5 
Asymmetric Algorithms cs:CALG_RSA_SIGN, cs:CALG_RSA_KEYX 
Symmetric Algorithms cs:CALG_RC2, cs:CALG_RC4, cs:CALG_DES, cs:CALG_3DES
For more information on this provider see http://msdn.microsoft.com/en-us/library/windows/desktop/aa386986(v=vs.85).aspx

Microsoft AES Cryptographic Provider

The Microsoft AES Cryptographic Provider supports the same capabilities as the Microsoft Base Cryptographic Provider, called the Base Provider. The AES Provider supports stronger security through longer keys and additional algorithms. It can be used with all versions of CryptoAPI.
Provider type cs:PROV_RSA_AES
Provider name cs:MS_ENH_RSA_AES_PROV
Hashing Algorithms cs:CALG_MD2, cs:CALG_MD5, cs:CALG_SHA, cs:CALG_SHA1, cs:CALG_SHA_256, cs:CALG_SHA_384, cs:CALG_SHA_512, cs:CALG_MAC, cs:CALG_HMAC, cs:CALG_SSL3_SHAMD5 
Asymmetric Algorithms cs:CALG_RSA_SIGN, cs:CALG_RSA_KEYX
Symmetric Algorithms cs:CALG_DES, cs:CALG_3DES, cs:CALG_3DES_112, cs:CALG_AES_128, cs:CALG_AES_192, cs:CALG_AES_256
For more information on this provider see http://msdn.microsoft.com/en-us/library/windows/desktop/aa386979(v=vs.85).aspx

Microsoft Provider Key Lengths

The following table highlights differences between the Base Provider, Strong Provider, and Enhanced Provider. The key lengths shown are the default key lengths.
Algorithm Base Provider Strong Provider Enhanced Provider AES Provider
RSA public key signature algorithm 512 bits 1,024 bits 1,024 bits 1,024 bits
RSA public key exchange algorithm 512 bits 1,024 bits 1,024 bits 1,024 bits
RC2 block encryption algorithm 40 bits 128 bits 128 bits
Salt length can be set.
128 bits
Salt length can be set
RC4 stream encryption algorithm 40 bits 128 bits 128 bits
Salt length can be set
128 bits
Salt length can be set
DES 56 bits 56 bits 56 bits 56 bits
Triple DES (2 key) Not supported 112 bits 112 bits 112 bits
Triple DES (3 key) Not supported 168 bits 168 bits 168 bits
AES Not supported Not supported Not supported 128, 192 or 256 bits.

The Strong Provider and the Enhanced Provider are backward-compatible with the Base Provider except that the providers can only generate RC2 or RC4 keys of default key length. The default length for the Base Provider is 40 bits. The default length for the Enhanced Provider is 128 bits. Thus the Enhanced Provider cannot create keys with Base Provider-compatible key lengths. However, the Enhanced Provider can import RC2 and RC4 keys of up to 128 bits. Therefore, the Enhanced Provider can import and use 40 bit keys generated using the Base Provider.

Microsoft DSS Cryptographic Provider

The Microsoft DSS Cryptographic Provider supports hashing, data signing, and signature verification using the Secure Hash Algorithm (SHA) and Digital Signature Standard (DSS) algorithms. It can be exported outside North America.
Provider type cs:PROV_DSS
Provider name cs:MS_DEF_DSS_PROV
Hashing Algorithms cs:CALG_MD5, cs:CALG_SHA, cs:CALG_SHA1
Signature Algorithm cs:CALG_DSS_SIGN

Microsoft Base DSS and Diffie-Hellman Cryptographic Provider

The Microsoft Base DSS and Diffie-Hellman Cryptographic Provider supports Diffie-Hellman (D-H) key exchange (a 40-bit DES derivative), SHA hashing, DSS data signing, and DSS signature verification. It can be exported to other countries/regions.
Provider type cs:PROV_DSS_DH
Provider name cs:MS_DEF_DSS_DH_PROV

Microsoft DSS and Diffie-Hellman/Schannel Cryptographic Provider

The Microsoft DSS and Diffie-Hellman/Schannel Cryptographic Provider supports hashing, data signing with DSS, generating Diffie-Hellman (D-H) keys, exchanging D-H keys, and exporting a D-H key. This CSP supports key derivation for the SSL3 and TLS1 protocols. It can be exported to other countries/regions.
Provider type cs:PROV_DH_SCHANNEL
Provider name cs:MS_DEF_DH_SCHANNEL_PROV

Microsoft RSA/Schannel Cryptographic Provider

The Microsoft RSA/Schannel Cryptographic Provider supports hashing, data signing, and signature verification. The algorithm identifier CALG_SSL3_SHAMD5 is used for SSL 3.0 and TLS 1.0 client authentication. This CSP supports key derivation for the SSL2, PCT1, SSL3, and TLS1 protocols. The hash consists of a concatenation of a MD5 hash with a SHA hash and signed with a RSA private key. It can be exported to other countries/regions.
Provider type cs:PROV_RSA_SCHANNEL
Provider name cs:MS_DEF_RSA_SCHANNEL_PROV

Microsoft RSA Signature Cryptographic Provider

The Microsoft RSA signature Cryptographic Provider provides data signing and signature verification.
Provider type cs:PROV_RSA_SIG
Provider name cs:MS_DEF_RSA_SIG_PROV

Available Provider Types

The provider type is used to identify the type of a specific provider, which determines the algorithms available and the options used for encryption mode, padding and so on. Providers of different types are not guaranteed to be compatible even if they implement the same algorithms (they may use different key lengths, padding options or default modes).

cs:PROV_RSA_FULL

The PROV_RSA_FULL provider type supports both digital signatures and data encryption. It is considered a general purpose CSP. The RSA public key algorithm is used for all public key operations

Algorithms Supported
Purpose Supported algorithms
Key Exchange RSA
Signature RSA
Encryption RC2
RC4
Hashing MD5
SHA

cs:PROV_RSA_AES

The PROV_RSA_AES provider type supports both digital signatures and data encryption. It is considered a general purpose CSP. The RSA public key algorithm is used for all public key operations.

Algorithms Supported
Purpose Supported algorithms
Key Exchange RSA
Signature RSA
Encryption RC2
RC4
AES
Hashing MD5
SHA

cs:PROV_RSA_SIG

The PROV_RSA_SIG provider type is a subset of PROV_RSA_FULL. It supports only those functions and algorithms required for hashes and digital signatures.

Algorithms Supported
Purpose Supported algorithms
Key Exchange None
Signature RSA
Encryption None
Hashing MD5
SHA

cs:PROV_DSS

The PROV_DSS provider type, like PROV_RSA_SIG, only supports hashes and digital signatures. The signature algorithm specified by the PROV_DSS provider type is the Digital Signature Algorithm

Algorithms Supported
Purpose Supported algorithms
Key Exchange None
Signature DSS
Encryption None
Hashing MD5
SHA

cs:PROV_DSS_DH

The PROV_DSS_DH provider is a superset of the PROV_DSS provider type.

Algorithms Supported

For descriptions of each of these algorithms, see the glossary.
Purpose Supported algorithms
Key Exchange DH
Signature DSS
Encryption CYLINK_MEK
Hashing MD5
SHA

cs:PROV_DH_SCHANNEL

The PROV_DH_SCHANNEL provider type supports both Diffie-Hellman and Schannel protocols.

Algorithms Supported

For descriptions of each of these algorithms, see the glossary.
Purpose Supported algorithms
Key Exchange DH (ephemeral)
Signature DSS
Encryption DES
Triple DES
Hashing MD5
SHA

cs:PROV_FORTEZZA

The PROV_FORTEZZA provider type contains a set of cryptographic protocols and algorithms owned by the National Institute of Standards and Technology(NIST).

Algorithms Supported

For descriptions of each of these algorithms, see the glossary.

Purpose Supported algorithms
Key Exchange KEA
Signature DSS
Encryption Skipjack
Hashing SHA

cs:PROV_MS_EXCHANGE

The PROV_MS_EXCHANGE provider type is designed for the cryptographic needs of the Microsoft Exchange mail application and other applications compatible with Microsoft Mail.

Algorithms Supported

For descriptions of each of these algorithms, see the glossary.

Purpose Supported algorithms
Key Exchange RSA
Signature RSA
Encryption CAST
Hashing MD5

Available Algorithms

The algorithms available to you depend on the provider and provider type being used.
 
AES


The CryptoAPI algorithm name for the Advanced Encryption Standard algorithm. AES is available in different bit lengths, depending on the provider being used;
cs:ALG_SID_AES, cs:ALG_SID_AES_128, cs:ALG_SID_AES_192, cs:ALG_SID_AES_256

ALG_CLASS_DATA_ENCRYPT

The CryptoAPI algorithm class for data encryption algorithms. Typical data encryption algorithms include RC2 and RC4.
cs:ALG_SID_RC2, cs:ALG_SID_RC4

ALG_CLASS_HASH

The CryptoAPI algorithm class for hashing algorithms. Typical hashing algorithms include MD2, MD5, SHA-1, and MAC.
cs:ALG_SID_MD2, cs:ALG_SID_MD5, cs:ALG_SID_SHA1, cs:ALG_SID_MAC, cs:ALG_SID_SHA_256, cs:ALG_SID_SHA_384, cs:ALG_SID_SHA_512

ALG_CLASS_KEY_EXCHANGE

The CryptoAPI algorithm class for key exchange algorithms. A typical key exchange algorithm is RSA_KEYX.
cs:CALG_RSA_KEYX

ALG_CLASS_SIGNATURE

The CryptoAPI algorithm class for signature algorithms. A typical digital signature algorithm is RSA_SIGN.
cs:CALG_RSA_SIGN

Glossary

hash

A fixed-size result obtained by applying a mathematical function (the hashing algorithm) to an arbitrary amount of data. (Also known as "message digest.")

See also hashing functions.

hash object

An object used to hash messages or session keys. The hash object is created by a call to MakeHash. The definition of the object is defined by the CSP specified in the call.

hashing algorithm

An algorithm used to produce a hash value of some piece of data, such as a message or session key. Typical hashing algorithms include MD2, MD4, MD5, and SHA-1.

hashing functions

A set of functions used to create and destroy hash objects, get or set the parameters of a hash object, and hash data and session keys.

Hash-Based Message Authentication Code

(HMAC) A symmetric keyed hashing algorithm implemented by Microsoft cryptographic service providers. An HMAC is used to verify the integrity of data to help ensure it has not been modified while in storage or transit. It can be used with any iterated cryptographic hash algorithm, such as MD5 or SHA-1. CryptoAPI references this algorithm by its algorithm identifier (CALG_HMAC) and class (ALG_CLASS_HASH).

MD2

The CryptoAPI algorithm name for the MD2 hash algorithm. Other hashing algorithms include MD4, MD5, and SHA. See also MD2 algorithm.

MD2 algorithm

(MD2) A hashing algorithm that creates a 128-bit hash value. MD2 was optimized for use with 8-bit computers. CryptoAPI references this algorithm by its type (CALG_MD2), name (MAC), Security, Inc.

See also MD4 algorithm, MD5 algorithm.

MD4

The CryptoAPI algorithm name for the MD4 hash algorithm. Other hashing algorithms include MD2, MD5, and SHA.

See MD4 algorithm.

MD4 algorithm

(MD4) A hashing algorithm that creates a 128-bit hash value. MD4 was optimized for 32-bit computers. It is now considered broken because collisions can be found too quickly and easily. MD4 was developed by RSA Data Security, Inc.

See also MD2 algorithm, MD5 algorithm.

MD5

The CryptoAPI algorithm name for the MD5 hash algorithm. Other hashing algorithms include MD2, MD4, and SHA.

See also MD5 algorithm.

MD5 algorithm

(MD5) A hashing algorithm that creates a 128-bit hash value. MD5 was optimized for 32-bit computers. CryptoAPI references this algorithm by its algorithm identifier (CALG_MD5), name (MD5), and class (ALG_CLASS_HASH). MD5 was developed by RSA Data Security, Inc. and is specified by PROV_RSA_FULL, PROV_RSA_SIG, PROV_DSS, PROV_DSS_DH, and PROV_MS_EXCHANGE provider types.

See also MD2 algorithm, MD4 algorithm.

message

Any data that has been encoded for transmission to or received from a person or entity. Messages may be encrypted for privacy, digitally signed for authentication purposes, or both.

message digest

See hash.

Message Authentication Code

(MAC) A keyed hashing algorithm that uses a symmetric session key to help ensure that a block of data has retained its integrity from the time it was sent until the time it was received. When using this type of algorithm, the receiving application must also possess the session key to recompute the hash value so it can verify that the base data has not changed. CryptoAPI references this algorithm by its type (CALG_MAC), name (MAC), and class (ALG_CLASS_HASH).

message encoding type

Defines how the message is encoded. The message encoding type is stored in the high-order word of the encoding type structure. Current defined encoding types are: CRYPT_ASN_ENCODING, X509_ASN_ENCODING, and PKCS_7_ASN_ENCODING.

RC2

The CryptoAPI algorithm name for the RC2 algorithm.

See also RC2 block algorithm.

RC2 block algorithm

A data encryption algorithm based on the RC2 64-bit symmetric block cipher. RC2 is specified by PROV_RSA_FULL provider types. CryptoAPI references this algorithm by its identifier (CALG_RC2), name (RC2), and class (ALG_CLASS_DATA_ENCRYPT).

RC4

The CryptoAPI algorithm name for the RC4 algorithm.

See also RC4 stream algorithm.

RC4 stream algorithm

A data encryption algorithm based on the RC4 symmetric stream cipher. RC4 is specified by PROV_RSA_FULL provider types. CryptoAPI references this algorithm by its identifier (CALG_RC4), name (RC4), and class (ALG_CLASS_DATA_ENCRYPT).

RSA

RSA Data Security, Inc., a major developer and publisher of public key cryptography standards (PKCS). The "RSA" in the name stands for the names of the company's three developers and the owners: Rivest, Shamir, and Adleman.

RSA_KEYX

The CryptoAPI algorithm name for the RSA key exchange algorithm. CryptoAPI also references this algorithm by its algorithm identifier (CALG_RSA_KEYX) and class (ALG_CLASS_KEY_EXCHANGE).

RSA_SIGN

The CryptoAPI algorithm name for the RSA signature algorithm. CryptoAPI also references this algorithm by its algorithm identifier (CALG_RSA_SIGN) and class (ALG_CLASS_SIGNATURE).

RSA Public Key algorithm

A key exchange and signature algorithm based on the popular RSA Public Key cipher. This algorithm is used by PROV_RSA_FULL, PROV_RSA_SIG, PROV_MS_EXCHANGE, and PROV_SSL provider types. CryptoAPI references this algorithm by its identifiers (CALG_RSA_KEYX and CALG_RSA_SIGN), names (RSA_KEYX and RSA_SIGN) and class (ALG_CLASS_KEY_EXCHANGE).

Secure Hash Standard

A standard designed by NIST and NSA. This standard defines the Secure Hash Algorithm (SHA-1) for use with the Digital Signature Standard (DSS).

Certificates

Certificate Formats

Certificates and private key files are provided in a variety of formats such as PFX, PEM, DER, CER, CRT and KEY. The CryptoAPI uses the PFX format, which can contain multiple certificates and a private key. These are often provided separately as a certificate (.crt, .cer, .der, pem etc.) and a private key (typically a .key file).  The following are all just different types of the same thing. It is relatively easy to convert between types.

PKCS#12

Also known as PFX files. Can contain all of private keys, public keys and certificates. It stores them in a binary format. This is the primary format supported by the CryptoAPI and hence Cryptonite.

PEM

Can contain all of private keys (RSA and DSA), public keys (RSA and DSA) and (x509) certificates. It is the default format for OpenSSL. It stores data Base64 encoded DER format, surrounded by ASCII headers, so is suitable for text mode transfers between systems.

DER

Can contain all of private keys, public keys and certificates. It stored according to the ASN1 DER format. It is headerless - PEM is text header wrapped DER. It is the default format for most browsers.

Making a Certificate

You can create your own PFX file very easily using the makecert.exe utility. (This utility ships as part of the Windows SDK, and may already be installed on your computer.

Additional reading

A Blog Post by Daniel Chambers is an excellent background resource to understanding creating certificates with MakeCert, from a developer point of view. It's a strongly recommended read.

Getting a Certificate

Certificates are available from a number of Certificate Authorities (CAs). These include Comodo, Thawte, Verisign and others.

You can get a free certificate (best used for testing) directly from Comodo:

Managing Certificates

Microsoft provide a Certificate management snapin for the Microsoft Management Console. You can create your own Certificates Management Console as follows: You now have a certificate management console that allows you to view, edit and delete certificates. The Personal store will contain the bulk of the certificates that you use.

A certificate can be imported by dragging and dropping a PFX file into a store, or simply by double clicking on the PFX file. You can also double click on a certificate in any store and export it to a file.

To save the console that you have created for future use choose File->Save As and choose a name for the file. This creates a small XML file with the extension .msc that will launch the console with your chosen Snap-ins.

Converting Using OpenSSL

Cryptonite ships with the OpenSSL tools required to manage and convert certificates and keys between the various formats. The OpenSSL.exe utility is install into your Clarion\accessory\bin\ folder.

These commands allow you to convert certificates and keys to different formats to make them compatible with specific types of servers or software. For example, you can convert a normal PEM file that would work with Apache to a PFX (PKCS#12) file.

Other formats

Checking and validating files

Classes

Cryptonite

The main Cryptonite class, handles the primary encryption and decryption tasks, as well as hashing, encoding, loading and saving data etc..

Cryptonite Method List

These methods provide the ability to easily encrypt and decrypt data while handling the underlying complexity and providing a clean and simple interface.
Common Quick Methods
Start Returns the object to a Start state with all defaults reset.
MakeHash Generate the HASH of a particular string or file.
MakeHMAC Generate a HMAC for a specific Message, using a specific secret key.
EncryptString and DecryptString Encrypt, or Decrypt a string.
EncryptStringAES and DecryptStringAES Encrypt, or Decrypt a string using the AES 256 Algorithm.
SignMessage and VerifySignature Generate or Verify the signature for a block of data.
Signing Data
SignMessage Generate a signature for a string, file, or StringTheory object.
VerifySignature Verify a signature by matching it to a block of data, a file, or a StringTheory object
AppendSignature Writes the signature to the end of a file.
GetExpiryDate Get the expiry date of a certificate in the store.
GetSerialNumber Get the serial number of a certificate in the store.
Context (container) management
GetContainer Attempt the fetch an existing context and container. Optionally creates the container if it doesn't exist.
CreateContainer Acquires a CSP context and creates a new key container using the default setting
DeleteContainer Deletes the keyset from the current container
Methods for handling cryptographic certificates.
CertOpenSystemStore Opens a certificate store to allow certificates to be located and used
CertCloseStore Closes an opened store
CertFind Find a certificate by name in the specified store and allows it to be used for encryption, signing etc.
CertNext Retrieves the next certificate in the store that matches the passed name
CertFree Frees memory allocated when a certificate is retrieved from a store
CertGetContainer Retrieve a Cryptographic Context and key set using the specified certificate handle
CertGetPrivateKey Internal method for retrieving the Provider context for a specified certificate. Use CertGetContainer in normal use.
GetCertificateChain Get all the information for a certificate, and parent certificates.
GetExpiryDate Get the expiry date of a certificate in the store.
GetSerialNumber Get the serial number of a certificate in the store.
Handling for importing and exporting PFX files which contain certificates and keys.
PFXImport
Methods for import, exporting, creating and transferring keys.
GetUserKey Gets the user's current exchange key and stores the handle in the object property.
BlobToKey Store the passed session key as an encrypted BLOB in the passed StringTheory object
KeyToBlob Stores the key reference by the hSessionKey handle as an encrypted key BLOB in the passed StringTheory object.
NewSessionKey Create a new session key. Use KeyToBlob to save this session key and BlobToKey to load it.
KeyFromPassword Create a session key derived from the passed password.
ExchangeKeyToBlob Creates an encrypted BLOB of the exchange key pair.
ExchangeKeyFromBlob Imports an exchange key pair from an encrypted BLOB.
ExchangeKeyToFile Creates an encrypted BLOB from the exchange key pair and saves it.
ExchangeKeyFromFile Imports an exchange key pair from an encrypted BLOB on disk.
Encryption and decryption in memory and on disk.
EncryptFile Encrypt a file when passed the file name. Require a context and public/private key pair in the current container
DecryptFile encrypts the passed file and saves the unencrypted output to the file name specified by the plainFile parameter. Assumes that the EncryptFile method was used to encrypt the file and the a context has been acquired with the correct PPK pair.
Encrypt Encrypts the passed data, using the passed key
Decrypt Decrypts the passed data, using the passed key
Object Management
Init
Kill
Advanced Methods
AcquireContext Gets a Cryptographic context and key container
ReleaseContext Releases a Cryptographic context that has been acquired
ChooseCertificate Selects a certificate from the certificates store
GetCertList This is a diagnostic function for inspecting the contents of a given certificate store
Get_OID Get the type of encoding algorithm used in the encryption. Typically not called directly.
EnumProviders Lists all Cryptographic Service Providers available
EnumProviderTypes List the types of Cryptographic Service providers
EncryptDecrypt Wraps encryption and decryption, encrypts or decrypts any passed data using the provided key.
DestroyKey Destroys the passed key handle (cleans up allocated memory)
ExportKey Exports a key to the specified key BLOB
GenPPK Creates a Public Private key pair and stores the handle in the .hExchangeKey property
GenKey Generates a new key key of the specified type
GetKey Returns the key handle to the session or exchange key stored by the object.
GetKeyBlob Exports the specified keytype to the associated key BLOB property of the object.
GetKeyBlobSize Returns the size required to store a specified key as a BLOB
GetKeyFromBlob Extracts the session key from the passed encrypted message BLOB.
GetProviderAlgs Populates a queue with all the algorithms supported by the current Cryptographic Services Provider, and details for each algorithms such as the name, ALG_ID, key lengths etc.
PutKeyBlobToFile Writes a session key to disk, encypted using the current exchange key, used when writing an encrypted message to disk.
ImportKey Imports a key BLOB into the current container
SetKey Sets the exchange or signing key to the passed key handle
SetKeyBlob Stores the passed key BLOB in the specified object key BLOB property.
PutSignature Creates a signature and appends it to a the specified file
SignMessage Obtains and uses the user certificate and hash algorithm identifier to generate a signature for the message.
VerifySignature Verifies that a signature was created using a specific certificate
PFXAddToStore Adds a PFX BLOB to a temporary store for processing
PFXImportStore Processes the passed PFX store and adds all certificates to a system store
CreateHash Creates a Hash (Digest) using the specified algorithm
HashData Adds data to a hash (digest)
DestroyHash Deallocates memory assigned for a hash object
GetHash Retrieves the hash from the object
GetHashInfo Retrieves the hash size or hash from a Hash object
Internal Utility methods
ToCstring Converts a Clarion string to a cstring and returns a pointer to the new cstring
ReverseBytes Swaps the byte order in the passed string (the byte order is swapped for the entire string, so the string is inverted entirely in ordering on a byte level.
StripLineBreaks Removes linebreaks from the passed string
LocateProcedure Load a function at runtime from a DLL
Internal Methods
_CheckCertificate Check the validity of a certificate
_CryptAcquireContext Acquires a Cryptographic context for a specific Cryptographic provider and a specific container.
_GetIdentityList Searches the certificates for a match on the substring parameter. A list is constructed of all matches. Each element in the list will contain "Common Name, Email".
_GetCertChain Retrieves each certificate name in the CA chain
_GetSubjectFromCert Returns the Subject field of the certificate as a string. The Subject field contains all the identification information for the certificate.
_GetIssuerCert Locate the issuer certificate in one of the stores on the local machine.
_FindCertificate Enumerates all the certificates in the given store and selects the one that matches the specified owner.
_FindRDNAttr Takes a given certificate context and retrieves the specified attribute.
_LoadDLLs Runtime DLL loading of the CryptoAPI libraries
_TestSignatureProperty Tests a given certificate context for whether or not it has the AT_SIGNATURE property in its key info.
_TrustSigner Check whether the signer or the chain of issuance of the signer is trusted
_freelist Deprecated
_instring Deprecated
_realloc Deprecated

Cryptonite Property List

defaultHash The currently used hashing algorithm. The default value is cs:CALG_SHA1.
HashAlgorithm the default is SUSign:SHA1_Hash
PaddingMode Used before calls to EncryptString and DecryptString. Default is cs:PKCS5_PADDING. Other options are cs:RANDOM_PADDING, CS:ZERO_PADDING and cs:NO_PADDING.
   
hProvider A handle to the current Cryptographic Service Provider
hExchangeKey A handle to the current Exchange key pair.
hSignKey A handle to the current key used for signing
hCryptKey A handle to the current session key
hHash A handle to the current Hash object
exchangeKeyBlob BLOB storage for importing and exporting the Exchange key pair
signKeyBlob BLOB storage for importing and exporting the Signing key
sessionKeyBlob BLOB storage for importing and exporting the Session key
iv Initialization vector for encryption.
exchangeBlobSize Size of the exchangeKeyBlob, in bytes
signBlobSize Size of the signKeyBlob, in bytes
sessionBlobSize Size of the sessionKeyBlob, in bytes
encryptBlockSize Block size for encryption
BFCrypt The Blowfish encryption object, see Blowfish Encryption and Decryption
logging If set errors are logged to the system debug output
displayErrors If set errors are displayed to the user using the Clarion Message() function

Blowfish

Provides Blowfish encryption and decryption. Blowfish is a symmetric key cipher - the same key (password) is used to encrypt and decrypt the data. The Cryptonite class provides methods for creating a Blowfish object and encrypting and decrypting data. The Blowfish class can be used directly (see the csBlowfish Class Documentation), or via the Cryptonite class, which provides methods that encapsulate this functionality, see the Cryptonite BlowFish Section for more information.

Blowfish Method List

Important Notes Introduction to use Blowfish Encryption
Example An example of using Cryptonite to encrypt and decrypt data using the Blowfish cipher
InitBlowfish Initialise the Blowfish object. Must be called before any of the Blowfish functionality can be used
KillBlowfish Cleans up and diposes all allocated memory
bfEncrypt Encrypt data stored in a StringTheory object using the current key
bfDecrypt Decrypt data stored in a StringTheory object using the current key
bfEncryptString Encrypt a Clarion string
bfDecryptString Decrypt a Clarion string
bfSetKey Set the key to use for encryption and decryption
bfSetIv Sets the Intialization vector for CBC and CFB mode encryption
bfSetMode Sets the encryption mode
bfSetPadding Allows the use of padding or cipher text stealing in ECB and CBC mode
bfResetChain Resets the chain
bfSetMultiBlock Allows very large amount of data to be encrypted or decrypted in multiple calls to the Encrypt/Decrypt methods (allowing data to be processed when not all the data may be in memory at once).

CryptoIni

A replacement class for the standard ABC INI manager. Provides the ability to encrypt and decrypt fields in the file.

CryptoniteCallback

The CryptoniteCallback implements the ABC FileCallBackInterface interface to allow on the fly encryption and decryption of fields within tables, regardless of the backend.

Important: Because of a bug in the SoftVelocity SQL driver, version of Clarion prior to C6.3 9057 cannot use the FileCallBackInterface with SQL, as the REGET function will not cause the callback to be fired. This only applies to applications that use the SQL file driver.

Using the Cryptonite Class

There are two ways to add a Cryptonite object to a procedure in your application. You can use the local extension template, or you can declared the object yourself in the Data section of the procedure:
Cipher           Cryptonite

Cryptonite Method Reference

AppendSignature 

AppendSignature(string FileName, *StringTheory Signature),long

Description

Takes a block of text (typically the signature) and appends it to the file. If the file has already been signed with the signature, then nothing further is added to the file.

Note: This function is not the same as Code Signing an EXE or DLL. That's discussed elsewhere.

Parameters
Parameter DeDescription
FileName The name of the file
Signature A StringTheory object containing the signature.
Returns

Crypto:Ok if successful, Crypto:NotOk if not successful.
Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

See Also

SignMessage, VerifySignature

DecryptString

DecryptString (*StringTheory Data, String Password, Long ProviderType=cs:PROV_RSA_FULL, <string ProviderName>, Long AlgorithmId=cs:CALG_RC4, Long HashId=cs:CALG_SHA1,Long pCipherMode=cs:CRYPT_MODE_CBC, Long pPadding=0, <String pIV>),long

DecryptString (*String Data,*Long DataLen, String Password, Long ProviderType=cs:PROV_RSA_FULL, <string ProviderName>, Long AlgorithmId=cs:CALG_RC4, Long HashId=cs:CALG_SHA1,Long pCipherMode=cs:CRYPT_MODE_CBC, Long pPadding=0, <String pIV>),long

Description

Symmetrically decrypts either a string, or a StringTheory object. Symmetrical encryption means the same Password is used to both encrypt and decrypt the data.

Parameters
Parameter Description
Data The string, or StringTheory object, containing the data to decrypt.
DataLen The length of the Data in the string.
Password The Password that was used to encrypt the data
ProviderType [optional] The type of Provider to use.
ProviderName [optional] the name of the Provider to use.
AlgorithmId [optional] The Algorithm that you wish to use.
HashId
[optional]
The Hash Algorithm to use when hashing the password. If omitted the default is cs:CALG_SHA1. To force the password to be plain use cs:CALG_NOHASH. For more information on plain passwords see
Plain Passwords.
CipherMode [optional] Defaults to cs:CRYPT_MODE_CBC. A common alternative (although less secure) is cs:CRYPT_MODE_ECB.
Padding [optional] Defaults to cs:PKCS5_PADDING which is the standard supported by all the CryptoAPI providers. When interacting with an external system you may need to set this to cs:NO_PADDING.
IV [optional] This parameter is only applicable if the CipherMode is set to cs:CRYPT_MODE_CBC. It provides the initialization vector for the first block in the chain. This value needs to be the same for encryption and decryption.
Returns

Crypto:Ok if the decryption was successful. Crypto:NotOk if it was not successful.
If it is successful then the contents in the Data parameter are changed.

See Also

For more information on Symmetrical Encryption, including examples, see Symmetrically Encrypting A String
For the method call to Encrypt the string see EncryptString
To Decrypt a string using the AES algorithm see DecryptStringAES.

DecryptStringAES

DecryptStringAES(*StringTheory Data, String Password,Long HashId = cs:CALG_SHA_256, Long pCipherMode=cs:CRYPT_MODE_CBC, Long pPadding=0, <String pIV>),long

DecryptStringAES(*String Data,*Long DataLen, String Password,Long HashId = cs:CALG_SHA_256, Long pCipherMode=cs:CRYPT_MODE_CBC, Long pPadding=0, <String pIV>),long

Description

Symetrically decrypts a string using the AES algorithm. This method simply calls DecryptString with the AES 256 ProviderType, ProviderName and AlgorithmId. The Hash algorithm defaults to SHA256.

EncryptString

EncryptString (*StringTheory Data, String Password, Long ProviderType=cs:PROV_RSA_FULL, <string ProviderName>, Long AlgorithmId=cs:CALG_RC4, Long HashId, Long pCipherMode=cs:CRYPT_MODE_CBC, Long pPadding=0, <String pIV>),long

EncryptString (*String Data,*Long DataLen, String Password, Long ProviderType=cs:PROV_RSA_FULL, <string ProviderName>, Long AlgorithmId=cs:CALG_RC4, Long HashId, Long pCipherMode=cs:CRYPT_MODE_CBC, Long pPadding=0, <String pIV>),long

Description

Symmetrically encrypts either a string, or a StringTheory object. Symmetrical encryption means the same Password is used to both encrypt and decrypt the data.

Parameters
Parameter Description
Data The string, or StringTheory object, containing the data to encrypt.
DataLen The length of the Data in the string.
Password The Password that will be required to decrypt the data
ProviderType [optional] The type of Provider to use.
ProviderName [optional] the name of the Provider to use.
AlgorithmId [optional] The Algorithm that you wish to use.
HashId
[optional]
The Hash Algorithm to use when hashing the password. If omitted the default is cs:CALG_SHA1. To force the password to be plain use cs:CALG_NOHASH. For more information on plain passwords see
Plain Passwords.
CipherMode [optional] Defaults to cs:CRYPT_MODE_CBC. A common alternative (although less secure) is cs:CRYPT_MODE_ECB.
Padding [optional] Defaults to cs:PKCS5_PADDING which is the standard supported by all the CryptoAPI providers. When interacting with an external system you may need to set this to cs:NO_PADDING.
IV [optional] This parameter is only applicable if the CipherMode is set to cs:CRYPT_MODE_CBC. It provides the initialization vector for the first block in the chain. This value needs to be the same for encryption and decryption.
Returns

Crypto:Ok if the encryption was successful. Crypto:NotOk if it was not successful.
If it is successful then the contents in the Data parameter are changed.

See Also

For more information on Symmetrical Encryption, including examples, see Symmetrically Encrypting A String
For the method call to decrypt the string see DecryptString
To Encrypt a string using the AES algorithm see EncryptStringAES.

EncryptStringAES

EncryptStringAES (*StringTheory Data, String Password,Long HashId = cs:CALG_SHA_256, Long pCipherMode=cs:CRYPT_MODE_CBC, Long pPadding=0, <String pIV>),long

EncryptStringAES (*String Data,*Long DataLen, String Password,Long HashId = cs:CALG_SHA_256, Long pCipherMode=cs:CRYPT_MODE_CBC, Long pPadding=0, <String pIV>),long

Description

Symetrically encrypts a string using the AES algorithm. This method simply calls EncryptString with the AES 256 ProviderType, ProviderName and AlgorithmId. The Hash algorithm defaults to SHA256.

MakeHash [1]

MakeHash (*StringTheory st, long hashType=cs:CALG_SHA1, Long Encode = Crypto:EncHex), long

Description

Create a hash (a digest) of the data in the passed StringTheory (st) object. The hash is stored in the StringTheory object on return (by default it is a hex encoded string).

This method encapsulates all of the hashing functionality in a single easy to use method.

Parameters
Parameter Description
st A StringTheory object that contains the data to hash when the method is called and the hash value on return,
hashType [optional] The hashing algorithm to use. Defaults to cs:CALG_SHA1 for SHA-1 hashing. Other algorithms available are:

cs:CALG_MD5: MD5 hashing algorithm
cs:CALG_SHA1: SHA-1 hashing algorithm
cs:CALG_SHA_256: 256 bit SHA256 hashing algorithm. Requires Windows XP SP3 or later (also known as SHA-2)

cs:CALG_HUGHES_MD5: Hughes MD5 hashing algorithm
cs:CALG_HASH_REPLACE_OWF: One way function hashing algorithm (not supported under Windows 2000 or NT)
cs:CALG_HMAC: HMAC keyed hash algorithm.
cs:CALG_MAC: MAC keyed hash algorithm. A keyed hashing algorithm that uses a symmetric session key to help ensure that a block of data has retained its integrity from the time it was sent until the time it was received. When using this type of algorithm, the receiving application must also possess the session key to recompute the hash value so it can verify that the base data has not changed.

cs:CALG_MD2: MD2 hashing algorithm
cs:CALG_MD4: MD4 hashing algorithm
cs:CALG_SHA: SHA hashing algorithm

cs:CALG_SHA_384: 384 bit SHA384 hashing algorithm. Requires Windows XP SP3 or later (also known as SHA-2)
cs:CALG_SHA_512: 512 bit SHA512 hashing algorithm. Requires Windows XP SP3 or later (also known as SHA-2)
Encode [optional] Optional parameter to specify the encoding of the result.  Valid values are Crypto:EncNone, Crypto:EncHex (the default) and Crypto:EncBase64.

A hex encoded string stores the hash as text where each byte is represented the two character hexadecimal, true)) equivalent of the byte. This requires twice as much storage space as the binary representation.

A Base64 encoded string stores the hash using the Base64 format. This requires less space than the hex encoding, but is less commonly used.

[out] Pointer to a long variable that is set to length of the data returned in the hashValue parameter (in bytes)
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

MakeHash [2]

MakeHash (*string inData, *string hashValue, *long hashLen), long

Description

Create a hash (a digest) of the passed data and stores the result in the hashValue parameter and the length of the hash in the hashLen parameter. The .HashAlgorithm property specifies the algorithm to use for hashing.

For simpler hashing see the MakeHash method above which takes a StringTheory object and handles the algorithm and context acquisition automatically.

Creates a hash object if required, hashes the data passed and retrieves the hash value, returning it in the hashValueparameter and setting hashLen to the length of the retrieved data. Uses the algorithm specified by the self.defaultHash property, which is MD5 by default.

Parameters
Parameter Description
inData The data to be hashed
hashValue A string to take the hash value, must be long enough to store the returned value which is typically 16 or 20 bytes.
hashLen [in] The length of the data to be hashed (in bytes). If this is zero, then the entire string is hashed.

[out] Pointer to a long variable that is set to length of the data returned in the hashValue parameter (in bytes)
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

MakeHMAC

MakeHMAC (StringTheory Message, string Secret, long hashType=cs:CALG_SHA1, bool hexEncode = 1), long
MakeHMAC (StringTheory Message, StringTheory Secret, long hashType=cs:CALG_SHA1, bool hexEncode = 1), long

Description

Generates a Hash-based Message Authentication Code (HMAC) for a specific message.

Parameters
Parameter Description
Message A StringTheory object, containing the message to be HMAC'd.
The HMAC overwrites the Message in this object.
Secret (string) A string that contains the key value for the HMAC. This is sometimes also referred to as the "secret". This value is clipped.
Secret (StringTheory) A string that contains the key value for the HMAC. This is sometimes also referred to as the "secret". This value is not clipped. The contents of the object may be altered by the method to make a secret of the correct length. The altered string will be "returned" to the caller.
HashType (optional)

Defaults to SHA1. Valid options include;

  • cs:CALG_MD5
  • cs:CALG_SHA1
  • cs:CALG_SHA_256
  • cs:CALG_SHA_384
  • cs:CALG_SHA_512
hexEncode (optional) Defaults to true. If true then the string contains a Hexadecimal representation of the hash.
Return Value

Returns Crypto:OK for success and Crypto:NotOK in the event of a failure.
The Message object is altered to contain the result of the HMAC call.
 

PFXImport

PFXImport (string pfxFileName, <string Password>, <string Store>, Long pFlags=1), long

Description

Imports a PFX file from disk. Imports the certificates and public/private keys pairs that the PFX contains.

Note: A sample PFX file, called safetester.pfx, is included in the examples\cryptonite\demo folder. The password for this file is capesoft.

Parameters
Parameter Description
pfxFileName The name of the PFX file on disk to import
Password [optional] A string that contains the private key password, if there is one
Store [optional]

The system store to import into. Can be one of the following;

  • Crypto:StoreCA
  • Crypto:StoreMY        ! (default)
  • Crypto:StoreROOT
  • Crypto:StoreSPC
  • Crypto:StorePersonal ! Code Signing Certificates
pFlags [optional] one of
cs:CERT_STORE_ADD_NEW ! (default value)
cs:CERT_STORE_ADD_USE_EXISTING
cs:CERT_STORE_ADD_REPLACE_EXISTING
cs:CERT_STORE_ADD_ALWAYS
cs:CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES
cs:CERT_STORE_ADD_NEWER
cs:CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES

For more information see here.
Return Value

Returns Crypto:OK for success and Crypto:NotOK in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

SignMessage [1]

SignMessage (Stringtheory Data, string HashAlgorithm, string Signer, *StringTheory Signature, Long Encode=1, Long IncludeCerts=true, Long detach=true),long

Description

Message signing creates a Hash from the passed data, and then signs the message using the key associated with the specific certificate. This signature can then be used to verify the sender of the data, and to verify that the data has not been tampered with during transit.

After checking all parameters for validity, this function will begin by obtaining the correct user certificate. Then, the certificate and the hash algorithm identifier are used to generate a signature for the message.

Parameters
Parameter Description
Data A StringTheory object containing the data to sign. This can can be binary.
HashAlgorithm Names the hash algorithm to be used.  Valid options are cs:CALG_MD5, cs:CALG_SHA1, cs:CALG_SHA_256, cs:CALG_SHA_384, cs:CALG_SHA_512
Signer A string that identifies which user certificate to use to sign the message.
Signature A StringTheory object which will receive the returned data.
Encode [optional] The format to encode the result. Valid options are Crypto:EncNone, Crypto:EncHex (the default) or Crypto:EncBase64.
IncludeCerts [optional] If set to true (the default) then the public key of the certificate is included in the signature.
Detach [optional] If set to true (the default) then the Data itself is not included in the signature, only a hash of the data is included.
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

See Also

Signing Data Section, VerifySignature

SignMessage [2]

SignMessage (*string Data, long DataLen, long Csp, string HashAlgorithm, *cstring Signer, *StringTheory Signature, long IncludeCerts=1, long detach=true), long

Description

Note: A simpler form of this method, using a StringTheory object, is documented above.

Message signing creates a Hash (Digest) from the passed data, and then signs the message using the key associated with the specific certificate. This signature can then be used to verify the sender of the data, and to verify that the data has not been tampered with during transit.

After checking all parameters for validity, this function will begin by obtaining the correct user certificate. Then, the certificate and the hash algorithm identifier are used to generate a signature for the message.

Parameters
Parameter Description
Data Message content to be signed; can be binary
DataLen Length of message content; if <= 0, then it will be set equal to Len(pMsg).
csp Identifies the cryptographic service provider to use. If null or omitted, the Microsoft Default Provider (defined by MS_DEF_PROV) will be used. Also, this string can start with csptype=##\n to specify other provider types than the default, which is PROV_RSA_FULL (e.g. 2=RSA sig only, 3=DSS, 4=Fortezza).
HashAlgorithm Names the hash algorithm to be used.  Valid options are cs:CALG_MD5, cs:CALG_SHA, cs:CALG_SHA_256, cs:CALG_SHA_384, cs:CALG_SHA_512
signer A cstring that identifies which user certificate to use to sign the message.
Signature A StringTheory object which will receive the returned data.
IncludeCerts [optional] If set to true (the default) then the public key of the certificate is included in the signature.
Detach [optional] If set to true (the default) then the Data itself is not included in the signature, only a has of the data is included.
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

Start

Start ()

Description

This method returns the object to it's initial state, resetting the default values of all properties. It can be used between multiple uses of the same object to make sure that the result of one use does not flow into another.

VerifySignature [1]

VerifySignature (Stringtheory Data, StringTheory Signature, Long Encode=0, string Signer, <*string CertInfo>, <*CryCertFields CertChain>, <*long VerifyStatus>, Long detach=true), Long

Description

This function verifies that the hash value of the given message is equal to the one stored in the signature. It also tests the signature certificate for a number of error conditions (e.g. expired). Finally, it also obtains the demographic data on the certificates in the chain of issuance from (and including) the signer's certificate up to the root certificate authority.

Note: the blob of data pointed to by signature contains an indication of which hash algorithm was used to create it.

Parameters
Parameter Description
Data Message content to be verified
Signature A signature supposedly created by the signer which must match the contents of Data once the signature is decoded using the signer's public key.
Encode [optional] The encoding of the certificate. Valid values are Crypto:EncNone, Crypto:EncHex (the default) or Crypto:EncBase64
Signer The common name of the certificate that was used to sign the message.  If this parameter is not blank when the method is called, and the certificate does not match this parameter then the method returns Crypto:NotOk. In other words this form of the method explicitly requires the signer (if set) to match the signer in the certificate. Regardless if they match or not, this variable will be updated to match the value in the certificate when the method completes.
CertInfo
[optional]
A string to receive information about the certificate.
CertChain [optional] A queue which will be populated with the certificate chain information.
VerifyStatus [optional] A detailed explanation of why the signature failed. this is a bit field, where the possible values can be added together. Possible values are;

Crypto:NoProvider
Crypto:NTE_BAD_SIGNATURE
Crypto:NTE_BAD_ALGID
Crypto:CRYPT_E_NO_SIGNER
Crypto:CRYPT_E_UNEXPECTED_MSG_TYPE
Crypto:E_INVALIDARG

128: Crypto:CERTNOTTRUSTED  -If the certificate is marked as untrusted on the system (this is not implemented because it is application-specific)

64: Crypto:CERTEXPIRED -
If the certificate's time validity check fails

32: Crypto:CERTREVOKED -
If the certificate is in the issuer's CRL

16: Crypto:ISSUERSIGFAILED -
If the issuer signature on the certificate fails

8: Crypto:ISSUERCERTNOTFOUND -
If the issuer certificate not found on local machine

2: Crypto:MSG_CERTNOTFOUND -
If the message certificate is not found

1: Crypto:MSG_ALTERED -
The signature hash doesn't match the message hash
Detach [optional] If the incoming signature contains the message, as well as the signature then set this value to false. The default value here is true.

Return Value

Crypto:OK if the Signature is valid. Crypto:NotOk if the signature is not value. VerifyStatus contains more information if the signature is not ok.

See Also

SignMessage

VerifySignature [2]

VerifySignature (*string Data, long DataLen, long Csp, *string Signature, long SignatureLen, *cstring Signer, *long CertInfo, *CryCertFields CertChain, *long VerifyStatus), long

VerifySignature (string DataFile, long WhichSig, *cstring Signer, *long CertInfo, *CryCertFields CertChain, *long VerifyStatus), long

Description

Note: A simpler form of this method, using a StringTheory object, is documented above.

This function verifies that the hash value of the given message is equal to the one stored in the signature. It also tests the signature certificate for a number of error conditions (e.g. expired). Finally, it also obtains the demographic data on the certificates in the chain of issuance from (and including) the signer's certificate up to the root certificate authority.

Note: the blob of data pointed to by signature contains an indication of which hash algorithm was used to create it.

Parameters
Parameter Description
Data Message content to be verified
DataLen Length of message content; if less than or equal to 0, then it will be set equal to len(msg) (If the string contains binary data then msgLen should always be specified unless the data length is the same as the string length).
csp Identifies the cryptographic service provider to use. If NULL, the Microsoft Base Provider (defined by MS_DEF_PROV) will be used. Also, this string can start with csptype=##\n to specify other provider types than the default, which is PROV_RSA_FULL (e.g. 2=RSA sig only, 3=DSS, 4=Fortezza).
signature A signature supposedly created by the signer which must match the contents of msg once the signature is decoded using the signer's public key.
signatureLen The length of the signature data
Signer A cString containing the common name and email address of the signer.
CertInfo Returns a text description of additional certificate information. One piece of information is stored per line. Current info includes key length and expiry date. The lines start with "Key length" and "Not after".
CertChain A queue which will be populated with the certificate chain information.
VerifyStatus Contains specific information on why the signature is being rejected;

Crypto:NoProvider
Crypto:NTE_BAD_SIGNATURE
Crypto:NTE_BAD_ALGID
Crypto:CRYPT_E_NO_SIGNER
Crypto:CRYPT_E_UNEXPECTED_MSG_TYPE
Crypto:E_INVALIDARG

256: Crypto:SignerDidntMatch - the Signer parameter passed in did not match the certificate used to sign the message.

128: Crypto:CERTNOTTRUSTED - If the certificate is marked as untrusted on the system (this is not implemented because it is application-specific)

64: Crypto:CERTEXPIRED -
If the certificate's time validity check fails

32: Crypto:CERTREVOKED -
If the certificate is in the issuer's CRL

16: Crypto:ISSUERSIGFAILED -
If the issuer signature on the certificate fails

8: Crypto:ISSUERCERTNOTFOUND -
If the issuer certificate not found on local machine

2: Crypto:MSG_CERTNOTFOUND -
If the message certificate is not found

1: Crypto:MSG_ALTERED -
The signature hash doesn't match the message hash
Return Value

Crypto:OK if the Signature is valid. Crypto:NotOk if the signature is not value. VerifyStatus contains more information if the signature is not ok.

GetContainer

GetContainer (string container, bool createContainer=false, DWORD provType=cs:PROV_RSA_FULL, <string providerName>), long

Description

Gets a Cryptographic Context and a Key Container. A context and container (which holds a key set) is required for the majority of cryptographic functions.

Parameters
Parameter Description
container A string that identifies the container to create or retrieve. This should be a unique string that identifies the container being used by your application.

Note that containers are locked to individual users on the machine, so the container name should contain user-specific information if the program will be used by multiple users on the same machine.
createContainer If this is set to True and the container does not exist, it is created.
provType The type of Cryptographic Service Provider to acquire a context for, see Cryptographic Service Provider Types for more information. Must be one of the following :
  • cs:PROV_RSA_FULL
  • cs:PROV_RSA_AES
  • cs:PROV_RSA_SIG
  • cs:PROV_RSA_SCHANNEL
  • cs:PROV_DSS
  • cs:PROV_DSS_DH
  • cs:PROV_DH_SCHANNEL
  • cs:PROV_FORTEZZA
  • cs:PROV_MS_EXCHANGE
  • cs:PROV_SSL
Note that the provider type must be supported by the provider being acquired (which defaults to the Microsoft Enhanced Cryptographic Provider). The provider can be specified using the providerName parameter.
providerName The name of the provider to uses. Defaults to cs:MS_ENHANCED_PROV - Microsoft Enhanced Cryptographic Provider.
See Cryptographic Service Providers for more information)

May be one of the following:
Provider Name Description
cs:MS_DEF_DH_SCHANNEL_PROV
"Microsoft DH Schannel Cryptographic Provider"
The Microsoft DSS and Diffie-Hellman/Schannel Cryptographic Provider.
cs:MS_DEF_DSS_DH_PROV
"Microsoft Base DSS and Diffie-Hellman Cryptographic Provider"
The Microsoft Base DSS and Diffie-Hellman Cryptographic Provider.
cs:MS_DEF_DSS_PROV
"Microsoft Base DSS Cryptographic Provider"
The Microsoft DSS Cryptographic Provider.
cs:MS_DEF_PROV
"Microsoft Base Cryptographic Provider v1.0"
The Microsoft Base Cryptographic Provider.
cs:MS_DEF_RSA_SCHANNEL_PROV
"Microsoft RSA Schannel Cryptographic Provider"
The Microsoft RSA/Schannel Cryptographic Provider.
cs:MS_DEF_RSA_SIG_PROV
"Microsoft RSA Signature Cryptographic Provider"
The Microsoft RSA Signature Cryptographic Provider is not supported.
cs:MS_ENH_DSS_DH_PROV
"Microsoft Enhanced DSS and Diffie-Hellman Cryptographic Provider"
The Microsoft Enhanced DSS and Diffie-Hellman Cryptographic Provider.
cs:MS_ENH_RSA_AES_PROV
"Microsoft Enhanced RSA and AES Cryptographic Provider"
The Microsoft AES Cryptographic Provider.
Windows XP:  
"Microsoft Enhanced RSA and AES Cryptographic Provider (Prototype)"
cs:MS_ENHANCED_PROV
"Microsoft Enhanced Cryptographic Provider v1.0"
The Microsoft Enhanced Cryptographic Provider.
cs:MS_SCARD_PROV
"Microsoft Base Smart Card Crypto Provider"
The Microsoft Base Smart Card Cryptographic Service Provider.
cs:MS_STRONG_PROV
"Microsoft Strong Cryptographic Provider"
The Microsoft Strong Cryptographic Provider.
Return Value

Returns Crypto:OK for success and Crypto:NotOK in the event of a failure.

Remarks

TheMicrosoft Enhanced Cryptographic Service Provider is the default CSP. The provider type defaults to PROV_RSA_FULL, which is a general purpose CSP which supports the following algorithms:
Purpose Supported algorithms
Key Exchange RSA
Signature RSA
Encryption RC2
RC4
Hashing MD5
SHA

For additional algorithms the Provider and Provider Type can be specified from the list provided above.

Examples
Example
    if Crypto.GetContainer('MyCrypto', true) = Crypto:OK
Crypto.GetUserKey(cs:AT_KEYEXCHANGE, true) ! Get the key, and create one if needed.
end
See Also

CreateContainer, DeleteContainer

CreateContainer

CreateContainer (string container, DWORD provType=cs:PROV_RSA_FULL, <string providerName>), long

Description

Creates a new container using the specified Cryptographic service provider (or the default if none is specified). A container is required in order to use the encryption and decryption methods provided. Containers are identified using a string that contains a unique name. This method will be called automatically by GetContainer if the container does not already exist and createContainer parameter is set to True.

Parameters
containerThe name of the container to create. This should a string that uniquely identifies the container (for example the name of your application for an application specific container).
provTypeThe type of Cryptographic Service Provider to acquire a context for, see Cryptographic Service Provider Types for more information. Must be one of the following :
  • cs:PROV_RSA_FULL
  • cs:PROV_RSA_AES
  • cs:PROV_RSA_SIG
  • cs:PROV_RSA_SCHANNEL
  • cs:PROV_DSS
  • cs:PROV_DSS_DH
  • cs:PROV_DH_SCHANNEL
  • cs:PROV_FORTEZZA
  • cs:PROV_MS_EXCHANGE
  • cs:PROV_SSL
Note that the provider type must be supported by the provider being acquired (which defaults to the Microsoft Enhanced Cryptographic Provider). The provider can be specified using the providerName parameter.
providerName The name of the provider to uses. Defaults to cs:MS_ENHANCED_PROV - Microsoft Enhanced Cryptographic Provider. See Cryptographic Service Providers for more information)
May be one of the following:
Provider NameDescription
cs:MS_DEF_DH_SCHANNEL_PROV
"Microsoft DH Schannel Cryptographic Provider"
The  Microsoft DSS and Diffie-Hellman/Schannel Cryptographic Provider.
cs:MS_DEF_DSS_DH_PROV
"Microsoft Base DSS and Diffie-Hellman Cryptographic Provider"
The  Microsoft Base DSS and Diffie-Hellman Cryptographic Provider.
cs:MS_DEF_DSS_PROV
"Microsoft Base DSS Cryptographic Provider"
The Microsoft DSS Cryptographic Provider.
cs:MS_DEF_PROV
"Microsoft Base Cryptographic Provider v1.0"
The Microsoft Base Cryptographic Provider.
cs:MS_DEF_RSA_SCHANNEL_PROV
"Microsoft RSA Schannel Cryptographic Provider"
The Microsoft RSA/Schannel Cryptographic Provider.
cs:MS_DEF_RSA_SIG_PROV
"Microsoft RSA Signature Cryptographic Provider"
The Microsoft RSA Signature Cryptographic Provider is not supported.
cs:MS_ENH_DSS_DH_PROV
"Microsoft Enhanced DSS and Diffie-Hellman Cryptographic Provider"
The Microsoft Enhanced DSS and Diffie-Hellman Cryptographic Provider.
cs:MS_ENH_RSA_AES_PROV
"Microsoft Enhanced RSA and AES Cryptographic Provider"
The Microsoft AES Cryptographic Provider.
Windows XP:  "Microsoft Enhanced RSA and AES Cryptographic Provider (Prototype)"
cs:MS_ENHANCED_PROV
"Microsoft Enhanced Cryptographic Provider v1.0"
The Microsoft Enhanced Cryptographic Provider.
cs:MS_SCARD_PROV
"Microsoft Base Smart Card Crypto Provider"
The Microsoft Base Smart Card Cryptographic Service Provider.
cs:MS_STRONG_PROV
"Microsoft Strong Cryptographic Provider"
The Microsoft Strong Cryptographic Provider.
Return Value

Returns Crypto:OK for success and Crypto:NotOK in the event of a failure.

DeleteContainer

DeleteContainer (string container), long, proc

Description

Deletes the container specified by the container parameter. All keys associated with the container will be deleted along with the container itself.

Parameters
Parameter Description
containerThe name of the container to delete.
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) for failure.

Certificates

The following methods provide handling for cryptographic certificates. Certificates are used to store an identity, and optionally the public and/or private keys associated with that identity.

CertOpenSystemStore

CertOpenSystemStore <string name>), HCERTSTORE, virtual

Description

Opens one of the system stores. Call CertCloseStore to close the store once it is no longer needed.

Parameters
Parameter Description
storeNameOptional store name to open. Must be one of the system stores: 'MY', 'CA', 'ROOT' or 'SPC'. Defaults to opening the 'MY' system store for the current user.
Return Value

Returns a HCERTSTORE handle to the store if successful, or zero if it fails.

Remarks

The certificate store should be closed when it is no longer needed by passing the returned handle to the CertCloseStore method.

CertCloseStore

Description

CertCloseStore (HCERTSTORE hStore), virtual

Closes the specified certificate store

Parameters
Parameter Description
hStoreA handle to the certificate store returned by CertOpenStore
Return Value

None

CertFind

CertFind Procedure ( HCERTSTORE hStore, string certName), PCCERT_CONTEXT, virtual

Description

Find a certificate by name in the specified store.

Parameters
Parameter Description
hStoreThe handle to the store to search
certNameThe name to search the certificate's Subject field for. This is the name of the entity to which the certificate was issued - typically the company name for commercial certificates and the email address for free "email" certificates.
Return Value

A PCCERT_CONTEXT which points to the certificate context if succesful, otherwise zero.

CertFind

CertFind Procedure (HCERTSTORE hStore, ulong encoding, ulong flags, ulong type, <string pParam>, PCCERT_CONTEXT prevCert), PCCERT_CONTEXT, virtual

Description

Find a certificate that matches the passed parameters. Advanced use only. Note that the parameter passed can vary in type and length. This method provides a wrapper for the CertFindCertificateInStore API function.

In general use the simpler form of CertFind(HCERTSTORE hStore, string certName) provides all the functionality required

Parameters
Parameter Description
hStoreA handle to the store to search. Call CertOpenStore to get a handle to a store.
encodingSpecifies the type of encoding used. Both the certificate and message encoding types must be specified Adding them:

cs:X509_ASN_ENCODING + cs:PKCS_7_ASN_ENCODING

This parameter must either be zero or the above value, no other values are current supported by the CryptoAPI.
flagsThe flags used to modify the behaviour depending on the type parameter. This is zero for most options specified by the type parameter (see below)
prevCertThe handle to the previous matching certificate returned by the method. The next matching certificate will be retrieved. Set to zero to retrieve the first matching certificate from the store.
type Specifies the type of search being made. The search type determines the data type, contents, and the use of pParam. This parameter can be one of the following valuesK:
ValueMeaning
CERT_FIND_ANY Data type of pParam: Not used, should be omitted.

No search criteria used. Returns the next certificate in the store.

Note:The order of the certificate context may not be preserved within the store. To access a specific certificate you must iterate across the certificates in the store.
CERT_FIND_CERT_ID Data type of pParam: CERT_ID structure.

Find the certificate identified by the specified CERT_ID
CERT_FIND_CTL_USAGE Data type of pParam: CTL_USAGE structure.

Searches for a certificate that has a szOID_ENHANCED_KEY_USAGE extension or a CERT_CTL_PROP_ID that matches the pszUsageIdentifier member of the CTL_USAGE structure.
CERT_FIND_ENHKEY_USAGEData type of pParam: CERT_ENHKEY_USAGE structure.

Searches for a certificate in the store that has either anenhanced key usage extension or an enhanced key usage property and a usage identifier that matches the cUsageIdentifier member in the CERT_ENHKEY_USAGE structure.

A certificate has an enhanced key usage extension if it has a CERT_EXTENSION structure with the pszObjId member set to szOID_ENHANCED_KEY_USAGE.

A certificate has an enhanced key usage property if its CERT_ENHKEY_USAGE_PROP_ID identifier is set.

If CERT_FIND_OPTIONAL_ENHKEY_USAGE_FLAG is set in flags, certificates without the key usage extension or property are also matches. Setting this flag takes precedence over passing NULL in pParam.

If CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG is set, a match is done only on the key usage extension.

For information about flag modifications to search criteria, see Remarks.
CERT_FIND_EXISTINGData type of pParam: CERT_CONTEXT structure.

Searches for a certificate that is an exact match of the specified certificate context.
CERT_FIND_HASHData type of pParam: CRYPT_HASH_BLOB structure.

Searches for a certificate with a SHA1 hash that matches the hash in the CRYPT_HASH_BLOB structure.
CERT_FIND_ISSUER_ATTRData type of pParam: CERT_RDN structure.

Searches for a certificate with specified issuer attributes that match attributes in the CERT_RDN structure. If these values are set, the function compares attributes of the issuer in a certificate with elements of the CERT_RDN_ATTR array in this CERT_RDN structure. Comparisons iterate through the CERT_RDN_ATTR attributes looking for a match with the certificate's issuer attributes.

If the pszObjId member of CERT_RDN_ATTR is NULL, the attribute object identifier is ignored.

If the dwValueType member of CERT_RDN_ATTR is CERT_RDN_ANY_TYPE, the value type is ignored.

If the pbData member of CERT_RDN_VALUE_BLOB is NULL, any value is a match.

Currently only an exact, case-sensitive match is supported. For information about Unicode options, see Remarks. When these values are set, the search is restricted to certificates whose encoding type matches encoding.
CERT_FIND_ISSUER_NAMEData type of pParam: CERT_NAME_BLOB structure.

Search for a certificate with an exact match of the entire issuer name with the name in CERT_NAME_BLOB The search is restricted to certificates that match the encoding.
CERT_FIND_ISSUER_OF Data type of pParam: CERT_CONTEXT structure.

Searches for a certificate with an subject that matches the issuer in CERT_CONTEXT.

Instead of using CertFindCertificateInStore with this value, use the _GetCertChain method.
CERT_FIND_ISSUER_STR Data type of pParam: Null-terminated Unicode string.

Searches for a certificate that contains the specified issuer name string. The certificate's issuer member is converted to a name string of the appropriate type using the appropriate form of CertNameToStr formatted as CERT_SIMPLE_NAME_STR. Then a case-insensitive substring-within-a-string match is performed. When this value is set, the search is restricted to certificates whose encoding type matches encoding.

If the substring match fails and the subject contains an email RDN with Punycode encoded string, CERT_NAME_STR_ENABLE_PUNYCODE_FLAG is used to convert the subject to a Unicode string and the substring match is performed again.
CERT_FIND_KEY_IDENTIFIER Data type of pParam: CRYPT_HASH_BLOB structure.

Searches for a certificate with a CERT_KEY_IDENTIFIER_PROP_ID property that matches the key identifier in CRYPT_HASH_BLOB.
CERT_FIND_KEY_SPEC
Data type of pParam: DWORD variable that contains a key specification.

Searches for a certificate that has a CERT_KEY_SPEC_PROP_ID property that matches the key specification in pParam.
CERT_FIND_MD5_HASH Data type of pParam: CRYPT_HASH_BLOB structure.

Searches for a certificate with an MD5 hash that matches the hash in CRYPT_HASH_BLOB.
CERT_FIND_PROPERTY Data type of pParam: DWORD variable that contains a property identifier.

Searches for a certificate with a property that matches the property identifier specified by the DWORD value in pParam.
CERT_FIND_PUBLIC_KEYData type of pParam: CERT_PUBLIC_KEY_INFO structure.

Searches for a certificate with a public key that matches the public key in the CERT_PUBLIC_KEY_INFO structure.
CERT_FIND_SHA1_HASHData type of pParam: CRYPT_HASH_BLOB structure.

Searches for a certificate with a SHA1 hash that matches the hash in the CRYPT_HASH_BLOB structure.
CERT_FIND_SIGNATURE_HASH Data type of pParam: CRYPT_HASH_BLOB structure.

Searches for a certificate with a signature hash that matches the signature hash in the CRYPT_HASH_BLOB structure.
CERT_FIND_SUBJECT_ATTR Data type of pParam: CERT_RDN structure.

Searches for a certificate with specified subject attributes that match attributes in the CERT_RDN structure. If RDN values are set, the function compares attributes of the subject in a certificate with elements of the CERT_RDN_ATTR array in this CERT_RDN structure. Comparisons iterate through the CERT_RDN_ATTR attributes looking for a match with the certificate's subject's attributes.

If the pszObjId member of CERT_RDN_ATTR is NULL, the attribute object identifier is ignored.

If the dwValueType member of CERT_RDN_ATTR is CERT_RDN_ANY_TYPE, the value type is ignored.

If the pbData member of CERT_RDN_VALUE_BLOB is NULL, any value is a match.

Currently only an exact, case-sensitive match is supported.

For information about Unicode options, see Remarks. When these values are set, the search is restricted to certificates whose encoding type matches encoding.
CERT_FIND_SUBJECT_CERT Data type of pParam: CERT_INFO structure.

Searches for a certificate with both an issuer and a serial number that match the issuer and serial number in the CERT_INFO structure.
CERT_FIND_SUBJECT_NAME Data type of pParam: CERT_NAME_BLOB structure.

Searches for a certificate with an exact match of the entire subject name with the name in the CERT_NAME_BLOB structure. The search is restricted to certificates that match the value of encoding.
CERT_FIND_SUBJECT_STR Data type of pParam: Null-terminated Unicode string.

Searches for a certificate that contains the specified subject name string. The certificate's subject member is converted to a name string of the appropriate type using the appropriate form of CertNameToStr formatted as CERT_SIMPLE_NAME_STR. Then a case-insensitive substring-within-a-string match is performed. When this value is set, the search is restricted to certificates whose encoding type matches encoding.
CERT_FIND_CROSS_CERT_DIST_POINTS Data type of pParam: Not used.

Find a certificate that has either a cross certificate distribution point extension or property.

Windows 2000: This value is not supported.
CERT_FIND_PUBKEY_MD5_HASH Data type of pParam: CRYPT_HASH_BLOB structure.

Find a certificate whose MD5-hashed public key matches the specified hash.
Return Value

Returns a handle to the certificate if successful, otherwise returns zero.

CertNext

CertNext (HCERTSTORE hStore, PCCERT_CONTEXT prevCert, string certName), PCCERT_CONTEXT, virtual

Description

Retrieves the next matching certificate in the store after the certificate pointed to by prevCert.

Parameters
Parameter Description
HCERTSTORE hStoreA handle to the store to search. Call CertOpenStore to open a certificate store and retrieve a handle.
PCCERT_CONTEXT prevCertThe previous matching certificate - returned by either this method, or by CertFind.
string certNameThe name to search the certificate's Subject field for. This is the name of the entity to which the certificate was issued - typically the company name for commercial certificates and the email address for free "email" certificates.
Return Value

A PCCERT_CONTEXT which points to the certificate context if succesful, otherwise zero

CertFree

CertFree (PCCERT_CONTEXT hCert), virtual

Description

Frees a retrieved certificate when it is no longer needed.

Parameters
Parameter Description
PCCERT_CONTEXT hCertA handle to the certificate to free.
Return Value

None

CertGetContainer

CertGetContainer (PCCERT_CONTEXT hCert), long, virtual

Uses the provided certficate to retrieve a matching cryptographic service provider context, key container, and key set (if the certificate contains one). This method allows keys stored in certificates to be used. Call CertOpenStore to open a store, CertFind to locate the certificate and CertGetContainer to get the container and keys. This is equivilent in functionality to the GetContainer method. Once complete call CertFree to release the handle to the certificate.

Parameters
Parameter Description
PCCERT_CONTEXT hCertThe handle to the certificate to retrieve the context for and the keyset from. Call CertOpenStore to open a store, CertFind to locate the certificate and CertGetContainer to get the container and keys. This is equivilent in functionality to the GetContainer method. Once complete call CertFree to release the handle to the certificate.
Returns

Crypto:OK if successful and Crypto:NotOK otherwise.

CertGetPrivateKey

CertGetPrivateKey PCCERT_CONTEXT hCert, *bool freeKey, DWORD keySpec=cs:AT_KEYEXCHANGE), HCRYPTPROV, virtual

Description

Internal method for retrieving the a provider context and keyset from a certificate. Call the CertGetContainer to perform the required functionality withou having to handle the returned context and acquire the container and keyset manually.

Parameters
Parameter Description
hCertHandle to a CERT_CONTEXT returned by CertFind or CertNext which indicates which certificate to retrieve the key from
freeKeyIf the method sets this to True, then the caller should pass the returned handle to the ReleaseContext method once done.
DWORD keySpec=cs:AT_KEYEXCHANGEThe keyset to retrieve. Can be cs:AT_KEYEXCHANGE or cs:AT_KEYSIGNATURE
Return Value

If successful returns an HCRYPTPROV handle the provider context, or zero otherwise.

Key Management

Session Keys

Session keys are symmetric keys used to encrypt large amounts of data. A symmetric key algorithm uses the same key to encrypt and decrypt the data. Session keys are usually sent with the encrypted data and are protected by encrypting them using the public key of the recipient.

BlobToKey

BlobToKey (*HCRYPTKEY hSessionKey, *StringTheory keyBlob), long, proc

Description

Imports an encrypted session key into the current container. The hSessionKey parameter is set to the handle of the new key if successful. The keyBlob should contain a session key as exported by the KeyToBlob method. Call NewSessionKey to create a new session key. The session key will have been encrypted using the public key from the user's exchange key pair, and can only be decrypted using the matching private key.

The session key handle should be destroyed when it is no longer required by passing it the DestroyKey method.

For Exchange Key pairs see the ExchangeKeyToBlob and ExchangeKeyFromBlob methods as well as ExchangeKeyToFile and ExchangeKeyFromFile methods.

Parameters
Parameter Description
hSessionKeyA HCRYPTKEY which receives the Sessions Key handle if the method is successful.
keyBlobA StringTheory object which contains the BLOB used to the store the session key. The BLOB is created by calling KeyToBlob, which exports a sessions key and stored it in the StringTheory object. The key can be saved to disk using the StringTheory.SaveFile method and loaded using the StringTheory.LoadFile method.
Return Value

Returns Crypto:OK (0) if successful, or Crypto:NotOK (-1) if an error occurs. If the method succeeds the hSessionKey parameter stores the handle to the key created. If the method fails the ErrorTrap method is called with additional error information, including the API error code and corresponding error message.

KeyToBlob

KeyToBlob (HCRYPTKEY hSessionKey, *StringTheory keyBlob), long, proc

Description

Encrypts the passed session key using the current public key and creates a key BLOB. The key BLOB is encrypted using the public key of the current exchange key pair, and hence can only be decrypted using the private key from the same pair. 

The BLOB can then be stored, transmitted or saved to disk securely (use the StringTheory.SaveFile method to save the data from the StringTheory object to disk and the StringTheory.LoadFile method to load it).

For Exchange Key pairs see the ExchangeKeyToBlob and ExchangeKeyFromBlob methods as well as ExchangeKeyToFile and ExchangeKeyFromFilemethods.

Parameters
Parameter Description
hSessionKeyA handle to a session key which should be exported to a BLOB.
keyBlobA StringTheory object which contains the BLOB used to the store the session key. The BLOB is created by calling KeyToBlob, which exports a sessions key and stored it in the StringTheory object. The key can be saved to disk using the StringTheory.SaveFile method and loaded using the StringTheory.LoadFile method.
Return Value

Returns Crypto:OK (0) if sucessful, or Crypto:NotOK (-1) if an error occurs. If the method fails the ErrorTrap method is called with additional error information.

NewSessionKey

NewSessionKey (long algId = cs:CALG_3DES, long keyLen = 0), long, proc

Description

Create a new session key. Use KeyToBlob to save this session key and BlobToKey to load it from the saved BLOB.

The session key handle should be destroyed when it is no longer required by passing it the DestroyKey method.

Parameters
Parameter Description
algIDThe ALG_ID which identifies the algorithm to use. This must be an algorithm supported by the current Cryptographic Service provider. See the Supported Algorithms section for a list of ALG_IDs.
keyLenThe length of the key to create (in bits). This can be left as 0 to allow the default key length to be used.
Return Value

Returns the handle to the session key if successful, or zero if an error occurs. If the method fails the ErrorTrap method is called with additional error information.

Notes

The EnumProviders method can be used to list available providers on a machine and the EnumProviderTypes method lists available provider types. The GetProviderAlgs method can be used to list algorithms supported by the currently acquired service provider, along with the key lengths supported and algorithms available for that provider.

See the Providers example application for a demonstration of using these methods along with general key creating and handling.

KeyFromPassword

KeyFromPassword (string pPassword, ALG_ID hashAlg = cs:CALG_MD5), HCRYPTKEY

Description

Create a session key derived from the passed password. This method will return the same key each time it is called with the same password, which allows a password to be used as a session key. The password passed is used to create a Hash, which is then used to derive a session key.

The session key handle should be destroyed when it is no longer required by passing it the DestroyKey method.

Parameters
Return Value

Returns a handle to the newly created key if successful, or zero if it fails.

ExchangeKeyToBlob

ExchangeKeyToBlob (string pPassword, *StringTheory keyBlob, bool publicOnly = false, long flags = 0, ALG_ID hashAlg = cs:CALG_MD5), long

Description

Creates an encrypted BLOB of the exchange key pair. The BLOB is encrypted using a key generated from the passed password (if the pPassword string is not blank/empty). The password is hashed and the hash is used to generate a session key, which then encrypts the exchange key pair BLOB for security. The ExchangeKeyFromBLOB method can be used to import the key pair back into a key container.

Parameters
Parameter Description
algID The algorithm to using to use for hashing. Can be any one of the ALG_IDs supported by the current Cryptographic Service Provider, such as:
  • cs:CALG_MD5 (the default)
  • cs:CALG_SHA
  • cs:CALG_SHA1
  • cs:CALG_SHA_256
  • cs:CALG_SHA_384
  • cs:CALG_SHA_512
Parameter Description
pPasswordThe password to derive the session key for encrypting the blob from
keyBlobA StringTheory object will will hold the output encrypted key BLOB
publicOnlyIf True only the Public key is exported, otherwise both keys are exported
flagsAPI export flags, can be zero or a combination of one or more of the following:
ValueMeaning
cs:CRYPT_BLOB_VER3
00000080h
This flag causes this function to export version 3 of a BLOB type.
cs:CRYPT_DESTROYKEY
00000004h
This flag destroys the original key in the OPAQUEKEYBLOB. This flag is available in Schannel CSPs only.
cs:CRYPT_OAEP
00000040h
This flag causes PKCS #1 version 2 formatting to be created with the RSA encryption and decryption when exporting SIMPLEBLOBs.
cs:CRYPT_SSL2_FALLBACK
00000002h
The first eight bytes of the RSA encryption block padding must be set to 0x03 rather than to random data. This prevents version rollback attacks and is discussed in the SSL3 specification. This flag is available for Schannel CSPs only.
cs:CRYPT_Y_ONLY
00000001h
This flag is not used.
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

ExchangeKeyFromBlob

ExchangeKeyFromBlob (string pPassword, *StringTheory keyBlob, long flags = 0, ALG_ID hashAlg = cs:CALG_MD5), long

Description

Retrieves an Exchange key pair from and encrypted BLOB created by the ExchangeKeyToBlob method and imports it into the current context.

Parameters
Parameter Description
pPasswordThe password used to derive a session key with which the BLOB is encrypted.
keyBlobA StringTheory object which contains the encrypted key BLOB
flagsAdditional flags for importing the key. Defaults to 0.
hashAlgThe hashing algorithm used to derive the session key with which the key BLOB is encrypted. Defaults to MD5 hashing (cs:CALG_MD5).
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

ExchangeKeyToFile

ExchangeKeyToFile (string pPassword, string fileName), long

Description

Creates an encrypted BLOB from the exchange key pair and saves it to file. See the ExchangeKeyToBlob method for more information. The ExchangeKeyFromFile method can be used to import the key back from the file.

Parameters
Parameter Description
pPasswordThe password to derive the session key for encrypting the key BLOB.
fileNameThe name and path of the file to save the encrypted BLOB to.
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

ExchangeKeyFromFile

ExchangeKeyFromFile (string pPassword, string fileName), long

Description

Imports an exchange key pair from an encrypted BLOB on disk which was created by calling the ExchangeKeyToFile method. See the ExchnageKeyFromBlob documentation for more information on importing key BLOBs.

Parameters
Parameter Description
pPassword The password to derive the session key for decrypting the key BLOB.
fileNameThe name and path of the file to load the encrypted BLOB from.
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

Encryption And Decryption

Decrypt

Decrypt (HCRYPTKEY hCryptKey, *string pbData, *long dataLen, HCRYPTHASH hCryptHash=0, long flags=0), long, proc

Description

Decrypts the passed string using the specified key, and optionally uses the passed Hash object to check that the hash of the data.

Parameters
Parameter Description
hCryptKeyHandle to the decryption key.
pbDataPointer to a buffer holding the data to be decrypted. The decrypted data overwrites the data to be encrypted in this buffer.
dataLennumber of bytes to be decrypted, [out] number of bytes of decrypted data
hCryptHashHandle to a hash object, this receives a hash of the plain text
flagsFlag value to specify padding handling for RCA encryption using the Microsoft Enhanced CSP.

The following flag values are defined:
ValueMeaning
cs:CRYPT_OAEP
00000040h
Use Optimal Asymmetric Encryption Padding (OAEP) (PKCS #1 version 2). This flag is only supported by the Microsoft Enhanced Cryptographic Provider with RSA encryption/decryption. This flag cannot be combined with the CRYPT_DECRYPT_RSA_NO_PADDING_CHECK flag.

Windows 2000, Windows NT, and Windows Me/98/95: This flag is not supported.
cs:CRYPT_DECRYPT_RSA_NO_PADDING_CHECK
00000020h
Perform the decryption on the BLOB without checking the padding. This flag is only supported by the Microsoft Enhanced Cryptographic Provider with RSA encryption/decryption. This flag cannot be combined with the CRYPT_OAEP flag.

Windows 2000, Windows NT, and Windows Me/98/95: This flag is not supported.
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

DecryptFile

DecryptFile(string cipherFile, string plainFile), long

Description

Decrypts a file that was encrypted with the EncryptFile method and saves the decrypted output to the specified filename. The current users Exchange key pair is used to decrypt the session key stored in the file. The session key must have been encrypted using the public key of the current exchange key pair. The private key is used to decrypt the session key, which is then used to decrypt the data.

Parameters
Parameter Description
cipherFileThe name and path of the encrypted file to be decrypted.
plainFileThe name and path of the file to save the decrypted information to. If this file exists it is overwritten.
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

EncryptFile

EncryptFile (string inFileName, string outFileName), long

Description

Encrypts a file and saves the encrypted output to the specified file name. The file is encrypted using a random session key, which is then encrypted with the Public key from the current Exchange key pair and stored with the encrypted data. In order to decrypt the file the Private key that matches the Public key is required.

Parameters
Parameter Description
inFileNameThe name and path of the file to encrypt.
outFileNameThe name and path of the file to store the encrypted result in.
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

Encrypt

Encrypt Function (*string cipherData, *long dataLen, *string sessionKey, *long sessionLen, long algId = cs:CALG_RC4, long keyLen=0), long, proc

Description

Encrypts the passed string using the specified key and algorithm. Create a session key, encrypt it using the Public key, encrypt the provided data with the session key and return the encrypted key, along with the encrypted data. Functionally the same as EncryptFile, except that it function in memory, and returns the encrypted key BLOB and encrypted data separately.

Parameters
Parameter Description
cipherDataThe data to be encrypted. If the method succeeds, then this buffer will contain the encrypted data
dataLenThe length of the data to encrypt, set to the length of the data encrypted in cipherData.
sessionKeySet to the session key BLOB, encrypted using the current public key.
sessionLenSet this to the length of the SessionKey buffer, on return, it is set to the length of the encrypted session key stored in the sessionKey buffer.
algIDThe algorithm used. Defaults to RC4 stream encryption.
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

Remarks

If an initialization vector has been created by calling BuildID then the method will use the self.iv property as the IV.

Encrypt

Encrypt Procedure (HCRYPTKEY hCryptKey, *string pbData, *long dataLen, HCRYPTHASH hCryptHash=0, long flags=0), long, proc

Description

Encrypts the passed buffer using the provided key and optionally creates a hash of the data.

Parameters
Parameter Description
hCryptKeyHandle to the encryption key. From CryptGenKey() or the CryptImportKey()
pbDataPointer to a buffer holding the data to be encrypted. The encrypted data overwrites the data to be encrypted in this buffer
dataLenThe number of bytes to be encrypted, [out] number of bytes of encrypted data
hCryptHash (optional)Handle to a hash object, this receives a hash of the plain text. Set to zero if no hash is required.
flags(optional) Flag value to specify padding handling for RCA encryption using the Microsoft Enhanced CSP. The following flag values are defined:
ValueMeaning
cs:CRYPT_OAEP

00000040h
Use Optimal Asymmetric Encryption Padding (OAEP) (PKCS #1 version 2). This flag is only supported by the Microsoft Enhanced Cryptographic Provider with RSA encryption/decryption. This flag cannot be combined with the CRYPT_DECRYPT_RSA_NO_PADDING_CHECK flag.

Windows 2000: This flag is not supported.
cs:CRYPT_DECRYPT_RSA_NO_PADDING_CHECK

00000020h
Perform the decryption on the BLOB without checking the padding. This flag is only supported by the Microsoft Enhanced Cryptographic Provider with RSA encryption/decryption. This flag cannot be combined with the CRYPT_OAEP flag.

Windows 2000: This flag is not supported.
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

Object Management

Init

Init ()

Description

Initialises the object. Does not need to be called in normal use.

Kill

Kill ()

Description

Deallocates memory and cleans up. Does not need to be called in normal use.

Advanced Methods

AcquireContext

AcquireContext (string container, string providerName, ulong provType=cs:PROV_RSA_FULL, ulong flags=0), long, proc

Description

Acquires a Cryptographic context from the specified service provider. The handle to the provider context is stored in the.hProvider property of the object.

The GetContainer method providers a convenient wrapper for this functionality.

Parameters
Parameter Description
containerA string which contains a name that will uniquely identify this context from this provider. Any string can be used to allow your application to identify this context at a later state. If not flags are set then the method assumes that a new container and keyset need to be created.
providerNameThe name of the provider to uses. Defaultss to cs:MS_ENHANCED_PROV - Microsoft Enhanced Cryptographic Provider if blank. See Cryptographic Service Providers for more information)

May be one of the following (see table below):
Provider NameDescription
cs:MS_DEF_DH_SCHANNEL_PROV

"Microsoft DH Schannel Cryptographic Provider"
The Microsoft DSS and Diffie-Hellman/Schannel Cryptographic Provider.
cs:MS_DEF_DSS_DH_PROV

"Microsoft Base DSS and Diffie-Hellman Cryptographic Provider"
The Microsoft Base DSS and Diffie-Hellman Cryptographic Provider.
cs:MS_DEF_DSS_PROV

"Microsoft Base DSS Cryptographic Provider"
The Microsoft DSS Cryptographic Provider.
cs:MS_DEF_PROV

"Microsoft Base Cryptographic Provider v1.0"
The Microsoft Base Cryptographic Provider.
cs:MS_DEF_RSA_SCHANNEL_PROV

"Microsoft RSA Schannel Cryptographic Provider"
The Microsoft RSA/Schannel Cryptographic Provider.
cs:MS_DEF_RSA_SIG_PROV

"Microsoft RSA Signature Cryptographic Provider"
The Microsoft RSA Signature Cryptographic Provider is not supported.
cs:MS_ENH_DSS_DH_PROV"

Microsoft Enhanced DSS and Diffie-Hellman Cryptographic Provider"
The Microsoft Enhanced DSS and Diffie-Hellman Cryptographic Provider.
cs:MS_ENH_RSA_AES_PROV"

Microsoft Enhanced RSA and AES Cryptographic Provider"
The Microsoft AES Cryptographic Provider.

Windows XP: "Microsoft Enhanced RSA and AES Cryptographic Provider (Prototype)"
cs:MS_ENHANCED_PROV

"Microsoft Enhanced Cryptographic Provider v1.0"
The Microsoft Enhanced Cryptographic Provider.
cs:MS_SCARD_PROV

"Microsoft Base Smart Card Crypto Provider"
The Microsoft Base Smart Card Cryptographic Service Provider.
cs:MS_STRONG_PROV

"Microsoft Strong Cryptographic Provider"
The Microsoft Strong Cryptographic Provider.
Parameter Description
provType [optional]The type of Cryptographic Service Provider to acquire a context for, see Cryptographic Service Provider Types for more information. Defaults to cs:PROV_RSA_FULL.

Must be one of the following :
  • cs:PROV_RSA_FULL
  • cs:PROV_RSA_AES
  • cs:PROV_RSA_SIG
  • cs:PROV_RSA_SCHANNEL
  • cs:PROV_DSS
  • cs:PROV_DSS_DH
  • cs:PROV_DH_SCHANNEL
  • cs:PROV_FORTEZZA
  • cs:PROV_MS_EXCHANGE
  • cs:PROV_SSL
Note that the provider type must be supported by the provider being acquired (which defaults to the Microsoft Enhanced Cryptographic Provider). The provider can be specified using the providerName parameter.
flags [optional]Flag values. One or more of the following flas may be used. Defaults to cs:CRYPT_MACHINE_KEYSET + cs:CRYPT_NEWKEYSET.
ValueMeaning
cs:CRYPT_VERIFYCONTEXTThis option is intended for applications that are using ephemeral keys, or applications that do not require access to persisted private keys, such as applications that perform only hashing, encryption, and digital signature verification. Only applications that create signatures or decrypt messages need access to a private key. In most cases, this flag should be set.

For file-based CSPs, when this flag is set, the pszContainer parameter must be set to NULL. The application has no access to the persisted private keys of public/private key pairs. When this flag is set, temporary public/private key pairs can be created, but they are not persisted.

For hardware-based CSPs, such as a smart card CSP, if the pszContainer parameter is NULL or blank, this flag implies that no access to any keys is required, and that no UI should be presented to the user. This form is used to connect to the CSP to query its capabilities but not to actually use its keys. If the pszContainer parameter is not NULL and not blank, then this flag implies that access to only the publicly available information within the specified container is required. The CSP should not ask for a PIN. Attempts to access private information (for example, the CryptSignHash function) will fail.

When CryptAcquireContext is called, many CSPs require input from the owning user before granting access to the private keys in the key container. For example, the private keys can be encrypted, requiring a password from the user before they can be used. However, if the CRYPT_VERIFYCONTEXT flag is specified, access to the private keys is not required and the user interface can be bypassed.
cs:CRYPT_NEWKEYSETCreates a new key container with the name specified by pszContainer. If pszContainer is NULL, a key container with the default name is created.
cs:CRYPT_MACHINE_KEYSETBy default, keys and key containers are stored as user keys. For Base Providers, this means that user key containers are stored in the user's profile. A key container created without this flag by an administrator can be accessed only by the user creating the key container and a user with administration privileges.

Windows XP: A key container created without this flag by an administrator can be accessed only by the user creating the key container and the local system account.

A key container created without this flag by a user that is not an administrator can be accessed only by the user creating the key container and the local system account.

The CRYPT_MACHINE_KEYSET flag can be combined with all of the other flags to indicate that the key container of interest is a computer key container and the CSP treats it as such. For Base Providers, this means that the keys are stored locally on the computer that created the key container. If a key container is to be a computer container, the CRYPT_MACHINE_KEYSET flag must be used with all calls to CryptAcquireContext that reference the computer container. The key container created with CRYPT_MACHINE_KEYSET by an administrator can be accessed only by its creator and by a user with administrator privileges unless access rights to the container are granted using CryptSetProvParam.

Windows XP: The key container created with CRYPT_MACHINE_KEYSET by an administrator can be accessed only by its creator and by the local system account unless access rights to the container are granted using CryptSetProvParam.

The key container created with CRYPT_MACHINE_KEYSET by a user that is not an administrator can be accessed only by its creator and by the local system account unless access rights to the container are granted using CryptSetProvParam.

The CRYPT_MACHINE_KEYSET flag is useful when the user is accessing from a service or user account that did not log on interactively. When key containers are created, most CSPs do not automatically create any public/private key pairs. These keys must be created as a separate step with the CryptGenKey function.
cs:CRYPT_DELETEKEYSETDelete the key container specified by pszContainer. If pszContainer is NULL, the key container with the default name is deleted. All key pairs in the key container are also destroyed.

When this flag is set, the value returned in phProv is undefined, and thus, the CryptReleaseContext function need not be called afterward.
cs:CRYPT_SILENTThe application requests that the CSP not display any user interface (UI) for this context. If the CSP must display the UI to operate, the call fails and the NTE_SILENT_CONTEXT error code is set as the last error. In addition, if calls are made to CryptGenKey with the CRYPT_USER_PROTECTED flag with a context that has been acquired with the CRYPT_SILENT flag, the calls fail and the CSP sets NTE_SILENT_CONTEXT.

CRYPT_SILENT is intended for use with applications for which the UI cannot be displayed by the CSP.
cs:CRYPT_DEFAULT_CONTAINER_OPTIONALObtains a context for a smart card CSP that can be used for hashing and symmetric key operations but cannot be used for any operation that requires authentication to a smart card using a PIN. This type of context is most often used to perform operations on an empty smart card, such as setting the PIN by using CryptSetProvParam. This flag can only be used with smart card CSPs.

Windows Server 2003, Windows XP, and Windows 2000: This flag is not supported.
Remarks

The Microsoft Enhanced Cryptographic Service Provider is the default CSP. The provider type defaults to cs:PROV_RSA_FULL, which is a general purpose CSP which supports the following algorithms:
PurposeSupported algorithms
Key ExchangeRSA
SignatureRSA
EncryptionRC2

RC4
HashingMD5

SHA
For additional algorithms the Provider and Provider Type can be specified from the list provided above.

Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

AppendSignature

AppendSignature (string pInfile, *StringTheory pSignature), long, proc

This method checks whether the specified file already has a signature appended to it, and if not the passed signature is appended to it.

Parameters
Parameter Description
pInFileThe name and path of the file to append the signature to
pSignatureA StringTheory object which contains the signature data to append to the file
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

BuildIV

BuildIV (long ivBytes = 8, <string iv>), long, proc

Description

Creates an initialization vector (IV) of the specified length using cryptographically random data.

In cryptography, an initialization vector (IV) is a fixed-size input that is typically required to be random or pseudorandom. Randomization is crucial for encryption schemes to achieve semantic security, a property whereby repeated usage of the scheme under the same key does not allow distinction between the encrypted message and the message parts.

In order to decrypt the message the IV needs to be known, along with the key. The IV is typically sent with the encrypted data, etither as plain text, or encrypted in the same manner as the session key.

Parameters
Parameter Description
ivBytesThe length of the IV to generate, in bytes. Defaults to 8, which is typical for 8 byte block ciphers.
iv [optional]Optional string to store the IV created in. If this is omitted the generated IV is stored in the .iv property of the object.
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

CertFieldsToString

CertFieldsToString (*cryCertFields certFields), *cstring

Description

Converts a cryCertFields queue to a string of entries, seperated by a CR,LF pair. Primarily for display and backward compatibility.

Parameters
Parameter Description
certFieldsA pointer to a certFields queue with contains the certificate fields of interest (typically each individual field (value) within the Subject field).
Return Value

Returns a reference to a cstring that contains each of the field values seperated by two CR,LF pair if successful. Returns a null reference otherwise.

Notes and Example:

Important: The caller is responsible for disposing the returned reference.
Example
certFieldsString     &cstring
     
code
certFieldsString &= Crypto.CertFieldsToString(certFieldsQ)
if not certFieldsString &= null
! Use the string here
Dispose(certFieldsString) ! Dispose when no longer required
end

CertGetAttribute

CertGetAttribute (*PCCERT_CONTEXT pCertContext, string attName, *string attribute), long

Description

Retrieve an attribute from a certificate based on the name of the attribute.

Parameters
Parameter Description
pCertContext A pointer to the certificate context that contains the certificate to retrieve the details from. This is returned by the API functions such as csCertGetSubjectCertificateFromStore() and csCertEnumCertificatesInStore().
attNameThe attribute to retrieve, should be one of the cs:szOID equates such as cs:szOID_COMMON_NAME or cs:szOID_RSA_emailAddr.

An OID is number that uniquely identifies an object class or attribute. An object identifier is represented as a dotted decimal string, such as 1.2.3.4. Object identifiers are organized into a global hierarchy. National registration authorities issue root object identifiers to individuals or organizations, who manage the hierarchy below their root object identifier.
attributeA pointer to a string that will receive the value.
Return Value

Crypto:OK for success, or the API Error code in the event of a failure.

CertGetSubjectAsString

CertGetSubjectAsString (*PCCERT_CONTEXT pCertContext, *cstring subject, bool wholeSubject=false), *cstring

Description

Returns the certificate subject as a cstring. Each field value is seperated by a CR,LF pair.

Parameters
Parameter Description
pCertContextA pointer to the certificate context to retrieve the information from.This is returned by the API functions such as csCertGetSubjectCertificateFromStore() and csCertEnumCertificatesInStore()
wholeSubjectIf set to True all fields in the Subject are retrieved, otherwise only the Common Name and Email fields are retrieved.
Return Value

Returns a cstring reference if successful or Null if an error occurs. Note that the caller is responsible for disposing the returned cstring reference when it is not longer required.

CertMatchField

CertMatchField (string searchVal, *cryCertFields certFields, bool strict=false), long

Description

Searches the passed certFields queue for a field that matches the passed searchVal. If strict is set to true, then only exact matches are allowed.

If strict is set to false (the default) then if no exact matches are found a match will be returned to the first field that contains the search string, if one exists.

Parameters
Parameter Description
searchValThe string to match.
certFields A certCertFields queue that contains the certificate fields to search strict: If set to True this checks for an exact match for each field, otherwise it does and instring match.
Return Value

Zero for no match, or the position in the queue of the matching record

ChooseCertificate

ChooseCertificate (*cstring pEmail, *cstring pProvider, *cstring pSigner), long

Description

Automatically choose the correct certificate based on the e-mail address and the provider name. If the provider name is blank, any provider is used. The correct certificate is the one that expires the last and that is of the correct provider.

Parameters
Parameter Description
pEmailE-mail address or user name of the signer.
pProviderThe root certificate issuer uch as Thawte, Verisign, Comodo etc.
pSigner [out]This string is populated with the signer information
Return Value

Returns Crypto:OK if successful and Crypto:NotOK if an error occurs.

Construct

Construct ()

Description

The object contructor. Called when the object is created.

CreateHash

CreateHash (long algId, long phKey=0), long, proc

Description

Create a Hash object. The new Hash object is stored in the .hHash property and the currently selected provider is used based on the .hProvider property.

Parameters
Parameter Description
algIdAn ALG_ID value that identifies the hash algorithm to use.

Valid values for this parameter vary, depending on the CSP that is used. See Supported Algorithms.
phKey [optional]If the type of hash algorithm is a keyed hash, such as the Hash-Based Message Authentication Code (HMAC) or Message Authentication Code (MAC) algorithm, the key for the hash is passed in this parameter. For nonkeyed algorithms, this parameter must be set to zero.

For keyed algorithms, the key must be to a block cipher key, such as RC2, that has a cipher mode of Cipher Block Chaining (CBC).
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

CreateHash

CreateHash (long hProv, long algId, long phKey, long flags=0, *HCRYPTHASH hash), long, proc

Description

Create a Hash object. The new Hash object is stored in the passed hash paramters. Uses the CSP defined by the hProv parameter.

Parameters
Parameter Description
hProvA handle to the CSP context to use.
algId [optional]An ALG_ID value that identifies the hash algorithm to use.

Valid values for this parameter vary, depending on the CSP that is used. See Supported Algorithms.
flags [optional]API flags. Currently no flags are defined.
phKeyIf the type of hash algorithm is a keyed hash, such as the Hash-Based Message Authentication Code (HMAC) or Message Authentication Code (MAC) algorithm, the key for the hash is passed in this parameter. For nonkeyed algorithms, this parameter must be set to zero.

For keyed algorithms, the key must be to a block cipher key, such as RC2, that has a cipher mode of Cipher Block Chaining (CBC).
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

DestroyHash

DestroyHash ()

DestroyHash (*HCRYPTHASH hHash)

Description

Deallocates memory for a Hash object created by calling the CreateHash method. If no parameter is passed then the .hHash property is destroyed, otherwise the passed Hash object is destroyed.

Parameters
Parameter Description
hHash [optional]Handle to a Hash object to destroy.
Return Value

None.

DestroyKey

DestroyKey (ulong hCryptoKey), long, proc

Description

Destroys a key object (deallocated memory).

Parameters
Parameter Description
hCryptoKeyA handle to the Key object to be destroyed.
Return Value

Returns Crypto:OK if successful or Crypto:NotOK if the API failed to destroy the key.

Destruct

Destruct ()

Description

The object destructor. Called when the object exists the current scope.

EncryptDecrypt

EncryptDecrypt (HCRYPTKEY hCryptKey, *string pbData, *long dataLen, long decrypt=0, HCRYPTHASH hCryptHash=0, long flags=0), long, proc

Description

Generic procedure, wraps encryption and decryption

Parameters
Parameter Description
hCryptKeyHandle to the key to use
pbData [in, out] Pointer to a buffer containing data to be encrypted or decrypted
dataLen [in, out] Length of passed data, in bytes, when the method returns this contains the length of the encrypted or decrypted data, in bytes.
decrypt Set to 1 to decrypt the passed data, zero to encrypt it
hCryptHash (optional) Handle to a hash object to received a hash of the plaintext
flags (optional) Flag value to specify padding handle for RCA encryption using the Microsoft Enhanced CSP.
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

EnumProviders

EnumProviders (*providersQueueType providers), long, proc

Description

The EnumProviders function retrievesthe available cryptographic service providers (CSPs) available on a machine.

Possible CSPs include Microsoft Base Cryptographic Provider version 1.0 and Microsoft Enhanced Cryptographic Provider version 1.0.

Parameters
Parameter Description
providersA providerQueueType queue which will be populated with all the available providers. The queue type is defined as follows:

providerTypesQueueType queue, type
ptTypeName string(255)
ptType ulong
end
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

EnumProviderTypes

EnumProviderTypes (*providerTypesQueueType provTypes), long, proc

Description

Retrieves the types of cryptographic service provider (CSP) supported on the computer.

Provider types include cs:PROV_RSA_FULL, cs:PROV_RSA_SCHANNEL, and cs:PROV_DSS.

Parameters
Parameter Description
provTypes A providerTypesQueueType queue which will be populated with all the available providers. The queue type is defined as follows:

providersQueueType queue, type
pName string(255)
pType ulong
pTypeName string(255)
end
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

ExportKey

ExportKey (long phKey, long blobType, *string keyBlob, *long dataLen, long hExpKey=0, long flags=0), long

Description

Exports a cryptographic key or a key pair from a cryptographic service provider (CSP) in a secure manner.

A handle to the key to be exported is passed to the method, and the method returns a key BLOB. This key BLOB can be sent over a nonsecure transport or stored in a nonsecure storage location. This function can export an Schannel session key, regular session key, public key, or public/private key pair. The key BLOB to export is useless until the intended recipient uses the CryptImportKey function on it to import the key or key pair into a recipient's CSP.

Parameters
Parameter Description
phKeyA handle to the key to be exported
blobTypeSpecifies the type of key BLOB to be exported in pbData. This must be one of the following constants as discussed in Cryptographic Key Storage and Exchange.
ValueMeaning
cs:OPAQUEKEYBLOBUsed to store session keys in an Schannel CSP or any other vendor-specific format. OPAQUEKEYBLOBs are nontransferable and must be used within the CSP that generated the BLOB.
cs:PRIVATEKEYBLOBUsed to transport public/private key pairs.
cs:PUBLICKEYBLOB
Used to transport public keys.
cs:SIMPLEBLOBUsed to transport session keys.
cs:PLAINTEXTKEYBLOBUsed to export any key supported by the CSP in use. The key is exported in plaintext using the following format.

BLOBHEADER hdr;
DWORD cbKeySize;
BYTE rgbKeyData [];
Windows 2000: This value is not supported.
cs:SYMMETRICWRAPKEYBLOBUsed to export and import a symmetric key wrapped with another symmetric key. The actual wrapped key is in the format specified in the IETF RFC 3217 standard.
Parameter Description
keyBlobA string which will contain the keyBlob
dataLenShould be set to the length of the keyBlob string passed to the method. On return this will be set to the size of the key BLOB stored in the string.
hExpKey [optional] A handle to a cryptographic key of the destination user. The key data within the exported key BLOB is encrypted using this key. This ensures that only the destination user is able to make use of the key BLOB. Both hExpKey and hKey must come from the same CSP.

Most often, this is the key exchange public key of the destination user. However, certain protocols in some CSPs require that a session key belonging to the destination user be used for this purpose.

If the key BLOB type specified by dwBlobType is cs:PUBLICKEYBLOB, this parameter is unused and must be set to zero.

If the key BLOB type specified by dwBlobType is cs:PRIVATEKEYBLOB, this is typically a handle to a session key that is to be used to encrypt the key BLOB. Some CSPs allow this parameter to be zero, in which case the application must encrypt the private key BLOB manually so as to protect it.

To determine how Microsoft cryptographic service providers respond to this parameter, see the private key BLOB sections of Microsoft Cryptographic Service Providers.

Note
 

Some CSPs may modify this parameter as a result of the operation. Applications that subsequently use this key for other purposes should call the csCryptDuplicateKey APU function to create a duplicate key handle. When the application has finished using the handle, release it by calling the DestroyKey method
flags [optional]Specifies additional options for the function. This parameter can be zero or a combination of one or more of the following values:
ValueMeaning
cs:CRYPT_BLOB_VER3
00000080h
This flag causes this function to export version 3 of a BLOB type.
cs:CRYPT_DESTROYKEY
00000004h
This flag destroys the original key in the OPAQUEKEYBLOB. This flag is available in Schannel CSPs only.
cs:CRYPT_OAEP
00000040h
This flag causes PKCS #1 version 2 formatting to be created with the RSA encryption and decryption when exporting SIMPLEBLOBs.
cs:CRYPT_SSL2_FALLBACK
00000002h
The first eight bytes of the RSA encryption block padding must be set to 0x03 rather than to random data. This prevents version rollback attacks and is discussed in the SSL3 specification. This flag is available for Schannel CSPs only.
cs:CRYPT_Y_ONLY
000000001h
This flag is not used.
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

PutKeyBlobToFile

PutKeyBlobToFile (string fName, HCRYPTKEY hKey), long

Description

Writes a session key to disk, encypted using the current exchange key. The length of the encrypt key is written first, followed by the encrypted key data. The key can then key read back in by calling the GetKeyBlobFromFile method.

Parameters
Parameter Description
fNameName of the file to write the data to
hsKeyHandle to the session key to encrypt and write to the file
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

GenKey

GenKey (long algId, long options, long keyLength, *HCRYPTKEY phKey), long, proc

Description

Generates a random cryptographic session key or a public/private key pair. A handle to the key or key pair is returned in phKey. This handle can then be used as needed with any CryptoAPI function that requires a key handle.

The calling application must specify the algorithm when calling this function. Because this algorithm type is kept bundled with the key, the application does not need to specify the algorithm later when the actual cryptographic operations are performed.

Parameters
Parameter Description
algID An ALG_ID value that identifies the algorithm for which the key is to be generated. Values for this parameter vary depending on the CSP used.

For ALG_ID values to use with the Microsoft Base Cryptographic Provider, see Base Provider Algorithms.

For ALG_ID values to use with the Microsoft Strong Cryptographic Provider or the Microsoft Enhanced Cryptographic Provider, see Enhanced Provider Algorithms.

For a Diffie-Hellman CSP, use one of the following values:

cs:CALG_DH_EPHEM: Specifies an "Ephemeral" Diffie-Hellman key.

cs:CALG_DH_SF: Specifies a "Store and Forward" Diffie-Hellman key.

In addition to generating session keys for symmetric algorithms, this function can also generate public/private key pairs. Each CryptoAPI client generally possesses two public/private key pairs. To generate one of these key pairs, set the Algid parameter to one of the following values:

cs:AT_KEYEXCHANGE: Key exchange

cs:AT_SIGNATURE: Digital signature

Note:  When key specifications csAT_KEYEXCHANGE and csAT_SIGNATURE are specified, the algorithm identifiers that are used to generate the key depend on the provider used.
optionsCan be zero or a combination of the following values:

cs:CRYPT_ARCHIVABLE: If this flag is set, the key can be exported until its handle is closed by a call to CryptDestroyKey. This allows newly generated keys to be exported upon creation for archiving or key recovery. After the handle is closed, the key is no longer exportable.

cs:CRYPT_CREATE_IV: This flag is not used.

cs:CRYPT_CREATE_SALT: If this flag is set, then the key is assigned a random salt value automatically. You can retrieve this salt value by using the CryptGetKeyParam API function with the dwParam parameter set to cs:KP_SALT.

If this flag is not set, then the key is given a salt value of zero.

When keys with nonzero salt values are exported (when calling ExportKey), then the salt value must also be obtained and kept with the key BLOB.

cs:CRYPT_DATA_KEY: This flag is not used

cs:CRYPT_EXPORTABLE: If this flag is set, then the key can be transferred out of the CSP into a key BLOB by using the ExportKey method. Because session keys generally must be exportable, this flag should usually be set when they are created.

If this flag is not set, then the key is not exportable. For a session key, this means that the key is available only within the current session and only the application that created it will be able to use it. For a public/private key pair, this means that the private key cannot be transported or backed up.

This flag applies only to session key and private key BLOBs. It does not apply to public keys, which are always exportable.

cs:CRYPT_FORCE_KEY_PROTECTION_HIGH:This flag specifies strong key protection. When this flag is set, the user is prompted to enter a password for the key when the key is created. The user will be prompted to enter the password whenever this key is used.

This flag is only used by the CSPs that are provided by Microsoft. Third party CSPs will define their own behavior for strong key protection.

Specifying this flag causes the same result as calling this function with the cs:CRYPT_USER_PROTECTED flag when strong key protection is specified in the system registry.

If this flag is specified and the provider handle in the hProv parameter was created by using the cs:CRYPT_VERIFYCONTEXT or cs:CRYPT_SILENT flag, this function will set the last error to cs:NTE_SILENT_CONTEXT and return zero.
Windows Server 2003, Windows XP, and Windows 2000:  This flag is not supported.

cs:CRYPT_KEK:This flag is not used.

cs:CRYPT_INITIATOR: This flag is not used.

cs:CRYPT_NO_SALT: This flag specifies that a no salt value gets allocated for a forty-bit symmetric key. For more information, see Salt Value Functionality.

cs:CRYPT_ONLINE: This flag is not used.

cs:CRYPT_PREGEN: This flag specifies an initial Diffie-Hellman or DSS key generation. This flag is useful only with Diffie-Hellman and DSS CSPs. When used, a default key length will be used unless a key length is specified by passing a non zero value in the keyLen parameter.

cs:CRYPT_RECIPIENT: This flag is not used.

cs:CRYPT_SF: This flag is not used.

cs:CRYPT_SGCKEY:This flag is not used.

cs:CRYPT_USER_PROTECTED: If this flag is set, the user is notified through a dialog box or another method when certain actions are attempting to use this key. The precise behavior is specified by the CSP being used. If the provider context was opened with the cs:CRYPT_SILENT flag set, using this flag causes a failure and the last error is set to cs:NTE_SILENT_CONTEXT.

cs:CRYPT_VOLATILE: This flag is not used.
keyLengthThe length of the key to be generated,

The following table lists minimum, default, and maximum signature and exchange key lengths beginning with Windows XP.
Key type and provider Minimum lengthDefault length Maximum length
RSA Base Provider

Signature and ExchangeKeys
38451216,384
RSA Strong and Enhanced Providers

Signature and Exchange Keys
3841,02416,384
DSS Base Providers

Signature Keys
5121,0241,024
DSS Base Providers

Exchange Keys
Not applicableNot applicableNot applicable
DSS/DH Base Providers

Signature Keys
5121,0241,024
DSS/DH Base Providers

Exchange Keys
5125121,024
DSS/DH Enhanced Providers

Signature Keys
5121,0241,024
DSS/DH Enhanced Providers

Exchange Keys
5121,0244,096
The following table lists minimum, default, and maximum signature and exchange key lengths through Windows 2000.
Key type and provider Minimum length Default length Maximum length
RSA Base and Strong Providers

Signature Keys
38451216,384
RSA Base Provider

Exchange Keys
3845121,024
RSA Strong Provider

Exchange Keys
38451216,384
RSA Enhanced Provider

Signature and Exchange Keys
3841,02416,384
phKeySet to the handle of the newly created key. Call the DestroyKey method to destroy this key once it is no longer needed.
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

GenPPK

GenPPK (long keyLen=1024, long flags=cs:CRYPT_EXPORTABLE), long, proc

Description

Creates a public/private key pair using the current Context and Container.

Parameters
Parameter Description
keyLen [optional]The length of the key to create. See the GenKey method for supported key sizes for the standard CSPs.
flagsOne or more flags for determining the manner in which the key is created. See the options parameter of the GenKey method for a fill list of supported values. Defaults to cs:CRYPT_EXPORTABLE, which will create the a key pair that can be exported.
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

GetDerivedKey

GetDerivedKey (HCRYPTHASH hHash, ulong options = cs:CRYPT_EXPORTABLE, ulong keyLength = 0), HCRYPTKEY

Description

Derives a session key from the passed hash. The same hash value will always produce the same session key. The key uses the self.keyStorageAlg algorithm (RC4 by default). Typically this method is not used - the KeyFromPassword is called to derive the hash from a password and then create session key using that hash value rather than creating a hash and then passing it to this method manually.

Parameters
Parameter Description
hHashA handle to a Hash object to be used to derive the key from. Call CreateHash to create a hash object and HashData to hash data and add the hash value to the object.
options [optional]One or more flags for determining the manner in which the key is created. See the options parameter of the GenKey method for a fill list of supported values. Defaults to cs:CRYPT_EXPORTABLE, which will create the a key pair that can be exported.
keyLen [optional]The length of the key to create. See the GenKey method for supported key sizes for the standard CSPs.
Return Value

Returns a handle to the newly created key if successful, or zero if it fails. Call the DestroyKey method  to dispose this key one it is no longer required.

Get_OID

Get_OID (string pOIDstr),string

Description

Get the type of encoding algorithm used in the encryption. Returns the string that matches the passed OID equate.

Parameters
Parameter Description
pOIDstrA string containing one of the predefined the OIDs to retrieve the name of.
Return Value

A string that contains the OID description, or "Unknown" if the OID does not match any of the defined equates.

GetCertList

GetCertList (long pCsp, *cstring pCertStoreName, long pWholeSubject, *MsgQType pCertQ), long, proc

Description

This is a diagnostic function for inspecting the contents of a given certificate store.

Parameters
Parameter Description
pCspIdentifies the cryptographic service provider to use. If NULL, the Microsoft Base Provider (defined by MS_DEF_PROV) will be used. Also, this string can start with 'csptype=##<13,10>' to specify other provider types than the default, which is cs:PROV_RSA_FULL! (e.g. 2=RSA sig only, 3=DSS, 4=Fortezza)
pCertStoreNameThe name of the certificate store whose contents the caller would like to list.
pWholeSubjectIf False (0) retrieves the common name and email of each certificate if True (1) then the entire subject is retrieved
pCertQA queue to populate with the retrieved information
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

GetHash

GetHash (StringTheory pStr)

Description

Gets the hash value from the passed Hash object. the value is placed in the passed StringTheory object.

Parameters

Parameter Description
pStrA StringTheory object to hold the returned hash value.

Return Value

Nothing

Compatibility Note

This method changed from version 1.78. the previous prototype of this method was

GetHash (), *string

The earlier function returned a string reference containing the hash data, or Null if an error occured. The caller was responsible to dispose the returned string reference when it is no longer required. Changing the method to the current approach reduced the possible memory leak when the value was not disposed.

GetHashInfo

GetHashInfo ( long dType, <*string pHash>, <*long hashLen>), long, proc

Description

Retrieves information from a Hash object. Typically not called directly - use the MakeHash method to make a hash without needing to create a Hash object manually, or the CreateHash(), HashData() and GetHash() methods to manually create a hash, add data to it, and retrieve the resultant value.

Parameters
Parameter Description
dTypeThe type of information to retrieve, can be one of three values:

cs:HP_ALGID


Get the hash algorithm ID. An cs:ALG_ID that indicates the algorithm specified when the hash object was created.

cs:HP_HASHSIZE

Hash value size, indicating the number of bytes in the hash value. This value will usually be 16 or 20, depending on the hash algorithm.

cs:HP_HASHVAL

The actual Hash value genererated from the data added by calling HashData. The method should be called using cs:HP_HASHSIZE to retrieve the number of bytes of hash data.
pHash [optional]A string to store the returned value when the cs:HP_HASHVAL value is set for the dType parameter.
hashLen [optional]The length of the passed pHash string. Set to the length of the returned data.
Return Value

If dType is cs:HP_ALGID or cs:HP_HASHSIZE the return value is the AlgID or the size of the hash data respectively, if successful.

If dType is cs:HP_HASHVAL, then the return value is Crypto:OK (0) if successful.

The method returns Crypto:NotOK (-1) to indicate failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

GetCertificateChain

GetCertificateChain(string Signer, bool pSubject=false)

Description

Get all the details for a certificate in the store, and all the details for all parent certificates as well.

Parameters
Parameter Description
SignerThe IssuedTo field of a certificate in the certificate store. Note that this parameter is case sensitive.
pSubjectIf this field is set to true then it indicates that the Subject field of the certificate, rather than the IssuedTo field  is provided in the Signer parameter.
Return Value

Returns Crypto:NOTOK if the method fails. Returns Crypto:OK if the method succeeds.

The Certificates Queue is updated with the certificate, and all parent certificate information.


GetExpiryDate

GetExpiryDate(string Signer, *long ExpiryDate), long

Description

Finds the certificate in the certificate store (using the IssuedTo field) and gets the expiry date for that certificate.

Parameters
Parameter Description
Signerthe IssuedTo field of a certificate in the certificate store. Note that this parameter is case sensitive.
ExpiryDateThe expiry date of the certificate, as a Clarion LONG.
Return Value

Returns Crypto:NOTOK if the method fails. Returns Crypto:OK if the method succeeds.

GetKey

GetKey (long keyType), long

Description

Returns one of the key handles stored by the object. The properties can also be accessed directly.

Parameters
Parameter Description
keyTypeCan be one of the following values:

Crypto:ExchangeKey

Returns the .hExchangeKey property, which is a handle to the current Exchange (Public/Private) key pair.

Crypto:SignKey

Not typically used. Returns the .hSignKey property, which is a handle to the current Signing key pair (typically the Exchange key is used for both signing and encryption).
Return Value

Returns the handle to the key if successful or Crypto:NotOK if an invalid keyType is passed.

GetKeyFromBlob

GetKeyFromBlob (*string cipherData, *HCRYPTKEY hSessionKey, *long keyLen), long

Description

Decrypts and imports a session key contained in an encrypted message BLOB. This is used by the DecryptFile method when loading the file from disk and extracting and decrypting the session key from the start of the BLOB stored in the file. Extracts the session key from the passed cipher data. The passed string should contain the length, followed by the encrypted session key. The session key is decrypted using the current PPK pair and imported for use, and the hSessionKey parameter is set to the handle of the imported session key.

Parameters
Parameter Description
cipherDataPointer to a string that contains the data key BLOB
hSessionKeyPointer to a HCRYPTKEY which will be set to the handle of the key if it is imported sucessfully, or to zero if the method fails.
keyLenSet to the length of the key (in bytes) retrieved
Remarks

PutKeyBlobToFile is used to write the encrypted session key blob data and length to a file, and this method is used to then extract and decrypt that data when the file is read and the GetKeyBlobFromFile method is called.

Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

\Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

GetKeyBlob

GetKeyBlob (long keyType=0), *string

Description

This method is not typically used. Retrieves the property of the object that stores the key BLOB for the specified key type (if that key has been exported to a BLOB and stored in the object).

Parameters
Parameter Description
keyTypeCan be one of the following values:

Crypto:ExchangeKey

Returns the .exchangeKeyBlob property, which is a handle to the current Exchange (Public/Private) key pair.

Crypto:SignKey

Not typically used. Returns the .signKeyBlob property, which is a handle to the current Signing key pair (typically the Exchange key is used for both signing and encryption).

Crypto:SessionKey

Returns the .sessionKeyBlob property.
Return Value

Returns the string reference property of the class which stores the BLOB, or Null if an error occurs.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

GetKeyBlobSize

GetKeyBlobSize (long phKey, ulong blobType, long hExpKey = 0), long

Description

Returns the size of the BLOB required to store an exported key. Not typically called directly.

Parameters
Parameter Description
phKeyThe key handle to be exported
blobTypeThe type of BLOB to export to:

cs:OPAQUEKEYBLOB: Used to store session keys in an Schannel CSP or any other vendor-specific format. OPAQUEKEYBLOBs are nontransferable and must be used within the CSP that generated the BLOB.

cs:PRIVATEKEYBLOB: Used to transport public/private key pairs.

cs:PUBLICKEYBLOB: Used to transport public keys.

cs:SIMPLEBLOB: Used to transport session keys.

cs:PLAINTEXTKEYBLOB: Used to export any key supported by the CSP in use. The key is exported in plaintext using the following format.

BLOBHEADER hdr;
DWORD cbKeySize;
BYTE rgbKeyData [];
Windows 2000/NT and Windows Me/98/95: This value is not supported.

cs:SYMMETRICWRAPKEYBLOB:
Used to export and import a symmetric key wrapped with another symmetric key. The actual wrapped key is in the format specified in the IETF RFC 3217 standard.

Windows NT and Windows Me/98/95: This value is not supported.
hExpKey  [optional]The handle to the Exchange key pair that will be used to encrypt the BLOB.
Return Value

Returns the size of the BLOB required to store the exporteed key, or Crypto:NotOK if the method fails.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

GetProviderAlgs

GetProviderAlgs (*cryProviderAlgs provAlgs, HCRYPTPROV hProv=0), long, proc

Description

Enumerates all supported algortihms for the currently selected -provider, along with the details of the keys for each algorithm. See -the Providers example app for a demonstration of this method.

Parameters
Parameter Description
provAlgsA CryProviderAlgs queue type that will be populated with the list of supported algorithms.
hProv A handle to the provider to enumerate the algorithms of. Use the .hProvider property to enumerate algorithms supported by the current provider.
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

GetSerialNumber

GetSerialNumber(string Signer, *string Serial), long

Description

Finds the certificate in the certificate store (using the IssuedTo field) and gets the serial number for that certificate.

Parameters
Parameter Description
Signerthe IssuedTo field of a certificate in the certificate store. Note that this parameter is case sensitive.
SerialThe serial number of the certificate.
Return Value

Returns Crypto:NOTOK if the method fails. Returns Crypto:OK if the method succeeds.

GetUserKey

GetUserKey (ulong keyType=0, bool createKey=false, long keyLen=1024, long flags=cs:CRYPT_EXPORTABLE), long, proc

Description

Gets the user's Exchange key from the current key store (Container). Optionally creates the key pair if it does not exist.

Parameters
Parameter Description
keyType[optional]The type of key to retrieve or create. Can be cs:AT_KEYEXCHANGE for the Exchange key pair; or cs:AT_SIGNATURE for the signature key pair.
createKey [optional]If set to True the key pair is created if it does not exist.
keyLen[optional]The length of the key (in bits) to create if the the key is created.
flags[optional]Optional flags for the key creation if the ket is created. May be one or more of the following values:

CRYPT_ARCHIVABLE: If this flag is set, the key can be exported until its handle is closed by a call to CryptDestroyKey. This allows newly generated keys to be exported upon creation for archiving or key recovery. After the handle is closed, the key is no longer exportable.

CRYPT_CREATE_IV: This flag is not used.

CRYPT_CREATE_SALT: If this flag is set, then the key is assigned a random salt value automatically. You can retrieve this salt value by using the CryptGetKeyParam function with the dwParam parameter set to KP_SALT. If this flag is not set, then the key is given a salt value of zero.

When keys with nonzero salt values are exported (through CryptExportKey), then the salt value must also be obtained and kept with the key BLOB.

CRYPT_DATA_KEY:This flag is not used.

CRYPT_EXPORTABLE: If this flag is set, then the key can be transferred out of the CSP into a key BLOB by using the CryptExportKey function. Because session keys generally must be exportable, this flag should usually be set when they are created.

If this flag is not set, then the key is not exportable. For a session key, this means that the key is available only within the current session and only the application that created it will be able to use it. For a public/private key pair, this means that the private key cannot be transported or backed up.

This flag applies only to session key and private key BLOBs. It does not apply to public keys, which are always exportable.

CRYPT_FORCE_KEY_PROTECTION_HIGH: This flag specifies strong key protection. When this flag is set, the user is prompted to enter a password for the key when the key is created. The user will be prompted to enter the password whenever this key is used.

This flag is only used by the CSPs that are provided by Microsoft. Third party CSPs will define their own behavior for strong key protection.

Specifying this flag causes the same result as calling this function with the CRYPT_USER_PROTECTED flag when strong key protection is specified in the system registry.

If this flag is specified and the provider handle in the hProv parameter was created by using the CRYPT_VERIFYCONTEXT or CRYPT_SILENT flag, this function will set the last error to NTE_SILENT_CONTEXT and return zero.

Windows Server 2003, Windows XP, and Windows 2000:  This flag is not supported.

CRYPT_KEK: This flag is not used.

CRYPT_INITIATOR: This flag is not used.

CRYPT_NO_SALT: This flag specifies that a no salt value gets allocated for a forty-bit symmetric key. For more information, see Salt Value Functionality.

CRYPT_ONLINE: This flag is not used.

CRYPT_PREGEN: This flag specifies an initial Diffie-Hellman or DSS key generation. This flag is useful only with Diffie-Hellman and DSS CSPs. When used, a default key length will be used unless a key length is specified in the upper 16 bits of the dwFlags parameter. If parameters that involve key lengths are set on a PREGEN Diffie-Hellman or DSS key using CryptSetKeyParam, the key lengths must be compatible with the key length set here.

CRYPT_RECIPIENT: This flag is not used. CRYPT_SF: This flag is not used.

CRYPT_SGCKEY: This flag is not used.

CRYPT_USER_PROTECTED: If this flag is set, the user is notified through a dialog box or another method when certain actions are attempting to use this key. The precise behavior is specified by the CSP being used. If the provider context was opened with the CRYPT_SILENT flag set, using this flag causes a failure and the last error is set to NTE_SILENT_CONTEXT.

CRYPT_VOLATILE: This flag is not used.
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) in the event of a failure.

Note: The ErrorTrap method will be called in the event of a failure. If the .logging property of the class is set to True (1) then errors are logged to the system debug output and can be viewed using DebugView. If the .displayErrors property of the class is set to True (1), then errors are displayed to the user using the Clarion Message function.

HashData

HashData (*string inData, ulong dataLen=0), long
HashData (HCRYPTHASH hHash, *string inData, ulong dataLen = 0), long, proc


Description

Typically the MakeHash method is called to create a hash object, add the data, and retrieve the resultant hash. This method allows data to be added to a hash object manually and is not needed in most cases.

Hash the provided data using the current .hHash object or the passed Hash object and store the hash data in the object. The hash can then be retrieved by calling the GetHash method.

Parameters
Parameter Description
InDataThe data to add to the hash
dataLenThe length of the data being passed (in bytes) that should be hashed.
hHash (optional)

A handle to a hash object to use to create and store the hash data

Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) for failure.

ImportKey

ImportKey (*string pbData, long dataLen, *long hNewKey, long hProv =0, long phKey=0, long flags=0), long, proc
ImportKey
Procedure (long keyType=0), long, proc

Description

Imports a key pair BLOB into the CSP. The Private key is imported as non exportable by default and hence cannot be exported out of the CSP.

Parameters

If called without any parameters, or with just the keyType specified, the ImportKey method imports the .keyBlob property into the CSP.
Parameter Description
keyTypeThe type of key being imported. Can be cs:AT_KEYEXCHANGE or cs:AT_SIGNATURE. If omitted or passed as Zero (0), then cs:AT_KEYEXCHANGE is used.
The method can also be used to import a key stored in a BLOB which is passed.
pbDatastring containing the Key BLOB to import
dataLensize of the binary Key BLOB in bytes
hNewKey pointer to a long variable that will receive the handle to the newly imported key
hProvOptional handle to a CSP, if zero then self.hProvider will be used if possible
phKeyOptional parameter that specifies a handle to a key that was used to encrypt the Key BLOB (zero if the BLOB is unencrypted)
flagsOptional parameter only for use when imports a Public/Private key pair in the form of a PRIVATEKEYBLOB.
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) for failure.

LocateProcedure

Locate   (long hLib, string pProcedure), long

Description

Find a procedure in a DLL pointed to by hLib.

Parameters
Parameter Description
hLibHandle of the open DLL.
pProcedureThe name of the procedure to find.
Return Value

The address of the procedure in the DLL if successful, otherwise 0.

PFXAddFromStore

PFXAddFromStore (HCERTSTORE pfxStore, HCERTSTORE hDestStore, long flags = 1), long

Description

Imports all certificates from a PFX file in a store.

Parameters
Parameter Description
pfxStoreA handle to the store to import from (returned by the ImportPFXBlob method)
hDestStoreA handle to the store to import the certificates into
flags=cs:CERT_STORE_ADD_NEWFlag for importing, determines how the import handles existing certificates, can be one of the following values:

cs:CERT_STORE_ADD_ALWAYS
cs:CERT_STORE_ADD_NEW
cs:CERT_STORE_ADD_REPLACE_EXISTING
cs:CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES
cs:CERT_STORE_ADD_USE_EXISTING
Return Value

The number of certificates imported, zero if an error occurs or there is nothing to import.

PFXImportToStore

PFXImportToStore (*CRYPT_DATA_BLOB pfxBlob, ulong flags, <string pPassword>), HCERTSTORE

Description

Import a PFX (certificate) stored in a BLOB into the current Context.

Parameters
Parameter Description
pfxBlobPointer the the CERT_BLOB structure that contains the PFX data.
pPasswordA string that contains the password for the private key
flagsFlags for the store and protection, can have one or more of the following values added:

cs:CRYPT_EXPORTABLE - Imported keys are marked as exportable.
cs:CRYPT_USER_PROTECTED - The user is to be notified through a dialog box or other method when certain attempts to use this key are made
cs:CRYPT_MACHINE_KEYSET - The private keys are stored under the local computer and not under the current user.
cs:CRYPT_USER_KEYSET - The private keys are stored under the current user and not under the local computer even if the PFX BLOB specifies that they should go into the local computer.
Return Value

A handle to the pfxStore returned by the PFXImportCertStore API if successful, or zero if the method fails.

PutSignature

PutSignature (string pFilename, *cstring pEmail, *cstring pProvider), long, proc

Description

Selects a certificate from the system store the relates to the current Cryptographic Service Provider and uses that certificate to sign the specified file and appends the signature to the file.

Parameters
Parameter Description
pFilenameThe name of the file to add a signature to,
pEmailThe email address or common name associated with the certificate to use to sign the file.
pProviderThe name of the CSP to use to generate the signature.
Return Value

Returns Crypto:OK (0) for success and Crypto:NotOK (-1) for failure.

ReleaseContext

ReleaseContext (<*HCRYPTPROV hProvider>), long, proc

Description

Releases the currently acquired Provider context. If the hProvider parameter is omitted then this releases the current context reference by the self.hProvider property (if one has been acquired).

ReverseBytes

ReverseBytes (*string binData)

Description

Reverses the order of the bytes in the passed string. This is used when switching from little endian byte order to big endian byte order and vice versa.

SetKey

SetKey (long keyType, long phKey), long, proc

Description

Stores the passed key in the relevant class property based on the key type.

SetKeyBlob

SetKeyBlob (string keyBlob, long keyLen = 0, long keyType=0), long, proc

StripLineBreaks

StripLineBreaks (*string mText, byte replacement=0)

Description

Strips the linebreaks from a string and optionally replaces them with the specified character. Note that the ASCII code of the desired character should be passed in the replacement parameter, so use Val(character) to pass the ASCII code for a specific character.

ToCstring

ToCstring (*string s), *cstring

Description

Creates a new cstring and copies the contens from the passed string into it. Note that in order to prevent a memory leak, the returned cstring pointer must be disposed once it is no longer needed.

Supported Algorithms

The following algorithms are supported by the CryptoAPI built in CSPs. For a full list of algorithms for a particular provider, along with the key lengths suported by each algorithm, call the GetProviderAlgs method
IdentifierValue Description
cs:CALG_3DES00006603hTriple DES encryption algorithm.
cs:CALG_3DES_11200006609hTwo-key triple DES encryption with effective key length equal to 112 bits.
cs:CALG_AES00006611hAdvanced Encryption Standard (AES). This algorithm is supported by the Microsoft AES Cryptographic Provider.

Windows 2000/NT: This algorithm is not supported.
cs:CALG_AES_1280000660eh128 bit AES. This algorithm is supported by the Microsoft AES Cryptographic Provider.

Windows 2000/NT: This algorithm is not supported.
cs:CALG_AES_1920000660fh192 bit AES. This algorithm is supported by the Microsoft AES Cryptographic Provider.

Windows 2000/NT: This algorithm is not supported.
cs:CALG_AES_25600006610h256 bit AES. This algorithm is supported by the Microsoft AES Cryptographic Provider.

Windows 2000/NT: This algorithm is not supported.
cs:CALG_AGREEDKEY_ANY0000aa03hTemporary algorithm identifier for handles of Diffie-Hellman–agreed keys.
cs:CALG_CYLINK_MEK0000660chAn algorithm to create a 40-bit DES key that has parity bits and zeroed key bits to make its key length 64 bits. This algorithm is supported by the Microsoft Base Cryptographic Provider.
cs:CALG_DES00006601hDES encryption algorithm.
cs:CALG_DESX00006604hDESX encryption algorithm.
cs:CALG_DH_EPHEM0000aa02hDiffie-Hellman ephemeral key exchange algorithm.
cs:CALG_DH_SF0000aa01hDiffie-Hellman store and forward key exchange algorithm.
cs:CALG_DSS_SIGN00002200hDSA public key signature algorithm.
cs:CALG_ECDH0000aa05hElliptic curve Diffie-Hellman key exchange algorithm.

Windows Server 2003, Windows XP, and Windows 2000/NT: This algorithm is not supported.
cs:CALG_ECDSA00002203hElliptic curve digital signature algorithm.

Windows Server 2003, Windows XP, and Windows 2000/NT: This algorithm is not supported.
cs:CALG_ECMQV0000a001hElliptic curve Menezes, Qu, and Vanstone (MQV) key exchange algorithm.

Windows Server 2003, Windows XP, and Windows 2000/NT: This algorithm is not supported.
cs:CALG_HASH_REPLACE_OWF0000800bhOne way function hashing algorithm.

Windows 2000/NT: This algorithm is not supported.
cs:CALG_HUGHES_MD50000a003hHughes MD5 hashing algorithm.
cs:CALG_HMAC00008009hHMAC keyed hash algorithm. This algorithm is supported by the Microsoft Base Cryptographic Provider.
cs:CALG_KEA_KEYX0000aa04hKEA key exchange algorithm (FORTEZZA).
cs:CALG_MAC00008005hMAC keyed hash algorithm. This algorithm is supported by the Microsoft Base Cryptographic Provider.
cs:CALG_MD200008001hMD2 hashing algorithm. This algorithm is supported by the Microsoft Base Cryptographic Provider.
cs:CALG_MD400008002hMD4 hashing algorithm.
cs:CALG_MD500008003hMD5 hashing algorithm. This algorithm is supported by the Microsoft Base Cryptographic Provider.
cs:CALG_NO_SIGN00002000hNo signature algorithm.

Windows 2000/NT: This algorithm is not supported.
cs:CALG_OID_INFO_CNG_ONLYffffffffhThe algorithm is only implemented in CNG. The macro, IS_SPECIAL_OID_INFO_ALGID, can be used to determine whether a cryptography algorithm is only supported by using the CNG functions.
cs:CALG_OID_INFO_PARAMETERSfffffffehThe algorithm is defined in the encoded parameters. The algorithm is only supported by using CNG. The macro, IS_SPECIAL_OID_INFO_ALGID, can be used to determine whether a cryptography algorithm is only supported by using the CNG functions.
cs:CALG_PCT1_MASTER00004c04h Used by the Schannel.dll operations system. This ALG_ID should not be used by applications.
cs:CALG_RC200006602hvRC2 block encryption algorithm. This algorithm is supported by the Microsoft Base Cryptographic Provider.
cs:CALG_RC400006801h RC4 stream encryption algorithm. This algorithm is supported by the Microsoft Base Cryptographic Provider.
cs:CALG_RC50000660dhRC5 block encryption algorithm.
cs:CALG_RSA_KEYX0000a400h RSA public key exchange algorithm. This algorithm is supported by the Microsoft Base Cryptographic Provider.
cs:CALG_RSA_SIGN00002400h RSA public key signature algorithm. This algorithm is supported by the Microsoft Base Cryptographic Provider.
cs:CALG_SCHANNEL_ENC_KEY00004c07hUsed by the Schannel.dll operations system. This ALG_ID should not be used by applications.
cs:CALG_SCHANNEL_MAC_KEY00004c03h Used by the Schannel.dll operations system. This ALG_ID should not be used by applications.
cs:CALG_SCHANNEL_MASTER_HASH00004c02h Used by the Schannel.dll operations system. This ALG_ID should not be used by applications.
cs:CALG_SEAL00006802h SEAL encryption algorithm.
cs:CALG_SHA00008004h SHA hashing algorithm. This algorithm is supported by the Microsoft Base Cryptographic Provider.
cs:CALG_SHA100008004h Same as CALG_SHA. This algorithm is supported by the Microsoft Base Cryptographic Provider.
cs:CALG_SHA_2560000800ch256 bit SHA hashing algorithm. This algorithm is supported by the Microsoft Base Cryptographic Provider.

Windows XP and Windows 2000/NT: This algorithm is not supported.
cs:CALG_SHA_3840000800dh384 bit SHA hashing algorithm. This algorithm is supported by the Microsoft Base Cryptographic Provider.

Windows XP and Windows 2000/NT: This algorithm is not supported.
cs:CALG_SHA_5120000800eh512 bit SHA hashing algorithm. This algorithm is supported by the Microsoft Base Cryptographic Provider.

Windows XP and Windows 2000/NT: This algorithm is not supported.
cs:CALG_SKIPJACK0000660ahSkipjack block encryption algorithm (FORTEZZA).
cs:CALG_SSL2_MASTER00004c05h Used by the Schannel.dll operations system. This ALG_ID should not be used by applications.
cs:CALG_SSL3_MASTER00004c01h Used by the Schannel.dll operations system. This ALG_ID should not be used by applications.
cs:CALG_SSL3_SHAMD500008008h Used by the Schannel.dll operations system. This ALG_ID should not be used by applications.
cs:CALG_TEK0000660bhTEK (FORTEZZA).
cs:CALG_TLS1_MASTER00004c06h Used by the Schannel.dll operations system. This ALG_ID should not be used by applications.
cs:CALG_TLS1PRF0000800ah Used by the Schannel.dll operations system. This ALG_ID should not be used by applications.

Internal Methods

_CheckCertificate Procedure (PCCERT_CONTEXT pCertContext, HCRYPTPROV phCryptProv), long, proc

_CryptAcquireContext Procedure (*HCRYPTPROV phProv, LPSTR pszContainer, LPSTR pszProvider, DWORD dwFlags), long, proc

_FindCertificate Procedure (HCRYPTPROV hCryptProv, HCERTSTORE hCertStore, *cstring certId, *PCCERT_CONTEXT ppCertContext, bool pSubject=false), long, proc

_FindRDNAttr Procedure (*cstring pszAttrId, PCCERT_CONTEXT pCertContext, *long pAttr),bool, proc

_GetCertChain Procedure (PCCERT_CONTEXT pSignerCert, *DSUserDataForVerify pVerifyArg), long, proc

_GetIdentityList Procedure (long pCsp, *cstring pSubstring, bool pOnlyValidCerts, *MsgQType pListQ), long, proc

_GetIssuerCert Procedure (PCCERT_CONTEXT pSignerCert, HCRYPTPROV hCryptProv, *HCERTSTORE pStore, *PCCERT_CONTEXT pIssuerCert), long, proc

_GetSubjectFromCert Procedure (*PCCERT_CONTEXT pCertContext, *cryCertFields certFields, bool wholeSubject=false), bool, proc

_LoadDLLs Procedure (),HANDLE, proc

_TestSignatureProperty  Procedure (PCCERT_CONTEXT pCertContext), long, proc

_TrustSigner Procedure (*DSUserDataForVerify pVerifyArg, CERT_INFO pCertInfo, string pSerial), long, proc

Cryptonite Blowfish Encryption and Decryption Methods

The Cryptonite class supports BlowFish encryption and decryption of strings and files. This uses the csBlowFish class that is a part of Cryptonite. The csBlowfish class can also be used directly without using the Cryptonite class, see the csBlowfish Class Documents.

Typically only two methods are required bfEncrypt and bfDecrypt. These handle all encryption and decryption tasks, padding, encoding etc.

Important Notes
  1. The plainText (the data being encrypted) can contain binary data, not just plain text data.
  2. The cipherText (encrypted data) is binary data. To store it in ASCII text form call the Base64Encode method convert it to Base64 encoded data.
  3. The cipherText is always the same size as the plainText is (the data size is maintained when encrypting and decrypting, so both forms are the same length), unless CBC or ECB mode is used with PKCS padding, which increase the length of the data by between 1 and 8 bytes. We recommend using CFB mode, or using the Cipher Text Stealing option rather than PKCS padding. PKCS padding is provided primarily for compatibility with other systems that may use the padding scheme. This is not true of Base64 encoding, which increases the data size when performning encoding. The Base64Encode method handles automatically increasing the size of the string when encoding for you.

Encryption and Decryption Examples

The examples below demonstrate encrypting and decrypting data using the Cryptonite Blowfish functionality, as well as Base64 and Hex encoding and decoding of the data and using Cryptonite to encrypt and decrypt data stored in StringTheory objects

Example 1

Using the bfEncrypt and bfDecrypt methods to handle all Blowfish encryption and decryption tasks. This is the simplest method and encapsulates all the tasks required for Blowfish encryption and decryption in two easy to use methods. See the Blowfish example application.
Example
bfCipher       Cryptonite
st             StringTheory
  code
    st.SetValue('Some Value to be Encrypted.')

    ! Encrypting the data and Base64 encoding it
    bfCipher.bfEncrypt(st, 'SomeSecretKey', 'd*L_9)E8', Crypto:CFB, Crypto:PadNone, Crypto:EncBase64)

    Message('Encrypted Data: ' & st.GetValue())

    ! Decrypt the data (and handle the Base64 encoding)
    bfCipher.bfDecrypt(st, 'SomeSecretKey', 'd*L_9)E8', Crypto:CFB, Crypto:PadNone, Crypto:EncBase64)

    Message('Decrypted Data: ' & st.GetValue())


Example 2

This example demonstrates using the bfEncryptString and bfDecryptString methods to encrypt and decrypt strings (which can contains binary data), as well as the bfEncrypt method to encrypt a StringTheory object. This approach requires the Blowfish object to be initialized and killed, as well as the options for the cipher mode and padding to the set manually. Any encoding also needs to be handled manually using StringTheory. In most cases the bfEncrypt and bfDecrypt methods demonstrated above provide a simpler and quicker approach.

Example
bfCipher        Class(Cryptonite)
                end
st              Class(StringTheory)
                end       
  code
    bfCipher.InitBlowfish('j.vnhK/xNf6\$rtYidR\v;o#^bubRL`.vf?/lVa_lawDE^I#XT1!C!n3')

    ! ----- Example 1 -----!
    ! Encrypt a string from a plainText string to a cipherText string (note that you can pass the
    ! same string as both plainText and cipherText to encrypt the string "in place"
    bfCipher.bfEncryptString(plainText, cipherText)

    ! Decrypt the string
    bfCipher.bfDecryptString(plainText, cipherText)


    ! ----- Example 2 -----!
    ! Encrypt and Base64 encode using StringTheory
    st.SetValue(password, true)  ! Store the value. It is text, so we clip it
    bfCipher.bfEncrypt(st)       ! Encrypt the string
    st.Base64Encode()            ! Base64 encode for display or transport
                                 ! (also see ToHex for hex encoding)
    password = st.GetValue()     ! password now contains encrypted, Base64 encoded data.


    ! Decrypt the Base64 encoded value
    ! Assign and clip (Base64 encoded data can be clipped even if the data is binary)
    st.SetValue(password, true)
    st.Base64Decode()
    bfCipher.bfDecrypt(st)
    password = st.GetValue()
   
    bfCipher.KillBlowfish()

See the methods below for additional examples.

bfDecrypt

bfDecrypt (*StringTheory st, string pbKey, string pIV, long pMode=Crypto:CFB, long pPad=Crypto:PadNone, long pEnc=Crypto:EncNone), bool, proc, virtual

Description

Decrypts the current value stored in the passed StringTheory objects. This method handles initializes and destroying the Blowfish object, setting the key, padding and encryption modes and any encoding required automatically.

Parameters
Parameter Description
stA StringTheory object that contains the data to be decrypted (and optionally decoded). Can contain binary data.
pbKeyA string that contains the key to use for decryption. The maximum key length is 56 bytes (448 bits). This is treated as binary data.
pIV An Initialization Vector. Used to increase the security of the encrypted data. Should be 8 bytes of random data. This is treated as binary data. The same IV is required when encrypting the data (the IV does not need to be protected and can be sent with the data as plain text without compromising the strength of the encryption).
pMode [optional] The mode used when encrypting the data. This changes the way that each block is encrypted. The default is Crypto:CFB, which is Cipher Feedback mode. This is secure and can encrypted any length of data. This is the recommended mode.

Other modes supported are:

Crypto:ECB
- Electronic codebook. This is the least secure mode of operation and simply encrypts each block of 8 bytes. It requires padding or cipher text steal to be used to encrypt data that isn't a multiple of 8 bytes. This mode is only recommended for compatibility with other systems that use it. It does not hide data patterns well and cannot be considered to provide a serious level of security.

Crypto:CBC
- Cipher block chaining. Provides secure encryption that effectively hides data patterns and is cryptographically as strong as the default CFB mode is. This mode is only recommended for compatibility with other systems that use it.
pPad [optional] Sets the padding mode. This only applies when the pMode parameter is set to Crypto:ECB or Crypto:CBC. By default no padding is used. For ECB and CBC mode encryption padding is required for encrypt data of any length as the encryption modes only encrypt blocks of 8 bytes. Can be one of the following values:

Crypto:PadNone
- No padding (the default). Use this for CFB mode (which doesn't required padding) or when no padding is required.

Crypto:PadPKCS
- PKCS #7 style padding. Pads the data to a multiple of 8 bytes using the number of bytes as the value for each pad byte. Note that this adds a full 8 byte block of padding when encrypting data that is a multiple of 8 bytes in length.

Crypto:PadTextStealing
- Uses Cipher Text Stealing rather than padding to allow any length of data to be encrypted using ECB or CBC mode. The ciphertext (encrypted data) is the same length as the plaintext (unencrypted data).
pEnc [optional]Optional parameter that allows the data to be decoded before decryption. The encrypted data (ciphertext) is binary and is typically encoded for storage or transfer as plain text. Can be one of the following values:

Crypto:EncNone
- No encoding is used.

Crypto:EncBase64
- Base64 encoding. Uses standard Base 64 encoding which encodes the binary data to plain ASCII text. The size of the data increases by approximately 25% and is padded to a multiple of 4 bytes.

Crypto:EncHex
- Hexadecimal encoding. Encodes the data to plain text, where each byte is presented by the hexadecimal value for that byte stored as two plain text characters. This doubles the length of the data.
Return Value

Returns True (1) if successful and False (0) if encryption fails.

Example
Example
st                  StringTheory
iv string(8)
code
encData = 'WfNGgTDm4eo9F52RMv9Wtw==' ! Some data to decrypt (Base64 encoded in this case)
iv = 'd*L_9)E8' ! An initialization vector
encKey = 'DMP09dh0NDnd0a8s-32-M+J93n30#fHh' ! The encryption key (up to 56 bytes of binary data)
st.SetValue(encData, true) ! Store the data

! Base64 decode the data and then decrypt it uses CFB (the default) mode.
bfCipher.bfDecrypt(st, encKey, iv, Crypto:CFB, Crypto:PadNone, Crypto:EncBase64)

encData = st.GetValue() ! Retrieve the data

bfEncrypt

bfEncrypt (*StringTheory st, string pbKey, string pIV, long pMode=Crypto:CFB, long pPad=Crypto:PadNone, long pEnc=Crypto:EncNone), bool, proc, virtual

Description

Encrypts the current value stored in the passed StringTheory objects. This method handles initializes and destroying the Blowfish object, setting the key, padding and encryption modes and any encoding required automatically.

Parameters
Parameter Description
stA StringTheory object that contains the data to be encrypted (and optionally encoded). Can contain binary data.
pbKey A string that contains the key to use for encryption. The maximum key length is 56 bytes (448 bits). This is treated as binary data.
pIV An Initialization Vector. Used to increase the security of the resultant encrypted data. Should be 8 bytes of random data. This is treated as binary data. The same IV is required when decrypting the data (the IV does not need to be protected and can be sent with the data as plain text without compromising the strength of the encryption).
pMode [optional]The encryption mode. This changes the way that each block is encryped. The default is Crypto:CFB, which is Cipher Feedback mode. This is secure and can encrypted any length of data. This is the recommended mode.

Other modes supported are:

Crypto:ECB - Electronic codebook. This is the least secure mode of operation and simply encrypts each block of 8 bytes. It requires padding or cipher text steal to be used to encrypt data that isn't a multiple of 8 bytes. This mode is only recommended for compatibility with other systems that use it. It does not hide data patterns well and cannot be considered to provide a serious level of security.

Crypto:CBC - Cipher block chaining. Provides secure encryption that effectively hides data patterns and is cryptographically as strong as the default CFB mode is. This mode is only recommended for compatibility with other systems that use it.
pPad [optional]Sets the padding mode. This only applies when the pMode parameter is set to Crypto:ECB or Crypto:CBC. By default no padding is used. For ECB and CBC mode encryption padding is required for encrypt data of any length as the encryption modes only encrypt blocks of 8 bytes. Can be one of the following values:

Crypto:PadNone - No padding (the default). Use this for CFB mode (which doesn't required padding) or when no padding is required.

Crypto:PadPKCS - PKCS #7 style padding. Pads the data to a multiple of 8 bytes using the number of bytes as the value for each pad byte. Note that this adds a full 8 byte block of padding when encrypting data that is a multiple of 8 bytes in length.

Crypto:PadTextStealing - Uses Cipher Text Stealing rather than padding to allow any length of data to be encrypted using ECB or CBC mode. The ciphertext (encrypted data) is the same length as the plaintext (unencrypted data).
pEnc [optional]Optional parameter that allows the data to be encoded after encryption. The encrypted data (ciphertext) is binary and is typically encoded for storage or transfer as plain text. Can be one of the following values:

Crypto:EncNone
- No encoding is used.

Crypto:EncBase64
- Base64 encoding. Uses standard Base 64 encoding which encodes the binary data to plain ASCII text. The size of the data increases by approximately 25% and is padded to a multiple of 4 bytes.

Crypto:EncHex
- Hexadecimal encoding. Encodes the data to plain text, where each byte is presented by the hexadecimal value for that byte stored as two plain text characters. This doubles the length of the data.

 

Return Value

Returns True (1) if successful and False (0) if encryption fails.

Example
Example
st                  StringTheory
iv string(8)
code
encData = 'I have a secret' ! Some data to encrypt
iv = 'd*L_9)E8' ! An initialization vector
encKey = 'DMP09dh0NDnd0a8s-32-M+J93n30#fHh' ! The encryption key
st.SetValue(encData, true) ! Store the data

! Encrypt using CFB mode and Base64 encode the result
bfCipher.bfEncrypt(st, encKey, iv, Crypto:CFB, Crypto:PadNone, Crypto:EncBase64)

encData = st.GetValue() ! Retrieve the data

bfEncrypt

bfEncrypt (*StringTheory st)

Description

A manual alternative to the bfEncrypt method above. Encrypts the current value stored in the StringTheory object using the current class settings. In almost all cases the bfEncrypt and bfDecrypt methods provide a better approach than this and encapsulate all of the functionality provided.

Requires the Blowfish object to be initialized and the encryption parameters to be set manually. Does not provide any handling for encoding (the StringTheory methods need to be called manually for this, which is demonstrated in the example below).

See the "MoreFish.app" example in the Blowfish example folder.

Parameters
Parameter Description
stA StringTheory object that contains the data to be encrypted. Can contain binary data.
Return Value

Returns True (1) if successful and False (0) if encryption fails.

Example
Example
st                StringTheory
cipher            Cryptonite
encData           string(4096)
encKey            string(112)
iv                string(8)
  code
    ! Generate a cryptographically random initialization vector for CBC and CBF modes
    cipher.GetContainer('OurTempContainer', true)
    cipher.GenRandom(iv)     ! Fill the IV (Initialization Vector) with cryptographically random data
    
    ! Set the key (which is stored as a hexadecimal string in this case
    ! and needs to be decoded first before being used)    
    encKey = '1C587F1C13924FEF'         ! A hexademical encoded key  
    st.SetValue(encKey, true)           ! Store the key value
    st.FromHex()                        ! Decode the hex string

    ! Cipher parameters
    cipher.bfSetKey(st.value)           ! Set the key value, create the csBlowfish object if required
    cipher.bfSetMode(Crypto:CFB)        ! Cipher Feedback mode (recommended)
    cipher.bfSetPadding(Crypto:PadNone) ! No padding is required for CFB mode
    cipher.bfSetIv(iv)                  ! Set the Initialization Vector to the 8 random bytes generated above
	
    encData = 'A box without hinges, key, or lid,<13,10>' |
              'Yet golden treasure inside is hid.'
    st.SetValue(encData, true)          ! Store the data to be encrypted

    if not cipher.bfEncrypt(st)
        Message('Encrypting the data failed', 'Blowfish Encryption Error')
    else
       ! Base64 encode the encrypted data so that it can be stored 
       ! and transmitted as plain text. Retrieve the encrypted 
       ! and base64 encoded data from the StringTheory object.
        st.Base64Encode()        
        encData = st.GetValue()
    end

    ! We don't need the container to be retained as it was only for random data generation
    cipher.DeleteContainer('OurTempContainer')              
	
    ! IMPORTANT: The Initialization Vector that was created needs to be stored as it
    ! is required to decrypt the data. The IV itself does not need to be protected.

bfDecrypt

bfDecrypt (*StringTheory st)

Description

A manual alternative to the bfDecrypt method above. Decrypts the current value stored in the StringTheory object. See Important Notes for more information.  In almost all cases the bfEncrypt and bfDecrypt methods provide a better approach than this and encapsulate all of the functionality provided.

See the "MoreFish.app" example in the Blowfish example folder.

Parameters
Parameter Description
stA StringTheory object that contains the data to be decrypted. The encrypted data is binary (if it was encoded for storage it must be decoded before calling bfDecrypt).
Return Value

Returns True (1) if successful and False (0) if encryption fails.

Example
Example
st                StringTheory
cipher            Cryptonite
encData           string(4096)
encKey            string(112)
  code
    
    ! Set the key (which is stored as a hexadecimal string in this case
    ! and needs to be decoded first before being used)   
    encKey = '1C587F1C13924FEF'         ! A hexademical encoded key
    
    st.SetValue(encKey, true)           ! Store the key value
    st.FromHex()                        ! Decode the hex string

    ! Cipher parameters
    cipher.bfSetKey(st.value)           ! Set the key value, create the csBlowfish object if required
    cipher.bfSetMode(Crypto:CFB)        ! Cipher Feedback mode (recommended)
    cipher.bfSetPadding(Crypto:PadNone) ! No padding is required for CFB mode
    cipher.bfSetIv(iv)                  ! Set the Initialization Vector to the value that was used when encrypting

    ! Store the encrypted (and Base64 encoded) data
    encData = 'qF1rN/0uyDZZqHNwKmowaJ6XbfZIcTV+KdlLwCtX' |
            & 'qnGAaIVgomK9aDWKtRG5i9LjqwoRzboaztQwQTjZ' |
            & 'Bl9cMIMYm5jboQ=='
    st.SetValue(encData, true)          ! Store the data to be decrypted

    if not cipher.bfDecrypt(st)
        Message('Decrypting the data failed', 'Blowfish Decryption Error')
    else
        encData = st.GetValue()
    end	

bfEncryptString

bfEncryptString (*string plainText, *string cipherText)

Description

Encrypts the passed plainText string and stores the encrypted data in the passed cipherText string. See Important Notes for more information. The cipherText string should be at least the same length as the plainText string in order to store the encrypted data.

Parameters
Parameter Description
plainTextA string to store the decrypted data that results from decrypting the passed cipherText.
cipherTextThe data to decrypt
Return Value

Returns True (1) if succesful and False (0) if encryption fails.

Example
Example
s           Cryptonite
 
code
    s.InitBlowfish('
j.vnhK/xNf6\$rtYidR\v;o#^bubRL`.vf?/lVa_lawDE^I#XT1!C!n3')
    s.EncryptString(plainText, cipherText)

bfDecryptString

bfDecryptString (*string plainText, *string cipherText)

Description

Decrypts the passed cipherText string and stores the decrypted data in the passed plainText string. See Important Notes for more information. The plainText string should be at least the same length as the chipherText string in order to hold the data.

Parameters
Parameter Description
plainTextA string to store the decrypted data that results from decrypting the passed cipherText.
cipherTextThe data to decrypt
Return Value

Returns True (1) if succesful and False (0) if encryption fails.

Example
Example
s           Cryptonite
 
code
    s.InitBlowfish('
j.vnhK/xNf6\$rtYidR\v;o#^bubRL`.vf?/lVa_lawDE^I#XT1!C!n3')
    s.bfDecryptString(plainText, cipherText)

bfSetKey

bfSetKey (string key)

Description

This is the equivilent of calling the Init method. Setting the key involves clearing and recreating the S-Boxes used for encryption, so setting the key and initializing the object requires exactly the same process. Note that the key itself is not retained within the object, so the variable used to store it can be cleared as soon as the method returns (Once the S-Boxes have been created, they are no longer needed).

Parameters
Parameter Description
keyThe key to use for encryption. This string contains a binary value and can be up to 56 bytes (characters) long (448bit). Typically you should provide a string that is exactly 56 bytes in length.

InitBlowfish

InitBlowfish(string key)

Initialises the Blowfish object. This must be called before any of the other Blowfish methods are used.

Parameters
Parameter Description
keyThe key to use for encryption. This string contains a binary value and can be up to 56 bytes (characters) long (448bit). Typically you should provide a string that is exactly 56 bytes in length.
Return Value

Returns True (1) if succesful and False (0) if encryption fails.

Example
Example
s              Cryptonite
plainText string(256) ! unencrypted value
cipherText string(256) ! encrypted value
code
s.InitBlowfish('j.vnhK/xNf6\$rtYidR\v;o#^bubRL`.vf?/lVa_lawDE^I#XT1!C!n3')
plainText = 'Shhh, it's a secret!'
s.EncryptString(plainText, cipherText)
s.KillBlowFish

KillBlowfish

KillBlowfish ()

Description

Cleans up and deallocates memory. Will be called automatically when the Cryptonite object is destroyed.

Return Value

None

Example
Example
s              Cryptonite
plainText string(256) ! unencrypted value
cipherText string(256) ! encrypted value
code
s.InitBlowfish('j.vnhK/xNf6\$rtYidR\v;o#^bubRL`.vf?/lVa_lawDE^I#XT1!C!n3')
plainText = 'Shhh, it's a secret!'
s.EncryptString(plainText, cipherText)
s.KillBlowFish

Cryptonite Property Reference

Cryptonite Property Reference
HashAlgorithmstring(40)The hashing algorithm to use. Defaults to SHA-1.
CSPcstring(MaxFilenameLen)The name of the Cryptographic Service Provider currently in use
provTypeDWORDThe type of the CSP acquired.
hProviderHCRYPTPROV Handle to a CSP context, this stores the currently acquired context
Storage and handles for the exchange and sign keys
hExchangeKeyHCRYPTKEYHandle to the exchange public/private key pair.
hSignKeyHCRYPTKEYHandle to the signature public/private key pair, used for signing encrypted messages. Note that this is not used in normal usage - the Exchange and Signing key pair are the same.
hCryptKeyHCRYPTKEYHandle to the key created by CryptImportKey (session keys etc.)
hHashHCRYPTHASHHandle to a hashing object
keyStorageAlglongDefault algorithm for encrypting exported exchange key BLOBs
exchangeKeyBlob&stringStorage for the exchange key BLOB, used for exporting the exchange key pair (the private key should be encrypted)
signKeyBlob&stringStorage for the signature key BLOB
sessionKeyBlob&stringSession Key BLOB storage
iv&stringInitialization vector for block ciphers
exchangeBlobSizelongSize of the exchangeKeyBlob, assigned by the ExportKey function when the key BLOB is created
signBlobSizelongSize of the signKeyBlob
sessionBlobSizelongSession key blob size
defaultHash
The default hashing algorithm (set to SHA-1 when the object is initialized).
encryptBlockSizelongTypically 1 for stream ciphers, 8 for block ciphers. Defaults to 1 (stream cipher) if not set.
logginglongIf this is set to True (1) then errors are logged to the system debug output. This output can be viewed using a debugging tool such as DebugView (free from Microsoft Technet). The output and error can be trapped using the ErrorTrap method to customize the behavior. This option is particularly useful for providing debug output that can be enabled or disabled at runtime.
displayErrorslongIf this is set to True (1) then errors are displayed to the user using the Clarion Message() function. This flag can be turned on and off as needed. The output and error can be trapped using the ErrorTrap method to customize the behavior.

csBlowfish

Using the csBlowfish class

csBlowfish Method Reference

Blowfish

The csBlowfish class provides Blowfish encryption and decryption, along with support for multiple encryption modes (ECB, CBC and CBF) and padding options (PKCS compatible and Cipher Text Stealing) to allow data of any length of be encrypted and decrypted.
InitInitializes the Blowfish object, sets the key, and creates the S-Boxes used for encryption.
EncryptEncrypts a string of data
DecryptDecrypts a string of data
SetModeSets the encryption mode to ECB, CBC or CFB
SetPaddingSets the padding to PKCS or Cipher Text Stealing
SetKeySets the key (identical to calling Init)
SetIVSets the Initialization Vector used in CBC and CFB mode
SetMultiBlockSets whether the object is in multi-block mode. This is used to allow the Encrypt method to be called multiple times to encrypt the data in blocks, for example when loading large amounts of data from disk.
ResetChainResets the encryption chain to the Initialization Vector. Called by Encrypt and Decrypt if the .multiBlock property is not set to True.
ConstructConstructor.
DestructDestructor, releasing memory, clears data. Called when the object goes out of scope.
_EncryptInternal encryption of a 64 bit block using a 16 round cipher
_DecryptInternal decryption of a 64bit block using a 16 round cipher
_EncryptECBInternal method which implements ECB mode encryption.
_EncryptCBCInternal method which implements ECB mode encryption.
_EncryptCFBInternal method which implements ECB mode encryption.
_DecryptECBInternal method which implements ECB mode encryption.
_DecryptCBCInternal method which implements ECB mode encryption.
_DecryptCFBInternal method which implements ECB mode encryption.
_PArrayIntializes the PArray at construction. The array only needs to be initialized once, and thereafter it is used in the creation of the key dependant S-Boxes for each key used.
_SBoxIntializes the S-Box at construction. The array only needs to be initialized once, and thereafter it is used in the creation of the key dependant S-Boxes for each key used.
FFiestal cipher - F(xL) = ((S1,a + S2,b mod 232) XOR S3,c) + S4,d mod 232
_WriteBoxesInternal debug methods, writes the S-Boxes to disk using the C++ array syntax.

csBlowfish Property Reference

modeThe encryption mode, can be set to ECB, CBC or CBF mode encryption.
paddingAllows PKCS padding or Cipher Text Stealing to be enabled for ECB and CBC modes. Allows data of any length to be encrypted and decrypted.
multiblockResets the encryption chain to the Initialization Vector. Called by Encrypt and Decrypt if the .multiBlock property is not set to True. Set to True to allow encryption of large amounts of data in blocks of any size in CBC and CFB mode.
ivThe initialization vector for CBC and CFB modes. Call SetIV to set this.
chainInternal property. Used to store the encryption chain in CBC and CFB modes when the multiBlock property is set to True.
PInternal property. The PArray used for building the S-Boxes
SInternal property. The S-Boxes for the current key

Using the csBlowfish Class

Important Notes and terminology
  1. Plaintext refers to unencrypted data. It can contain binary data, not just "text" data.
  2. Ciphertext refers to encrypted data. Because this is binary data, not ASCII text it should be encoded to store it as text data. Call the Base64Encode method convert it to Base64 encoded data, which contains only 7-bit ASCII characters and can be used to store or transmit the encrypted data is text.
  3. The Ciphertext is always the same size as the Plaintext is (the data size is maintained when encrypting and decrypting, so both forms are the same length), unless CBC or ECB mode is used with PKCS padding, which increase the length of the data by between 1 and 8 bytes. We recommend using CFB mode, or using the Cipher Text Stealing option rather than PKCS padding. PKCS padding is provided primarily for compatibility with other systems that may use the padding scheme. This is not true of Base64 encoding, which increases the data size when performning encoding. The Base64Encode method handles automatically increasing the size of the string when encoding for you.
  4. There are three modes of encryption, which can be set using the .mode property of the class.


    1. csBlowfish.mode = Crypto:ECB

      Electronic Code Book mode encrypts each block of 8 bytes (64 bits) independantly. These blocks are appended to one another to form the Ciphertext. Because each block must be 64 bits long it cannot encrypt data that is not a multiple of 8 bytes without using padding or cipher text stealing, both of which are supported (see below). This mode is not recommended for use, as it does not provide serious message confidentially. Use the CBC or CFB modes instead.
    2. csBlowfish.mode = Crypto:CBC

      Cipher Block Chaining mode uses an Initialization Vector (an intial 8 byte block of data, usually random) for encryption and each block is dependant on the previous block. This mode is significantly more secure than ECB mode and can be safely used. For data where the length is not a multiple of 8 bytes it still requires that the padding or cipher text stealing options are used.
    3. csBlowfish.mode = Crypto:CFB (recommended)

      Cipher Feedback mode is similar to CBC, in that it uses an intialization vector, and each block is dependant on the last one, however it turns the block cipher into a stream cipher, allowing any length of data to be encrypted. This is the recommended mode.
  5. Padding and Cipher Text Stealing

    Cryptonite implements two schemes for allowing data of any length to be encrypted and decrypted using ECB and CBC modes mode:

    1. The first is Cipher Text Stealing, which allows any length of data to be encrypted and the Ciphertext is the same length as the Plaintext. Set the .padding property to Crypto:PadTextSteal to use this option.
    2. The second is padding using the same scheme as used in the PKCS#5 and #7 standards. The Ciphertext that is produces is between 1 and 8 bytes longer than the Plaintext. This is not recommend except for compatibility with external systems. Set the .padding property to Crypto:PadPKCS to use this option.
Using the Object

The basic usage is as follows:
cipher       csBlowfish
code
cipher.Init(key)
cipher.Encrypt(plainText, cipherText)

cipher.Decrypt(cipherText, plainText)
cipher.Kill()

csBlowfish Class Method Reference

Commonly Used Methods

Init

Init (*string key, long keyLen=0, <*SBlock chain>, long padding=-1, long mode=-1), bool, proc, virtual

Description

Intializes the object and creates the S-Boxes used for encryption using the passed key. Optionally sets the Intialization Vector, padding and cipher mode.

Parameters
Parameter Description
keyThe key to use for encryption, should be between 1 and 56 bytes
keyLenThe length of the key, in bytes
ivThe initialization vector
Returns

True if successful, False otherwise

Encrypt

Encrypt (*string in, *string out, long inLen=0, <*long outLen>,  long mode = -1), bool, proc, virtual

Descriptions

Encrypts the passed string using the Blowfish cipher. The object must have been initialised using a key before this method is called.

Parameters
Parameter Description
in The input plaintext to be encrypted.
Note: The term plaintext refers to unencrypted data, it does not imply that the data is text, it can be binary.
outThe output encrypted ciphertext. If ECB or CBC mode is used with PKCS padding, then this string must be large enough to hold the ciphertext (which will be between 1 and 8 bytes larger than the plaintext). For all other modes and options the ciphertext is the same size as the plaintext.
inLenOptional parameter. If not passed, or set to 0, the entire in string is assumed to contain the data to encrypt. If passed the specified number of bytes are encrypted rather than the entire string.
outLenOptional parameter, only used if ECB or CBC mode is used with PKCS padding. When the method returns this will be set to the size of the ciphertext with padding.
modeOptional parameter that allows the mode to be overridden. If not passed the .mode property is used. If passed, then this value is used for the mode instead. The value may be one of the following:
Crypto:ECB  (0)
Crypto:CBC  (1)
Crypto:CFB  (2)
Return Value

Returns True (1) for success and False (0) for failure.

Decrypt

Decrypt (*string in, *string out, long inLen=0, <*long outLen>, long mode = -1), bool, proc, virtual

Description

Decrypts the passed string of ciphertext.

Parameters
Parameter Description
inThe input ciphertext to be decrypted.
outThe output decrypted plaintext. If ECB or CBC mode is used with PKCS padding, then the plaintext will be between 1 and 8 bytes small than the ciphertext. For all other modes and options the ciphertext is the same size as the plaintext.

Note: The term plaintext simply means unencrypted (or decrypted) data. It does not imply that the data is text, it may be binary.
inLenOptional parameter. If not passed, or set to 0, the entire in string is assumed to contain the data to encrypt. If passed the specified number of bytes are encrypted rather than the entire string.
outLenOptional parameter, only used if ECB or CBC mode is used with PKCS padding. When the method returns this will be set to the size of the plaintext returned (the ciphertext will have been padded, and so the returned plaintext length will be between 1 and 8 bytes smaller than the ciphertext length).
modeOptional parameter that allows the mode to be overridden. If not passed the .mode property is used. If passed, then this value is used for the mode instead. The value may be one of the following:
Crypto:ECB  (0)
Crypto:CBC  (1)
Crypto:CFB  (2)
Return Value

Returns True (1) for success and False (0) for failure.

SetKey

SetKey (*string key, long keyLen=0, <*SBlock chain>, long padding=-1, long mode=-1), bool, proc, virtual

Description

Identical to calling the Init method.

Parameters
Parameter Description
keyThe key to use for encryption, should be between 1 and 56 bytes
keyLenThe length of the key, in bytes
ivThe initialization vector
Returns

True if successful, False otherwise

SetMode

SetMode (long mode), virtual

Description

Sets the cipher mode to ECB (Electronic Code Book), CBC (Cipher Block Chaining) or CFB (Cipher Feeback). Note: ECB mode does not provide serious message confidentiallity and is not recommended for general use (it is provided for compatibility with other systems using ECB mode).

Electronic codebook (ECB)

The simplest of the encryption modes is the electronic codebook (ECB) mode. The message is divided into blocks and each block is encrypted separately.

The disadvantage of this method is that identical plaintext blocks are encrypted into identical ciphertext blocks; thus, it does not hide data patterns well. In some senses, it doesn't provide serious message confidentiality, and it is not recommended for use in cryptographic protocols at all. A striking example of the degree to which ECB can leave plaintext data patterns in the ciphertext is shown below; a pixel-map version of the image on the left was encrypted with ECB mode to create the center image, versus a non-ECB mode for the right image.
Tux.jpg Tux ecb.jpg Tux secure.jpg
OriginalEncrypted using ECB modeModes other than ECB result
in pseudo-randomness
The image on the right is how the image might appear encrypted with CBC, CTR or any of the other more secure modes—indistinguishable from random noise. Note that the random appearance of the image on the right does not indicate whether the image has been securely encrypted; many kinds of insecure encryption have been developed which would produce output just as 'random-looking'.

ECB mode can also make protocols without integrity protection even more susceptible to replay attacks, since each block gets decrypted in exactly the same way. ECB mode requires message (plaintext) length is a multiple of the block size. Cryptonite provides both Cipher Text Stealing and PKCS padding options to allow any length of data with ECB mode. 

Cipher-block chaining (CBC)

In the cipher-block chaining (CBC) mode, each block of plaintext is XORed with the previous ciphertext block before being encrypted. This way, each ciphertext block is dependent on all plaintext blocks processed up to that point. Also, to make each message unique, an initialization vector must be used in the first block. CBC is the most commonly used mode of operation for ciphers. Like ECB mode, CBC mode requires message (plaintext) length is a multiple of the block size. Cryptonite provides both Cipher Text Stealing and PKCS padding options to allow any length of data with CBC mode. 

Cipher Feedback (CFB)

The cipher feedback (CFB) mode, a close relative of CBC, makes a block cipher into a self-synchronizing stream cipher. CFB uses an initialization vector, like CBC mode, but can be used with any length of data without using Cipher Text Stealing or padding.

Parameters
Parameter Description
modeThe value may be one of the following:
Crypto:ECB  (0)
Crypto:CBC  (1)
Crypto:CFB  (2)
Return Value

None

SetPadding

SetPadding (long padding) , virtual

Description

Sets the padding type to allow data of any length to be encrypted or decrypted when using ECB and CBC modes. The padding options have no meaning for CFB mode, as it handles data of any length.

For ECB and CBC modes Cipher Text Stealing (Crypto:PadTextSteal) is recommended. With cipher text stealing the plaintext and ciphertext are always the same length. PKCS compatible padding is also supported for compatibility with external system. PKCS padding pas the disadvantage that the ciphertext and plaintext will differ in length by 1 to 8 bytes.

Parameters
Parameter Description
paddingMay be one of the following values:
Crypto:PadNone
: No padding
Crypto:PadTextSteal
: Cipher text stealing
Crypto:PadPKCS
: PKCS padding

SetIv

SetIv (*string iv), virtual

Description

Sets the Initialization Vector for CBC and CFB modes. The same IV must be used for both encryption and decryption, and a random IV should be used for each piece of data to ensure maximum confidentially.

SetMultiBlock

SetMultiBlock (long bool), virtual

Description

If this is enabled the chain for CBC and CFB modes is not cleared between calls to Encrypt and Decrypt. This allows very large amounts of data to be processed in sections, so not all the data has to be in memory at the same time. If this option is being called the ResetChain method should be used to reset the chain to the IV to encrypt a different set of data if the same IV is being used (or SetIV should be called to set a new IV).

ResetChain

ResetChain (), virtual

Description

Reset the chain to the original IV in CBC and CFB modes.

Internal Methods

Construct

Construct ()

Description

Object Constructor

Destruct

Destruct ()

Description

Object Destructor

_Encrypt

Encrypt (*SBlock sb), virtual

Description

Sixteen round Fiestel network block cipher

_Decrypt

_Decrypt (*SBlock sb), virtual

Description

Sixteen round Fiestel network block decipher

_EncryptECB

_EncryptECB (*string in, *string out, long inLen, long padLen), virtual

Description

Wraps the ECB encryption process, handling padding and cipher text stealing options.

_EncryptCBC

_EncryptCBC Procedure(*string in, *string out, long inLen, long padLen), virtual

Description

Wraps the CBC encryption process, handling padding and cipher text stealing options.

_EncryptCFB

_EncryptCFB (*string in, *string out, long inLen), virtual

Description

Wraps the CFB encryption process, handling padding and cipher text stealing options.

_DecryptECB

_DecryptECB Procedure(*string in, *string out, long inLen, long padLen), virtual

Description

Wraps the ECB decryption process, handling padding and cipher text stealing options.

_DecryptCBC

_DecryptCBC (*string in, *string out, long inLen, long padLen), virtual

Description

Wraps the CBC decryption process, handling padding and cipher text stealing options.

_DecryptCFB

_DecryptCFB (*string in, *string out, long inLen), virtual

Description

Wraps the CFB decryption process, handling padding and cipher text stealing options.

_PArray

_PArray (), virtual

Description

Populates the intial array of digits of Pi (after the decimal point) used in the construction of the S-Boxes.

_SBox

_SBox (), virtual

Description

Populates the initial S-Box value

F

F (ulong x, bool debug=false), ulong, virtual

Description

Fiestel function.

_WriteBoxes

_WriteBoxes (long state=0), virtual

Description

Debug method, writes out the PArray and SBox array to a pair of text files (parray.txt and sbox.txt) using C/C++ array syntax to allow easy verification of the values.

csBlowfish Class Property Reference

Commonly Used Properties
padding long The type of padding (if any) to allow data of any length to be encrypted. Can be set to Cipher Text Steal (Crypto:PadTextSteal), which is the recommended option for ECB and CBC modes; or to PKCS padding (Crypto:PKCS), which is not recommended except for compatibility as the length of the cipher text is not equal to the length of the plaintext using this padding scheme.
modelong The encryption mode (ECB, CBC, CFB). CFB mode is recommended as it provides message confidentially and operates like a stream cipher (it can encrypt and decrypt data of any length). CBC mode also provides message confidentially, however either PKCS padding or Cipher Text Stealing has to be used to encrypt data where the length is not a multiple of 8 bytes (Cipher Text Stealing is recommended - see the .padding property). ECB mode is not recommended as it does not provide serious message confidentially. Use only for compatibility with other systems that use ECB mode.
multiBlockbool If set, the chain will not be cleared between calls, allowing data to be encrypted in blocks of any size. This is used if multiple calls need to be made to encrypt the data in section using CBC or CBF mode. An example of this would be encrypting a file from which is loaded in blocks rather than in one go. This allows very large amounts of data to be broken up. Breaking up the data using a block size that is a multiple of the Blowfish Cipher block size (8 bytes) is recommended for optimum efficiency (except for the final block, which can be any size).
Occasionally Used Properties
iv &SBlock

The Initialization vector. Can be set directly, but is typically set by calling SetIv(), or by passing the desired IV to the Init method.

chain&SBlock

Stores the current chain. Used primarily for maintaining the chain between call to Encrypt and Decrypt.

Internal Properties
P ulong, dim(18)The array of values of Pi, XOR'd with the key bits.
Sulong, dim(4, 256)The S-Boxes created when the object is initialized with a key.

FAQ - Frequently Asked Questions

Check out general product CompilerErrors.

  1. Unresolved Externals when compiling using Cryptonite:

    Unresolved External PFXIsPFXBlob in Cryptonite.obj
    Unresolved External PFXImportCertStore in Cryptonite.obj


  2. The Crypt32.lib being included in the Project is an old version. The simplest solution is to manually delete copies of this LIB in the Clarion or application directories and reinstall the latest release of Cryptonite.

  3. Cryptonite.Error in Cryptonite.AcquireContext - Windows Crypto API Error 5 : Access is Denied.

    Change the permissions of C:\ProgramData\Microsoft\Crypto\RSA and C:\ProgramData\Microsoft\Crypto folders so that everyone has full access to these folders. These folders are used by the Windows Crypto API.

     ICACLS C:\ProgramData\Microsoft\Crypto\RSA /grant "Authenticated Users":(M)
  4. Cryptonite.Error in Cryptonite.AcquireContext - Error 2: Unknown Error 2 ... error 1359: 054h: An Internal Error Occured.

    One of the key files in the C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys folder is corrupted. Delete all the files in that folder and run the program again.
  5. Problem with encrypting / decrypting

    The ESET Anti-Virus (and others) are using a system called HIPS (Host-Based Intrusion Prevention System) which blocks access to the Crypto API functions in some cases. (https://support.eset.com/en/kb3755-host-based-intrusion-prevention-system-hipsadvanced-setup). You may need to add your program as an exception to the anti-virus package.
  6. Windows Server 2016

    Most installs on Windows Server 2016 have no problems, but in one case it has been reported that it was necessary to make sure the 2018-05 Cumulative Update for Windows Server 2016 for x64 based Systems (KB4103720) was installed in order for Cryptonite to work.
  7. Programs runs Elevated, but does not run when in non-elevated mode.

    Change the permissions of C:\ProgramData\Microsoft\Crypto\RSA and C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys so that everyone has full access to the folders. These folders are used by the Windows Crypto API.

Support

CapeSoft Support
Email
Telephone +27 87 828 0123

Version History

Version 2.03 - 25 October 2021  
Version 2.02 - 24 May 2021  
Version 2.01 - 15 March 2020   Version 2.00 - 12 February 2020    Version 1.99 - 25 August 2020    Version 1.98 - 18 November 2019    Version 1.97 - 15 October 2019    Version 1.96 - 23 May 2019    Version 1.95 - 16 April 2019    Version 1.94 - 8 March 2019    Version 1.93 - 14 September 2018    Version 1.92 - 26 July 2018    Version 1.91 - 8 March 2018    Version 1.90 - 15 February 2018    Version 1.89 - 29 January 2018    Version 1.88 - 23 January 2018    Version 1.87 - 2 January 2018    Version 1.86 - 27 February 2017    Version 1.85 - 12 January 2017    Version 1.84 - 26 October 2016    Version 1.83 - 21 October 2016    Version 1.82 - 30 June 2016    Version 1.81 - 29 March 2016    Version 1.80 - 27 November 2015    Version 1.79 - 25 November 2015    Version 1.78 - 13 October 2015    Version 1.77 - 8 September 2015    Version 1.76 - 21 August 2015  (with thanks to Maarten Veenstra) Version 1.75 - 28 April 2015 Version 1.74 - 7 April 2015 Version 1.73 - 12 March 2015 Version 1.72 - 25 February 2015 Version 1.71 - 28 January 2015 Version 1.70 - 15 January 2015 Version 1.69 - 30 July 2014 Version 1.68 - 26 July 2014 Version 1.67 - 21 July 2014 Version 1.66 - 15 July 2014 Version 1.65 - 14 July 2014 Version 1.64 - 16 April 2014 VersioVersion 1.63 - 7 March 2014 Version 1.62 - 22 January 2014 Version 1.61 - 15 January 2014 Version 1.60 - 8 January 2014 Version 1.59 - 27 November 2013 Version 1.57 - 6 August 2013
Version 1.56 - 6 August 2013
Version 1.55 - 6 August 2013 Version 1.54 - 9 May 2013 Version 1.53 - 30 April 2013 Version 1.52 - 14 March 2013
Version 1.51 - 13 February 2013


Version 1.50 - 12 February 2013


Version 1.49 - 11 February 2013


Version 1.48 - 21 November 2012


Version 1.47 - 12 November 2012


Version 1.46 - 8 November 2012


Version 1.45 - 7 November 2012

Version 1.43 - 12 October 2012
Version 1.42 - 12 October 2012
Version 1.41 - 11 October 2012
Version 1.40 - 30 August 2012 Version 1.28 - 18 May 2012 Version 1.27 - 17 May 2012 Version 1.26 - 14 May 2012 Version 1.25 - 10 February 2012

Requires StringTheory 1.38 or later Version 1.24 - 03 January 2012

Requires StringTheory 1.38 or later Version 1.23 - 10 November 2011

Requires StringTheory 1.38 or later Version 1.22- 21 July 2011

Requires StringTheory 1.38 or later Version 1.21 - 1 July 2011

Requires StringTheory 1.38 or later Version 1.20 - 29 June 2011

Requires StringTheory 1.38 or later Version 1.19 - 6 June 2011

Requires StringTheory 1.38 or later Version 1.18 - 3 June 2011

Requires StringTheory 1.37 Version 1.17 - 6 May 2011 Version 1.16 - 4 May 2011 Version 1.15 - 7 April 2011

Important: Requires StringTheory 1.32 or higher. Version 1.14 - 7 April 2011

Important
: Requires StringTheory 1.32 or higher. Version 1.13 - 23 March 2011

Important: Requires StringTheory 1.32 or higher. Version 1.12 - 22 March 2011

Important: Requires StringTheory 1.32 or higher. Version 1.11 - 15 March 2011

Important
: Requires StringTheory 1.29 or higher. Version 1.10 - 21 January 2011

Important: Requires Stringtheory 1.29 or higher. Version 1.09 - 19 January 2011

Important: Requires Stringtheory 1.29 or higher. Version 1.08 - 18 January 2011

Important: Requires Stringtheory 1.29 or higher. Version 1.07 - 2 January 2011

Important: Requires Stringtheory 1.29 or higher. Version 1.06 - 24 December 2010

Important: Requires Stringtheory 1.29 or higher. Version 1.05 - 10 December 2010

Important: Requires Stringtheory 1.29 or higher. Version 1.04 - 03 December 2010 Version 1.02 - 30 September 2010

Important: Requires StringTheory 1.26 or higher. Version 1.01 - 23 September 2010 Version 1.00 - 22 September 2010