Blowfish return key length

General Help regarding HMG, Compilation, Linking, Samples

Moderator: Rathinagiri

Post Reply
User avatar
karweru
Posts: 220
Joined: Fri Aug 01, 2008 1:51 pm
DBs Used: DBF,mysql,mariadb,postgresql,sqlite,odbc
Contact:

Blowfish return key length

Post by karweru »

Hello All,

I can't seem to predict the length of string returned in this code

Code: Select all

FUNCTION encode(cStr,cPass)
local cBfKey
cBfKey := hb_blowfishKey(cPass)
Return hb_StrToHex(hb_blowfishEncrypt(cBfKey, cStr))

FUNCTION decode(cEncoded,cPass)
local cBfKey
cBfKey := hb_blowfishKey(cPass)
Return hb_blowfishDecrypt(cBfKey, cEncoded:=hb_HexToStr(cEncoded))
In case one needs to write the result of encode() into a fixed length field, it can become a amjor problem. Is there any way to ensure a pre-determined length is returned?

Kind regards,
Kind regards,
Gilbert.
PeteWG
Posts: 176
Joined: Sun Mar 21, 2010 5:45 pm

Re: Blowfish return key length

Post by PeteWG »

karweru wrote: Sun Oct 13, 2019 4:59 pm In case one needs to write the result of encode() into a fixed length field, it can become a amjor problem. Is there any way to ensure a pre-determined length is returned?
Keep in mind some important notes about the cipher produced by hb_blowFish():
1. An extra byte (of checksum code) is always added at the end of created cipher.
so the final length will be: Len( Str ) + 1
2. The length of cipher (i.e., the resulting encrypted text) will be a multiple of 8 and if is not, it will be right-padded up to the next number that's multiple of 8.

Combined the above two rules mean that the length of the cipher will always be 1 to 8 bytes lengthier than the original string. For example:
  • a 2, 3 or 7 bytes long string will be returned as 8 bytes long cipher
    2+1= 3 (multiple of 8: no!), final PADDED cipher length: 8
    7+1 = 8 (multiple of 8: yes), final cipher length: 8
  • an 8 bytes long string will be returned as 16 bytes long cipher
    8 + 1 = 9 (multiple of 8: no!), final PADDED cipher length: 16
    other examples: 127 => 128, 131 => 136, 256 => 264, 509 => 512, et.c
So, in order to be able to store safely the cipher in a field, that field must have a length of Len(string)+8
and since you're converting to hex, the field must be Len(string)+16 bytes lengthier than the unencrypted text.
Conclusion: adapt (change) your field(s) length to conform above rules.

[by the way, this is a pure harbour question and perhaps it could be better if such messages posted at harbour-users group to get more attention and possibly better answers.]

regards,
Pete
User avatar
karweru
Posts: 220
Joined: Fri Aug 01, 2008 1:51 pm
DBs Used: DBF,mysql,mariadb,postgresql,sqlite,odbc
Contact:

Re: Blowfish return key length

Post by karweru »

Thank you Pete for your help,...much appreciated.
Kind regards,
Gilbert.
Post Reply