Then again you are in a B4X forum... PHP is outside the scope of this forum.The link is about b4x while my need is between b4a and php.
The communication between b4a and php is not, I'm afraid.PHP is outside the scope of this forum.
Indeed.The communication between b4a and php is not, I'm afraid.
Public Sub AES_Encrypt(data As String, secretkey As String) As String
Dim SU As StringUtils
Dim iv As String= RandomIVString(16)
Dim IVb() As Byte = iv.GetBytes("UTF8")
Dim kg As KeyGenerator
Dim C As Cipher
Dim SU As StringUtils
kg.Initialize("AES")
kg.KeyFromBytes(secretkey.GetBytes("UTF8"))
C.Initialize("AES/CBC/PKCS5Padding")
C.InitialisationVector = IVb
Dim datas() As Byte = C.Encrypt(data.GetBytes("UTF8"), kg.Key, True)
Return iv & SU.EncodeBase64(datas)
End Sub
Public Sub AES_Decrypt(data As String, secretkey As String) As String
Dim SU As StringUtils
Dim iv As String = data.SubString2(0,16)
Dim msg As String=data.Replace(iv,"")
Dim IVb() As Byte = iv.GetBytes("UTF8")
Dim kg As KeyGenerator
Dim C As Cipher
kg.Initialize("AES")
kg.KeyFromBytes(secretkey.GetBytes("UTF8"))
C.Initialize("AES/CBC/PKCS5Padding")
C.InitialisationVector = IVb
Dim datas() As Byte = C.Decrypt(SU.DecodeBase64(msg), kg.Key, True)
Dim SU As StringUtils
Return BytesToString(datas,0,datas.Length,"UTF8")
End Sub
Private Sub RandomIVString(length As Int) As String
Dim abc As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Dim randomstr As String = ""
For i = 0 To length - 1
randomstr = randomstr & (abc.CharAt(Rnd(0,abc.Length)))
Next
Return randomstr
End Sub
function EncryptString($key,$plainText){
$bytes = random_bytes(8);
$iv=bin2hex($bytes);
$encryptedData = openssl_encrypt($plainText, 'AES-256-CBC', $key, $options=0, $iv);
return $iv.$encryptedData;
}
function DecryptString($key,$encText){
$iv=substr($encText,0,16);
$decryptedData = openssl_decrypt(substr($encText,16), 'AES-256-CBC', $key, $options=0, $iv);
return $decryptedData;
}
I missed this part earlier and set the key length to 16. It works quite well on both ends once the key length problem is fixed. Thank you @Hamied Abou Hulaikah very much for sharing the code!- Secret key should be 32 characters.