null
null

Reputation: 3517

Gzip Compression with Scala resulting in not an archive error

I'm making changes to a document, I then need to compress the doc using gzip, encrypt it and then save it.

Each of the separate blocks of code pass units tests as expected but together they fail, when I then go to open the file I receive an error saying that it's not an archive.

The rudimentary code is below, any help is hugely appreciated, thank you in advance!

val zipped = compressFile1(replaced)

def compressFile1(fileContents: String): Array[Byte] = {
  val bos = new ByteArrayOutputStream()
  val gzs = new GZIPOutputStream(bos)
  gzs.write(fileContents.getBytes("UTF-8"))
  gzs.close()
  val compressed = bos.toByteArray
  bos.close()
  compressed
}

I then encrypt the file

val encrypted = encrypt(zipped.toString)

def encrypt(value: String): String = {
  val cipher: Cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
  cipher.init(Cipher.ENCRYPT_MODE, keyToSpec(encryptionPassword))
  Base64.encodeBase64String(cipher.doFinal(value.getBytes("UTF-8")))
}

and then save it

val file = writeStringToFile(new File("testfile1.gz"), encrypted)

thank you again

Upvotes: 1

Views: 501

Answers (1)

JRomero
JRomero

Reputation: 4868

Calling .toString on Array[Byte] is actually returning something like [B@4d2f7117 (the standard toString implementation). It's not doing what you are expecting which is...

val encrypted = encrypt(new String(zipped))

instead of

val encrypted = encrypt(zipped.toString)

Upvotes: 1

Related Questions