· 6 years ago · Apr 01, 2019, 09:52 PM
1import javax.crypto.spec.*;
2import java.security.*;
3import javax.crypto.*;
4
5public class RC4
6{
7 private static String algorithm = "RC4";
8
9 public static void main(String []args) throws Exception {
10 String toEncrypt = "hello world";
11
12 System.out.println("Encrypting...");
13 byte[] encrypted = encrypt(toEncrypt, "password");
14
15 System.out.println("Decrypting...");
16 String decrypted = decrypt(encrypted, "password");
17
18 System.out.println("Decrypted text: " + decrypted);
19 }
20
21 public static byte[] encrypt(String toEncrypt, String key) throws Exception {
22 // create a binary key from the argument key (seed)
23 SecureRandom sr = new SecureRandom(key.getBytes());
24 KeyGenerator kg = KeyGenerator.getInstance(algorithm);
25 kg.init(sr);
26 SecretKey sk = kg.generateKey();
27
28 // create an instance of cipher
29 Cipher cipher = Cipher.getInstance(algorithm);
30
31 // initialize the cipher with the key
32 cipher.init(Cipher.ENCRYPT_MODE, sk);
33
34 // enctypt!
35 byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
36
37 return encrypted;
38 }
39
40 public static String decrypt(byte[] toDecrypt, String key) throws Exception {
41 // create a binary key from the argument key (seed)
42 SecureRandom sr = new SecureRandom(key.getBytes());
43 KeyGenerator kg = KeyGenerator.getInstance(algorithm);
44 kg.init(sr);
45 SecretKey sk = kg.generateKey();
46
47 // do the decryption with that key
48 Cipher cipher = Cipher.getInstance(algorithm);
49 cipher.init(Cipher.DECRYPT_MODE, sk);
50 byte[] decrypted = cipher.doFinal(toDecrypt);
51
52 return new String(decrypted);
53 }
54}