001/*
002 * (C) Copyright 2015-2017 Nuxeo (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     jcarsique
018 *     Kevin Leturc <kleturc@nuxeo.com>
019 */
020package org.nuxeo.common.codec;
021
022import java.io.File;
023import java.io.FileInputStream;
024import java.io.FileOutputStream;
025import java.io.IOException;
026import java.io.InputStream;
027import java.io.OutputStream;
028import java.nio.ByteBuffer;
029import java.nio.CharBuffer;
030import java.nio.charset.Charset;
031import java.security.GeneralSecurityException;
032import java.security.InvalidKeyException;
033import java.security.KeyStore;
034import java.security.KeyStore.PasswordProtection;
035import java.security.KeyStoreException;
036import java.security.MessageDigest;
037import java.security.NoSuchAlgorithmException;
038import java.security.Security;
039import java.util.Arrays;
040import java.util.HashMap;
041import java.util.Map;
042import java.util.regex.Matcher;
043import java.util.regex.Pattern;
044
045import javax.crypto.BadPaddingException;
046import javax.crypto.Cipher;
047import javax.crypto.IllegalBlockSizeException;
048import javax.crypto.NoSuchPaddingException;
049import javax.crypto.SecretKey;
050import javax.crypto.spec.SecretKeySpec;
051
052import org.apache.commons.codec.binary.Base64;
053import org.apache.commons.lang3.StringUtils;
054import org.apache.commons.logging.Log;
055import org.apache.commons.logging.LogFactory;
056
057/**
058 * Supported algorithms (name, keysize):
059 * <ul>
060 * <li>AES/ECB/PKCS5Padding (128)</li>
061 * <li>DES/ECB/PKCS5Padding (64)</li>
062 * <ul/>
063 *
064 * @since 7.4
065 */
066public class Crypto {
067
068    protected static final Pattern CRYPTO_PATTERN = Pattern.compile("\\{\\$(?<algo>.*)\\$(?<value>.+)\\}");
069
070    private static final Log log = LogFactory.getLog(Crypto.class);
071
072    public static final String AES = "AES";
073
074    public static final String AES_ECB_PKCS5PADDING = "AES/ECB/PKCS5Padding";
075
076    public static final String DES = "DES";
077
078    public static final String DES_ECB_PKCS5PADDING = "DES/ECB/PKCS5Padding";
079
080    public static final String[] IMPLEMENTED_ALGOS = { AES, DES, AES_ECB_PKCS5PADDING, DES_ECB_PKCS5PADDING };
081
082    public static final String DEFAULT_ALGO = AES_ECB_PKCS5PADDING;
083
084    private static final String SHA1 = "SHA-1";
085
086    private final byte[] secretKey;
087
088    private final Map<String, SecretKey> secretKeys = new HashMap<>();
089
090    private boolean initialized = true;
091
092    private final byte[] digest;
093
094    public Crypto(byte[] secretKey) {
095        this.secretKey = secretKey;
096        digest = getSHA1DigestOrEmpty(secretKey);
097        if (digest.length == 0) {
098            clear();
099        }
100    }
101
102    /**
103     * Initialize cryptography with a map of {@link SecretKey}.
104     *
105     * @param secretKeys Map of {@code SecretKey} per algorithm
106     */
107    public Crypto(Map<String, SecretKey> secretKeys) {
108        this(secretKeys, Crypto.class.getName().toCharArray());
109    }
110
111    /**
112     * Initialize cryptography with a map of {@link SecretKey}.
113     *
114     * @param digest Digest for later use by {@link #verifyKey(byte[])}
115     * @param secretKeys Map of {@code SecretKey} per algorithm
116     */
117    public Crypto(Map<String, SecretKey> secretKeys, char[] digest) {
118        secretKey = new byte[0];
119        this.digest = getSHA1DigestOrEmpty(getBytes(digest));
120        this.secretKeys.putAll(secretKeys);
121        if (this.digest.length == 0) {
122            clear();
123        }
124    }
125
126    /**
127     * Initialize cryptography with a keystore.
128     *
129     * @param keystorePath Path to the keystore.
130     * @param keystorePass Keystore password. It is also used to generate the digest for {@link #verifyKey(byte[])}
131     * @param keyAlias Key alias prefix. It is suffixed with the algorithm.
132     * @param keyPass Key password
133     * @throws IOException
134     * @throws GeneralSecurityException
135     */
136    public Crypto(String keystorePath, char[] keystorePass, String keyAlias, char[] keyPass)
137            throws GeneralSecurityException, IOException {
138        this(Crypto.getKeysFromKeyStore(keystorePath, keystorePass, keyAlias, keyPass), keystorePass);
139    }
140
141    public static final class NoOp extends Crypto {
142
143        public static final Crypto NO_OP = new NoOp();
144
145        private NoOp() {
146            super(new byte[0]);
147        }
148
149        @Override
150        public String encrypt(String algorithm, byte[] bytesToEncrypt) throws GeneralSecurityException {
151            return null;
152        }
153
154        @Override
155        public byte[] decrypt(String strToDecrypt) {
156            return strToDecrypt.getBytes();
157        }
158
159        @Override
160        public void clear() {
161            // NO OP
162        }
163    }
164
165    protected SecretKey getSecretKey(String algorithm, byte[] key) throws NoSuchAlgorithmException {
166        if (!initialized) {
167            throw new RuntimeException("The Crypto object has been cleared.");
168        }
169        if (AES_ECB_PKCS5PADDING.equals(algorithm)) {
170            algorithm = AES; // AES_ECB_PKCS5PADDING is the default for AES
171        } else if (DES_ECB_PKCS5PADDING.equals(algorithm)) {
172            algorithm = DES; // DES_ECB_PKCS5PADDING is the default for DES
173        }
174        if (!secretKeys.containsKey(algorithm)) {
175            if (secretKey.length == 0) {
176                throw new NoSuchAlgorithmException("Unsupported algorithm: " + algorithm);
177            }
178            if (AES.equals(algorithm)) { // default for AES
179                key = Arrays.copyOf(getSHA1Digest(key), 16); // use a 128 bits secret key
180                secretKeys.put(AES, new SecretKeySpec(key, AES));
181            } else if (DES.equals(algorithm)) { // default for DES
182                key = Arrays.copyOf(getSHA1Digest(key), 8); // use a 64 bits secret key
183                secretKeys.put(DES, new SecretKeySpec(key, DES));
184            } else {
185                throw new NoSuchAlgorithmException("Unsupported algorithm: " + algorithm);
186            }
187        }
188        return secretKeys.get(algorithm);
189    }
190
191    public byte[] getSHA1Digest(final byte[] key) throws NoSuchAlgorithmException {
192        MessageDigest sha = MessageDigest.getInstance(SHA1);
193        return sha.digest(key);
194    }
195
196    public byte[] getSHA1DigestOrEmpty(final byte[] bytes) {
197        byte[] aDigest = new byte[0];
198        try {
199            aDigest = getSHA1Digest(bytes);
200        } catch (NoSuchAlgorithmException e) {
201            log.error(e);
202        }
203        return aDigest;
204    }
205
206    public String encrypt(byte[] bytesToEncrypt) throws GeneralSecurityException {
207        return encrypt(null, bytesToEncrypt);
208    }
209
210    /**
211     * @param algorithm cipher transformation of the form "algorithm/mode/padding" or "algorithm". See the Cipher
212     *            section in the <a
213     *            href=http://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#Cipher>Java
214     *            Cryptography Architecture Standard Algorithm Name Documentation</a>.
215     * @throws NoSuchPaddingException if {@code algorithm} contains a padding scheme that is not available.
216     * @throws NoSuchAlgorithmException if {@code algorithm} is in an invalid or not supported format.
217     * @throws GeneralSecurityException
218     */
219    public String encrypt(String algorithm, byte[] bytesToEncrypt) throws GeneralSecurityException {
220        final String encryptedAlgo;
221        if (StringUtils.isBlank(algorithm)) {
222            algorithm = DEFAULT_ALGO;
223            encryptedAlgo = "";
224        } else {
225            encryptedAlgo = Base64.encodeBase64String(algorithm.getBytes());
226        }
227        Cipher cipher = Cipher.getInstance(algorithm);
228        cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(algorithm, secretKey));
229        final String encryptedString = Base64.encodeBase64String(cipher.doFinal(bytesToEncrypt));
230        return String.format("{$%s$%s}", encryptedAlgo, encryptedString);
231    }
232
233    /**
234     * The method returns either the decrypted {@code strToDecrypt}, either the {@code strToDecrypt} itself if it is not
235     * recognized as a crypted string or if the decryption fails. The return value is a byte array for security purpose,
236     * it is your responsibility to convert it then to a String or not (use of {@code char[]} is recommended).
237     *
238     * @return the decrypted {@code strToDecrypt} as an array of bytes, never {@code null}
239     * @see #getChars(byte[])
240     */
241    public byte[] decrypt(String strToDecrypt) {
242        Matcher matcher = CRYPTO_PATTERN.matcher(strToDecrypt);
243        if (!matcher.matches()) {
244            return strToDecrypt.getBytes();
245        }
246        Cipher decipher;
247        try {
248            String algorithm = new String(Base64.decodeBase64(matcher.group("algo")));
249            if (StringUtils.isBlank(algorithm)) {
250                algorithm = DEFAULT_ALGO;
251            }
252            decipher = Cipher.getInstance(algorithm);
253            decipher.init(Cipher.DECRYPT_MODE, getSecretKey(algorithm, secretKey));
254            return decipher.doFinal(Base64.decodeBase64(matcher.group("value")));
255        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
256            log.trace("Available algorithms: " + Security.getAlgorithms("Cipher"));
257            log.trace("Available security providers: " + Arrays.asList(Security.getProviders()));
258            log.debug(e, e);
259        } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
260            log.debug(e, e);
261        }
262        return strToDecrypt.getBytes();
263    }
264
265    /**
266     * Clear sensible values. That makes the current object unusable.
267     */
268    public void clear() {
269        Arrays.fill(secretKey, (byte) 0);
270        Arrays.fill(digest, (byte) 0);
271        secretKeys.clear();
272        initialized = false;
273    }
274
275    /**
276     * Test the given {@code candidateDigest} against the configured digest. In case of failure, the secret data is
277     * destroyed and the object is made unusable.<br>
278     * Use that method to check if some code is allowed to request that Crypto object.
279     *
280     * @return true if {@code candidateDigest} matches the one used on creation.
281     * @see #clear()
282     * @see #verifyKey(char[])
283     */
284    public boolean verifyKey(byte[] candidateDigest) {
285        boolean success = Arrays.equals(getSHA1DigestOrEmpty(candidateDigest), digest);
286        if (!success) {
287            clear();
288        }
289        return success;
290    }
291
292    /**
293     * Test the given {@code candidateDigest} against the configured digest. In case of failure, the secret data is
294     * destroyed and the object is made unusable.<br>
295     * Use that method to check if some code is allowed to request that Crypto object.
296     *
297     * @return true if {@code candidateDigest} matches the one used on creation.
298     * @see #clear()
299     * @see #verifyKey(byte[])
300     */
301    public boolean verifyKey(char[] candidateDigest) {
302        return verifyKey(getBytes(candidateDigest));
303    }
304
305    /**
306     * Utility method to get {@code byte[]} from {@code char[]} since it is recommended to store passwords in
307     * {@code char[]} rather than in {@code String}.<br>
308     * The default charset of this Java virtual machine is used. There can be conversion issue with unmappable
309     * characters: they will be replaced with the charset's default replacement string.
310     *
311     * @param chars char array to convert
312     * @return the byte array converted from {@code chars} using the default charset.
313     */
314    public static byte[] getBytes(char[] chars) {
315        CharBuffer charBuffer = CharBuffer.wrap(chars);
316        ByteBuffer byteBuffer = Charset.defaultCharset().encode(charBuffer);
317        return Arrays.copyOfRange(byteBuffer.array(), 0, byteBuffer.limit());
318    }
319
320    /**
321     * Utility method to get {@code char[]} from {@code bytes[]} since it is recommended to store passwords in
322     * {@code char[]} rather than in {@code String}.<br>
323     * The default charset of this Java virtual machine is used. There can be conversion issue with unmappable
324     * characters: they will be replaced with the charset's default replacement string.
325     *
326     * @param bytes byte array to convert
327     * @return the char array converted from {@code bytes} using the default charset.
328     */
329    public static char[] getChars(byte[] bytes) {
330        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
331        CharBuffer charBuffer = Charset.defaultCharset().decode(byteBuffer);
332        return Arrays.copyOfRange(charBuffer.array(), 0, charBuffer.limit());
333    }
334
335    /**
336     * @return true if the given {@code value} is encrypted
337     */
338    public static boolean isEncrypted(String value) {
339        return value != null && CRYPTO_PATTERN.matcher(value).matches();
340    }
341
342    /**
343     * Extract secret keys from a keystore looking for {@code keyAlias + algorithm}
344     *
345     * @param keystorePath Path to the keystore
346     * @param keystorePass Keystore password
347     * @param keyAlias Key alias prefix. It is suffixed with the algorithm.
348     * @param keyPass Key password
349     * @throws GeneralSecurityException
350     * @throws IOException
351     * @see #IMPLEMENTED_ALGOS
352     */
353    public static Map<String, SecretKey> getKeysFromKeyStore(String keystorePath, char[] keystorePass, String keyAlias,
354            char[] keyPass) throws GeneralSecurityException, IOException {
355        KeyStore keystore = KeyStore.getInstance("JCEKS");
356        try (InputStream keystoreStream = new FileInputStream(keystorePath)) {
357            keystore.load(keystoreStream, keystorePass);
358        }
359        Map<String, SecretKey> secretKeys = new HashMap<>();
360        for (String algo : IMPLEMENTED_ALGOS) {
361            if (keystore.containsAlias(keyAlias + algo)) {
362                SecretKey key = (SecretKey) keystore.getKey(keyAlias + algo, keyPass);
363                secretKeys.put(algo, key);
364            }
365        }
366        if (secretKeys.isEmpty()) {
367            throw new KeyStoreException(String.format("No alias \"%s<algo>\" found in %s", keyAlias, keystorePath));
368        }
369        return secretKeys;
370    }
371
372    /**
373     * Store a key in a keystore.<br>
374     * The keystore is created if it doesn't exist.
375     *
376     * @param keystorePath Path to the keystore
377     * @param keystorePass Keystore password
378     * @param keyAlias Key alias prefix. It must be suffixed with the algorithm ({@link SecretKey#getAlgorithm()} is
379     *            fine).
380     * @param keyPass Key password
381     * @throws GeneralSecurityException
382     * @throws IOException
383     * @see #IMPLEMENTED_ALGOS
384     */
385    public static void setKeyInKeyStore(String keystorePath, char[] keystorePass, String keyAlias, char[] keyPass,
386            SecretKey key) throws GeneralSecurityException, IOException {
387        KeyStore keystore = KeyStore.getInstance("JCEKS");
388        if (!new File(keystorePath).exists()) {
389            log.info("Creating a new JCEKS keystore at " + keystorePath);
390            keystore.load(null);
391        } else {
392            try (InputStream keystoreStream = new FileInputStream(keystorePath)) {
393                keystore.load(keystoreStream, keystorePass);
394            }
395        }
396        KeyStore.SecretKeyEntry keyStoreEntry = new KeyStore.SecretKeyEntry(key);
397        PasswordProtection keyPassword = new PasswordProtection(keyPass);
398        keystore.setEntry(keyAlias, keyStoreEntry, keyPassword);
399        try (OutputStream keystoreStream = new FileOutputStream(keystorePath)) {
400            keystore.store(keystoreStream, keystorePass);
401        }
402    }
403
404}