Help on Encryption library please.

Eugenio Serrano

Member
Licensed User
Longtime User
Hi All,

First I want to say, I am very happy with B4A.

So, I am fighting with the Encryption library right now.
I am using the follow C# code to encrypt my data, and I need the code in B4A to decrypt it.

B4X:
 public static string Encrypt(string sourceString, string key)
 {
 Byte[] buffer = Encoding.ASCII.GetBytes(sourceString);

 TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();

 MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();

 des.Key = MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key)) ;

 des.IV = _Iv; // _Iv is a byte array (Initialization Vector)

 string result = Convert.ToBase64String(des.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length));

 des.Clear();

 MD5.Clear();

 return result;
 }

I am sure I can decrypt the message with B4A but I not sure how write the code..

Can someone help me?

Thanks in Advance.
Eugenio Serrano
 
Last edited:

Eugenio Serrano

Member
Licensed User
Longtime User
Thank you.

I solve my problem as follow:

Here is VB.Net 4.0 code:
B4X:
    Public Function Encrypt(dataToEncrypt As String) As String
        Dim buffer As Byte() = Encoding.ASCII.GetBytes(dataToEncrypt)
        Dim des As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
        des.IV = New Byte() {211, 5, 233, 24, 55, 166, 7, 88}
        des.Key = ASCIIEncoding.ASCII.GetBytes("1234567890123456")
        Dim result = System.Convert.ToBase64String(des.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length))
        des.Clear()
        Return result
    End Function

    Public Function Decrypt(encryptedData As String) As String
        Dim buffer As Byte() = Convert.FromBase64String(encryptedData)
        Dim des As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
        des.IV = New Byte() {211, 5, 233, 24, 55, 166, 7, 88}
        des.Key = ASCIIEncoding.ASCII.GetBytes("123456780123456")
        Dim result As String = Encoding.ASCII.GetString(des.CreateDecryptor().TransformFinalBlock(buffer, 0, buffer.Length))
        des.Clear()
        Return result
    End Function

And here is my code in B4A:

B4X:
Sub Encrypt(dataToEncrypt As String ) As String 

   Dim kg As KeyGenerator
   Dim c As Cipher
   Dim B64 As Base64
   Dim bconv As ByteConverter

   Dim data(0) As Byte
   Dim iv(0) As Byte
   iv = Array As Byte(211, 5, 233, 24, 55, 166, 7, 88) ' 16 bytes for AES
      
   c.Initialize("DESEDE/CBC/PKCS5Padding")    
   c.InitialisationVector = iv
   kg.Initialize("DESEDE") 
   
   kg.KeyFromBytes(bconv.StringToBytes("1234567890123456","ASCII"))
   data = Bconv.StringToBytes(dataToEncrypt, "ASCII")      
   data = c.Encrypt(data, kg.Key, True)            

   Return B64.EncodeBtoS(data, 0, data.Length)
   
End Sub 

Sub Decrypt(encryptedData As String ) As String 

   Dim kg As KeyGenerator
   Dim c As Cipher
   Dim B64 As Base64
   Dim bconv As ByteConverter

   Dim data(0) As Byte
   Dim iv(0) As Byte
   iv = Array As Byte(211, 5, 233, 24, 55, 166, 7, 88) ' 16 bytes for AES
      
   c.Initialize("DESEDE/CBC/PKCS5Padding")    
   c.InitialisationVector = iv
   kg.Initialize("DESEDE")    
   kg.KeyFromBytes(bconv.StringToBytes("1234567890123456","ASCII"))
   
   
   data = B64.DecodeStoB(encryptedData)
   data = c.Decrypt(data, kg.Key, True)   

   Return Bconv.StringFromBytes(data, "ASCII")

End Sub

I can exchange encrypted data bewteen my web site and my android device.
:)
 
Upvote 0

quaker

Member
Licensed User
Longtime User
Thank you.

I solve my problem as follow:

Here is VB.Net 4.0 code:
B4X:
    Public Function Encrypt(dataToEncrypt As String) As String
        Dim buffer As Byte() = Encoding.ASCII.GetBytes(dataToEncrypt)
        Dim des As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
        des.IV = New Byte() {211, 5, 233, 24, 55, 166, 7, 88}
        des.Key = ASCIIEncoding.ASCII.GetBytes("1234567890123456")
        Dim result = System.Convert.ToBase64String(des.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length))
        des.Clear()
        Return result
    End Function

    Public Function Decrypt(encryptedData As String) As String
        Dim buffer As Byte() = Convert.FromBase64String(encryptedData)
        Dim des As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
        des.IV = New Byte() {211, 5, 233, 24, 55, 166, 7, 88}
        des.Key = ASCIIEncoding.ASCII.GetBytes("123456780123456")
        Dim result As String = Encoding.ASCII.GetString(des.CreateDecryptor().TransformFinalBlock(buffer, 0, buffer.Length))
        des.Clear()
        Return result
    End Function

And here is my code in B4A:

B4X:
Sub Encrypt(dataToEncrypt As String ) As String 

   Dim kg As KeyGenerator
   Dim c As Cipher
   Dim B64 As Base64
   Dim bconv As ByteConverter

   Dim data(0) As Byte
   Dim iv(0) As Byte
   iv = Array As Byte(211, 5, 233, 24, 55, 166, 7, 88) ' 16 bytes for AES
      
   c.Initialize("DESEDE/CBC/PKCS5Padding")    
   c.InitialisationVector = iv
   kg.Initialize("DESEDE") 
   
   kg.KeyFromBytes(bconv.StringToBytes("1234567890123456","ASCII"))
   data = Bconv.StringToBytes(dataToEncrypt, "ASCII")      
   data = c.Encrypt(data, kg.Key, True)            

   Return B64.EncodeBtoS(data, 0, data.Length)
   
End Sub 

Sub Decrypt(encryptedData As String ) As String 

   Dim kg As KeyGenerator
   Dim c As Cipher
   Dim B64 As Base64
   Dim bconv As ByteConverter

   Dim data(0) As Byte
   Dim iv(0) As Byte
   iv = Array As Byte(211, 5, 233, 24, 55, 166, 7, 88) ' 16 bytes for AES
      
   c.Initialize("DESEDE/CBC/PKCS5Padding")    
   c.InitialisationVector = iv
   kg.Initialize("DESEDE")    
   kg.KeyFromBytes(bconv.StringToBytes("1234567890123456","ASCII"))
   
   
   data = B64.DecodeStoB(encryptedData)
   data = c.Decrypt(data, kg.Key, True)   

   Return Bconv.StringFromBytes(data, "ASCII")

End Sub

I can exchange encrypted data bewteen my web site and my android device.
:)

Hi thanks for code info.

Which library are you using for encryption.I ask this because i tried your code and doesnt find "KeyGenerator".

Thanks for help!
 
Upvote 0

Cableguy

Expert
Licensed User
Longtime User
If you had used the search engine of the forum, using the words "encryption lib", you would have found this one among the results....Search engines are user friendly, and usually a user friend...
 
Upvote 0

realblue

Member
Licensed User
Longtime User
Hi Eugenio Serrano;

The below is my encryption algorithm (vb.net) and I couldn't convert it to B4A do you think you can guide me? Thanks in advance.

B4X:
    Friend Shared Function EncryptPasswordMD5(ByVal plainText As String, ByVal p_strSaltValue As String) As String
            Dim strReturn As String = String.Empty
            Try
                Dim initVectorBytes As Byte()
                initVectorBytes = System.Text.Encoding.ASCII.GetBytes(m_strInitVector)

                Dim saltValueBytes As Byte()
                saltValueBytes = System.Text.Encoding.ASCII.GetBytes(p_strSaltValue)

                ' Convert our plaintext into a byte array.
                ' Let us assume that plaintext contains UTF8-encoded characters.
                Dim plainTextBytes As Byte()
                plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText)

                ' First, we must create a password, from which the key will be derived.
                ' This password will be generated from the specified passphrase and 
                ' salt value. The password will be created using the specified hash 
                ' algorithm. Password creation can be done in several iterations.

                Dim password As Rfc2898DeriveBytes

                password = New Rfc2898DeriveBytes(m_strPassPhrase, _
                saltValueBytes, _
                m_strPasswordIterations)

                ' Use the password to generate pseudo-random bytes for the encryption
                ' key. Specify the size of the key in bytes (instead of bits).
                Dim keyBytes As Byte()
                Dim intKeySize As Integer = 0

                intKeySize = CType((m_intKeySize / 8), Integer)

                keyBytes = password.GetBytes(intKeySize)

                ' Create uninitialized Rijndael encryption object.
                Dim symmetricKey As System.Security.Cryptography.RijndaelManaged
                symmetricKey = New System.Security.Cryptography.RijndaelManaged

                ' It is reasonable to set encryption mode to Cipher Block Chaining
                ' (CBC). Use default options for other symmetric key parameters.
                symmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC

                'symmetricKey.Padding = PaddingMode.Zeros


                ' Generate encryptor from the existing key bytes and initialization 
                ' vector. Key size will be defined based on the number of the key 
                ' bytes.
                Dim encryptor As System.Security.Cryptography.ICryptoTransform
                encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)

                ' Define memory stream which will be used to hold encrypted data.
                Dim memoryStream As System.IO.MemoryStream
                memoryStream = New System.IO.MemoryStream

                ' Define cryptographic stream (always use Write mode for encryption).
                Dim cryptoStream As System.Security.Cryptography.CryptoStream
                cryptoStream = New System.Security.Cryptography.CryptoStream(memoryStream, _
                encryptor, _
                System.Security.Cryptography.CryptoStreamMode.Write)
                ' Start encrypting.
                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length)

                ' Finish encrypting.
                cryptoStream.FlushFinalBlock()

                ' Convert our encrypted data from a memory stream into a byte array.
                Dim cipherTextBytes As Byte()
                cipherTextBytes = memoryStream.ToArray()

                ' Close both streams.
                memoryStream.Close()
                cryptoStream.Close()

                ' Convert encrypted data into a base64-encoded string.
                Dim cipherText As String
                cipherText = Convert.ToBase64String(cipherTextBytes)

                ' Return encrypted string.
                strReturn = cipherText

            Catch ex As Exception
                strReturn = Nothing
            End Try

            Return strReturn

        End Function
 
Upvote 0

sigster

Active Member
Licensed User
Longtime User
Hi

I test the code from Eugenio Serrano and it works well

but how can I use this in PHP

I try this with no luck
$str_to_decode = 'eX7lXOeDz6g=';
echo base64_decode($str_to_decode);



B4X:
  Public Function Encrypt(ByVal dataToEncrypt As String) As String
        Dim buffer As Byte() = Encoding.UTF8.GetBytes(dataToEncrypt)
        Dim des As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
        des.IV = New Byte() {211, 5, 233, 24, 55, 166, 7, 88}
        des.Key = ASCIIEncoding.UTF8.GetBytes("1234567890123456")
        Dim result = System.Convert.ToBase64String(des.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length))
        des.Clear()
        Return result
    End Function

    Public Function Decrypt(ByVal encryptedData As String) As String
        On Error Resume Next
        Dim buffer As Byte() = Convert.FromBase64String(encryptedData)
        Dim des As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
        des.IV = New Byte() {211, 5, 233, 24, 55, 166, 7, 88}
        des.Key = ASCIIEncoding.UTF8.GetBytes("1234567890123456")
        Dim result As String = Encoding.UTF8.GetString(des.CreateDecryptor().TransformFinalBlock(buffer, 0, buffer.Length))
        des.Clear()
        Return result
    End Function
 
Upvote 0

Derek Jee

Active Member
Licensed User
Longtime User
Thank you.

I solve my problem as follow:

Here is VB.Net 4.0 code:
B4X:
    Public Function Encrypt(dataToEncrypt As String) As String
        Dim buffer As Byte() = Encoding.ASCII.GetBytes(dataToEncrypt)
        Dim des As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
        des.IV = New Byte() {211, 5, 233, 24, 55, 166, 7, 88}
        des.Key = ASCIIEncoding.ASCII.GetBytes("1234567890123456")
        Dim result = System.Convert.ToBase64String(des.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length))
        des.Clear()
        Return result
    End Function

    Public Function Decrypt(encryptedData As String) As String
        Dim buffer As Byte() = Convert.FromBase64String(encryptedData)
        Dim des As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
        des.IV = New Byte() {211, 5, 233, 24, 55, 166, 7, 88}
        des.Key = ASCIIEncoding.ASCII.GetBytes("123456780123456")
        Dim result As String = Encoding.ASCII.GetString(des.CreateDecryptor().TransformFinalBlock(buffer, 0, buffer.Length))
        des.Clear()
        Return result
    End Function

And here is my code in B4A:

B4X:
Sub Encrypt(dataToEncrypt As String ) As String

   Dim kg As KeyGenerator
   Dim c As Cipher
   Dim B64 As Base64
   Dim bconv As ByteConverter

   Dim data(0) As Byte
   Dim iv(0) As Byte
   iv = Array As Byte(211, 5, 233, 24, 55, 166, 7, 88) ' 16 bytes for AES
     
   c.Initialize("DESEDE/CBC/PKCS5Padding")   
   c.InitialisationVector = iv
   kg.Initialize("DESEDE")
  
   kg.KeyFromBytes(bconv.StringToBytes("1234567890123456","ASCII"))
   data = Bconv.StringToBytes(dataToEncrypt, "ASCII")     
   data = c.Encrypt(data, kg.Key, True)           

   Return B64.EncodeBtoS(data, 0, data.Length)
  
End Sub

Sub Decrypt(encryptedData As String ) As String

   Dim kg As KeyGenerator
   Dim c As Cipher
   Dim B64 As Base64
   Dim bconv As ByteConverter

   Dim data(0) As Byte
   Dim iv(0) As Byte
   iv = Array As Byte(211, 5, 233, 24, 55, 166, 7, 88) ' 16 bytes for AES
     
   c.Initialize("DESEDE/CBC/PKCS5Padding")   
   c.InitialisationVector = iv
   kg.Initialize("DESEDE")   
   kg.KeyFromBytes(bconv.StringToBytes("1234567890123456","ASCII"))
  
  
   data = B64.DecodeStoB(encryptedData)
   data = c.Decrypt(data, kg.Key, True)  

   Return Bconv.StringFromBytes(data, "ASCII")

End Sub

I can exchange encrypted data bewteen my web site and my android device.
:)


Thank you too.. This code helped me..
 
Upvote 0

Derek Jee

Active Member
Licensed User
Longtime User
Hello

I have a further question on this encryption which I got working but now have a different key length. I have tried various things but do not get the right results.. This is my VB code

B4X:
    Private key() As Byte = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}
    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

I have this:
B4X:
Dim kg As KeyGenerator
   Dim c As Cipher
   Dim B64 As Base64
   Dim bconv As ByteConverter

   Dim data(0) As Byte
   Dim iv(0) As Byte
   iv = Array As Byte(11, 11, 11, 11, 11, 111, 111, 111) ' 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)

Could anyone point out where I am going wrong?

Thank you..


Derek.
 
Upvote 0
Top