Sub Globals
'These global variables will be redeclared each time the activity is created.
'These variables can only be accessed from this module.
Dim bc As ByteConverter
Dim sr As SecureRandom
End Sub
Sub Activity_Create(FirstTime As Boolean)
Dim cmd As String=HexToString("01000000A707192BFF4CFFEFCCAA67C8")
Dim pwd As String=HexToString("00000000000000040123456701234567")
Dim su As StringUtils
Dim c As Cipher
Dim k As KeyGenerator
Dim cipherText As String = ""
Dim keyBytes() As Byte = MakeKeyBytes(128, pwd)
Dim dataBytes() As Byte = cmd.GetBytes("UTF8")
k.Initialize("AES")
k.KeyFromBytes(keyBytes)
'Autogenerate nonce and insert into IV
Dim nonce(8) As Byte
sr.GetRandomBytes(nonce)
Dim IV(16) As Byte
bc.ArrayCopy(nonce, 0, IV, 0, 8)
If dataBytes.Length > 15 Then
c.Initialize("AES/CTR/NoPadding")
Else
c.Initialize("AES/CFB8/NoPadding")
End If
c.InitialisationVector = IV
Dim encryptedBytes() As Byte = c.Encrypt(dataBytes, k.Key, True)
'Create result byte array, consisting of nonce and encrypted data
Dim cipherTextBytes(encryptedBytes.Length + 8) As Byte
bc.ArrayCopy(nonce, 0, cipherTextBytes, 0, 8)
bc.ArrayCopy(encryptedBytes, 0, cipherTextBytes, 8, encryptedBytes.Length)
cipherText= bc.HexFromBytes(cipherTextBytes)
End Sub
Sub Activity_Resume
End Sub
Sub Activity_Pause (UserClosed As Boolean)
End Sub
Private Sub MakeKeyBytes(keySize As Int, password As String) As Byte()
'If the password is keySize / 8 bytes or greater in length, just truncate password to proper byte size
'If password is less than keySize /8 bytes in length, create a SHA1 digest of the password
' (20 bytes), and concatenate the digest and truncate to proper byte size.
Dim bc As ByteConverter
Dim keyBytes(keySize / 8) As Byte
Dim passwordBytes() As Byte = password.GetBytes("UTF8")
If passwordBytes.Length >= keyBytes.Length Then
bc.ArrayCopy(passwordBytes, 0, keyBytes, 0, keyBytes.Length)
Else
Dim md As MessageDigest
Dim hash() As Byte = md.GetMessageDigest(passwordBytes, "SHA1")
Dim offset As Int = 0
Do While offset < keyBytes.Length
If offset + hash.Length < keyBytes.Length Then
bc.ArrayCopy(hash, 0, keyBytes, offset, hash.Length)
Else
bc.ArrayCopy(hash, 0, keyBytes, offset, keyBytes.Length - offset)
End If
offset = offset + hash.Length
Loop
End If
Return keyBytes
End Sub
Sub HexToString(HexToStr As String) As String
Dim bc As ByteConverter
Dim b() As Byte = bc.HexToBytes(HexToStr)
Return BytesToString(b, 0, b.Length, "UTF8")
End Sub