溫馨提示×

C++通過ASCII碼實現加解密技術

c++
小樊
150
2024-07-21 12:58:04
欄目: 編程語言

在C++中,可以通過簡單的ASCII碼加解密技術來加密和解密字符串。下面是一個簡單的示例代碼,用于實現基于ASCII碼的加密和解密功能:

#include <iostream>
#include <string>

using namespace std;

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

// 解密函數
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;
}

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

main函數中,我們定義了一個字符串text和一個密鑰值key,然后分別對這個字符串進行加密和解密操作,并輸出結果。

請注意,這只是一個簡單的示例,實際上這種基于ASCII碼的加密方法并不是很安全,可以很容易地被破解。在實際應用中,建議使用更加安全的加密算法,如AES、DES等。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女