01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17:
18: package org.apache.harmony.luni.util;
19:
20: import java.io.FilterInputStream;
21: import java.io.IOException;
22: import java.io.InputStream;
23:
24: /**
25: * This class implements a password-protected input stream. The algorithm used
26: * for protection is a Vigenere (repeated-key) cipher. The encrypted data is the
27: * result of <original data> XOR KEYKEYKEY...
28: */
29: public class PasswordProtectedInputStream extends FilterInputStream {
30:
31: private byte[] password; // Password to use to decrypt the input bytes
32:
33: private int pwdIndex; // Index into the password array.
34:
35: /**
36: * Constructs a new instance of the receiver.
37: *
38: * @param in The actual input stream where to read the bytes from.
39: * @param password The password bytes to use to decrypt the input bytes
40: */
41: public PasswordProtectedInputStream(InputStream in, byte[] password) {
42: super (in);
43: this .password = password.clone();
44: }
45:
46: @Override
47: public int read() throws IOException {
48: int read = in.read();
49: if (read >= 0) {
50: read ^= password[pwdIndex];
51: pwdIndex = (pwdIndex + 1) % password.length;
52: }
53: return read;
54: }
55:
56: @Override
57: public int read(byte b[], int off, int len) throws IOException {
58: int read = in.read(b, off, len);
59: if (read > 0) {
60: int lastIndex = off + read;
61: for (int i = off; i < lastIndex; i++) {
62: b[i] ^= password[pwdIndex];
63: pwdIndex = (pwdIndex + 1) % password.length;
64: }
65: }
66: return read;
67: }
68:
69: @Override
70: public long skip(long n) throws IOException {
71: long skip = super.skip(n);
72: pwdIndex += skip;
73: return skip;
74: }
75: }
|