Skip to content

Instantly share code, notes, and snippets.

@hemeda3
Created September 29, 2024 03:23
Show Gist options
  • Select an option

  • Save hemeda3/7bed1bc9dd24861c496cd2e3bbb66652 to your computer and use it in GitHub Desktop.

Select an option

Save hemeda3/7bed1bc9dd24861c496cd2e3bbb66652 to your computer and use it in GitHub Desktop.
package io.mapledoum.telegram.starter.exams.tools;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;
public class EncryptDecryptExample {
private static final String ENCRYPTION_KEY = "your32characterkeygoesrighthere!";
private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
private static final OkHttpClient client = new OkHttpClient();
public static void main(String[] args) throws Exception {
List<Message> messages = new ArrayList<>();
messages.add(new Message("user", "1+1"));
messages.add(new Message("assistant", "2?"));
messages.add(new Message("user", "2+1"));
String jsonRequest = buildJsonRequest(messages);
System.out.println("JSON Request: " + jsonRequest);
String encryptedText = encrypt(jsonRequest);
System.out.println("Encrypted Text: " + encryptedText);
String responseEncryptedText = sendPostRequest(encryptedText);
System.out.println("Response Encrypted Text: " + responseEncryptedText);
String decryptedResponse = decrypt(responseEncryptedText);
System.out.println("Decrypted Response: " + decryptedResponse);
}
public static String sendPostRequest(String encryptedText) throws Exception {
URL url = new URL("https://us-central1-test.cloudfunctions.net/MicrostttoftHandler");
// Create JSON request
JSONObject jsonInput = new JSONObject();
jsonInput.put("encryptedData", encryptedText);
RequestBody body = RequestBody.create(
MediaType.get("application/json; charset=utf-8"),
jsonInput.toString()
);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
String responseBody = response.body().string();
return new JSONObject(responseBody).getString("encryptedData");
}
}
public static String encrypt(String text) throws Exception {
IvParameterSpec iv = new IvParameterSpec(generateIv());
SecretKeySpec keySpec = new SecretKeySpec(getSHA256Key(ENCRYPTION_KEY), "AES");
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
byte[] encrypted = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
String ivHex = bytesToHex(iv.getIV());
String encryptedText = Base64.getEncoder().encodeToString(encrypted);
return ivHex + ":" + encryptedText;
}
public static String decrypt(String encryptedText) throws Exception {
String[] parts = encryptedText.split(":");
if (parts.length != 2) {
throw new IllegalArgumentException("Invalid encrypted text format");
}
IvParameterSpec iv = new IvParameterSpec(hexToBytes(parts[0]));
SecretKeySpec keySpec = new SecretKeySpec(getSHA256Key(ENCRYPTION_KEY), "AES");
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
byte[] decodedEncryptedText = Base64.getDecoder().decode(parts[1]);
byte[] decrypted = cipher.doFinal(decodedEncryptedText);
return new String(decrypted, StandardCharsets.UTF_8);
}
private static byte[] generateIv() {
byte[] newSeed = new byte[16];
SecureRandom random = new SecureRandom();
random.nextBytes(newSeed);
return newSeed;
}
private static byte[] getSHA256Key(String key) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return digest.digest(key.getBytes(StandardCharsets.UTF_8));
}
private static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder(2 * bytes.length);
for (byte b : bytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
private static byte[] hexToBytes(String hex) {
int len = hex.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) +
Character.digit(hex.charAt(i + 1), 16));
}
return data;
}
public static String buildJsonRequest(List<Message> messages) {
JSONArray jsonMessagesArray = new JSONArray();
for (Message msg : messages) {
JSONObject jsonMessage = new JSONObject();
jsonMessage.put("role", msg.getRole());
jsonMessage.put("content", new JSONArray().
put(new JSONObject().put("type", "text").put("text", msg.getContent())));
jsonMessagesArray.put(jsonMessage);
}
JSONObject request = new JSONObject();
request.put("messages", jsonMessagesArray);
return request.toString();
}
static class Message {
private String role;
private String content;
public Message(String role, String content) {
this.role = role;
this.content = content;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment