'Byte array to Firestore

I have a byte array how do I store it in Firestore? preferable to store as a File in Firestore Storage but storing them as custom object is fine too in Cloud Firestore.

I tried to make a file and use the function write Bytes() and on retrieving use read bytes but that is not able to work proper and causing some disruption as my byte array is a encrypted form of image which I need to store in Firestore. And Retrieve later and decrypt it.

Before I was trying to convert Byte Array to string but many people told that is no good practice as it will cause loss of data.

Than when I researched a bit few people recommended to use Blob and store the byte array but unfortunately I was unable to get the sample code for it.

val z = cipher.doFinal(byteArray)
 val file = File.createTempFile("$name", null)
      file.writeBytes(z)
      Log.d("first","quick")
      val storageReference = FirebaseStorage.getInstance()
          .getReference("/image/0XhL4jD4XCemk38rcRkIEjJMgjh2/Aadhar/")
      storageReference.putFile(Uri.fromFile(file))
          .addOnSuccessListener {
          Toast.makeText(context , "Success", Toast.LENGTH_SHORT).show()
    }

Basically Z is the encrypted byte array that I somehow need to push to Firestore. I tried to make file and push in storage. Its Successfully completed. But when I retrieve it back Something like below:-

   val storageRef =
        FirebaseStorage.getInstance().reference?.child("/image/0XhL4jD4XCemk38rcRkIEjJMgjh2/Aadhar/")
    val localfile = File.createTempFile("temp", ".txt")
    storageRef.getFile(localfile)
        .addOnSuccessListener {

            val bytes = localfile.readBytes()
            var decryptedText: ByteArray = cipher.doFinal(bytes)
            val configBmp = Bitmap.Config.valueOf(bitmap.config.name)
            val bitmap_tmp = Bitmap.createBitmap(width, height, configBmp)
            val buffer = ByteBuffer.wrap(decryptedText)
            bitmap_tmp.copyPixelsFromBuffer(buffer)

            img.setImageBitmap(bitmap_tmp)
        }

The problem when I read bytes I got no clue what but something is going wrong there. I can be of sure that encryption and decryption both are working fine as I tested it Locally without pushing the byte array to Firestore and Just decrypt and it works perfectly good. But when for the same byte array I try to store in file and push and retrieve later it doesn't works. The error I get is Illegal block size.

Simplified Question:-

Assume I have a byte array 'X' How can I store it in Firestore [Cloud Firestore / Storage in form of files[preferred] with 0 loss of data and retrieve it back.

Help would be highly appreciated guys with a snippet of code to understand, Thanks in adv.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source