CryptUtils: clear the key array after use
[nikiroo-utils.git] / src / be / nikiroo / utils / CryptUtils.java
index b82a169ac21fffd4eb6d95f6df86c46a43566bfd..681692a00e6323531b1dae680bf5d0b774c8190a 100644 (file)
@@ -42,7 +42,11 @@ public class CryptUtils {
         */
        public CryptUtils(String key) {
                try {
-                       init(key2key(key));
+                       byte[] bytes32 = key2key(key);
+                       init(bytes32);
+                       for (int i = 0 ; i < bytes32.length ; i++) {
+                               bytes32[i] = 0;
+                       }
                } catch (InvalidKeyException e) {
                        // We made sure that the key is correct, so nothing here
                        e.printStackTrace();
@@ -62,6 +66,9 @@ public class CryptUtils {
         */
        public CryptUtils(byte[] bytes32) throws InvalidKeyException {
                init(bytes32);
+               for (int i = 0 ; i < bytes32.length ; i++) {
+                       bytes32[i] = 0;
+               }
        }
 
        /**
@@ -267,6 +274,28 @@ public class CryptUtils {
                }
        }
 
+       /**
+        * Decode the data which is assumed to be encrypted with the same utilities
+        * and to be a {@link String}.
+        * 
+        * @param data
+        *            the encrypted data to decode
+        * 
+        * @return the original, decoded data,as a {@link String}
+        * 
+        * @throws SSLException
+        *             in case of I/O error
+        */
+       public String decrypts(byte[] data) throws SSLException {
+               try {
+                       return new String(decrypt(data), "UTF-8");
+               } catch (UnsupportedEncodingException e) {
+                       // UTF-8 is required in all confirm JVMs
+                       e.printStackTrace();
+                       return null;
+               }
+       }
+
        /**
         * Decode the data which is assumed to be encrypted with the same utilities
         * and is a Base64 encoded value.