Archived Forum Post

Index of archived forum posts

Question:

Simple string encryption

May 13 '16 at 19:33

I'm trying to do some simple string encryption/decryption to protect values in an ini file. It looks like the encryption is working, but the decryption returns an empty string.

In the example below, I expected INPUT and OUTPUT to be the same:

procedure TForm1.Test;
var vCrypt: HCkCrypt2;
vSuccess: Wordbool;
vValue: Widestring;
begin
    vCrypt := CkCrypt2_Create;
    try
      CkCrypt2_putVerboseLogging(vCrypt, true);

  vValue := 'trial';
  vSuccess := CkCrypt2_UnlockComponent(vCrypt, PWideChar(vValue));
  if (not vSuccess) then begin
     vValue := CkCrypt2__lastErrorText(vCrypt);
     raise Exception.createFmt('Unable to initialize crypto library - %s', [vValue]);
  end;

  CkCrypt2_putEncodingMode(vCrypt, 'modBase64');

  //  Set the encryption algorithm to AES
  CkCrypt2_putCryptAlgorithm(vCrypt, 'aes');

  vValue := eKey.Text;
  CkCrypt2_SetSecretKeyViaPassword(vCrypt, PWideChar(vValue));

  vValue := 'ansi';
  CKCrypt2_putEncodingMode(vCrypt, PWideChar(vValue));

  vValue := eInputString.text;
  eEncryptedResult.text := CkCrypt2__encryptStringENC(vCrypt, PWideChar(vValue));

  vValue := eEncryptedResult.text;
  eDecryptedResult.text := CkCrypt2__decryptStringENC(vCrypt, PWideChar(vValue));

  vValue := CkCrypt2__lastErrorText(vCrypt);
  memo1.Lines.Text := vValue;

finally CkCrypt2_Dispose(vCrypt); end; end;

LastErrorText value is:

ChilkatLog:
DecryptStringENC:
DllDate: Mar 11 2016
ChilkatVersion: 9.5.0.56
Architecture: Little Endian; 32-bit
Language: Delphi/C++ Builder XE2/XE3
VerboseLogging: 1
encodedEncryptedData: "<UJGKU?6 lyK.
sizeAfterDecoding: 16
decryptBytesNew:
keyLength: 256
--decryptBytesNew
decryptedSizeInBytes: 0
codePage: 1252
cryptDetails:
algorithm: aes
keyLength: 256
paddingScheme: 0
cipherMode: cbc
encodingMode: ansi
charset: windows-1252
secretKeyLen: 32
iv: 0000 0000 0000 0000 0000 0000 0000 0000
dataNumBytes: 0
--cryptDetails
Success.
--DecryptStringENC
--ChilkatLog


Accepted Answer

You've overwritten the EncodingMode property here:

  vValue := 'ansi';
  CKCrypt2_putEncodingMode(vCrypt, PWideChar(vValue));
I suspect you want this:
  vValue := 'ansi';
  CKCrypt2_putCharset(vCrypt, PWideChar(vValue));


Answer

Thanks jpbro! "modBase64" is a url-friendly version of base64. It's a valid encoding. The list of valid encodings is kept here: http://cknotes.com/chilkat-binary-encoding-list/


Answer

Good eyes! Thank you for the quick response. That change works.

I'm going back to bed..


Answer

Also - is 'modBase64' a valid encoding mode? Shouldn't it just be 'base64'?