我需要在服务器中执行DES加密,将加密发送到客户端 并在客户端解密。
服务器:
const EVP_CIPHER *c = EVP_des_cbc();
EVP_CIPHER_CTX *x = malloc(sizeof(EVP_CIPHER_CTX));
EVP_CIPHER_CTX_init(x);
EVP_EncryptInit (x, c, key, iv); // initlizing encryption
EVP_EncryptUpdate (x, encryptedDataBuffer, &encryptedDataLength, dataBuffer, strlen(dataBuffer));
EVP_EncryptFinal (x, encryptedDataBuffer + encryptedDataLength, &encryptedDataLength);
write(client_sock , encryptedDataBuffer , encryptedDataLength);
printf("Encrypted Data Sent to Client\n");
此处服务器对数据进行加密并将其发送给客户端。到目前为止一切都很好。
客户端:
serverDataLength = recv(sockfd , dataBuffer , MAXDATASIZE , 0);
printf("Encrypted Data is Received\n");
const EVP_CIPHER *c = EVP_des_cbc();
EVP_CIPHER_CTX *x = malloc(sizeof(EVP_CIPHER_CTX));
EVP_CIPHER_CTX_init(x);
EVP_DecryptInit(x, c, key, iv);
EVP_DecryptUpdate(x, decryptedDataBuffer, &sizeOfDecryptedBuffer , dataBuffer, serverDataLength);
EVP_DecryptFinal(x, decryptedDataBuffer+sizeOfDecryptedBuffer, &sizeOfDecryptedBuffer);
printf("\n\nDecrypted Data: %s\n", decryptedDataBuffer);
客户端接收数据并对其进行解密。
然而问题是当我在客户端打印解密数据时,它会打印一些垃圾值以及解密数据。如何摆脱这些垃圾值?客户端/服务器工作正常,没问题。
我不想在这里发布完整的代码,它会变得混乱。我很确定问题出现在发布的代码中。
谢谢!
答案 0 :(得分:4)
您提供的程序错误。
尝试以下方法:
int ciphertext_len;
EVP_EncryptUpdate (x, encryptedDataBuffer, &encryptedDataLength, dataBuffer, strlen(dataBuffer));
ciphertext_len = encryptedDataLength;
EVP_EncryptFinal (x, encryptedDataBuffer + encryptedDataLength, &encryptedDataLength);
ciphertext_len += encryptedDataLength;
int plaintext_len;
EVP_DecryptUpdate(x, decryptedDataBuffer, &sizeOfDecryptedBuffer , dataBuffer, ciphertext_len);
plaintext_len = sizeOfDecryptedBuffer;
EVP_DecryptFinal(x, decryptedDataBuffer+sizeOfDecryptedBuffer, &sizeOfDecryptedBuffer);
plaintext_len += sizeOfDecryptedBuffer;
现在打印解密数据:
/* Add a NULL terminator. We are expecting printable text */
decryptedDataBuffer[plaintext_len] = '\0';
/* Show the decrypted text */
printf("Decrypted text is:\n");
printf("%s\n", decryptedDataBuffer);
答案 1 :(得分:3)
我认为理由很简单。
在服务器中,您使用swapping("Boys and girls left the school.", "boys", "girls")
swapping("Boys and girls left the school.", "GIRLS", "bOYS")
should both have an output: "GIRLS and BOYS left the school."
# Basically swapping the words that are typed out after writing down a string
来获取内容长度,因此您忽略了在字符串末尾终止'\ 0'。您解密内容并打印它,忽略终止'\ 0'。所以你在解密消息的末尾从内存中打印垃圾。
您需要发送数据,包括使用strlen()
来终止'\ 0',或者您需要添加来接收内容。
2旁注:
strlen(dataBuffer)+1
算法是一种非常不安全的算法,从不使用它。