OpenSSL Crypto

Cryptography LibraryOpenSSLTLSSSLEncryptionHashCertificateC/C++

Authentication Library

OpenSSL Crypto

Overview

OpenSSL is an open-source toolkit that provides TLS/SSL protocols and a general-purpose cryptography library.

Details

OpenSSL is one of the world's most widely used cryptography libraries, providing implementations of TLS (Transport Layer Security) and SSL (Secure Sockets Layer) protocols. Licensed under the Apache License 2.0, it's an open-source project written in C. It provides comprehensive cryptographic functionality including symmetric encryption (AES, DES, 3DES), asymmetric encryption (RSA, ECC, DSA), hash functions (SHA, MD5), message authentication codes (HMAC), digital signatures, and X.509 certificate processing. It can handle a wide range of security requirements including network communication security, file encryption, digital certificate management, and PKI (Public Key Infrastructure) construction. Bindings are available for many programming languages, and it's cross-platform compatible, running on various operating systems.

Pros and Cons

Pros

  • Industry Standard: Widely adopted cryptography library worldwide
  • Comprehensive Features: Full support for symmetric/asymmetric encryption, hashing, digital signatures
  • Protocol Support: Implementation of security protocols like TLS/SSL, DTLS, QUIC
  • Multi-language Support: Bindings available for various programming languages
  • Cross-platform: Support for Linux, Windows, macOS, embedded systems
  • High Performance: Optimized algorithm implementations
  • Rich Algorithms: Wide range of cryptographic algorithms from classic to modern

Cons

  • Complexity: API complexity due to extensive functionality
  • Security Updates: Regular vulnerability responses and updates required
  • Memory Management: Careful memory management required due to C language base
  • Documentation: Some features lack detailed documentation
  • Build Complexity: Platform-specific build configurations can be complex
  • Debugging Difficulty: Cryptography-related issues can be hard to debug

Key Links

Code Examples

Basic AES Encryption/Decryption

#include <openssl/evp.h>
#include <openssl/aes.h>
#include <openssl/rand.h>

// AES-256-CBC encryption
int encrypt_aes(unsigned char *plaintext, int plaintext_len,
                unsigned char *key, unsigned char *iv,
                unsigned char *ciphertext) {
    EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
    int len, ciphertext_len;

    // Initialize encryption
    EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv);

    // Perform encryption
    EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len);
    ciphertext_len = len;

    // Finalize encryption
    EVP_EncryptFinal_ex(ctx, ciphertext + len, &len);
    ciphertext_len += len;

    EVP_CIPHER_CTX_free(ctx);
    return ciphertext_len;
}

// AES-256-CBC decryption
int decrypt_aes(unsigned char *ciphertext, int ciphertext_len,
                unsigned char *key, unsigned char *iv,
                unsigned char *plaintext) {
    EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
    int len, plaintext_len;

    // Initialize decryption
    EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv);

    // Perform decryption
    EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len);
    plaintext_len = len;

    // Finalize decryption
    EVP_DecryptFinal_ex(ctx, plaintext + len, &len);
    plaintext_len += len;

    EVP_CIPHER_CTX_free(ctx);
    return plaintext_len;
}

RSA Key Pair Generation and Digital Signature

#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/evp.h>

// Generate RSA key pair
EVP_PKEY* generate_rsa_keypair(int key_length) {
    EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL);
    EVP_PKEY *pkey = NULL;

    // Initialize key generation
    EVP_PKEY_keygen_init(ctx);
    EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, key_length);

    // Generate key pair
    EVP_PKEY_keygen(ctx, &pkey);

    EVP_PKEY_CTX_free(ctx);
    return pkey;
}

// Create digital signature
int sign_data(unsigned char *data, size_t data_len,
              EVP_PKEY *private_key, unsigned char **signature,
              size_t *signature_len) {
    EVP_MD_CTX *ctx = EVP_MD_CTX_new();
    
    // Initialize signing
    EVP_DigestSignInit(ctx, NULL, EVP_sha256(), NULL, private_key);
    
    // Update with data
    EVP_DigestSignUpdate(ctx, data, data_len);
    
    // Get signature length
    EVP_DigestSignFinal(ctx, NULL, signature_len);
    
    // Create signature
    *signature = OPENSSL_malloc(*signature_len);
    int ret = EVP_DigestSignFinal(ctx, *signature, signature_len);
    
    EVP_MD_CTX_free(ctx);
    return ret;
}

SHA-256 Hash Calculation

#include <openssl/sha.h>
#include <openssl/evp.h>

// Calculate SHA-256 hash
int calculate_sha256(unsigned char *data, size_t data_len,
                     unsigned char *hash) {
    EVP_MD_CTX *ctx = EVP_MD_CTX_new();
    unsigned int hash_len;

    // Initialize hash
    EVP_DigestInit_ex(ctx, EVP_sha256(), NULL);
    
    // Update with data
    EVP_DigestUpdate(ctx, data, data_len);
    
    // Finalize hash
    EVP_DigestFinal_ex(ctx, hash, &hash_len);

    EVP_MD_CTX_free(ctx);
    return hash_len;
}

// Calculate HMAC-SHA256
int calculate_hmac_sha256(unsigned char *data, size_t data_len,
                          unsigned char *key, size_t key_len,
                          unsigned char *hmac) {
    unsigned int hmac_len;
    
    HMAC(EVP_sha256(), key, key_len, data, data_len, hmac, &hmac_len);
    
    return hmac_len;
}

X.509 Certificate Processing

#include <openssl/x509.h>
#include <openssl/x509v3.h>

// Load certificate
X509* load_certificate(const char *cert_file) {
    FILE *fp = fopen(cert_file, "r");
    if (!fp) return NULL;
    
    X509 *cert = PEM_read_X509(fp, NULL, NULL, NULL);
    fclose(fp);
    
    return cert;
}

// Print certificate information
void print_certificate_info(X509 *cert) {
    // Get subject
    X509_NAME *subject = X509_get_subject_name(cert);
    char *subject_str = X509_NAME_oneline(subject, NULL, 0);
    printf("Subject: %s\n", subject_str);
    OPENSSL_free(subject_str);
    
    // Get issuer
    X509_NAME *issuer = X509_get_issuer_name(cert);
    char *issuer_str = X509_NAME_oneline(issuer, NULL, 0);
    printf("Issuer: %s\n", issuer_str);
    OPENSSL_free(issuer_str);
    
    // Check validity period
    ASN1_TIME *not_before = X509_get_notBefore(cert);
    ASN1_TIME *not_after = X509_get_notAfter(cert);
    printf("Valid from: ");
    ASN1_TIME_print(stdout, not_before);
    printf(" to ");
    ASN1_TIME_print(stdout, not_after);
    printf("\n");
}

TLS/SSL Client Connection

#include <openssl/ssl.h>
#include <openssl/err.h>

// Initialize SSL/TLS
void init_openssl() {
    SSL_load_error_strings();
    OpenSSL_add_ssl_algorithms();
}

// Create SSL connection
SSL* create_ssl_connection(const char *hostname, int port) {
    // Create SSL context
    SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
    if (!ctx) return NULL;
    
    // Configure certificate verification
    SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
    SSL_CTX_set_default_verify_paths(ctx);
    
    // Create socket (omitted)
    int sock = create_socket(hostname, port);
    
    // Create SSL structure
    SSL *ssl = SSL_new(ctx);
    SSL_set_fd(ssl, sock);
    
    // TLS handshake
    if (SSL_connect(ssl) <= 0) {
        ERR_print_errors_fp(stderr);
        SSL_free(ssl);
        SSL_CTX_free(ctx);
        return NULL;
    }
    
    return ssl;
}

Random Number Generation

#include <openssl/rand.h>

// Generate cryptographically secure random bytes
int generate_random_bytes(unsigned char *buffer, int length) {
    return RAND_bytes(buffer, length);
}

// Password generation example
void generate_password(char *password, int length) {
    const char charset[] = "abcdefghijklmnopqrstuvwxyz"
                          "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                          "0123456789!@#$%^&*";
    unsigned char random_bytes[length];
    
    if (RAND_bytes(random_bytes, length) == 1) {
        for (int i = 0; i < length; i++) {
            password[i] = charset[random_bytes[i] % (sizeof(charset) - 1)];
        }
        password[length] = '\0';
    }
}