View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.vfs2.util;
18  
19  import javax.crypto.Cipher;
20  import javax.crypto.spec.SecretKeySpec;
21  
22  /**
23   * Allows passwords to be encrypted and decrypted.
24   * <p>
25   * Warning: This uses AES128 with a fixed encryption key. This is only an obfuscation no cryptographic secure
26   * protection.
27   * </p>
28   *
29   * @since 2.0
30   */
31  public class DefaultCryptor implements Cryptor {
32      private static final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
33              'F' };
34  
35      private static final byte[] KEY_BYTES = { 0x41, 0x70, 0x61, 0x63, 0x68, 0x65, 0x43, 0x6F, 0x6D, 0x6D, 0x6F, 0x6E,
36              0x73, 0x56, 0x46, 0x53 };
37  
38      private static final int INDEX_NOT_FOUND = -1;
39  
40      private static final int BITS_IN_HALF_BYTE = 4;
41  
42      private static final char MASK = 0x0f;
43  
44      /**
45       * Encrypt the plain text password.
46       * <p>
47       * Warning: This uses AES128 with a fixed encryption key. This is only an obfuscation no cryptographic secure
48       * protection.
49       *
50       * @param plainKey The password.
51       * @return The encrypted password String.
52       * @throws Exception If an error occurs.
53       */
54      @Override
55      public String encrypt(final String plainKey) throws Exception {
56          final byte[] input = plainKey.getBytes();
57          final SecretKeySpec key = new SecretKeySpec(KEY_BYTES, "AES");
58  
59          final Cipher cipher = Cipher.getInstance("AES");
60  
61          // encryption pass
62          cipher.init(Cipher.ENCRYPT_MODE, key);
63  
64          final byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
65          int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
66          ctLength += cipher.doFinal(cipherText, ctLength);
67          return encode(cipherText);
68      }
69  
70      /**
71       * Decrypts the password.
72       *
73       * @param encryptedKey the encrypted password.
74       * @return The plain text password.
75       * @throws Exception If an error occurs.
76       */
77      @Override
78      public String decrypt(final String encryptedKey) throws Exception {
79          final SecretKeySpec key = new SecretKeySpec(KEY_BYTES, "AES");
80          final Cipher cipher = Cipher.getInstance("AES");
81          cipher.init(Cipher.DECRYPT_MODE, key);
82          final byte[] decoded = decode(encryptedKey);
83          final byte[] plainText = new byte[cipher.getOutputSize(decoded.length)];
84          int ptLength = cipher.update(decoded, 0, decoded.length, plainText, 0);
85          ptLength += cipher.doFinal(plainText, ptLength);
86          return new String(plainText).substring(0, ptLength);
87      }
88  
89      /** Hex-encode bytes. */
90      private String encode(final byte[] bytes) {
91          final StringBuilder builder = new StringBuilder();
92  
93          for (final byte b : bytes) {
94              builder.append(HEX_CHARS[(b >> BITS_IN_HALF_BYTE) & MASK]);
95              builder.append(HEX_CHARS[b & MASK]);
96          }
97          return builder.toString();
98      }
99  
100     /** Decodes Hex-Bytes. */
101     private byte[] decode(final String str) {
102         final char[] chars = str.toCharArray();
103         final int length = chars.length / 2;
104         final byte[] decoded = new byte[length];
105         if (length * 2 != chars.length)
106         {
107         	throw new IllegalArgumentException("The given string must have even number of hex chars.");
108         }
109         int index = 0;
110         for (int i = 0; i < length; i++) {
111             final int id1 = indexOf(HEX_CHARS, chars[index++]);
112             if (id1 == INDEX_NOT_FOUND) {
113                 throw new IllegalArgumentException(
114                         "Character " + chars[index-1] + " at position " + (index-1) + " is not a valid hexidecimal character");
115             }
116             final int id2 = indexOf(HEX_CHARS, chars[index++]);
117             if (id2 == INDEX_NOT_FOUND) {
118                 throw new IllegalArgumentException(
119                         "Character " + chars[index-1] + " at position " + (index-1) + " is not a valid hexidecimal character");
120             }
121             decoded[i] = (byte) ((id1 << BITS_IN_HALF_BYTE) | id2);
122         }
123         return decoded;
124     }
125 
126     private int indexOf(final char[] array, final char valueToFind) {
127         if (array == null) {
128             return INDEX_NOT_FOUND;
129         }
130         for (int i = 0; i < array.length; i++) {
131             if (valueToFind == array[i]) {
132                 return i;
133             }
134         }
135         return INDEX_NOT_FOUND;
136     }
137 }