View Javadoc
1   /*
2   * Licensed to the Apache Software Foundation (ASF) under one
3   * or more contributor license agreements.  See the NOTICE file
4   * distributed with this work for additional information
5   * regarding copyright ownership.  The ASF licenses this file
6   * to you under the Apache License, Version 2.0 (the
7   * "License"); you may not use this file except in compliance
8   * with the License.  You may obtain a copy of the License at
9   *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18  package org.apache.commons.crypto.cipher;
19  
20  import java.nio.ByteBuffer;
21  import java.security.InvalidAlgorithmParameterException;
22  import java.security.spec.AlgorithmParameterSpec;
23  
24  import javax.crypto.BadPaddingException;
25  import javax.crypto.IllegalBlockSizeException;
26  import javax.crypto.ShortBufferException;
27  
28  import org.apache.commons.crypto.utils.Utils;
29  
30  /**
31   * This class represents a block cipher in one of its modes.
32   */
33  abstract class AbstractOpenSslFeedbackCipher {
34  
35      protected long context;
36      protected final int algorithmMode;
37      protected final int padding;
38  
39      protected int cipherMode = OpenSsl.DECRYPT_MODE;
40  
41      AbstractOpenSslFeedbackCipher(final long context, final int algorithmMode, final int padding) {
42          this.context = context;
43          this.algorithmMode = algorithmMode;
44          this.padding = padding;
45      }
46  
47      public void checkState() {
48          Utils.checkState(context != 0, "Cipher context is invalid.");
49      }
50  
51      public void clean() {
52          if (context != 0) {
53              OpenSslNative.clean(context);
54              context = 0;
55          }
56      }
57  
58      abstract int doFinal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)
59              throws ShortBufferException, IllegalBlockSizeException, BadPaddingException;
60  
61      abstract int doFinal(ByteBuffer input, ByteBuffer output) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException;
62  
63      abstract void init(int mode, byte[] key, AlgorithmParameterSpec params) throws InvalidAlgorithmParameterException;
64  
65      abstract int update(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException;
66  
67      abstract int update(ByteBuffer input, ByteBuffer output) throws ShortBufferException;
68  
69      abstract void updateAAD(byte[] aad);
70  }