· 4 years ago · Jun 11, 2021, 09:28 AM
1package org.example.bouncyzeneca;
2
3import org.bouncycastle.crypto.StreamCipher;
4import org.bouncycastle.crypto.engines.HC128Engine;
5import org.bouncycastle.crypto.params.KeyParameter;
6
7import java.io.UnsupportedEncodingException;
8import java.nio.charset.StandardCharsets;
9import java.util.Base64;
10
11public class App {
12 private static String encrypt(String plaintext, String secretKey) {
13 final StreamCipher cipher;
14 byte[] secretKeyBytes = secretKey.getBytes(StandardCharsets.UTF_8);
15
16 byte[] plaintextBytes;
17 plaintextBytes = plaintext.getBytes(StandardCharsets.UTF_8);
18
19 byte[] encryptedBytes = new byte[plaintextBytes.length];
20
21 cipher = new HC128Engine();
22 KeyParameter keyParameter = new KeyParameter(secretKeyBytes);
23
24 cipher.init(true, keyParameter);
25
26 cipher.processBytes(plaintextBytes, 0, plaintextBytes.length, encryptedBytes, 0);
27 return Base64.getEncoder().encodeToString(encryptedBytes);
28 }
29
30 private static String decrypt(String ciphertext, String secretKey) {
31 final StreamCipher cipher;
32 byte[] byteSecretKey = secretKey.getBytes(StandardCharsets.UTF_8);
33 byte[] ciphertextBytes = Base64.getDecoder().decode(ciphertext.getBytes(StandardCharsets.UTF_8));
34 byte[] plaintextBytes = new byte[ciphertextBytes.length];
35
36 cipher = new HC128Engine();
37 KeyParameter keyParameter = new KeyParameter(byteSecretKey);
38
39 cipher.init(false, keyParameter);
40
41 cipher.processBytes(ciphertextBytes, 0, ciphertextBytes.length, plaintextBytes, 0);
42 return new String(plaintextBytes);
43 }
44 public static void main(String[] args) throws UnsupportedEncodingException {
45 String secretKey = "1234567890abcdef";
46 String plaintext = "Alice got vaccinated";
47
48 String encryptedText = encrypt(plaintext, secretKey);
49 System.out.println("Encrypted text:");
50 System.out.println(encryptedText);
51
52 String decryptedText = decrypt(encryptedText, secretKey);
53 System.out.println("Decrypted text:");
54 System.out.println(decryptedText);
55
56 }
57}
58