C++通過(guò)ASCII碼實(shí)現(xiàn)加解密技術(shù)

c++
小樊
102
2024-07-21 12:58:04

在C++中,可以通過(guò)簡(jiǎn)單的ASCII碼加解密技術(shù)來(lái)加密和解密字符串。下面是一個(gè)簡(jiǎn)單的示例代碼,用于實(shí)現(xiàn)基于ASCII碼的加密和解密功能:

#include <iostream>
#include <string>

using namespace std;

// 加密函數(shù)
string encrypt(string text, int key) {
    string result = "";
    for (int i = 0; i < text.length(); i++) {
        result += char(int(text[i]) + key);
    }
    return result;
}

// 解密函數(shù)
string decrypt(string text, int key) {
    string result = "";
    for (int i = 0; i < text.length(); i++) {
        result += char(int(text[i]) - key);
    }
    return result;
}

int main() {
    string text = "Hello, world!";
    int key = 3;

    string encryptedText = encrypt(text, key);
    string decryptedText = decrypt(encryptedText, key);

    cout << "Original Text: " << text << endl;
    cout << "Encrypted Text: " << encryptedText << endl;
    cout << "Decrypted Text: " << decryptedText << endl;

    return 0;
}

在這個(gè)示例中,我們定義了兩個(gè)函數(shù)encryptdecrypt,分別用于加密和解密字符串。在encrypt函數(shù)中,我們將字符串中的每個(gè)字符的ASCII碼加上一個(gè)密鑰值,得到加密后的字符;在decrypt函數(shù)中,我們將加密后的字符串中的每個(gè)字符的ASCII碼減去密鑰值,得到解密后的字符。

main函數(shù)中,我們定義了一個(gè)字符串text和一個(gè)密鑰值key,然后分別對(duì)這個(gè)字符串進(jìn)行加密和解密操作,并輸出結(jié)果。

請(qǐng)注意,這只是一個(gè)簡(jiǎn)單的示例,實(shí)際上這種基于ASCII碼的加密方法并不是很安全,可以很容易地被破解。在實(shí)際應(yīng)用中,建議使用更加安全的加密算法,如AES、DES等。

0