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