001/*
002 * (C) Copyright 2015-2019 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     */
134    public Crypto(String keystorePath, char[] keystorePass, String keyAlias, char[] keyPass)
135            throws GeneralSecurityException, IOException {
136        this(Crypto.getKeysFromKeyStore(keystorePath, keystorePass, keyAlias, keyPass), keystorePass);
137    }
138
139    public static final class NoOp extends Crypto {
140
141        public static final Crypto NO_OP = new NoOp();
142
143        private NoOp() {
144            super(new byte[0]);
145        }
146
147        @Override
148        public String encrypt(String algorithm, byte[] bytesToEncrypt) {
149            return null;
150        }
151
152        @Override
153        public byte[] decrypt(String strToDecrypt) {
154            return strToDecrypt.getBytes();
155        }
156
157        @Override
158        public void clear() {
159            // NO OP
160        }
161    }
162
163    protected SecretKey getSecretKey(String algorithm, byte[] key) throws NoSuchAlgorithmException {
164        if (!initialized) {
165            throw new RuntimeException("The Crypto object has been cleared.");
166        }
167        if (AES_ECB_PKCS5PADDING.equals(algorithm)) {
168            algorithm = AES; // AES_ECB_PKCS5PADDING is the default for AES
169        } else if (DES_ECB_PKCS5PADDING.equals(algorithm)) {
170            algorithm = DES; // DES_ECB_PKCS5PADDING is the default for DES
171        }
172        if (!secretKeys.containsKey(algorithm)) {
173            if (secretKey.length == 0) {
174                throw new NoSuchAlgorithmException("Unsupported algorithm: " + algorithm);
175            }
176            if (AES.equals(algorithm)) { // default for AES
177                key = Arrays.copyOf(getSHA1Digest(key), 16); // use a 128 bits secret key
178                secretKeys.put(AES, new SecretKeySpec(key, AES));
179            } else if (DES.equals(algorithm)) { // default for DES
180                key = Arrays.copyOf(getSHA1Digest(key), 8); // use a 64 bits secret key
181                secretKeys.put(DES, new SecretKeySpec(key, DES));
182            } else {
183                throw new NoSuchAlgorithmException("Unsupported algorithm: " + algorithm);
184            }
185        }
186        return secretKeys.get(algorithm);
187    }
188
189    public byte[] getSHA1Digest(final byte[] key) throws NoSuchAlgorithmException {
190        MessageDigest sha = MessageDigest.getInstance(SHA1);
191        return sha.digest(key);
192    }
193
194    public byte[] getSHA1DigestOrEmpty(final byte[] bytes) {
195        byte[] aDigest = new byte[0];
196        try {
197            aDigest = getSHA1Digest(bytes);
198        } catch (NoSuchAlgorithmException e) {
199            log.error(e);
200        }
201        return aDigest;
202    }
203
204    public String encrypt(byte[] bytesToEncrypt) throws GeneralSecurityException {
205        return encrypt(null, bytesToEncrypt);
206    }
207
208    /**
209     * @param algorithm cipher transformation of the form "algorithm/mode/padding" or "algorithm". See the Cipher
210     *            section in the <a
211     *            href=http://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#Cipher>Java
212     *            Cryptography Architecture Standard Algorithm Name Documentation</a>.
213     * @throws NoSuchPaddingException if {@code algorithm} contains a padding scheme that is not available.
214     * @throws NoSuchAlgorithmException if {@code algorithm} is in an invalid or not supported format.
215     */
216    public String encrypt(String algorithm, byte[] bytesToEncrypt) throws GeneralSecurityException {
217        final String encryptedAlgo;
218        if (StringUtils.isBlank(algorithm)) {
219            algorithm = DEFAULT_ALGO;
220            encryptedAlgo = "";
221        } else {
222            encryptedAlgo = Base64.encodeBase64String(algorithm.getBytes());
223        }
224        Cipher cipher = Cipher.getInstance(algorithm);
225        cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(algorithm, secretKey));
226        final String encryptedString = Base64.encodeBase64String(cipher.doFinal(bytesToEncrypt));
227        return String.format("{$%s$%s}", encryptedAlgo, encryptedString);
228    }
229
230    /**
231     * The method returns either the decrypted {@code strToDecrypt}, either the {@code strToDecrypt} itself if it is not
232     * recognized as a crypted string or if the decryption fails. The return value is a byte array for security purpose,
233     * it is your responsibility to convert it then to a String or not (use of {@code char[]} is recommended).
234     *
235     * @return the decrypted {@code strToDecrypt} as an array of bytes, never {@code null}
236     * @see #getChars(byte[])
237     */
238    public byte[] decrypt(String strToDecrypt) {
239        Matcher matcher = CRYPTO_PATTERN.matcher(strToDecrypt);
240        if (!matcher.matches()) {
241            return strToDecrypt.getBytes();
242        }
243        Cipher decipher;
244        try {
245            String algorithm = new String(Base64.decodeBase64(matcher.group("algo")));
246            if (StringUtils.isBlank(algorithm)) {
247                algorithm = DEFAULT_ALGO;
248            }
249            decipher = Cipher.getInstance(algorithm);
250            decipher.init(Cipher.DECRYPT_MODE, getSecretKey(algorithm, secretKey));
251            return decipher.doFinal(Base64.decodeBase64(matcher.group("value")));
252        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
253            log.trace("Available algorithms: " + Security.getAlgorithms("Cipher"));
254            log.trace("Available security providers: " + Arrays.asList(Security.getProviders()));
255            log.debug(e, e);
256        } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException | IllegalArgumentException e) {
257            log.debug(e, e);
258        }
259        return strToDecrypt.getBytes();
260    }
261
262    /**
263     * Clear sensible values. That makes the current object unusable.
264     */
265    public void clear() {
266        Arrays.fill(secretKey, (byte) 0);
267        Arrays.fill(digest, (byte) 0);
268        secretKeys.clear();
269        initialized = false;
270    }
271
272    /**
273     * Test the given {@code candidateDigest} against the configured digest. In case of failure, the secret data is
274     * destroyed and the object is made unusable.<br>
275     * Use that method to check if some code is allowed to request that Crypto object.
276     *
277     * @return true if {@code candidateDigest} matches the one used on creation.
278     * @see #clear()
279     * @see #verifyKey(char[])
280     */
281    public boolean verifyKey(byte[] candidateDigest) {
282        boolean success = Arrays.equals(getSHA1DigestOrEmpty(candidateDigest), digest);
283        if (!success) {
284            clear();
285        }
286        return success;
287    }
288
289    /**
290     * Test the given {@code candidateDigest} against the configured digest. In case of failure, the secret data is
291     * destroyed and the object is made unusable.<br>
292     * Use that method to check if some code is allowed to request that Crypto object.
293     *
294     * @return true if {@code candidateDigest} matches the one used on creation.
295     * @see #clear()
296     * @see #verifyKey(byte[])
297     */
298    public boolean verifyKey(char[] candidateDigest) {
299        return verifyKey(getBytes(candidateDigest));
300    }
301
302    /**
303     * Utility method to get {@code byte[]} from {@code char[]} since it is recommended to store passwords in
304     * {@code char[]} rather than in {@code String}.<br>
305     * The default charset of this Java virtual machine is used. There can be conversion issue with unmappable
306     * characters: they will be replaced with the charset's default replacement string.
307     *
308     * @param chars char array to convert
309     * @return the byte array converted from {@code chars} using the default charset.
310     */
311    public static byte[] getBytes(char[] chars) {
312        CharBuffer charBuffer = CharBuffer.wrap(chars);
313        ByteBuffer byteBuffer = Charset.defaultCharset().encode(charBuffer);
314        return Arrays.copyOfRange(byteBuffer.array(), 0, byteBuffer.limit());
315    }
316
317    /**
318     * Utility method to get {@code char[]} from {@code bytes[]} since it is recommended to store passwords in
319     * {@code char[]} rather than in {@code String}.<br>
320     * The default charset of this Java virtual machine is used. There can be conversion issue with unmappable
321     * characters: they will be replaced with the charset's default replacement string.
322     *
323     * @param bytes byte array to convert
324     * @return the char array converted from {@code bytes} using the default charset.
325     */
326    public static char[] getChars(byte[] bytes) {
327        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
328        CharBuffer charBuffer = Charset.defaultCharset().decode(byteBuffer);
329        return Arrays.copyOfRange(charBuffer.array(), 0, charBuffer.limit());
330    }
331
332    /**
333     * @return true if the given {@code value} is encrypted
334     */
335    public static boolean isEncrypted(String value) {
336        return value != null && CRYPTO_PATTERN.matcher(value).matches();
337    }
338
339    /**
340     * Extract secret keys from a keystore looking for {@code keyAlias + algorithm}
341     *
342     * @param keystorePath Path to the keystore
343     * @param keystorePass Keystore password
344     * @param keyAlias Key alias prefix. It is suffixed with the algorithm.
345     * @param keyPass Key password
346     * @see #IMPLEMENTED_ALGOS
347     */
348    public static Map<String, SecretKey> getKeysFromKeyStore(String keystorePath, char[] keystorePass, String keyAlias,
349            char[] keyPass) throws GeneralSecurityException, IOException {
350        KeyStore keystore = KeyStore.getInstance("JCEKS");
351        try (InputStream keystoreStream = new FileInputStream(keystorePath)) {
352            keystore.load(keystoreStream, keystorePass);
353        }
354        Map<String, SecretKey> secretKeys = new HashMap<>();
355        for (String algo : IMPLEMENTED_ALGOS) {
356            if (keystore.containsAlias(keyAlias + algo)) {
357                SecretKey key = (SecretKey) keystore.getKey(keyAlias + algo, keyPass);
358                secretKeys.put(algo, key);
359            }
360        }
361        if (secretKeys.isEmpty()) {
362            throw new KeyStoreException(String.format("No alias \"%s<algo>\" found in %s", keyAlias, keystorePath));
363        }
364        return secretKeys;
365    }
366
367    /**
368     * Store a key in a keystore.<br>
369     * The keystore is created if it doesn't exist.
370     *
371     * @param keystorePath Path to the keystore
372     * @param keystorePass Keystore password
373     * @param keyAlias Key alias prefix. It must be suffixed with the algorithm ({@link SecretKey#getAlgorithm()} is
374     *            fine).
375     * @param keyPass Key password
376     * @see #IMPLEMENTED_ALGOS
377     */
378    public static void setKeyInKeyStore(String keystorePath, char[] keystorePass, String keyAlias, char[] keyPass,
379            SecretKey key) throws GeneralSecurityException, IOException {
380        KeyStore keystore = KeyStore.getInstance("JCEKS");
381        if (!new File(keystorePath).exists()) {
382            log.info("Creating a new JCEKS keystore at " + keystorePath);
383            keystore.load(null);
384        } else {
385            try (InputStream keystoreStream = new FileInputStream(keystorePath)) {
386                keystore.load(keystoreStream, keystorePass);
387            }
388        }
389        KeyStore.SecretKeyEntry keyStoreEntry = new KeyStore.SecretKeyEntry(key);
390        PasswordProtection keyPassword = new PasswordProtection(keyPass);
391        keystore.setEntry(keyAlias, keyStoreEntry, keyPassword);
392        try (OutputStream keystoreStream = new FileOutputStream(keystorePath)) {
393            keystore.store(keystoreStream, keystorePass);
394        }
395    }
396
397}