· 7 years ago · Nov 26, 2018, 06:40 PM
1import javax.crypto.Cipher;
2import javax.crypto.spec.SecretKeySpec;
3import javax.xml.bind.DatatypeConverter;
4
5public class ECBTest {
6 public static void main(String[] args) throws Exception {
7 byte[] plain = "jakistamsupertekstdoszyfruszyfru".getBytes();
8 byte[] key = "supersekretnykey".getBytes();
9
10 SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
11 Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
12
13 // szyfrowanie
14 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
15 byte[] encrypted = cipher.doFinal(plain);
16 String enc = DatatypeConverter.printHexBinary(encrypted);
17 System.out.printf("Encrypted: 0x%s\n", enc);
18 System.out.println();
19
20 // deszyfrowanie
21 cipher.init(Cipher.DECRYPT_MODE, secretKey);
22 byte[] decrypted = cipher.doFinal(encrypted);
23
24 String decodedString = new String(decrypted, "UTF-8");
25 System.out.printf("Decrypted : %s\n", decodedString);
26 }
27}