· 4 years ago · Jun 02, 2021, 12:46 PM
1package Mike.MasterKeyManaging;
2
3import javax.crypto.*;
4import javax.crypto.spec.DESKeySpec;
5import java.io.*;
6import java.security.SecureRandom;
7
8public class DES {
9
10
11 public static void encryptDecrypt(String key, int ciphermode, File in, File out) {
12 try {
13 FileInputStream fis = new FileInputStream(in);
14 FileOutputStream fos = new FileOutputStream(out);
15
16
17 DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
18
19 SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
20 SecretKey secretKey = skf.generateSecret(desKeySpec);
21
22 Cipher cipher = Cipher.getInstance("DES/EBC/PKCS5Padding");
23
24 if(ciphermode == Cipher.ENCRYPT_MODE) {
25 cipher.init(Cipher.ENCRYPT_MODE, secretKey, SecureRandom.getInstance("SHA1PRNG"));
26 CipherInputStream cis = new CipherInputStream(fis, cipher);
27 write(cis, fos);
28 } else if(ciphermode == Cipher.DECRYPT_MODE) {
29 cipher.init(Cipher.DECRYPT_MODE, secretKey, SecureRandom.getInstance("SHA1PRNG"));
30 CipherOutputStream cos = new CipherOutputStream(fos, cipher);
31 System.out.println(cos.toString());
32 write(fis, cos);
33
34 }
35
36 } catch (Exception e) {
37 e.printStackTrace();
38 }
39 }
40
41
42 public static void write(InputStream in, OutputStream out) throws IOException {
43 byte[] buffer = new byte[64];
44 int numOfBytesRead;
45 while((numOfBytesRead = in.read(buffer)) != -1) {
46 out.write(buffer, 0, numOfBytesRead);
47 }
48 out.close();
49 in.close();
50 }
51}
52