openssl GCM
时间: 2023-09-12 16:11:07 浏览: 122
OpenSSL is a widely-used open-source cryptographic library that provides support for various cryptographic algorithms, including the GCM (Galois/Counter Mode) encryption mode.
GCM is an authenticated encryption mode that provides both confidentiality and integrity. It combines the Counter (CTR) mode of encryption with a universal hash function called Galois Message Authentication Code (GMAC). GCM is commonly used for secure communication protocols like TLS.
To use GCM with OpenSSL, you can utilize the EVP (Envelope) API provided by OpenSSL. Here's an example of how you can use OpenSSL to perform GCM encryption and decryption:
```c
#include <openssl/evp.h>
void encrypt_decrypt_gcm(const unsigned char* key, const unsigned char* iv, const unsigned char* aad,
const unsigned char* ciphertext, int ciphertext_len, unsigned char* tag,
unsigned char* plaintext) {
EVP_CIPHER_CTX* ctx;
int len;
int plaintext_len;
// Create and initialize the context
ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
// Set the key and IV
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_KEY_LEN, 256, NULL);
EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv);
// Set the AAD (Additional Authenticated Data)
EVP_EncryptUpdate(ctx, NULL, &len, aad, sizeof(aad));
// Perform the encryption
EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len);
// Finalize the encryption (generates the authentication tag)
EVP_EncryptFinal_ex(ctx, ciphertext + len, &len);
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag);
// Cleanup
EVP_CIPHER_CTX_free(ctx);
}
int main() {
unsigned char key[32]; // 256-bit key
unsigned char iv[12]; // 96-bit IV
unsigned char aad[16]; // Additional Authenticated Data
unsigned char ciphertext[128];
unsigned char tag[16];
unsigned char plaintext[128];
// Initialize the key, IV, AAD, and plaintext
encrypt_decrypt_gcm(key, iv, aad, ciphertext, sizeof(ciphertext), tag, plaintext);
return 0;
}
```
In this example, you would need to replace the placeholders for the key, IV, AAD, ciphertext, and plaintext with the actual data you want to use. Additionally, make sure to include the necessary OpenSSL headers and link against the OpenSSL library when compiling.
This is just a basic example and it's important to use proper cryptographic practices and ensure the security of your implementation. It's recommended to refer to the OpenSSL documentation and consult cryptographic experts for more guidance on using GCM with OpenSSL.
阅读全文