File D:\maven-qcr-plugin-testsunitaires\qcr4java\h2-1.3.170-sources\target\site\qc\lecode\tools\ChangeFileEncryption.java.html

1 /*
2 * Copyright 2004-2011 H2 Group. Multiple-Licensed under the H2 License,
3 * Version 1.0, and under the Eclipse Public License, Version 1.0
4 * (http://h2database.com/html/license.html).
5 * Initial Developer: H2 Group
6 */
7 package org.h2.tools;
8
9 import java.sql.SQLException;
10 import java.util.ArrayList;
11 import org.h2.message.DbException;
12 import org.h2.security.SHA256;
13 import org.h2.store.FileLister;
14 import org.h2.store.FileStore;
15 import org.h2.store.fs.FileUtils;
16 import org.h2.util.Tool;
17
18 /**
19 * Allows changing the database file encryption password or algorithm.
20 * <br />
21 * This tool can not be used to change a password of a user.
22 * The database must be closed before using this tool.
23 * @h2.resource
24 */
25 public class ChangeFileEncryption extends Tool {
26
27 private String directory;
28 private String cipherType;
29 private byte[] decrypt;
30 private byte[] encrypt;
31
32 /**
33 * Options are case sensitive. Supported options are:
34 * <table>
35 * <tr><td>[-help] or [-?]</td>
36 * <td>Print the list of options</td></tr>
37 * <tr><td>[-cipher type]</td>
38 * <td>The encryption type (AES or XTEA)</td></tr>
39 * <tr><td>[-dir &lt;dir&gt;]</td>
40 * <td>The database directory (default: .)</td></tr>
41 * <tr><td>[-db &lt;database&gt;]</td>
42 * <td>Database name (all databases if not set)</td></tr>
43 * <tr><td>[-decrypt &lt;pwd&gt;]</td>
44 * <td>The decryption password (if not set: not yet encrypted)</td></tr>
45 * <tr><td>[-encrypt &lt;pwd&gt;]</td>
46 * <td>The encryption password (if not set: do not encrypt)</td></tr>
47 * <tr><td>[-quiet]</td>
48 * <td>Do not print progress information</td></tr>
49 * </table>
50 * @h2.resource
51 *
52 * @param args the command line arguments
53 */
54 public static void main(String... args) throws SQLException {
55 new ChangeFileEncryption().runTool(args);
56 }
57
58 public void runTool(String... args) throws SQLException {
59 String dir = ".";
60 String cipher = null;
61 char[] decryptPassword = null;
62 char[] encryptPassword = null;
63 String db = null;
64 boolean quiet = false;
65 for (int i = 0; args != null && i < args.length; i++) {
66 String arg = args[i];
67 if (arg.equals("-dir")) {
68 dir = args[++i];
69 } else if (arg.equals("-cipher")) {
70 cipher = args[++i];
71 } else if (arg.equals("-db")) {
72 db = args[++i];
73 } else if (arg.equals("-decrypt")) {
74 decryptPassword = args[++i].toCharArray();
75 } else if (arg.equals("-encrypt")) {
76 encryptPassword = args[++i].toCharArray();
77 } else if (arg.equals("-quiet")) {
78 quiet = true;
79 } else if (arg.equals("-help") || arg.equals("-?")) {
80 showUsage();
81 return;
82 } else {
83 showUsageAndThrowUnsupportedOption(arg);
84 }
85 }
86 if ((encryptPassword == null && decryptPassword == null) || cipher == null) {
87 showUsage();
88 throw new SQLException("Encryption or decryption password not set, or cipher not set");
89 }
90 try {
91 process(dir, db, cipher, decryptPassword, encryptPassword, quiet);
92 } catch (Exception e) {
93 throw DbException.toSQLException(e);
94 }
95 }
96
97 /**
98 * Get the file encryption key for a given password.
99 * The password must be supplied as char arrays and is cleaned in this method.
100 *
101 * @param password the password as a char array
102 * @return the encryption key
103 */
104 private static byte[] getFileEncryptionKey(char[] password) {
105 if (password == null) {
106 return null;
107 }
108 return SHA256.getKeyPasswordHash("file", password);
109 }
110
111 /**
112 * Changes the password for a database.
113 * The passwords must be supplied as char arrays and are cleaned in this method.
114 * The database must be closed before calling this method.
115 *
116 * @param dir the directory (. for the current directory)
117 * @param db the database name (null for all databases)
118 * @param cipher the cipher (AES, XTEA)
119 * @param decryptPassword the decryption password as a char array
120 * @param encryptPassword the encryption password as a char array
121 * @param quiet don't print progress information
122 * @throws SQLException
123 */
124 public static void execute(String dir, String db, String cipher,
125 char[] decryptPassword, char[] encryptPassword, boolean quiet) throws SQLException {
126 try {
127 new ChangeFileEncryption().process(dir, db, cipher, decryptPassword, encryptPassword, quiet);
128 } catch (Exception e) {
129 throw DbException.toSQLException(e);
130 }
131 }
132
133 private void process(String dir, String db, String cipher,
134 char[] decryptPassword, char[] encryptPassword, boolean quiet) throws SQLException {
135 dir = FileLister.getDir(dir);
136 ChangeFileEncryption change = new ChangeFileEncryption();
137 if (encryptPassword != null) {
138 for (char c : encryptPassword) {
139 if (c == ' ') {
140 throw new SQLException("The file password may not contain spaces");
141 }
142 }
143 }
144 change.out = out;
145 change.directory = dir;
146 change.cipherType = cipher;
147 change.decrypt = getFileEncryptionKey(decryptPassword);
148 change.encrypt = getFileEncryptionKey(encryptPassword);
149
150 ArrayList<String> files = FileLister.getDatabaseFiles(dir, db, true);
151 FileLister.tryUnlockDatabase(files, "encryption");
152 files = FileLister.getDatabaseFiles(dir, db, false);
153 if (files.size() == 0 && !quiet) {
154 printNoDatabaseFilesFound(dir, db);
155 }
156 // first, test only if the file can be renamed
157 // (to find errors with locked files early)
158 for (String fileName : files) {
159 String temp = dir + "/temp.db";
160 FileUtils.delete(temp);
161 FileUtils.moveTo(fileName, temp);
162 FileUtils.moveTo(temp, fileName);
163 }
164 // if this worked, the operation will (hopefully) be successful
165 // TODO changeFileEncryption: this is a workaround!
166 // make the operation atomic (all files or none)
167 for (String fileName : files) {
168 // Don't process a lob directory, just the files in the directory.
169 if (!FileUtils.isDirectory(fileName)) {
170 change.process(fileName);
171 }
172 }
173 }
174
175 private void process(String fileName) {
176 FileStore in;
177 if (decrypt == null) {
178 in = FileStore.open(null, fileName, "r");
179 } else {
180 in = FileStore.open(null, fileName, "r", cipherType, decrypt);
181 }
182 in.init();
183 copy(fileName, in, encrypt);
184 }
185
186 private void copy(String fileName, FileStore in, byte[] key) {
187 if (FileUtils.isDirectory(fileName)) {
188 return;
189 }
190 String temp = directory + "/temp.db";
191 FileUtils.delete(temp);
192 FileStore fileOut;
193 if (key == null) {
194 fileOut = FileStore.open(null, temp, "rw");
195 } else {
196 fileOut = FileStore.open(null, temp, "rw", cipherType, key);
197 }
198 fileOut.init();
199 byte[] buffer = new byte[4 * 1024];
200 long remaining = in.length() - FileStore.HEADER_LENGTH;
201 long total = remaining;
202 in.seek(FileStore.HEADER_LENGTH);
203 fileOut.seek(FileStore.HEADER_LENGTH);
204 long time = System.currentTimeMillis();
205 while (remaining > 0) {
206 if (System.currentTimeMillis() - time > 1000) {
207 out.println(fileName + ": " + (100 - 100 * remaining / total) + "%");
208 time = System.currentTimeMillis();
209 }
210 int len = (int) Math.min(buffer.length, remaining);
211 in.readFully(buffer, 0, len);
212 fileOut.write(buffer, 0, len);
213 remaining -= len;
214 }
215 in.close();
216 fileOut.close();
217 FileUtils.delete(fileName);
218 FileUtils.moveTo(temp, fileName);
219 }
220
221 }
222