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 java.nio.charset.StandardCharsets;
20  
21  import javax.crypto.Cipher;
22  import javax.crypto.spec.SecretKeySpec;
23  
24  /**
25   * Allows passwords to be encrypted and decrypted.
26   * <p>
27   * Warning: This uses AES128 with a fixed encryption key. This is only an obfuscation no cryptographic secure
28   * protection.
29   * </p>
30   *
31   * @since 2.0
32   */
33  public class DefaultCryptor implements Cryptor {
34      private static final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
35              'F' };
36  
37      private static final byte[] KEY_BYTES = { 0x41, 0x70, 0x61, 0x63, 0x68, 0x65, 0x43, 0x6F, 0x6D, 0x6D, 0x6F, 0x6E,
38              0x73, 0x56, 0x46, 0x53 };
39  
40      private static final int INDEX_NOT_FOUND = -1;
41  
42      private static final int BITS_IN_HALF_BYTE = 4;
43  
44      private static final char MASK = 0x0f;
45  
46      /**
47       * Encrypt the plain text password.
48       * <p>
49       * Warning: This uses AES128 with a fixed encryption key. This is only an obfuscation no cryptographic secure
50       * protection.
51       *
52       * @param plainKey The password.
53       * @return The encrypted password String.
54       * @throws Exception If an error occurs.
55       */
56      @Override
57      public String encrypt(final String plainKey) throws Exception {
58          final byte[] input = plainKey.getBytes(StandardCharsets.UTF_8);
59          final SecretKeySpec key = new SecretKeySpec(KEY_BYTES, "AES");
60  
61          final Cipher cipher = Cipher.getInstance("AES");
62  
63          // encryption pass
64          cipher.init(Cipher.ENCRYPT_MODE, key);
65  
66          final byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
67          int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
68          ctLength += cipher.doFinal(cipherText, ctLength);
69          return encode(cipherText);
70      }
71  
72      /**
73       * Decrypts the password.
74       *
75       * @param encryptedKey the encrypted password.
76       * @return The plain text password.
77       * @throws Exception If an error occurs.
78       */
79      @Override
80      public String decrypt(final String encryptedKey) throws Exception {
81          final SecretKeySpec key = new SecretKeySpec(KEY_BYTES, "AES");
82          final Cipher cipher = Cipher.getInstance("AES");
83          cipher.init(Cipher.DECRYPT_MODE, key);
84          final byte[] decoded = decode(encryptedKey);
85          final byte[] plainText = new byte[cipher.getOutputSize(decoded.length)];
86          int ptLength = cipher.update(decoded, 0, decoded.length, plainText, 0);
87          ptLength += cipher.doFinal(plainText, ptLength);
88          return new String(plainText, StandardCharsets.UTF_8).substring(0, ptLength);
89      }
90  
91      /** Hex-encode bytes. */
92      private String encode(final byte[] bytes) {
93          final StringBuilder builder = new StringBuilder();
94  
95          for (final byte b : bytes) {
96              builder.append(HEX_CHARS[(b >> BITS_IN_HALF_BYTE) & MASK]);
97              builder.append(HEX_CHARS[b & MASK]);
98          }
99          return builder.toString();
100     }
101 
102     /** Decodes Hex-Bytes. */
103     private byte[] decode(final String str) {
104         final char[] chars = str.toCharArray();
105         final int length = chars.length / 2;
106         final byte[] decoded = new byte[length];
107         if (length * 2 != chars.length)
108         {
109         	throw new IllegalArgumentException("The given string must have even number of hex chars.");
110         }
111         int index = 0;
112         for (int i = 0; i < length; i++) {
113             final int id1 = indexOf(HEX_CHARS, chars[index++]);
114             if (id1 == INDEX_NOT_FOUND) {
115                 throw new IllegalArgumentException(
116                         "Character " + chars[index-1] + " at position " + (index-1) + " is not a valid hexidecimal character");
117             }
118             final int id2 = indexOf(HEX_CHARS, chars[index++]);
119             if (id2 == INDEX_NOT_FOUND) {
120                 throw new IllegalArgumentException(
121                         "Character " + chars[index-1] + " at position " + (index-1) + " is not a valid hexidecimal character");
122             }
123             decoded[i] = (byte) ((id1 << BITS_IN_HALF_BYTE) | id2);
124         }
125         return decoded;
126     }
127 
128     private int indexOf(final char[] array, final char valueToFind) {
129         if (array == null) {
130             return INDEX_NOT_FOUND;
131         }
132         for (int i = 0; i < array.length; i++) {
133             if (valueToFind == array[i]) {
134                 return i;
135             }
136         }
137         return INDEX_NOT_FOUND;
138     }
139 }