-
Notifications
You must be signed in to change notification settings - Fork 0
/
BlowfishKey.java
74 lines (53 loc) · 2.04 KB
/
BlowfishKey.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import javax.crypto.Cipher;
import java.security.Key;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Security;
import javax.crypto.spec.SecretKeySpec;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
public class BlowfishKey {
public static void main(String[] args) throws Exception {
String encoded = encryptAndEncode("hello world!");
System.out.println("Encoded: " + encoded);
System.out.println(decodeAndDecrypt(encoded));
}
public static String encryptAndEncode(String plainText) throws Exception {
byte[] encrypted = encrypt(plainText);
String base64encoded = Base64.encodeBytes(encrypted);
return java.net.URLEncoder.encode(base64encoded, "UTF-8");
}
public static byte[] encrypt(String plainText) throws Exception {
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, getKeySpec());
return cipher.doFinal(plainText.getBytes());
}
public static String decodeAndDecrypt(String cipherText) throws Exception {
String base64encoded = java.net.URLDecoder.decode(cipherText, "UTF-8");
byte[] encrypted = Base64.decode(base64encoded);
return decrypt(encrypted);
}
public static String decrypt(byte[] cipherText) throws Exception {
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, getKeySpec());
byte[] decrypted = cipher.doFinal(cipherText);
return(new String(decrypted));
}
public static SecretKeySpec getKeySpec() throws Exception {
byte[] raw = getKey();
return (new SecretKeySpec(raw, "Blowfish"));
}
public static byte[] getKey() throws Exception {
File key = new File("key");
long length = key.length();
final FileInputStream fis = new FileInputStream(key);
byte[] bytes = new byte[(int)length];
fis.read(bytes);
fis.close();
return bytes;
}
}