CryptEncode Function

**Description:** Transforms the data from an array using the specified method.

**Syntax:**

int CryptEncode(
  ENUM_CRYPT_METHOD method, // Method of transformation
  const uchar&      data[],  // Source array
  const uchar&      key[],   // Key array
  uchar&            result[] // Destination array
);

**Parameters:**

  • method [in]: Specifies the data transformation method. Must be one of the values from the ENUM_CRYPT_METHOD enumeration.
  • data[] [in]: The source array containing the data to be transformed.
  • key[] [in]: The key array used for the transformation.
  • result[] [out]: The destination array where the transformed data will be stored.
  • **Return Value:**

  • Returns the number of bytes written to the result[] array upon successful completion.
  • Returns 0 if an error occurs. To get specific error information, call the GetLastError() function.
  • **Related Functions:**

  • Array Functions
  • CryptDecode()
  • **Example:**

    // Helper function to convert byte array to HEX string
    string ArrayToHex(uchar &arr[], int count = -1)
    {
      string res = "";
      if (count < 0 || count > ArraySize(arr))
        count = ArraySize(arr);
      for (int i = 0; i < count; i++)
        res += StringFormat("%.2X", arr[i]);
      return res;
    }

    void OnStart() { string text = "The quick brown fox jumps over the lazy dog"; string keystr = "ABCDEFG"; uchar src[], dst[], key[];

    // Prepare key StringToCharArray(keystr, key); // Copy text to source array src[] StringToCharArray(text, src);

    PrintFormat("Initial data: size=%d, string='%s'", ArraySize(src), CharArrayToString(src));

    // Encrypt src[] with DES 56-bit key in key[] int res = CryptEncode(CRYPT_DES, src, key, dst);

    // Check for encryption error if (res > 0) { PrintFormat("Encoded data: size=%d %s", res, ArrayToHex(dst));

    // Decode dst[] back to src[] res = CryptDecode(CRYPT_DES, dst, key, src);

    // Check for decryption error if (res > 0) { PrintFormat("Decoded data: size=%d, string='%s'", ArraySize(src), CharArrayToString(src)); } else Print("Error in CryptDecode. Error code=", GetLastError()); } else Print("Error in CryptEncode. Error code=", GetLastError()); }

    **See Also:**

  • [Array Functions](/array)
  • [CryptDecode()](/common/cryptdecode)
  • [ENUM_CRYPT_METHOD](/constants/namedconstants/otherconstants#enum_crypt_method)
  • [GetLastError()](/check/getlasterror)