1/*
2 * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package com.sun.crypto.provider;
27
28import java.security.InvalidKeyException;
29import java.security.ProviderException;
30
31/**
32 * This class represents ciphers in cipher-feedback (CFB) mode.
33 *
34 * <p>This mode is implemented independently of a particular cipher.
35 * Ciphers to which this mode should apply (e.g., DES) must be
36 * <i>plugged-in</i> using the constructor.
37 *
38 * <p>NOTE: This class does not deal with buffering or padding.
39 *
40 * @author Gigi Ankeny
41 */
42
43final class CipherFeedback extends FeedbackCipher {
44
45    /*
46     * encrypt/decrypt output buffer
47     */
48    private final byte[] k;
49
50    /*
51     * register value, initialized with iv
52     */
53    private final byte[] register;
54
55    /*
56     * number of bytes for each stream unit, defaults to the blocksize
57     * of the embedded cipher
58     */
59    private int numBytes;
60
61    // variables for save/restore calls
62    private byte[] registerSave = null;
63
64    CipherFeedback(SymmetricCipher embeddedCipher, int numBytes) {
65        super(embeddedCipher);
66        if (numBytes > blockSize) {
67            numBytes = blockSize;
68        }
69        this.numBytes = numBytes;
70        k = new byte[blockSize];
71        register = new byte[blockSize];
72    }
73
74    /**
75     * Gets the name of this feedback mode.
76     *
77     * @return the string <code>CFB</code>
78     */
79    String getFeedback() {
80        return "CFB";
81    }
82
83    /**
84     * Initializes the cipher in the specified mode with the given key
85     * and iv.
86     *
87     * @param decrypting flag indicating encryption or decryption
88     * @param algorithm the algorithm name
89     * @param key the key
90     * @param iv the iv
91     *
92     * @exception InvalidKeyException if the given key is inappropriate for
93     * initializing this cipher
94     */
95    void init(boolean decrypting, String algorithm, byte[] key, byte[] iv)
96            throws InvalidKeyException {
97        if ((key == null) || (iv == null) || (iv.length != blockSize)) {
98            throw new InvalidKeyException("Internal error");
99        }
100        this.iv = iv;
101        reset();
102        // always encrypt mode for embedded cipher
103        embeddedCipher.init(false, algorithm, key);
104    }
105
106    /**
107     * Resets the iv to its original value.
108     * This is used when doFinal is called in the Cipher class, so that the
109     * cipher can be reused (with its original iv).
110     */
111    void reset() {
112        System.arraycopy(iv, 0, register, 0, blockSize);
113    }
114
115    /**
116     * Save the current content of this cipher.
117     */
118    void save() {
119        if (registerSave == null) {
120            registerSave = new byte[blockSize];
121        }
122        System.arraycopy(register, 0, registerSave, 0, blockSize);
123    }
124
125    /**
126     * Restores the content of this cipher to the previous saved one.
127     */
128    void restore() {
129        System.arraycopy(registerSave, 0, register, 0, blockSize);
130    }
131
132    /**
133     * Performs encryption operation.
134     *
135     * <p>The input plain text <code>plain</code>, starting at
136     * <code>plainOffset</code> and ending at
137     * <code>(plainOffset + plainLen - 1)</code>, is encrypted.
138     * The result is stored in <code>cipher</code>, starting at
139     * <code>cipherOffset</code>.
140     *
141     * @param plain the buffer with the input data to be encrypted
142     * @param plainOffset the offset in <code>plain</code>
143     * @param plainLen the length of the input data
144     * @param cipher the buffer for the result
145     * @param cipherOffset the offset in <code>cipher</code>
146     * @exception ProviderException if <code>plainLen</code> is not
147     * a multiple of the <code>numBytes</code>
148     * @return the length of the encrypted data
149     */
150    int encrypt(byte[] plain, int plainOffset, int plainLen,
151                byte[] cipher, int cipherOffset) {
152        if ((plainLen % numBytes) != 0) {
153            throw new ProviderException("Internal error in input buffering");
154        }
155
156        int nShift = blockSize - numBytes;
157        int loopCount = plainLen / numBytes;
158
159        for (; loopCount > 0 ;
160             plainOffset += numBytes, cipherOffset += numBytes,
161             loopCount--) {
162            embeddedCipher.encryptBlock(register, 0, k, 0);
163            if (nShift != 0) {
164                System.arraycopy(register, numBytes, register, 0, nShift);
165            }
166            for (int i = 0; i < numBytes; i++) {
167                register[nShift + i] = cipher[i + cipherOffset] =
168                        (byte)(k[i] ^ plain[i + plainOffset]);
169            }
170        }
171        return plainLen;
172    }
173
174    /**
175     * Performs the last encryption operation.
176     *
177     * <p>The input plain text <code>plain</code>, starting at
178     * <code>plainOffset</code> and ending at
179     * <code>(plainOffset + plainLen - 1)</code>, is encrypted.
180     * The result is stored in <code>cipher</code>, starting at
181     * <code>cipherOffset</code>.
182     *
183     * @param plain the buffer with the input data to be encrypted
184     * @param plainOffset the offset in <code>plain</code>
185     * @param plainLen the length of the input data
186     * @param cipher the buffer for the result
187     * @param cipherOffset the offset in <code>cipher</code>
188     * @return the number of bytes placed into <code>cipher</code>
189     */
190    int encryptFinal(byte[] plain, int plainOffset, int plainLen,
191                     byte[] cipher, int cipherOffset) {
192
193        int oddBytes = plainLen % numBytes;
194        int len = encrypt(plain, plainOffset, (plainLen - oddBytes),
195                          cipher, cipherOffset);
196        plainOffset += len;
197        cipherOffset += len;
198        if (oddBytes != 0) {
199            embeddedCipher.encryptBlock(register, 0, k, 0);
200            for (int i = 0; i < oddBytes; i++) {
201                 cipher[i + cipherOffset] =
202                    (byte)(k[i] ^ plain[i + plainOffset]);
203            }
204        }
205        return plainLen;
206    }
207
208    /**
209     * Performs decryption operation.
210     *
211     * <p>The input cipher text <code>cipher</code>, starting at
212     * <code>cipherOffset</code> and ending at
213     * <code>(cipherOffset + cipherLen - 1)</code>, is decrypted.
214     * The result is stored in <code>plain</code>, starting at
215     * <code>plainOffset</code>.
216     *
217     * @param cipher the buffer with the input data to be decrypted
218     * @param cipherOffset the offset in <code>cipherOffset</code>
219     * @param cipherLen the length of the input data
220     * @param plain the buffer for the result
221     * @param plainOffset the offset in <code>plain</code>
222     * @exception ProviderException if <code>cipherLen</code> is not
223     * a multiple of the <code>numBytes</code>
224     * @return the length of the decrypted data
225     */
226    int decrypt(byte[] cipher, int cipherOffset, int cipherLen,
227                byte[] plain, int plainOffset) {
228        if ((cipherLen % numBytes) != 0) {
229            throw new ProviderException("Internal error in input buffering");
230        }
231
232        int nShift = blockSize - numBytes;
233        int loopCount = cipherLen / numBytes;
234
235        for (; loopCount > 0;
236             plainOffset += numBytes, cipherOffset += numBytes,
237             loopCount--) {
238            embeddedCipher.encryptBlock(register, 0, k, 0);
239            if (nShift != 0) {
240                System.arraycopy(register, numBytes, register, 0, nShift);
241            }
242            for (int i = 0; i < numBytes; i++) {
243                register[i + nShift] = cipher[i + cipherOffset];
244                plain[i + plainOffset]
245                    = (byte)(cipher[i + cipherOffset] ^ k[i]);
246            }
247        }
248        return cipherLen;
249    }
250
251    /**
252     * Performs the last decryption operation.
253     *
254     * <p>The input cipher text <code>cipher</code>, starting at
255     * <code>cipherOffset</code> and ending at
256     * <code>(cipherOffset + cipherLen - 1)</code>, is decrypted.
257     * The result is stored in <code>plain</code>, starting at
258     * <code>plainOffset</code>.
259     *
260     * @param cipher the buffer with the input data to be decrypted
261     * @param cipherOffset the offset in <code>cipherOffset</code>
262     * @param cipherLen the length of the input data
263     * @param plain the buffer for the result
264     * @param plainOffset the offset in <code>plain</code>
265     * @return the length of the decrypted data
266     */
267    int decryptFinal(byte[] cipher, int cipherOffset, int cipherLen,
268                byte[] plain, int plainOffset) {
269
270        int oddBytes = cipherLen % numBytes;
271        int len = decrypt(cipher, cipherOffset, (cipherLen - oddBytes),
272                          plain, plainOffset);
273        cipherOffset += len;
274        plainOffset += len;
275        if (oddBytes != 0) {
276            embeddedCipher.encryptBlock(register, 0, k, 0);
277            for (int i = 0; i < oddBytes; i++) {
278                plain[i + plainOffset]
279                    = (byte)(cipher[i + cipherOffset] ^ k[i]);
280            }
281        }
282        return cipherLen;
283    }
284}
285