Archived Forum Post

Index of archived forum posts

Question:

Decrypt AES encrypted and Base64 encoded string

Oct 11 '13 at 08:57

Hi,

I have a Base64 encoded value that is AES CBC encrypted with a null IV. I tried all sorts of combinations, but the original string is not comming back. I can decrypt fine with AESManaged, but the target machine is Windows Server 2000, so we'll go for the Chilkat Chilkat.Crypt2 (It's a classic asp application).

This is what I have so far. (Key = "6F2F108EB7F65452A1EE3E5B007103ED" Testvalue = "Td6cGqFDvaKQes/ewPHX+Ygwl5IipdnyJf9hKiZbNv8="

unlocked = crypt.UnlockComponent("30-day trial")
if unlocked then
  crypt.CryptAlgorithm = "aes"
  crypt.CipherMode = "cbc"
  crypt.KeyLength = 128
  Dim iv: iv=HexStringToByteArray("0000000000000000")
  crypt.IV = iv 
  crypt.SecretKey =HexStringToByteArray(aeskey)
  Dim encryptedText: encryptedText = Base64Decode(encryptedBlock)
  numcard = ByteArrayToString(crypt.DecryptBytes(encryptedText))
else
  errorCode = 99
  errorText = "License Expired"
  numcard = ""
end if

Function hexStringToByteArray(s)
Dim r()
ReDim r(Len(s)/2-1)
Dim x
For i = 0 To  Len(s)-2 Step 2
    x= "&H" & Mid(s,i+1,2)
    r(i/2) = CInt(x)
Next
hexStringToByteArray= r
End Function

function ByteArrayToString(theArray)
    dim i, str
    if vartype(theArray) < 8192 then
           exit function
    end if
    for i=lbound(theArray) to ubound(theArray) 
      str = str & asc(theArray(i))
    next
    ByteArrayToString = str
end function

What am I doing wrong?


Answer

Your key is in hex, and the data you are trying to decrypt is the Base64 string representation of the encrypted bytes. Chilkat makes it easy to use the encoded strings directly, so you don't have to go through the pain and complexity of dealing with byte arrays.

With this solution, you can discard the functions for converting hex strings to byte arrays:

crypt.CryptAlgorithm = "aes"
crypt.CipherMode = "cbc"
crypt.KeyLength = 128
crypt.SetEncodedIV "0000000000000000", "hex"
crypt.SetEncodedKey "6F2F108EB7F65452A1EE3E5B007103ED", "hex"

crypt.EncodingMode = "base64"
dim outStr as String
outStr = crypt.DecryptStringENC("Td6cGqFDvaKQes/ewPHX+Ygwl5IipdnyJf9hKiZbNv8=")

Also, see this for a more detailed description of EncryptStringENC and DecryptStringENC: http://www.cknotes.com/?p=504 (The discussion at this web page pertains to any programming language)