' Note: REQUIRES: Encryption, B4XEncryption, ByteConverter, StringUtils libraries
' In Starter module:
Public Const PART_3 As String = "16RANDOMBYTESOne" ' command line parameter encryption
Public Const PART_4 As String = "16RANDOMBYTESTwo"
' in a module:
'Takes a plain string and returns as HEX-ENCODED string of the encrytped text.
Public Sub AES_Encrypt(DataToEncrypt As String) As String
Dim poKG As KeyGenerator
Dim poCy As Cipher
Dim poBC As ByteConverter
Dim poData() As Byte
' doing AES
poCy.Initialize("AES/CBC/PKCS7Padding")
' set InitializationVector value
poCy.InitialisationVector = poBC.StringToBytes(Starter.PART_3, "utf8")
' Generate a key
poKG.Initialize("AES")
poKG.KeyFromBytes(poBC.StringToBytes(Starter.PART_4, "utf8"))
' encrypt the string into a byte array
poData = poCy.Encrypt(poBC.StringToBytes(DataToEncrypt, "utf8"), poKG.Key, True)
' convert the byte array to a HEX string and return it
Return poBC.HexFromBytes(poData)
End Sub
' Takes a HEX-ENCODED string of the encrytped text and returns the plain text.
Public Sub AES_Decrypt(HexEncodedString As String) As String
Dim poKG As KeyGenerator
Dim poCy As Cipher
Dim poBC As ByteConverter
Dim poData() As Byte
poData = poBC.HexToBytes(HexEncodedString)
' doing AES
poCy.Initialize("AES/CBC/PKCS7Padding")
' set InitializationVector value
poCy.InitialisationVector = poBC.StringToBytes(Starter.PART_3, "utf8")
' Generate a key
poKG.Initialize("AES")
poKG.KeyFromBytes(poBC.StringToBytes(Starter.PART_4, "utf8"))
' encrypt the string into a byte array
poData = poCy.Decrypt(poBC.HexToBytes(HexEncodedString), poKG.Key, True)
' Convert it back to utf8 string
Return BytesToString(poData, 0, poData.Length, "utf8")
End Sub