Android Question File Encryption

Javier Alonso

Member
Licensed User
Longtime User
Dear all,

I need some help with encrypting/decrypting a file. I've tried to use DES encryption as follows:

B4X:
    Dim Ins As InputStream
    Dim Outs, Out2 As OutputStream
    Dim data() As Byte
    Dim k As KeyGenerator
    Dim cph as Cipher
    Dim bc As ByteConverter

    k.Initialize("DES")
    k.KeyFromBytes(bc.HexToBytes("8512851A5CF27849"))
    InitializeCipher(cph, "DES")
    cph.InitialisationVector = "8512851A5CF27849"

    Outs.InitializeToBytesArray(100)
    File.Copy2(Ins, Outs)

    data = Starter.cph.Encrypt(Outs.ToBytesArray, k.key, True)
    Out2 = File.OpenOutput(cdestino, fdestino, False)
    Out2.WriteBytes(data, 0, data.length)

    Out2.Close
    Outs.Close
    Return bc.HexFromBytes(k.KeyToBytes)

The problem is that I get an OutOfMemory error if the input file is too big. If I split the input file in chunks (I tried 64k chunks) it only works with AES/CFB encryption, which is not supported by many devices, while regular AES/ECB or AES/CBC fails. The tutorial http://docstore.mik.ua/orelly/java-ent/security/ch13_05.htm explains the difference, but I have not been able to find a solution splitting the file.

I've been searching in Android Developers and there is an object called "CipherInputStream" (https://developer.android.com/reference/javax/crypto/CipherInputStream.html) that could do the trick: it is supposed to be a virtual stream linked to InputStream doing the encryption so you just need to File.Copy2 it to an OutputStream, but it is not included in Agraham's Encryption Library. I'm not familiar to java. Could it be possible to build such a stream using the reflection library, or wrap the function in some way?

Thanks
 

Javier Alonso

Member
Licensed User
Longtime User
Update: I made a workaround. Using AES/CBC/PKCS5Padding, a block of 64kbytes (65536 bytes), once encrypted becomes 65552 bytes long, so it is possible to split the file taking care that the block size when decrypting is different than encrypting. For the last block (which will probably be smaller), use a differnt array of byte (or resize it to make sure that the encryption is correct) and use a Padding algorithm like PKCS5Padding to avoid problems if the original size is not a multiple of 8.

This is not general, i.e. using AES/CFB/PKCS5Padding the encrypted and decrypted block size is the same.

It will probably be faster and more elegant to use CipherInputStream. If someone is so kind to upload it, thanks in advance.
 
Upvote 0
Top