溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C++中string庫對字符串的加密解密

發(fā)布時間:2024-10-09 18:49:20 來源:億速云 閱讀:78 作者:小樊 欄目:編程語言

在C++中,你可以使用<string>庫來處理字符串,但它本身并不提供加密和解密的直接方法。為了實現(xiàn)字符串的加密和解密,你需要使用其他庫,如OpenSSL或Crypto++。

下面是一個使用OpenSSL庫進行AES加密和解密的示例:

首先,確保你已經(jīng)安裝了OpenSSL庫。然后,你可以使用以下代碼進行加密和解密:

#include <iostream>
#include <string>
#include <openssl/aes.h>

// AES加密函數(shù)
std::string aes_encrypt(const std::string& plaintext, const std::string& key) {
    AES_KEY enc_key;
    AES_set_encrypt_key(reinterpret_cast<const unsigned char*>(key.c_str()), 256, &enc_key);

    std::string ciphertext(plaintext.size() + AES_BLOCK_SIZE, '\0');
    AES_cbc_encrypt(reinterpret_cast<const unsigned char*>(plaintext.c_str()),
                    reinterpret_cast<unsigned char*>(&ciphertext[0]),
                    plaintext.size(), &enc_key, AES_BLOCK_SIZE, nullptr);

    return ciphertext;
}

// AES解密函數(shù)
std::string aes_decrypt(const std::string& ciphertext, const std::string& key) {
    AES_KEY dec_key;
    AES_set_decrypt_key(reinterpret_cast<const unsigned char*>(key.c_str()), 256, &dec_key);

    std::string plaintext(ciphertext.size(), '\0');
    AES_cbc_encrypt(reinterpret_cast<const unsigned char*>(ciphertext.c_str()),
                    reinterpret_cast<unsigned char*>(&plaintext[0]),
                    ciphertext.size(), &dec_key, AES_BLOCK_SIZE, nullptr);

    // 去除填充
    plaintext.erase(std::remove(plaintext.begin(), plaintext.end(), '\0'), plaintext.end());

    return plaintext;
}

int main() {
    std::string plaintext = "Hello, World!";
    std::string key = "0123456789abcdef";  // 16字節(jié)密鑰

    std::string ciphertext = aes_encrypt(plaintext, key);
    std::cout << "Encrypted text: " << ciphertext << std::endl;

    std::string decrypted_text = aes_decrypt(ciphertext, key);
    std::cout << "Decrypted text: " << decrypted_text << std::endl;

    return 0;
}

注意:

  1. 這個示例使用了AES加密算法和CBC模式。你可以根據(jù)需要選擇其他加密算法和模式。
  2. 密鑰的長度必須與所選加密算法的要求相匹配。在這個例子中,我們使用了256位的密鑰。
  3. 在解密后,我們需要去除填充(PKCS#7填充)。這個示例中的填充去除方法可能不適用于所有情況,你可能需要根據(jù)你的具體需求進行調(diào)整。
  4. 請確保在使用OpenSSL庫之前已經(jīng)正確安裝并配置了它。

如果你不想使用OpenSSL庫,你還可以考慮使用Crypto++庫,它提供了更豐富的加密和解密功能。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

c++
AI