bitwise DectoHex

derez

Expert
Licensed User
Longtime User
While playing with crypto library and example, I found that the example is "cheating" by using the secret array that was created during the encryption, for the decryption.
I tried to reconstruct the array from the encrypted string , taking two characters at a time and converting them from hex to decimal, until at some trial I found that the conversion DectoHex provides one character in the cases that the value is small.
so I added a check and added a zero to complete it to two characters.

see below the modified example.

I am not sure if this is how it should work or it needs correction :confused:

B4X:
Sub Globals
      Dim string(0) As Byte, secret(0) As Byte 
      PassPhrase = "" 
End Sub


Sub App_Start
      Form1.Show
      Bit.New1
      Crypto.New1
End Sub


Sub btnEncrypt_Click
passPhrase = pass.Text
string() = Bit.StringToBytes(txtString.Text,0,StrLength(txtString.Text)) 'Convert the string to an array of bytes.
secret() = Crypto.Encrypt(PassPhrase, string()) 'Save the encrypted data.
For i = 0 To ArrayLen(secret())-1 'Show the encrypted data in the TextBox
    x = bit.DecToHex(secret(i))
    If StrLength(x) = 1 Then x = "0" & x    ' check if one character
    s = s & x
Next
cr.Text = s
End Sub


Sub btnDecrypt_Click
passPhrase = pass.Text

st = cr.Text
len = StrLength(st)   
Dim secret(len/2) As byte   ' re-build  secret() from the string
For i = 0 To len - 1 Step 2
    secret(i/2) = bit.HexToDec(StrAt(st,i) & StrAt(st,i+1))
Next

string() = Crypto.Decrypt(PassPhrase,secret()) 'Decrypt the data.
tb.Text = Bit.BytesToString(string(),0,ArrayLen(string())) 'Convert the array to a string.
End Sub
 
Last edited:
Top