1/*
2 * Copyright (c) 1997, 2017, 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 output-feedback (OFB) 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 */
42final class OutputFeedback extends FeedbackCipher {
43
44    /*
45     * output buffer
46     */
47    private byte[] k = null;
48
49    /*
50     * register buffer
51     */
52    private byte[] register = null;
53
54    /*
55     * number of bytes for each stream unit, defaults to the blocksize
56     * of the embedded cipher
57     */
58    private int numBytes;
59
60    // variables for save/restore calls
61    private byte[] registerSave = null;
62
63    OutputFeedback(SymmetricCipher embeddedCipher, int numBytes) {
64        super(embeddedCipher);
65        if (numBytes > blockSize) {
66            numBytes = blockSize;
67        }
68        this.numBytes = numBytes;
69        k = new byte[blockSize];
70        register = new byte[blockSize];
71    }
72
73    /**
74     * Gets the name of this feedback mode.
75     *
76     * @return the string <code>OFB</code>
77     */
78    String getFeedback() {
79        return "OFB";
80    }
81
82    /**
83     * Initializes the cipher in the specified mode with the given key
84     * and iv.
85     *
86     * @param decrypting flag indicating encryption or decryption
87     * @param algorithm the algorithm name
88     * @param key the key
89     * @param iv the iv
90     *
91     * @exception InvalidKeyException if the given key is inappropriate for
92     * initializing this cipher
93     */
94    void init(boolean decrypting, String algorithm, byte[] key, byte[] iv)
95            throws InvalidKeyException {
96        if ((key == null) || (iv == null) || (iv.length != blockSize)) {
97            throw new InvalidKeyException("Internal error");
98        }
99        this.iv = iv;
100        reset();
101        // always encrypt mode for embedded cipher
102        embeddedCipher.init(false, algorithm, key);
103    }
104
105    /**
106     * Resets the iv to its original value.
107     * This is used when doFinal is called in the Cipher class, so that the
108     * cipher can be reused (with its original iv).
109     */
110    void reset() {
111        System.arraycopy(iv, 0, register, 0, blockSize);
112    }
113
114    /**
115     * Save the current content of this cipher.
116     */
117    void save() {
118        if (registerSave == null) {
119            registerSave = new byte[blockSize];
120        }
121        System.arraycopy(register, 0, registerSave, 0, blockSize);
122    }
123
124    /**
125     * Restores the content of this cipher to the previous saved one.
126     */
127    void restore() {
128        System.arraycopy(registerSave, 0, register, 0, blockSize);
129    }
130
131    /**
132     * Performs encryption operation.
133     *
134     * <p>The input plain text <code>plain</code>, starting at
135     * <code>plainOffset</code> and ending at
136     * <code>(plainOffset + plainLen - 1)</code>, is encrypted.
137     * The result is stored in <code>cipher</code>, starting at
138     * <code>cipherOffset</code>.
139     *
140     * @param plain the buffer with the input data to be encrypted
141     * @param plainOffset the offset in <code>plain</code>
142     * @param plainLen the length of the input data
143     * @param cipher the buffer for the result
144     * @param cipherOffset the offset in <code>cipher</code>
145     * @exception ProviderException if <code>plainLen</code> is not
146     * a multiple of the <code>numBytes</code>
147     * @return the length of the encrypted data
148     */
149    int encrypt(byte[] plain, int plainOffset, int plainLen,
150                byte[] cipher, int cipherOffset) {
151
152        if ((plainLen % numBytes) != 0) {
153            throw new ProviderException("Internal error in input buffering");
154        }
155        int nShift = blockSize - numBytes;
156        int loopCount = plainLen / numBytes;
157
158        for (; loopCount > 0;
159             plainOffset += numBytes, cipherOffset += numBytes,
160             loopCount--) {
161            embeddedCipher.encryptBlock(register, 0, k, 0);
162            for (int i = 0; i < numBytes; i++) {
163                cipher[i + cipherOffset] =
164                    (byte)(k[i] ^ plain[i + plainOffset]);
165            }
166            if (nShift != 0) {
167                System.arraycopy(register, numBytes, register, 0, nShift);
168            }
169            System.arraycopy(k, 0, register, nShift, numBytes);
170        }
171        return plainLen;
172    }
173
174    /**
175     * Performs 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 length of the encrypted data
189     */
190    int encryptFinal(byte[] plain, int plainOffset, int plainLen,
191                     byte[] cipher, int cipherOffset) {
192        int oddBytes = plainLen % numBytes;
193        int len = encrypt(plain, plainOffset, (plainLen - oddBytes),
194                          cipher, cipherOffset);
195        plainOffset += len;
196        cipherOffset += len;
197
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    // OFB encrypt and decrypt are identical
209    int decrypt(byte[] cipher, int cipherOffset, int cipherLen,
210                byte[] plain, int plainOffset) {
211        return encrypt(cipher, cipherOffset, cipherLen, plain, plainOffset);
212    }
213
214    // OFB encrypt and decrypt are identical
215    int decryptFinal(byte[] cipher, int cipherOffset, int cipherLen,
216                     byte[] plain, int plainOffset) {
217        // OFB encrypt and decrypt are identical
218        return encryptFinal(cipher, cipherOffset, cipherLen, plain, plainOffset);
219    }
220}
221