-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathCBC.java
More file actions
53 lines (40 loc) · 1.38 KB
/
CBC.java
File metadata and controls
53 lines (40 loc) · 1.38 KB
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
/*
Kasun De Zoysa @ UCSC
*/
import java.io.*;
import java.security.*;
import javax.crypto.*;
import java.util.Formatter;
import javax.crypto.spec.*;
public class CBC{
public static void main(String[] args) throws Exception {
String msg= "Hello123Hello123";
byte[] input =msg.getBytes();
//Generate a key
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(128);
Key key = generator.generateKey();
//Set a IV
byte iv[] = new byte[16];
SecureRandom secRandom = new SecureRandom() ;
secRandom.nextBytes(iv);
IvParameterSpec ivSpec = new IvParameterSpec(iv) ;
// encryption pass
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key,ivSpec);
byte[] cipherText = cipher.doFinal(input);
System.out.println("Cipher text length: " +cipherText.length);
System.out.println("Cipher text: " +byteArray2Hex(cipherText));
// decryption pass
cipher.init(Cipher.DECRYPT_MODE, key,ivSpec);
byte[] plainText= cipher.doFinal(cipherText);
System.out.println("Plain text length: "+plainText.length);
String s= new String(plainText);
System.out.println("plain text: " + s);
}
private static String byteArray2Hex(byte[] data) {
Formatter formatter = new Formatter();
for (byte b : data) formatter.format("%02x", b);
return formatter.toString();
}
}