1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.forgerock.json.jose.jwe.handlers.compression;
18
19 import java.io.ByteArrayInputStream;
20 import java.io.ByteArrayOutputStream;
21 import java.io.IOException;
22 import java.util.zip.Deflater;
23 import java.util.zip.DeflaterOutputStream;
24 import java.util.zip.Inflater;
25 import java.util.zip.InflaterInputStream;
26
27 import org.forgerock.json.jose.exceptions.JweCompressionException;
28
29
30
31
32
33
34
35 public class DeflateCompressionHandler implements CompressionHandler {
36
37
38
39
40 @Override
41 public byte[] compress(byte[] bytes) {
42 ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
43 try (DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteOutputStream,
44 new Deflater(Deflater.DEFLATED, true))) {
45 deflaterOutputStream.write(bytes);
46 } catch (IOException e) {
47 throw new JweCompressionException("Failed to apply compression algorithm.", e);
48 }
49
50 return byteOutputStream.toByteArray();
51 }
52
53
54
55
56 @Override
57 public byte[] decompress(byte[] bytes) {
58 ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
59 try (InflaterInputStream inflaterInputStream = new InflaterInputStream(new ByteArrayInputStream(bytes),
60 new Inflater(true));
61 ByteArrayOutputStream out = byteOutputStream) {
62 byte[] buffer = new byte[1024];
63 int l;
64 while ((l = inflaterInputStream.read(buffer)) > 0) {
65 out.write(buffer, 0, l);
66 }
67 } catch (IOException e) {
68 throw new JweCompressionException("Failed to apply de-compression algorithm.", e);
69 }
70
71 return byteOutputStream.toByteArray();
72 }
73 }