常用的加密字符串的方式有几种请用C加加示例一下
时间: 2023-03-31 18:02:55 浏览: 125
C#各种字符串加密方法
4星 · 用户满意度95%
常用的加密字符串的方式有很多种,比如MD5、SHA1、SHA256、AES等。下面以AES加密为例,示例代码如下:
```c++
#include <iostream>
#include <string>
#include <cstring>
#include <openssl/aes.h>
using namespace std;
string aes_encrypt(string plain_text, string key) {
AES_KEY aes_key;
unsigned char iv[AES_BLOCK_SIZE];
memset(iv, , AES_BLOCK_SIZE);
if (AES_set_encrypt_key((const unsigned char*)key.c_str(), 128, &aes_key) < ) {
return "";
}
int len = plain_text.length();
int padding = AES_BLOCK_SIZE - len % AES_BLOCK_SIZE;
len += padding;
unsigned char* input = new unsigned char[len];
memcpy(input, plain_text.c_str(), plain_text.length());
for (int i = ; i < padding; i++) {
input[plain_text.length() + i] = padding;
}
unsigned char* output = new unsigned char[len];
AES_cbc_encrypt(input, output, len, &aes_key, iv, AES_ENCRYPT);
string cipher_text((char*)output, len);
delete[] input;
delete[] output;
return cipher_text;
}
int main() {
string plain_text = "Hello, world!";
string key = "1234567890123456";
string cipher_text = aes_encrypt(plain_text, key);
cout << "Plain text: " << plain_text << endl;
cout << "Cipher text: " << cipher_text << endl;
return ;
}
```
以上代码使用AES算法对字符串进行加密,其中key为密钥,plain_text为明文,cipher_text为密文。
阅读全文