· 8 years ago · Dec 21, 2017, 06:12 PM
1import static org.apache.commons.codec.binary.Hex.*;
2import static org.apache.commons.io.FileUtils.*;
3
4import java.io.File;
5import java.io.FileInputStream;
6import java.io.FileOutputStream;
7import java.io.IOException;
8import java.security.InvalidKeyException;
9import java.security.Key;
10import java.security.NoSuchAlgorithmException;
11
12import javax.crypto.BadPaddingException;
13import javax.crypto.Cipher;
14import javax.crypto.IllegalBlockSizeException;
15import javax.crypto.KeyGenerator;
16import javax.crypto.NoSuchPaddingException;
17import javax.crypto.SecretKey;
18import javax.crypto.spec.SecretKeySpec;
19
20import org.apache.commons.codec.DecoderException;
21
22
23public class MasterCryptoUtil {
24 //КлаÑÑ-утилита Ð´Ð»Ñ ÑˆÐ¸Ñ„Ñ€Ð¾Ð²Ð°Ð½Ð¸Ñ Ñ„Ð°Ð¹Ð»Ð° Ñ Ð¼Ð°Ñтер-паролем
25 private static final String ALGORITHM = "AES";
26 private static final String TRANSFORMATION = "AES";
27
28
29 public static SecretKey GenerateKey() throws NoSuchAlgorithmException {
30 KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
31 keyGenerator.init(256); // 128 default; 192 and 256 also possible
32 return keyGenerator.generateKey();
33 }
34
35
36 public static void SaveKey(SecretKey key, File file) throws IOException { //ЗапиÑываем в файл ключ Ð´Ð»Ñ ÑƒÐ´Ð¾Ð±Ð½Ð¾Ñти хранениÑ
37 char[] hex = encodeHex(key.getEncoded()); //ЗдеÑÑŒ проÑто ключ в Ñтроку превращаем
38 writeStringToFile(file, String.valueOf(hex));
39 }
40
41
42 public static SecretKey LoadKey(File file) throws IOException {
43 String data = new String(readFileToByteArray(file));
44 byte[] encoded;
45
46 try {
47 encoded = decodeHex(data.toCharArray());
48 } catch (DecoderException e) {
49 e.printStackTrace();
50 return null;
51 }
52
53 return new SecretKeySpec(encoded, "AES"); //готовый Ð´Ð»Ñ Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ð½Ð¸Ñ ÐºÐ»ÑŽÑ‡
54 }
55
56 /* SecretKey key получаешь из LoadKey, inputFile, outputFile
57 * можешь переделать под Ñтроки(да вообще вÑе функции тут надо
58 * под Ñтроки переделывать, вмеÑто файлов, проÑто Ñто у Ð¼ÐµÐ½Ñ ÐºÐ»Ð°ÑÑ
59 * Ð´Ð»Ñ Ñ€Ð°Ñшифровки файл-паролÑ), тогда тут в Decrypt возвращаешь
60 * Ñтроку Ñ Ð¿Ð°Ñ€Ð¾Ð»ÐµÐ¼ раÑшифрованным, в Encrypt проÑто шифруешь
61 */
62 public void Encrypt(SecretKey key, File inputFile, File outputFile) throws Exception {
63 ExecCrypto(Cipher.ENCRYPT_MODE, key, inputFile, outputFile);
64 }
65
66
67 public void Decrypt(SecretKey key, File inputFile, File outputFile) throws Exception {
68 ExecCrypto(Cipher.DECRYPT_MODE, key, inputFile, outputFile);
69 }
70
71
72 private static void ExecCrypto(int cipherMode, SecretKey key, File inputFile,
73 File outputFile) throws Exception {
74 try {
75 Key secretKey = key;
76 Cipher cipher = Cipher.getInstance(TRANSFORMATION);
77 cipher.init(cipherMode, secretKey);
78
79 FileInputStream inputStream = new FileInputStream(inputFile);
80 byte[] inputBytes = new byte[(int) inputFile.length()];
81 inputStream.read(inputBytes);
82
83 byte[] outputBytes = cipher.doFinal(inputBytes);
84
85 FileOutputStream outputStream = new FileOutputStream(outputFile);
86 outputStream.write(outputBytes);
87
88 inputStream.close();
89 outputStream.close();
90
91 } catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException
92 | BadPaddingException | IllegalBlockSizeException | IOException ex) {
93 throw new Exception("Error encrypting/decrypting file", ex);
94 }
95 }
96}