1 49 package com.lowagie.text.pdf; 50 import com.lowagie.text.ExceptionConverter; 51 import com.lowagie.text.pdf.crypto.AESCipher; 52 import com.lowagie.text.pdf.crypto.IVGenerator; 53 import com.lowagie.text.pdf.crypto.ARCFOUREncryption; 54 import java.io.IOException ; 55 import java.io.OutputStream ; 56 57 public class OutputStreamEncryption extends OutputStream { 58 59 protected OutputStream out; 60 protected ARCFOUREncryption arcfour; 61 protected AESCipher cipher; 62 private byte[] sb = new byte[1]; 63 private static final int AES_128 = 4; 64 private boolean aes; 65 private boolean finished; 66 67 68 public OutputStreamEncryption(OutputStream out, byte key[], int off, int len, int revision) { 69 try { 70 this.out = out; 71 aes = revision == AES_128; 72 if (aes) { 73 byte[] iv = IVGenerator.getIV(); 74 byte[] nkey = new byte[len]; 75 System.arraycopy(key, off, nkey, 0, len); 76 cipher = new AESCipher(true, nkey, iv); 77 write(iv); 78 } 79 else { 80 arcfour = new ARCFOUREncryption(); 81 arcfour.prepareARCFOURKey(key, off, len); 82 } 83 } catch (Exception ex) { 84 throw new ExceptionConverter(ex); 85 } 86 } 87 88 public OutputStreamEncryption(OutputStream out, byte key[], int revision) { 89 this(out, key, 0, key.length, revision); 90 } 91 92 102 public void close() throws IOException { 103 finish(); 104 out.close(); 105 } 106 107 119 public void flush() throws IOException { 120 out.flush(); 121 } 122 123 133 public void write(byte[] b) throws IOException { 134 write(b, 0, b.length); 135 } 136 137 152 public void write(int b) throws IOException { 153 sb[0] = (byte)b; 154 write(sb, 0, 1); 155 } 156 157 185 public void write(byte[] b, int off, int len) throws IOException { 186 if (aes) { 187 byte[] b2 = cipher.update(b, off, len); 188 if (b2 == null || b2.length == 0) 189 return; 190 out.write(b2, 0, b2.length); 191 } 192 else { 193 byte[] b2 = new byte[Math.min(len, 4192)]; 194 while (len > 0) { 195 int sz = Math.min(len, b2.length); 196 arcfour.encryptARCFOUR(b, off, sz, b2, 0); 197 out.write(b2, 0, sz); 198 len -= sz; 199 off += sz; 200 } 201 } 202 } 203 204 public void finish() throws IOException { 205 if (!finished) { 206 finished = true; 207 if (aes) { 208 byte[] b; 209 try { 210 b = cipher.doFinal(); 211 } catch (Exception ex) { 212 throw new ExceptionConverter(ex); 213 } 214 out.write(b, 0, b.length); 215 } 216 } 217 } 218 } | Popular Tags |