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.examples;
19  
20  import java.nio.ByteBuffer;
21  import java.nio.charset.StandardCharsets;
22  import java.util.Arrays;
23  import java.util.Properties;
24  
25  import javax.crypto.Cipher;
26  import javax.crypto.spec.IvParameterSpec;
27  import javax.crypto.spec.SecretKeySpec;
28  
29  import org.apache.commons.crypto.cipher.CryptoCipher;
30  import org.apache.commons.crypto.utils.AES;
31  import org.apache.commons.crypto.utils.Utils;
32  
33  /**
34   * Example showing the CryptoCipher API using a ByteBuffer
35   */
36  public class CipherByteBufferExample {
37  
38      /**
39       * Converts ByteBuffer to String
40       *
41       * @param buffer input byte buffer
42       * @return the converted string
43       */
44      private static String asString(final ByteBuffer buffer) {
45          final ByteBuffer copy = buffer.duplicate();
46          final byte[] bytes = new byte[copy.remaining()];
47          copy.get(bytes);
48          return new String(bytes, StandardCharsets.UTF_8);
49      }
50  
51      /**
52       * Converts String to UTF8 bytes
53       *
54       * @param input the input string
55       * @return UTF8 bytes
56       */
57      private static byte[] getUTF8Bytes(final String input) {
58          return input.getBytes(StandardCharsets.UTF_8);
59      }
60  
61      public static void main(final String[] args) throws Exception {
62          final SecretKeySpec key = AES.newSecretKeySpec(getUTF8Bytes("1234567890123456"));
63          final IvParameterSpec iv = new IvParameterSpec(getUTF8Bytes("1234567890123456"));
64          final Properties properties = new Properties();
65          //Creates a CryptoCipher instance with the transformation and properties.
66          final String transform = AES.CBC_PKCS5_PADDING;
67          final ByteBuffer outBuffer;
68          final int bufferSize = 1024;
69          final int updateBytes;
70          final int finalBytes;
71          try (CryptoCipher encipher = Utils.getCipherInstance(transform, properties)) {
72  
73              final ByteBuffer inBuffer = ByteBuffer.allocateDirect(bufferSize);
74              outBuffer = ByteBuffer.allocateDirect(bufferSize);
75              inBuffer.put(getUTF8Bytes("hello world!"));
76  
77              inBuffer.flip(); // ready for the cipher to read it
78              // Show the data is there
79              System.out.println("inBuffer=" + asString(inBuffer));
80  
81              // Initializes the cipher with ENCRYPT_MODE,key and iv.
82              encipher.init(Cipher.ENCRYPT_MODE, key, iv);
83              // Continues a multiple-part encryption/decryption operation for byte buffer.
84              updateBytes = encipher.update(inBuffer, outBuffer);
85              System.out.println(updateBytes);
86  
87              // We should call do final at the end of encryption/decryption.
88              finalBytes = encipher.doFinal(inBuffer, outBuffer);
89              System.out.println(finalBytes);
90          }
91  
92          outBuffer.flip(); // ready for use as decrypt
93          final byte [] encoded = new byte[updateBytes + finalBytes];
94          outBuffer.duplicate().get(encoded);
95          System.out.println(Arrays.toString(encoded));
96  
97          // Now reverse the process
98          try (CryptoCipher decipher = Utils.getCipherInstance(transform, properties)) {
99              decipher.init(Cipher.DECRYPT_MODE, key, iv);
100             final ByteBuffer decoded = ByteBuffer.allocateDirect(bufferSize);
101             decipher.update(outBuffer, decoded);
102             decipher.doFinal(outBuffer, decoded);
103             decoded.flip(); // ready for use
104             System.out.println("decoded="+asString(decoded));
105         }
106     }
107 
108 }