Skip to content

Commit fd19233

Browse files
committed
PDFBOX-6072: refactor, as suggested by Valery Bokov; closes #247
git-svn-id: https://svn.apache.org/repos/asf/pdfbox/trunk@1928618 13f79535-47bb-0310-9956-ffa450edef68
1 parent 21811e4 commit fd19233

File tree

1 file changed

+21
-12
lines changed
  • pdfbox/src/main/java/org/apache/pdfbox/pdmodel/encryption

1 file changed

+21
-12
lines changed

pdfbox/src/main/java/org/apache/pdfbox/pdmodel/encryption/RC4Cipher.java

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,15 @@ private static void swap( int[] data, int firstIndex, int secondIndex )
9595
data[ secondIndex ] = tmp;
9696
}
9797

98+
private int encrypt(byte aByte)
99+
{
100+
b = (b + 1) % 256;
101+
c = (salt[b] + c) % 256;
102+
swap(salt, b, c);
103+
int saltIndex = (salt[b] + salt[c]) % 256;
104+
return aByte ^ (byte) salt[saltIndex];
105+
}
106+
98107
/**
99108
* This will encrypt and write the next byte.
100109
*
@@ -105,11 +114,7 @@ private static void swap( int[] data, int firstIndex, int secondIndex )
105114
*/
106115
public void write( byte aByte, OutputStream output ) throws IOException
107116
{
108-
b = (b + 1) % 256;
109-
c = (salt[b] + c) % 256;
110-
swap( salt, b, c );
111-
int saltIndex = (salt[b] + salt[c]) % 256;
112-
output.write(aByte ^ (byte)salt[saltIndex]);
117+
output.write(encrypt(aByte));
113118
}
114119

115120
/**
@@ -122,10 +127,7 @@ public void write( byte aByte, OutputStream output ) throws IOException
122127
*/
123128
public void write( byte[] data, OutputStream output ) throws IOException
124129
{
125-
for (byte aData : data)
126-
{
127-
write(aData, output);
128-
}
130+
write(data, 0, data.length, output);
129131
}
130132

131133
/**
@@ -142,7 +144,7 @@ public void write( InputStream data, OutputStream output ) throws IOException
142144
int amountRead;
143145
while( (amountRead = data.read( buffer )) != -1 )
144146
{
145-
write( buffer, 0, amountRead, output );
147+
write(buffer, 0, amountRead, output, buffer);
146148
}
147149
}
148150

@@ -158,9 +160,16 @@ public void write( InputStream data, OutputStream output ) throws IOException
158160
*/
159161
public void write( byte[] data, int offset, int len, OutputStream output) throws IOException
160162
{
161-
for( int i = offset; i < offset + len; i++ )
163+
write(data, offset, len, output, new byte[len]);
164+
}
165+
166+
private void write(byte[] data, int offset, int len, OutputStream output, byte[] buffer) throws IOException
167+
{
168+
for (int i = 0, j = offset; i < len; ++i, ++j)
162169
{
163-
write( data[i], output );
170+
buffer[i] = (byte) encrypt(data[j]);
164171
}
172+
173+
output.write(buffer, 0, len);
165174
}
166175
}

0 commit comments

Comments
 (0)