· 6 years ago · May 04, 2019, 06:08 PM
1import javax.crypto.Cipher;
2import javax.crypto.spec.IvParameterSpec;
3import javax.crypto.spec.SecretKeySpec;
4//import java.util.Base64;
5import java.security.InvalidKeyException;
6import javax.crypto.NoSuchPaddingException;
7import java.security.NoSuchAlgorithmException;
8import javax.crypto.BadPaddingException;
9import javax.crypto.IllegalBlockSizeException;
10import org.apache.commons.codec.binary.Base64;
11public class ECBEncryption
12{
13 public void main() throws Exception {
14
15 String encryptionKeyString = "thisisa128bitkey";
16 String originalMessage = "secret message";
17 byte[] encryptionKeyBytes = encryptionKeyString.getBytes("UTF-8");
18 byte[] messageBytes = originalMessage.getBytes("UTF-8");
19
20 byte[] encryptedMessageBytes = encryptMessage(messageBytes, encryptionKeyBytes);
21
22 String out = Base64.encodeBase64String(encryptedMessageBytes);
23 System.out.println(out);
24
25 byte[] decryptedMessageBytes = decryptMessage(encryptedMessageBytes,encryptionKeyBytes);
26
27 String de = Base64.encodeBase64String(decryptedMessageBytes);
28 System.out.println(de);
29 //cipher.init(Cipher.DECRYPT_MODE, secretKey);
30
31 //byte[] decryptedMessageBytes = cipher.doFinal(encryptedMessageBytes);
32 //assertThat(originalMessage).isEqualTo(new String(decryptedMessageBytes));
33
34 }
35
36 public byte[] encryptMessage(byte[] message, byte[] keyBytes)
37 throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException,
38 BadPaddingException, IllegalBlockSizeException {
39 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
40 SecretKeySpec Key = new SecretKeySpec(keyBytes, "AES");
41 cipher.init(Cipher.ENCRYPT_MODE, Key);
42 return cipher.doFinal(message);
43 }
44
45 public byte[] decryptMessage(byte[] message, byte[] keyBytes)
46 throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException,
47 BadPaddingException, IllegalBlockSizeException {
48 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
49 SecretKeySpec Key = new SecretKeySpec(keyBytes, "AES");
50 cipher.init(Cipher.DECRYPT_MODE, Key);
51 return cipher.doFinal(message);
52 }
53}