· 9 years ago · Nov 16, 2016, 07:28 PM
1import java.io.FileInputStream;
2import java.io.FileOutputStream;
3import java.io.IOException;
4import java.io.InputStream;
5import java.io.OutputStream;
6import java.security.Key;
7import javax.crypto.Cipher;
8import javax.crypto.CipherInputStream;
9import javax.crypto.CipherOutputStream;
10import javax.crypto.KeyGenerator;
11
12public class Blowfish {
13
14public static void main(String[] args) {
15 try {
16 String key = "squirrel123";
17
18 FileInputStream fis = new FileInputStream("original.txt");
19 FileOutputStream fos = new FileOutputStream("encrypted.txt");
20 encrypt(key, fis, fos);
21
22 FileInputStream fis2 = new FileInputStream("encrypted.txt");
23 FileOutputStream fos2 = new FileOutputStream("decrypted.txt");
24 decrypt(key, fis2, fos2);
25 } catch (Throwable e) {
26 e.printStackTrace();
27 }
28}
29
30public static void encrypt(String key, InputStream is, OutputStream os)
31 throws Throwable {
32 encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
33}
34
35public static void decrypt(String key, InputStream is, OutputStream os)
36 throws Throwable {
37 encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os);
38}
39
40public static void encryptOrDecrypt(String key, int mode, InputStream is,
41 OutputStream os) throws Throwable {
42
43 KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
44 keyGenerator.init(128);
45 Key secretKey = keyGenerator.generateKey();
46 Cipher cipher = Cipher.getInstance("Blowfish/CFB/NoPadding");
47
48 if (mode == Cipher.ENCRYPT_MODE) {
49
50 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
51 CipherInputStream cis = new CipherInputStream(is, cipher);
52 doCopy(cis, os);
53 } else if (mode == Cipher.DECRYPT_MODE) {
54
55 cipher.init(Cipher.DECRYPT_MODE, secretKey);
56 CipherOutputStream cos = new CipherOutputStream(os, cipher);
57 doCopy(is, cos);
58 }
59}
60
61public static void doCopy(InputStream is, OutputStream os)
62 throws IOException {
63 byte[] bytes = new byte[64];
64 int numBytes;
65 while ((numBytes = is.read(bytes)) != -1) {
66 os.write(bytes, 0, numBytes);
67 }
68 os.flush();
69 os.close();
70 is.close();
71}