Android Question Encryption Assistance

Discussion in 'Android Questions' started by Derek Jee, Jun 22, 2015.

  1. Derek Jee

    Derek Jee Active Member Licensed User

    Hello there

    I am having trouble with encryption. My VB code is below which encrypts some text but I need B4A to encrypt it.. I copied some code from another thread but of course I cannot get it to work as I don't know what needs changing.. can anyone help me please?



    Code:
    Private key() As Byte = {123456789101112131415161718192021222324}
        Private iv() As Byte = {11, 11, 11, 11, 11, 111, 111, 111} 'Not the real iv

        Public Function Encrypt(ByVal plainText As String) As Byte()
            Dim utf8encoder As UTF8Encoding = New UTF8Encoding()
            Dim inputInBytes() As Byte = utf8encoder.GetBytes(plainText)
            Dim tdesProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
            Dim cryptoTransform As ICryptoTransform = tdesProvider.CreateEncryptor(Me.key, Me.iv)
            Dim encryptedStream As MemoryStream = New MemoryStream()
            Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write)
            cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
            cryptStream.FlushFinalBlock()
            encryptedStream.Position = 0
            Dim result(encryptedStream.Length - 1) As Byte
            encryptedStream.Read(result, 0, encryptedStream.Length)
            cryptStream.Close()
            Return result
        End Function
    and I have this:
    Code:
    Dim kg As KeyGenerator
       
    Dim c As Cipher
       
    Dim B64 As Base64
       
    Dim bconv As ByteConverter

       
    Dim data(0As Byte
       
    Dim iv(0As Byte
       iv = 
    Array As Byte(1111111111111111111' 16 bytes for AES
        
       c.Initialize(
    "DESEDE/CBC/PKCS5Padding")  
       c.InitialisationVector = iv
       kg.Initialize(
    "DESEDE")
       kg.KeyFromBytes(bconv.StringToBytes(
    "123456789012345678901234","UTF8"))
       data = bconv.StringToBytes(dataToEncrypt, 
    "UTF8")    
       data = c.Encrypt(data, kg.Key, 
    True)          
       
    Return B64.EncodeBtoS(data, 0, data.Length)
    Thank you, as always..

    Derek.
     
  2. Erel

    Erel Administrator Staff Member Licensed User

    The key is wrong. It should be kg.KeyFromBytes (Array As Byte (1, 2, 3, 4, ...))
     
    Derek Jee likes this.
  3. Derek Jee

    Derek Jee Active Member Licensed User

    Thank you Erel.. Worked a treat!!
     
Loading...