C++中string库对字符串的加密解密

发布时间:2024-10-09 18:49:20 作者:小樊
来源:亿速云 阅读:78

在C++中,你可以使用<string>库来处理字符串,但它本身并不提供加密和解密的直接方法。为了实现字符串的加密和解密,你需要使用其他库,如OpenSSL或Crypto++。

下面是一个使用OpenSSL库进行AES加密和解密的示例:

首先,确保你已经安装了OpenSSL库。然后,你可以使用以下代码进行加密和解密:

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

// AES加密函数
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解密函数
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字节密钥

    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模式。你可以根据需要选择其他加密算法和模式。
  2. 密钥的长度必须与所选加密算法的要求相匹配。在这个例子中,我们使用了256位的密钥。
  3. 在解密后,我们需要去除填充(PKCS#7填充)。这个示例中的填充去除方法可能不适用于所有情况,你可能需要根据你的具体需求进行调整。
  4. 请确保在使用OpenSSL库之前已经正确安装并配置了它。

如果你不想使用OpenSSL库,你还可以考虑使用Crypto++库,它提供了更丰富的加密和解密功能。

推荐阅读:
  1. c++和python的区别是什么
  2. c++、php、java三种语言的详细分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:string库对字符串的模糊匹配算法

下一篇:字符串中重复字符的删除策略

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》