[CTF from 0 to 1 learning] 2. CTF cryptography

cryptography

Summary

  • Cryptography is a technical science that studies the compilation and deciphering of passwords
  • The technical and scientific science of keeping information confidential is called cryptocoding
  • Cryptography is the science and technology for deciphering cryptography

Basic Model of Information Security

Basic cryptographic concepts

  • Plain text: unencrypted text or string

  • Ciphertext: Message encrypted to plain text

  • Encryption algorithm:

  • Decryption algorithm

  • encryption key

  • decryption key

  • Single Key Cryptography

  • Double Key Cryptography

History and Development of Cryptography

Stage 1 (pre-1949) Development of Classical Cryptography

  • Steganography, Secret Words, Hidden Words, Tibetan Head Poems, etc.

  • Implemented by manual or mechanical transformation

  • Form Substitution Password: Caesar Password, Affine Password

  • Multi-table substitution password: Vigenere, Hill password, etc.

  • Runner Password: Enigma, Red Password, etc.

Phase 2: Modern Password Phase (1949-1976)

  • In 1949, Shannon published Communication Theory of Secret System, which analyzed the basic principles of cryptography from the perspective of information theory, and established the basic theory of cryptography.
  • The Translator was published by David Kahn in 1967

Modern Cryptography (1976-present)

  • In 1976, Diffie and Hellman published New Directions in Cryptography, which opened up a new field of public key cryptography.
  • In 1976, the United States established DES as a federal standard

The main development direction of modern cryptography

  • Chaotic cryptography: The basic principle of chaotic encryption is to use chaotic system to generate chaotic series as key sequence, and the receiver uses chaotic synchronization to extract clear text signals for decryption.

  • Quantum cryptography: The science of quantum cryptography that uses the properties of quantum mechanics to encrypt. Any attempt to read a quantum state alters the quantum state itself.

Cryptography Classification

  • restricted algorithm: The algorithm's confidentiality is based on the secret of the secret algorithm.

  • key-based algorithm: The algorithm's confidentiality is based on the key's confidentiality.

An encryption system S can be described in mathematical symbols as follows:

S={P,C,K,E,D}

P --- Clear text space, representing all possible clear text collections
C --- Ciphertext space, representing all possible collections of ciphertext
K --- Key space, the key is a variable parameter in the encryption algorithm
E --- An encryption algorithm consisting of formulas, rules, or programs
D --- Decryption algorithm, E Inverse of

The relationship between the symbols given the key k

C = Ek(P), For plain text P Encrypted ciphertext C
P = Dk(C) = Dk(Ek(P)), Ciphertext C Clear text after decryption P
 Encryption design is primarily determined E,D,K

Good cryptographic algorithms should be key-based, not algorithm-based.

Modern cryptography uses keys to solve problems, and keys are represented in K

The range of possible values for key K is called keyspace.

Single Key System, Symmetric Encryption

Stream Password

block cipher

Two key system

Diffie and Hellman were first introduced in 1976

A pair of keys: public key and key

Password attack

Attack TypeAttacker Mastery
Ciphertext-only attackencryption algorithm
Intercepted Secret Text
Known plaintext attackencryption algorithm
Intercepted Secret Text
One or more plain-cipher pairs
Select Clear Text Attackencryption algorithm
Intercepted Secret Text
Clear text messages of your choice and relative ciphertext generated by the key
Select ciphertext attackencryption algorithm
Intercepted Secret Text
The ciphertext message you choose and the corresponding decrypted plain text

Security of the algorithm

Encryption algorithms are secure if the cost of the decoding algorithm is greater than the value of the encrypted data

If the decoding algorithm takes longer than encrypting the data to be kept secret, you may be safe

Encoding and Password

Coding Base

ASCII

Standard ASCII code that uses 7-bit binary numbers (the remaining bit is 0) to represent all uppercase and lowercase letters, numbers, and punctuation symbols.

The last 128 are called extended ASCII codes, and many x86-based systems support using extended ASCII. Extended ASCII code allows the eighth bit of each character to be used to determine additional 128 special symbol characters, foreign letters, and graphic symbols

Extending ASCII tables

unicode

ASCII only has 8 bits and can only express 256 characters. So there is unicode, which is a character encoding scheme developed by international organizations to accommodate all the words and symbols in the world. Use 16-bit encoding space (2 bytes per character)

UTF-8 (8-bit Unicode Transformation Format) is a variable-length character encoding for Unicode.

UTF-8 uses 1-6 bytes to encode each character

BASE64

Base64 is a representation of binary data based on 64 printable characters.

Every 6 bits of a unit, corresponding to a printable character in addition to A-Z, a-z, 0-9 of 62 characters there are "+", "/", and finally "=" to fill the space that cannot be completely divided by 3.

Classical Cryptography

Classic password encryption replaces each letter of plain text with another letter in the alphabet.

monoalphabetic substitution cipher

Caesar cipher

When encrypting a Caesar password, move each letter of the plain text forward or backward by a fixed number in alphabetical order as ciphertext

Shift Password

Similar to the Caesar code, the earliest Caesar code was a fixed 3-bit left shift.

The shift password can be moved around freely and will handle not only 26 letters but also numbers and special characters later. Displacement referring to ASCII table

Affine Password

Example:

encryption

Decrypt:

Polyalphabetic Ciphers

Find Matrix Replacement:

If two letters are in the same row, replace them with the right one

If two letters are in the same column, replace them with the letters below

Replace each row with a diagonal letter of the matrix

polybius password (checkerboard password)

vigenere password

Use 26 letters to form a clear text column for the horizontal behavior of the alphabet matrix and a key column vertically

Other types of passwords

Bacon's cipher

Binary thinking: bold B, normal A

rail fence cipher

Divide plaintext into N groups and join the first of each group

Morse code

Use. and _ Indicates that it was previously used to produce telegrams

Strange passwords in CTF

Reverse Encryption

Computer keyboard password

Keyboard Password

Mobile Keyboard Encryption

Pawnshop password

Numbers are represented by men and coded. Men are characterized by the number of heads

Pigpen cipher

Symmetric Encryption

Basic concepts

Feature: Encryption and decryption use the same key (single key encryption)

Divided into

  • Stream Encryption: Each encryption uses a key to generate a key stream. Decryption also uses the same key stream. The plain text and the same length of the key stream are XOR operations to get the ciphertext, and the ciphertext and the same key stream are XOR operations to get the plain text. Typical algorithm RC4.

    • RC4:

RC4 is a typical stream encryption algorithm commonly used in SSL/TSL, 802.11 and WAP.

Stream encryption encrypts data byte by byte, and RC4 essentially uses a random number generated from a key as seed to byte XOR plain text.

The difference between a block cipher and a stream cipher is whether or not it has memory.

Encryption Procedure

1. Initialize the S table

(1) Linear filling of the S table, generally 256 bytes

(2) Fill another 256-byte K-table with a seed key

(3) Initial replacement of S table with K table

2. Generation of the key stream (a pseudo-random number is generated for each byte to be encrypted for XOR, and once the S table is initialized, the seed key is no longer used).



RC4 Encryption Implementation

# RC4 Encryption Algorithm Implementation


# Initialize the S table
def ini_S(K):
    S = [a for a in range(256)]
    j = 0
    for i in range(256):
        j = (j + S[i] + K[i]) % 256
        S[i],S[j] = S[j],S[i]

    return S

# Seed Password Generation Temporary Table
def create_R(seeds):
    T = bytes(seeds, encoding='utf-8')  # Decode utf-8 byte code to Python default unicode string
    T = list(T)  # Convert to List Type
    print('private seeds:', T)  # Output Key
    len_key = len(T)  # Determine the length of the key
    R = [T[i % len_key] for i in range(256)]  # Copy and populate T and save it in the R array

    return R

# Generation of key stream
def steam_K(S,length):
    i = 0
    j = 0
    Sh = []  # Sh Save Stream
    length = int(length)  # Save half the length of plain text or ciphertext
    for i in range(length):
        i = (i + 1) % 256  # If 256 locations are used up, start with S[i]
        j = (j + S[i]) % 256  # Select another byte of S[i] and S
        # Swap another byte of S[i] and s
        temp = S[i]
        S[j] = S[j]
        S[i] = temp
        h = (S[j] + S[i]) % 256  # Overflow prevention operation
        k = S[h]
        Sh.append(k)  # Add k to the end of Sh a new object
    return Sh

if __name__ == '__main__':
    choose = input('choose 1--encryption, 2--decryption:')  # 1 for encryption and 2 for decryption

    if choose == '1':
        key = input("input the key:")
        R = create_R(key)
        S = ini_S(R)
        plaintext = input("input the plaintext:")
        K = steam_K(S,len(plaintext))
        ciphertext = ''
        for i in range(len(plaintext)):
            ciphertext = ciphertext + '%02x' % (K[i] ^ ord(plaintext[i]))  # Do XOR and save in ciphertext
        print('ciphertext:', ciphertext)  # Output ciphertext

# Decryption operation
    if choose == '2':
        key = input('input the key:')  # key Save key
        K = create_R(key)  # K Save auxiliary table for key
        S = ini_S(K)  # Initialization of S
        ciphertext = input('input the ciphertext:')  # Ciphertext saves ciphertext
        plaintext = ''  # Plaintext saves plaintext
        Sh = steam_K(S, len(ciphertext)/2)  # Stream to generate ciphertext
        # Sh does XOR with the next byte of ciphertext
        for i in range(int(len(ciphertext)/2)):
            plaintext = plaintext + chr(int(ciphertext[0:2], 16) ^ Sh[i])  # Do XOR and save in plaintext
            ciphertext = ciphertext[2:]
        print('plaintext:', plaintext)  # Output ciphertext

Block encryption (group password), encryption and decryption sequences are divided into groups, and finally each sequence is combined to form clear or cipher text. Depending on how the groups are encrypted, each group may or may not be related. Typical algorithms DES and AES

DES (data encryption standard)


Initial Substitution

Wheel transformation

S-box

Encryption mode

ECB(Electronic CodeBook)

Is the simpler encryption mode in block encryption. In ECB mode, each clear data block is encrypted independently to generate an encrypted block. This means that if you find two blocks with the same content, you can be sure that the original text of the two blocks is the same.

CBC(cipher-Block Chaining)

The most common block encryption mode. In CBC, each clear text block is XOR by using the previous clear text before encrypting. The decryption process is the opposite. The first clear block is XOR using IV and initialization vectors.

Cryptanalysis

  • Differential cryptography is one of the most effective methods to attack iterated cryptography. The basic idea is to recover some key bits by analyzing the influence of the difference between plaintext pairs on the difference between ciphertext pairs.
  • Linear cryptanalysis is a known clear-text attack on iterative cryptography, utilizing "unbalanced (valid) linear approximation" in cryptographic algorithms.

AES(advanced encryotion standard)

Public Key Cryptography

Public Key Cryptography Constitution Algorithm Conditions

Generating a pair of keys is computationally feasible

Given the public key, plain text, generating ciphertext is computationally feasible

It is computationally feasible to get clear text by using private key and ciphertext

Inferring that a private key is computationally infeasible using a public key

Using public keys and cryptography to get plain text is not computationally feasible

RSA algorithm


CTF Wp

The things given are different from the titles, but that's okay, because the first few titles are very general encoding

Code Decoding

1.AAencode


Found a lot of facial text, AAencode is mainly to convert js code into network emoticons. We put ciphertext directly into the browser console

2.brainfuck


Title Tip brainfuck encoding, Baidu a lot

Online Codec Website: https://www.splitbrain.org/services/ook

3.Ook


Online Codec Tool

4.Quoted-Printable encoding


Quoted-Printable encoding stands for Printable Character Reference and is an implementation of the Multipurpose Internet Mail Extension (MIME). The encoding principle is that any 8-bit byte value can be encoded as 3 characters, an equal sign followed by two hexadecimal digits (0~9or A~F)

5.UUencode

6.XXencode

Classic Password

Simple transposition password


Write decryption scripts based on Title tips

ciphertext = "foerlu_ia_ssglue{ir!ykp}"

key = 6 # Several Groups
numrow = key
numcol = round(len(ciphertext)/key) # 4
plaintext = [""] * int(numcol)
# print(plaintext)

col = 0
row = 0
for symbol in ciphertext:
    plaintext[col] += symbol
    col += 1
    # print(plaintext)
    #
    if col == numcol:
        col = 0
        row += 1
        # print(row,plaintext)
    print(''.join(plaintext))

Pigpen cipher


When you see the title, think of the pigsty code and decrypt it according to the corresponding relationship*

Etbash password


First look at base64 encoding


Write a script yourself

arr1 = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
        "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
arr2 = list(reversed(arr1))
ciphertext = "UOZTSZSZXGURHMRXV"
plaintext = ""
for k in ciphertext:
    plaintext += arr2[arr1.index(k)]
    print(plaintext)

Chardo Password


Corresponding decoding will do

Pawnshop password



Get 9 1 5 8 7 5 3 6 2 4, incorrect
Biwalk found compressed files in the picture

Bacon's cipher


1. First look like the Moses code

2. Because the title is Bacon, think of the Bacon password

Nine palace code

Because it was received by mobile phone, guess is related to mobile phone

The book says flagsimple, but I can't figure it out?

Caesar


Write a script

cipher = "mshnjhlzhypzmbuufek" # mshn{jhlzhy_pz_mbuufek}
# flagcaesarisftnnxwd flag{caesar_is_ftnnxwd}
# print(ord("a"),ord("z")) 97 122
for n in range(1,26):
    tmp = []
    for i in cipher:
        # Trinomial operation used
        tmp.append(chr(ord(i)-n if ord(i)-n >= 97 else 122 - n + ord(i) - 97))
    print(''.join(tmp))

Vigenere Cipher


Try it

Rabbit password

Rot13 Password


Caesar encryption shift 13

Barrier Dilemma

Look at the question, Caesar is fenced down by 13 fences, 13 intervals

On Conversion Equation, Euler Theorem, Inverse Multiplication Element, Inverse Matrix Defined on Zm

Reference resources: https://blog.csdn.net/Pioo_/article/details/110390802

This story is fairly clear.

1. Modular Congruence

Modular congruence: Given a positive integer m, if two integers a and B satisfy that A-B can be integerly divided by m, that is, (a-b)/m yields an integer, then the integer a and B modular m are called integer m congruence and are recorded as a_b(mod m). M-congruence is an equivalent relationship of integers.
For example:
3 divided by 2 1

5 divided by 2 1

3,5 divided by 2 has the same remainder

So 3 redundant 5 modulus 1, write down: 3_5 (mod 1)


Some Properties of Congruence


3. Euler Functions and Euler Theorems

I'll just multiply the inverse by myself.

hill cipher

Affine Password

Reference resources: https://blog.csdn.net/Pioo_/article/details/110235362


Notice that the hash sign is not equal to the third sign

See the reference article if you can't understand it!!!



Code

'''
Affine Password K = (a,b)
The encryption function is E(x)= (ax + b) (mod 26)
The decryption function is D(x) = (a^-1)(x - b) (mod 26),among a^-1 yes a The inverse of multiplication of
'''

def fangsheEncode(a, b, e):
    cipher = []
    for i in e:
        tmp = chr(((ord(i) - 65) * a + b) % 26 + 65) # a ascii 97
        cipher.append(tmp)
    print("The ciphertext is:" + "".join(cipher).upper())
# Traversal Multiplication Inverse Element
def get_multiplicative_inverse(a):
    for i in range(0,100):
        if(a * i % 26 == 1):
            # print(i)
            return i


def fangsheDecode(a, b, e):
    ny = get_multiplicative_inverse(a)
    plaintext = []

    for i in e:
        tmp = ((ord(i) - 65) - b) * ny % 26 + 65 # A ascii 65
        plaintext.append(chr(tmp))
    print("The plain text is:" + "".join(plaintext).upper())


if __name__ == '__main__':
    a,b = 3,9
    e = "JYYHWVPIDCOZ"
    fangsheDecode(a, b, e)
    fangsheEncode(a,b,"AFFINECRYPTO")
    # print(ord("A")) 65

Symmetric Password

DES Decryption


DES-CBC


https://gchq.github.io/CyberChef/ Decrypt Web Site

Tags: Blockchain security Web Security

Posted on Sat, 04 Dec 2021 14:11:13 -0500 by mhewall