View Javadoc
1   /*
2    * Copyright (c) 2002-2017, Mairie de Paris
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met:
8    *
9    *  1. Redistributions of source code must retain the above copyright notice
10   *     and the following disclaimer.
11   *
12   *  2. Redistributions in binary form must reproduce the above copyright notice
13   *     and the following disclaimer in the documentation and/or other materials
14   *     provided with the distribution.
15   *
16   *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
17   *     contributors may be used to endorse or promote products derived from
18   *     this software without specific prior written permission.
19   *
20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
24   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30   * POSSIBILITY OF SUCH DAMAGE.
31   *
32   * License 1.0
33   */
34  package fr.paris.lutece.util.keydiversification;
35  
36  import java.io.UnsupportedEncodingException;
37  import java.security.InvalidKeyException;
38  import java.security.NoSuchAlgorithmException;
39  import java.security.spec.InvalidKeySpecException;
40  import java.security.spec.KeySpec;
41  import java.util.Base64;
42  import javax.crypto.BadPaddingException;
43  import javax.crypto.Cipher;
44  import javax.crypto.IllegalBlockSizeException;
45  import javax.crypto.NoSuchPaddingException;
46  import javax.crypto.SecretKey;
47  import javax.crypto.SecretKeyFactory;
48  import javax.crypto.spec.DESedeKeySpec;
49  
50  /**
51   * This service encrypts / decrypts strings
52   */
53  public class CryptoService
54  {
55  
56      private static final String UNICODE_FORMAT = "UTF8";
57      private static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
58  
59      private final Cipher _cipher;
60      private final SecretKey _key;
61  
62      /**
63       * Constructor
64       *
65       * @param strEncryptionKey
66       *            An encryption key
67       * @throws KeyDiversificationException
68       *             If an error occurs
69       * @throws InvalidKeyException
70       * @throws NoSuchAlgorithmException
71       * @throws NoSuchPaddingException
72       * @throws InvalidKeySpecException
73       */
74      public CryptoService( String strEncryptionKey ) throws KeyDiversificationException
75      {
76          try
77          {
78              byte [ ] arrayBytes = new byte [ DESedeKeySpec.DES_EDE_KEY_LEN];
79  
80              for ( int i = 0; i < DESedeKeySpec.DES_EDE_KEY_LEN; i++ )
81              {
82                  if ( i < strEncryptionKey.length( ) )
83                  {
84                      arrayBytes [i] = (byte) strEncryptionKey.charAt( i );
85                  }
86              }
87              KeySpec keySpec = new DESedeKeySpec( arrayBytes );
88              SecretKeyFactory skf = SecretKeyFactory.getInstance( DESEDE_ENCRYPTION_SCHEME );
89              _cipher = Cipher.getInstance( DESEDE_ENCRYPTION_SCHEME );
90              _key = skf.generateSecret( keySpec );
91          }
92          catch( InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeySpecException e )
93          {
94              throw new KeyDiversificationException( "Error during the initialisation of encryption!", e );
95          }
96      }
97  
98      /**
99       * Encrypts the specified string
100      *
101      * @param strSource
102      *            the string to encrypt
103      * @return The encrypted string
104      * @throws KeyDiversificationException
105      *             if there is an error during the treatment
106      */
107     public String encrypt( String strSource ) throws KeyDiversificationException
108     {
109         try
110         {
111             String strEncrypted;
112             _cipher.init( Cipher.ENCRYPT_MODE, _key );
113             byte [ ] plainText = strSource.getBytes( UNICODE_FORMAT );
114             byte [ ] encryptedText = _cipher.doFinal( plainText );
115             strEncrypted = new String( Base64.getEncoder( ).encode( encryptedText ), UNICODE_FORMAT );
116             return strEncrypted;
117         }
118         catch( InvalidKeyException | UnsupportedEncodingException | IllegalBlockSizeException | BadPaddingException e )
119         {
120             throw new KeyDiversificationException( "Error during the encryption of '" + strSource + "'", e );
121         }
122     }
123 
124     /**
125      * Decrypts the specified string
126      *
127      * @param strEncrypted
128      *            The encrypted string
129      * @return The decrypted string
130      * @throws KeyDiversificationException
131      *             if there is an error during the treatment
132      */
133     public String decrypt( String strEncrypted ) throws KeyDiversificationException
134     {
135         try
136         {
137             String strDecrypted;
138             _cipher.init( Cipher.DECRYPT_MODE, _key );
139             byte [ ] encryptedText = Base64.getDecoder( ).decode( strEncrypted );
140             byte [ ] plainText = _cipher.doFinal( encryptedText );
141             strDecrypted = new String( plainText, UNICODE_FORMAT );
142             return strDecrypted;
143         }
144         catch( IllegalBlockSizeException | BadPaddingException | InvalidKeyException | UnsupportedEncodingException e )
145         {
146             throw new KeyDiversificationException( "Error during the decryption of '" + strEncrypted + "'", e );
147         }
148     }
149 
150 }