· 8 years ago · Jan 24, 2018, 04:48 AM
1package org.t5.cipher;
2
3
4
5import java.security.InvalidKeyException;
6
7import java.security.Key;
8
9import java.security.NoSuchAlgorithmException;
10
11import java.util.logging.Logger;
12
13import javax.crypto.Cipher;
14
15import javax.crypto.KeyGenerator;
16
17import javax.crypto.NoSuchPaddingException;
18
19import javax.crypto.SecretKey;
20
21import javax.crypto.spec.SecretKeySpec;
22
23import sun.misc.BASE64Decoder;
24
25import sun.misc.BASE64Encoder;
26
27
28
29public class BlowFish {
30
31 private static final Logger log = Logger.getLogger("BlowFish");
32
33 protected static String algorithm = "Blowfish";
34
35 protected static final String IV = "12348765";
36
37 protected static Cipher cipher;
38
39 protected static Cipher decipher;
40
41 protected static BASE64Encoder encoder;
42
43 protected static BASE64Decoder decoder;
44
45
46
47 static {
48
49 try {
50
51 cipher = getCipher(IV, Cipher.ENCRYPT_MODE);
52
53 decipher = getCipher(IV, Cipher.DECRYPT_MODE);
54
55 encoder = new BASE64Encoder();
56
57 decoder = new BASE64Decoder();
58
59 } catch (Exception e) {
60
61 log.warning("Creando encriptadores " + e.getMessage());
62
63 }
64
65 }
66
67
68
69 public static SecretKey generateKey() throws NoSuchAlgorithmException {
70
71 KeyGenerator kg = KeyGenerator.getInstance(algorithm);
72
73
74
75 return kg.generateKey();
76
77 }
78
79
80
81 public static String encrypt(String normalText) {
82
83 try {
84
85 byte byteEncrypted[];
86
87 byte byteText[] = normalText.getBytes("ISO-8859-1");
88
89 byteEncrypted = cipher.doFinal(byteText);
90
91
92
93 return encoder.encode(byteEncrypted);
94
95 } catch (Exception e) {
96
97 log.warning("Encriptando " + e.getMessage());
98
99 }
100
101
102
103 return null;
104
105 }
106
107
108
109 public static String decrypt(String encryptedText) {
110
111 try {
112
113 byte byteText[];
114
115 byte byteEncryptedText[] = decoder.decodeBuffer(encryptedText);
116
117 byteText = new byte[encryptedText.length()];
118
119 byteText = decipher.doFinal(byteEncryptedText);
120
121
122
123 return new String(byteText, "ISO-8859-1");
124
125 } catch (Exception e) {
126
127 log.warning("Desencriptando " + e.getMessage());
128
129 }
130
131
132
133 return null;
134
135 }
136
137
138
139 private static Cipher getCipher(String secretKey, int cipherMode) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
140
141 byte byteSecretKey[] = secretKey.getBytes();
142
143 SecretKeySpec secretKeySpec = new SecretKeySpec(byteSecretKey, algorithm);
144
145 Key mykey = secretKeySpec;
146
147 Cipher cipher = Cipher.getInstance(algorithm);
148
149 cipher.init(cipherMode, mykey);
150
151
152
153 return cipher;
154
155 }
156
157}