1 31 package org.pdfbox.encryption; 32 33 import java.io.IOException ; 34 import java.io.InputStream ; 35 import java.io.OutputStream ; 36 37 43 public class ARCFour 44 { 45 private int[] salt; 46 private int b; 47 private int c; 48 49 53 public ARCFour() 54 { 55 salt = new int[256]; 56 } 57 58 63 public void setKey( byte[] key ) 64 { 65 b = 0; 66 c = 0; 67 68 if(key.length < 1 || key.length > 32) 69 { 70 throw new IllegalArgumentException ("number of bytes must be between 1 and 32"); 71 } 72 for(int i = 0; i < salt.length; i++) 73 { 74 salt[i] = i; 75 } 76 77 int keyIndex = 0; 78 int saltIndex = 0; 79 for( int i = 0; i < salt.length; i++) 80 { 81 saltIndex = (fixByte(key[keyIndex]) + salt[i] + saltIndex) % 256; 82 swap( salt, i, saltIndex ); 83 keyIndex = (keyIndex + 1) % key.length; 84 } 85 86 } 87 88 95 private static final int fixByte( byte aByte ) 96 { 97 return aByte < 0 ? 256 + aByte : aByte; 98 } 99 100 107 private static final void swap( int[] data, int firstIndex, int secondIndex ) 108 { 109 int tmp = data[ firstIndex ]; 110 data[ firstIndex ] = data[ secondIndex ]; 111 data[ secondIndex ] = tmp; 112 } 113 114 122 public void write( byte aByte, OutputStream output ) throws IOException 123 { 124 b = (b + 1) % 256; 125 c = (salt[b] + c) % 256; 126 swap( salt, b, c ); 127 int saltIndex = (salt[b] + salt[c]) % 256; 128 output.write(aByte ^ (byte)salt[saltIndex]); 129 } 130 131 139 public void write( byte[] data, OutputStream output ) throws IOException 140 { 141 for( int i = 0; i < data.length; i++ ) 142 { 143 write( data[i], output ); 144 } 145 } 146 147 155 public void write( InputStream data, OutputStream output ) throws IOException 156 { 157 byte[] buffer = new byte[1024]; 158 int amountRead = 0; 159 while( (amountRead = data.read( buffer )) != -1 ) 160 { 161 write( buffer, 0, amountRead, output ); 162 } 163 } 164 165 175 public void write( byte[] data, int offset, int len, OutputStream output) throws IOException 176 { 177 for( int i = offset; i < offset + len; i++ ) 178 { 179 write( data[i], output ); 180 } 181 } 182 } | Popular Tags |