Caesar cipher (including kanji) in Python

Caesar cipher

[Caesar Cipher-Wikipedia](https://ja.wikipedia.org/wiki/%E3%82%B7%E3%83%BC%E3%82%B6%E3%83%BC%E6%9A%97% E5% 8F% B7) It is a primitive encryption method that shifts the alphabet by the specified number of characters.

Implementation (alphabet / number only)

For alphabets and numbers only, you can use the python built-in function ROT13. According to the Wiki, the number of shifts is traditionally 13 in such cases. If you set it to 13, the alphabet is 26 characters, so it seems that the same function can be used for encryption and decryption. (Because I will go around and come back)

import codecs
codecs.decode('Hello, World!', 'rot13')
# 'Uryyb, Jbeyq!'
codecs.decode('Uryyb, Jbeyq!', 'rot13')
# 'Hello, World!'

Implementation (including kanji)

This time, I needed to mask the data of the character string including Chinese characters, so I made it myself. In addition to the restriction that alphabets and numbers loop in the range of A-Z, a-z, 0-1 and symbols are not encrypted. I had to save the data in Shift-Jis for religious reasons, so I made it.

However, there are the following restrictions. --Symbol as it is --Alphabet (uppercase / lowercase) Numbers are only for the characters set with key --Kana / Kana / Kanji 1 or more characters (until the next existing character exists)

Please note that Kana-Kana-Kanji is a code that shifts one character regardless of the key number. The reason will be described later.

def caesar(plaintext):
    key=13    # key:Numbers that shift the character code for alphabets and numbers
    enc="cp932"
    ciphertext = ""
    for ch in list(plaintext): #Scan character by character and use if minutes to determine the type of character from the number in the character code.
        #symbol
        if (' ' <= ch <= '/') or (':' <= ch <= '@') or ('[' <= ch <= '`') or ('{' <= ch <= '~') or ('、' <= ch <= '◯') :
            ciphertext +=chr(ord(ch))
        #A-Z
        elif 'A' <= ch <= 'Z':
            ciphertext += chr((ord(ch) - ord('A') + int(key)) % 26 + ord('A'))
        #a-z
        elif 'a' <= ch <= 'z':
            ciphertext += chr((ord(ch) - ord('a') + int(key)) % 26 + ord('a'))
        #0-9
        elif '0' <= ch <= '9':
            ciphertext += chr((ord(ch) - ord('0') + int(key)) % 10 + ord('0'))
        #Others (Hiragana, Katakana, Kanji, etc.)
        else:
            byte=bytearray(ch.encode(enc)) #Encode by specifying the character code. Since this output is a 2-byte byte string, convert it to bytearray before handling it.
            while(1): #Bytes are shifted one by one until the character hits the existing character code.
                try:
                    try:
                        byte[-1]+=0x01  #Shift the last byte part by 1 bit,
                    except:
                        byte[-1]=0x00   #Carry-up consideration. Return the last byte to 00 and increment the next byte
                        byte[-2]+=0x01  
                    x=byte.decode(enc)  #Try decoding with enc and detect the occurrence of an error
                except:
                    pass
                else:
                    break
            ciphertext += x
    return ciphertext

Supplement

The following is an example of a character code that does not have a character. For example, when encrypting "On", if you try to convert it to a character after adding +1 to the character code, an error will occur because the character does not exist. For this reason, we have added the operation of repeating +1 until the character code is reached. In this case, "on" becomes "like". However, this time I assume that the amount of shifting is 1, so I have not done anything more, If you want to increase the number to 2 or more, the situation will be such that "both" milk "and" on "will be encrypted", so please modify accordingly. Due to this relationship, Kana-Kana-Kanji is a program that "shifts only one next to it" regardless of "the number of characters specified by key".

Recommended Posts

Caesar cipher (including kanji) in Python
Write a Caesar cipher program in Python
Create and decrypt Caesar cipher with python
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
I made a Caesar cryptographic program in Python.
Daily AtCoder # 36 in Python
Clustering text in Python
Implement Enigma in python
Daily AtCoder # 32 in Python
Daily AtCoder # 6 in Python
Daily AtCoder # 18 in Python
Edit fonts in Python
Singleton pattern in Python
File operations in Python
Read DXF in python
Daily AtCoder # 53 in Python
Key input in Python
Use config.ini in Python
Solve ABC168D in Python
Daily AtCoder # 7 in Python
LU decomposition in Python