· 8 years ago · Nov 24, 2017, 03:16 PM
1public class TWOFISH {
2
3 public static byte[] encrypt(String toEncrypt, String key) throws Exception {
4 // create a binary key from the argument key (seed)
5 SecureRandom sr = new SecureRandom(key.getBytes());
6 KeyGenerator kg = KeyGenerator.getInstance("twofish");
7 kg.init(sr);
8 SecretKey sk = kg.generateKey();
9
10 // create an instance of cipher
11 Cipher cipher = Cipher.getInstance("twofish");
12
13 // initialize the cipher with the key
14 cipher.init(Cipher.ENCRYPT_MODE, sk);
15
16 // enctypt!
17 byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
18
19 return encrypted;
20 }
21
22 public static String decrypt(byte[] toDecrypt, String key) throws Exception {
23 // create a binary key from the argument key (seed)
24 SecureRandom sr = new SecureRandom(key.getBytes());
25 KeyGenerator kg = KeyGenerator.getInstance("twofish");
26 kg.init(sr);
27 SecretKey sk = kg.generateKey();
28
29 // do the decryption with that key
30 Cipher cipher = Cipher.getInstance("twofish");
31 cipher.init(Cipher.DECRYPT_MODE, sk);
32 byte[] decrypted = cipher.doFinal(toDecrypt);
33
34 return new String(decrypted);
35 }
36}