c++ 凯撒密码

        凯撒密码(Caesar Cipher)是一种简单的替代加密技术,以罗马大帝凯撒·尤利乌斯·凯撒(Julius Caesar)的名字命名。它通过将每个字母按照字母表向后移动固定数量的位置来进行加密。

示例一:

/**
 * @file caesar_cipher.cpp
 * @brief Implementation of [Caesar cipher](https://en.wikipedia.org/wiki/Caesar_cipher) algorithm.
 *
 * @details
 * In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, 
 * Caesar's code or Caesar shift, is one of the simplest and most widely known encryption 
 * techniques. It is a type of substitution cipher in which each letter in the plaintext 
 * is replaced by a letter some fixed number of positions down the alphabet. For example, 
 * with a left shift of 3, D would be replaced by A, E would become B, and so on. 
 * The method is named after Julius Caesar, who used it in his private correspondence.
 *
 * ### Algorithm
 * The encryption can also be represented using modular arithmetic by first transforming 
 * the letters into numbers, according to the scheme, A → 0, B → 1, ..., Z → 25.
 * Encryption of a letter x by a shift n can be described mathematically as,
 * \f[ E(x) = (x + n)\;\mbox{mod}\; 26\f]
 * while decryption can be described as,
 * \f[ D(x) = (x - n) \;\mbox{mod}\; 26\f]
 * 
 * \note This program implements caesar cipher for only uppercase English alphabet characters (i.e. A-Z). 
 * 
 * @author [Deep Raval](https://github.com/imdeep2905)
 */
#include <iostream>
#include <string>
#include <cassert>

/** \namespace ciphers
 * \brief Algorithms for encryption and decryption
 */
namespace ciphers {
    /** \namespace caesar
     * \brief Functions for [Caesar cipher](https://en.wikipedia.org/wiki/Caesar_cipher) algorithm.
     */
    namespace caesar {   
        namespace {
            /**
             * This function finds character for given value (i.e.A-Z)
             * @param x value for which we want character 
             * @returns  corresponding character for perticular value
             */        
            inline char get_char(const int x) {
                // By adding 65 we are scaling 0-25 to 65-90. 
                // Which are in fact ASCII values of A-Z. 
                return char(x + 65); 
            }
            /**
             * This function finds value for given character (i.e.0-25)
             * @param c character for which we want value
             * @returns returns corresponding value for perticular character
             */  
            inline int get_value(const char c) {
                // A-Z have ASCII values in range 65-90.
                // Hence subtracting 65 will scale them to 0-25.
                return int(c - 65);
            }
        } // Unnamed namespace
        /**
         * Encrypt given text using caesar cipher.
         * @param text text to be encrypted
         * @param shift number of shifts to be applied
         * @returns new encrypted text
         */
        std::string encrypt (const std::string &text, const int &shift) {
            std::string encrypted_text = ""; // Empty string to store encrypted text
            for (char c : text) { // Going through each character
                int place_value = get_value(c); // Getting value of character (i.e. 0-25)
                place_value = (place_value + shift) % 26; // Applying encryption formula
                char new_char = get_char(place_value); // Getting new character from new value (i.e. A-Z)
                encrypted_text += new_char; // Appending encrypted character
            }
            return encrypted_text; // Returning encrypted text
        }
        /**
         * Decrypt given text using caesar cipher.
         * @param text text to be decrypted
         * @param shift number of shifts to be applied
         * @returns new decrypted text
         */        
        std::string decrypt (const std::string &text, const int &shift) {
            std::string decrypted_text = ""; // Empty string to store decrypted text
            for (char c : text) { // Going through each character
                int place_value = get_value(c); // Getting value of character (i.e. 0-25)
                place_value = (place_value - shift) % 26;// Applying decryption formula
                if(place_value < 0) { // Handling case where remainder is negative 
                    place_value = place_value + 26;
                }
                char new_char = get_char(place_value); // Getting original character from decrypted value (i.e. A-Z)
                decrypted_text += new_char; // Appending decrypted character
            }
            return decrypted_text; // Returning decrypted text
        }
    } // namespace caesar
} // namespace ciphers

/**
 * Function to test above algorithm
 */
void test() {
    // Test 1
    std::string text1 = "ALANTURING";
    std::string encrypted1 = ciphers::caesar::encrypt(text1, 17);
    std::string decrypted1 = ciphers::caesar::decrypt(encrypted1, 17);
    assert(text1 == decrypted1);
    std::cout << "Original text : " << text1;
    std::cout << " , Encrypted text (with shift = 21) : " << encrypted1;
    std::cout << " , Decrypted text : "<< decrypted1 << std::endl;
    // Test 2
    std::string text2 = "HELLOWORLD";
    std::string encrypted2 = ciphers::caesar::encrypt(text2, 1729);
    std::string decrypted2 = ciphers::caesar::decrypt(encrypted2, 1729);
    assert(text2 == decrypted2);
    std::cout << "Original text : " << text2;
    std::cout << " , Encrypted text (with shift = 1729) : " << encrypted2;
    std::cout << " , Decrypted text : "<< decrypted2 << std::endl;
}

/** Driver Code */
int main() {
    // Testing
    test();
    return 0;
}

示例二:

使用C++实现凯撒密码的示例:

#include <iostream>
#include <string>

using namespace std;

// 凯撒密码加密函数
string encryptCaesarCipher(string plaintext, int shift) {
    string ciphertext = "";
    
    for (int i = 0; i < plaintext.length(); i++) {
        if (isalpha(plaintext[i])) {
            // 获取字符的ASCII码
            int ascii = int(plaintext[i]);
            
            // 根据移动位数进行替代
            if (islower(plaintext[i])) {
                ascii = (ascii - 97 + shift) % 26 + 97;
            } else {
                ascii = (ascii - 65 + shift) % 26 + 65;
            }
            
            // 将替代后的字符添加到密文中
            ciphertext += char(ascii);
        } else {
            // 非字母字符直接添加到密文中
            ciphertext += plaintext[i];
        }
    }
    
    return ciphertext;
}

// 凯撒密码解密函数
string decryptCaesarCipher(string ciphertext, int shift) {
    string plaintext = "";
    
    // 将移位数转换为负数,以实现向前移动的效果
    shift = -shift;
    
    // 调用加密函数进行解密
    plaintext = encryptCaesarCipher(ciphertext, shift);
    
    return plaintext;
}

int main() {
    string plaintext = "Hello, World!";
    int shift = 3;
    
    // 加密并输出密文
    string ciphertext = encryptCaesarCipher(plaintext, shift);
    cout << "Ciphertext: " << ciphertext << endl;
    
    // 解密并输出明文
    string decryptedText = decryptCaesarCipher(ciphertext, shift);
    cout << "Decrypted Text: " << decryptedText << endl;
    
    return 0;
}
        在上述示例代码中,`encryptCaesarCipher`函数实现了凯撒密码的加密过程,`decryptCaesarCipher`函数实现了凯撒密码的解密过程。使用`main`函数来测试加密和解密功能,并输出结果。

        注意,该凯撒密码实现只对字母字符进行加密和解密,非字母字符将保持原样。同时,移位数应为正整数,表示向后移动的位数。解密过程是通过将移位数转换为负数,然后调用加密函数实现的。

  • 21
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++是一种通用的高级编程语言,它支持面向对象编程和泛型编程。C++由Bjarne Stroustrup于1983年开发,是C语言的扩展版本。C++具有强大的功能和广泛的应用领域,包括系统开发、游戏开发、嵌入式系统、图形界面等。 凯撒密码是一种简单的替换密码,它通过将字母按照一定的偏移量进行替换来加密消息。例如,偏移量为3时,字母A会被替换为D,字母B会被替换为E,以此类推。解密过程则是将每个字母按照相反的偏移量进行替换。 在C++中实现凯撒密码可以使用字符数组和循环来完成。首先,将明文消息存储在字符数组中,然后通过循环遍历数组中的每个字符,并根据偏移量进行替换。最后,将加密后的消息输出。 以下是一个简单的C++代码示例,实现了凯撒密码的加密和解密功能: ```cpp #include <iostream> using namespace std; void encrypt(string& message, int offset) { for (int i = 0; i < message.length(); i++) { if (isalpha(message[i])) { if (isupper(message[i])) { message[i] = ((message[i] - 'A' + offset) % 26) + 'A'; } else { message[i] = ((message[i] - 'a' + offset) % 26) + 'a'; } } } } void decrypt(string& message, int offset) { encrypt(message, 26 - offset); } int main() { string message = "Hello, World!"; int offset = 3; cout << "Original message: " << message << endl; encrypt(message, offset); cout << "Encrypted message: " << message << endl; decrypt(message, offset); cout << "Decrypted message: " << message << endl; return 0; } ``` 这段代码中,encrypt函数用于加密消息,decrypt函数用于解密消息。在main函数中,我们定义了一个明文消息和偏移量,然后调用encrypt函数进行加密,再调用decrypt函数进行解密。最后,输出加密和解密后的消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值