Я хочу зашифровать данные с клиента и отправить их на сервер через сокет. Клиент написан на Java, а сервер - на C. Однако результат не совпадает с моим ожидаемым. Программа C выглядит следующим образом:
#define MAX_BUFF 1024
#define MAX_LENGTH_DATA 1024
static void decrypt128(unsigned char intput[], unsigned char output[]) {
mbedtls_aes_context context_out;
unsigned char key1[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P'};
unsigned char iv1[16] = { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P' };
unsigned char decrypt[128];
mbedtls_aes_init(&context_out);
mbedtls_aes_setkey_dec(&context_out, key1, 128);
mbedtls_aes_crypt_cbc(&context_out, MBEDTLS_AES_DECRYPT, 16, iv1, intput,decrypt);
printf("\nInside of decrypt128 function:\n");
for (unsigned index = 0; index < 128; ++index)
printf("%c", (char) decrypt[index]);
strcpy(output, decrypt);
}
int main(int argc, char * argv[]){
int socket_desc, client_sock, c, read_size, rc, option = 1, ret,
encrypt_size, counter_data_receive;
struct sockaddr_in server, client;
int opt = 1;
struct timeval timeout_receive;
unsigned char encrypt_bufferr[MAX_LENGTH_DATA] = { 0 };
unsigned char decrypt_bufferr[MAX_LENGTH_DATA] = { 0 };
// Creating socket file descriptor
printf("Creating socket...!!!!!\n");
if ((socket_desc = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// Forcefully attaching socket to the port 4434
if (setsockopt(socket_desc, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt,
sizeof(opt))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(4434);
// Forcefully attaching socket to the port 4434
if (bind(socket_desc, (struct sockaddr *) &server, sizeof(server)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
c = sizeof(struct sockaddr_in);
printf("Start waiting for incoming connections!\n");
listen(socket_desc, 1);
client_sock = accept(socket_desc, (struct sockaddr*) &client,
(socklen_t*) &c);
if (client_sock < 0) {
printf("Failed: accept connection");
exit(EXIT_FAILURE);
}
printf("Connection accepted\n");
timeout_receive.tv_sec = 5;
timeout_receive.tv_usec = 0;
setsockopt(client_sock, SOL_SOCKET, SO_RCVTIMEO,
(const void*) &timeout_receive, sizeof(struct timeval));
memset(encrypt_bufferr, 0x00, sizeof(encrypt_bufferr));
memset(decrypt_bufferr, 0x00, sizeof(decrypt_bufferr));
ret = recv(client_sock, encrypt_bufferr, sizeof(encrypt_bufferr), 0);
printf("\n+++++++++++++byte receive: %d\n", ret);
printf("\n+++++++++++++received buff: %s\n", encrypt_bufferr);
decrypt128(encrypt_bufferr, decrypt_bufferr);
printf("\nFinal decrypted data = %s", decrypt_bufferr);
}
вывод
Creating socket...!!!!!
Start waiting for incoming connections!
Connection accepted
+++++++++++++byte receive: 24
+++++++++++++received buff: 8+4c4xcMC1FPhdJabnl/4w==
Inside of decrypt128 function:
R�V͵2�Q���˵��
Для клиентской части я написал ее, используя Java:
public class EncryptDecryptString {
private static final String cipherTransformation = "AES/CBC/PKCS5PADDING";
private static final String aesEncryptionAlgorithem = "AES";
public static String encrypt(String plainText) {
String encryptedText = "";
byte iv1[] = { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P' };
try {
Cipher cipher = Cipher.getInstance(cipherTransformation);
byte[] key = { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P' };
SecretKeySpec secretKey = new SecretKeySpec(key, aesEncryptionAlgorithem);
IvParameterSpec ivparameterspec = new IvParameterSpec(iv1);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivparameterspec);
byte[] cipherText = cipher.doFinal(plainText.getBytes("UTF-8"));
Base64.Encoder encoder = Base64.getEncoder();
encryptedText = encoder.encodeToString(cipherText);
} catch (Exception E) {
System.err.println("Encrypt Exception : "+E.getMessage());
}
return encryptedText;
}
public static String decrypt(String encryptedText) {
String decryptedText = "";
byte iv1[] = { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P' };
try {
Cipher cipher = Cipher.getInstance(cipherTransformation);
byte[] key = { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P' };//encryptionKey.getBytes(characterEncoding);
SecretKeySpec secretKey = new SecretKeySpec(key, aesEncryptionAlgorithem);
IvParameterSpec ivparameterspec = new IvParameterSpec(iv1);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivparameterspec);
Base64.Decoder decoder = Base64.getDecoder();
byte[] cipherText = decoder.decode(encryptedText.getBytes("UTF8"));
decryptedText = new String(cipher.doFinal(cipherText), "UTF-8");
} catch (Exception E) {
System.err.println("decrypt Exception : "+E.getMessage());
}
return decryptedText;
}
public static void main(String[] args) {
//System.out.println("Enter String : ");
System.out.println("Running.... ");
String plainString = "Hello world!";//sc.nextLine();
String encyptStr = encrypt(plainString);
String decryptStr = decrypt(encyptStr);
Socket socketOfClient;
try {
socketOfClient = new Socket("127.0.0.1", 4434);
BufferedWriter os = new BufferedWriter(new OutputStreamWriter(socketOfClient.getOutputStream()));
BufferedReader is = new BufferedReader(new InputStreamReader(socketOfClient.getInputStream()));
os.write(encyptStr);
os.flush();
System.out.printf("\nSent data to server....\n");
//os.flush();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Plain String : "+plainString);
System.out.println("Encrypt String : "+encyptStr);
System.out.println("Decrypt String : "+decryptStr);
}
}
Вывод
Running....
Sent data to server....
Plain String : Hello world!
Encrypt String : 8+4c4xcMC1FPhdJabnl/4w==
Decrypt String : Hello world!
Полученные зашифрованные данные одинаковы для обеих сторон, но когда я использовал mbedtl для расшифровки этих данных на стороне сервера, результат не тот же. Пожалуйста, помогите мне решить проблему. Спасибо !!!!