(CN) Secret-Key Encryption Lab

SEED Project官网

Secret-Key Encryption Lab

Task 1 Frequency Analysis

1.用频率分析破解单表代换密码。

#!/bin/env python3

s=['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']
b=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
f1=open("./ciphertext.txt","r+")

message=f1.read()
sum=0
for i in message:
    if('a'<=i<='z'):	#只记录字母
        sum=sum+1		#记录字母总数
        for j in range(0,26):
            if(s[j]==i):
                b[j]=b[j]+1
print(sum)#字母总数
print(b)#各个字母总数

for i in range(0,26):
    print(s[i],":",(b[i]/sum)*100)

ciphertext.txt中的词频

image-20221221103136223

已有词频数据:

image-20221221103319370

根据词频分析得出以下结论:

tr   ’abcdefghijklmnopqrstuvwxyz’ ’cfmypvbrlqxwiejdsgkhnazotu’ <ciphertext.txt> plaintext.txt
# plaintext.txt内容如下,解密成功

the oscars turn  on sunday which seems about right after this long strange
awards trip the bagger feels like a nonagenarian too

the awards race was bookended by the demise of harvey weinstein at its outset
and the apparent implosion of his film company at the end and it was shaped by
the emergence of metoo times up blackgown politics armcandy activism and
a national conversation as brief and mad as a fever dream about whether there
ought to be a president winfrey the season didnt just seem extra long it was
extra long because the oscars were moved to the first weekend in march to
avoid conflicting with the closing ceremony of the winter olympics thanks
pyeongchang

one big question surrounding this years academy awards is how or if the
ceremony will address metoo especially after the golden globes which became
a jubilant comingout party for times up the movement spearheaded by 
powerful hollywood women who helped raise millions of dollars to fight sexual
harassment around the country

Task 2 Encryption using Different Ciphers and Modes

2.用AES加密算法(128位密钥,CBC模式)加密一个文件并进行解密。

加密:

image-20221221112322626
# plaintext.txt内容如下
the oscars turn  on sunday which seems about right after this long strange
awards trip the bagger feels like a nonagenarian too

the awards race was bookended by the demise of harvey weinstein at its outset
and the apparent implosion of his film company at the end and it was shaped by
the emergence of metoo times up blackgown politics armcandy activism and
a national conversation as brief and mad as a fever dream about whether there
ought to be a president winfrey the season didnt just seem extra long it was
extra long because the oscars were moved to the first weekend in march to
avoid conflicting with the closing ceremony of the winter olympics thanks
pyeongchang
……

加密后内容如下:

image-20221221112430949

解密:

image-20221221112733094

加密的内容还原了:

image-20221221112753000

Task 3 Encryption Mode – ECB vs. CBC

3.用AES加密算法(128位密钥),分别采用ECB和CBC模式加密一个bmp图片,查看加密后的图片。

image-20221221114831563 image-20221221114816593 image-20221221115207411 image-20221221115310173

Task 4 Padding

  1. Padding:

(1)分别创建大小为5,10,15字节的文件;

image-20221228102102776

(2)先用AES加密算法(128位密钥,CBC模式)加密这些文件,然后解密这些密文(选择解密时不去除padding的选项),观察解密后各个文件的尺寸大小;

加密:

image-20221228102716252

加密后的文件大小:

image-20221228103115417

解密:

image-20221228103434013

解密后大小:

image-20221228103450837

(3)用xxd命令查看各个解密文件中padding的内容;

image-20221228103706286

(4)用AES加密算法(128位密钥,ECB模式,CFB模式,OFB模式)进行类似上述(2)和(3)的操作,查看各个解密文件中padding的内容。

ecb:

加密

image-20221228104056339 image-20221228104121268

解密

image-20221228104322966 image-20221228104309279 image-20221228104450920

cfb:

加密:

image-20221228104714122 image-20221228104732884

解密:

image-20221228104953031 image-20221228105009308 image-20221228105042526

OFB:

加密:

image-20221228105350468 image-20221228105411316

解密:

image-20221228105525025 image-20221228105559042 image-20221228105642035

Task 5 Error Propagation – Corrupted Cipher Text

5.密文的错误传递

(1)创建一个至少1000字节大的文本文件;

image-20221228110327949

(2)用AES加密算法(128位密钥,ECB模式)加密这个文件;

image-20221228110426042

(3)用bless工具修改密文中第55个字节中的1个bit;

原来BD 变成FD

image-20221228111524737

(4)解密被上述修改后的密文,查看解密后的明文有什么变化;

image-20221228112551560

ECB加密方式64bit为一组,其中一个字节出现错误,整组解密均错误

(5)用AES加密算法(128位密钥,CBC模式,OFB模式)进行类似上述(2)-(4)的操作,查看对应解密后的明文有什么变化。

cbc:

image-20221228112945559

原来06 变成07

image-20221228113051682 image-20221228113328084

当前一组64bit均解密错误,并且因为与下一组进行异或,下一组的第7个字节出现错误

OFB:

image-20221228113704499

原来08 变成 09

image-20221228114031729 image-20221228114013810

OFB不存在扩散问题,且因为与流密码异或加密,所以一个字节错误不会影响整组的解密错误,仅第55字节错误

Task 6 Initial Vector (IV) and Common Mistakes

6.1 IV的唯一性

image-20221229132105364

(1)用AES加密算法(128位密钥,CBC模式),采用相同的密钥和不同的初始化向量加密一个相同的文件,观察加密结果是否相同;

image-20221229132413070

答:不相同。IV也是aes加密算法cbc模式的一个重要部分。

(2)用AES加密算法(128位密钥,CBC模式),采用相同的密钥和相同的初始化向量加密一个相同的文件,观察加密结果是否相同;

image-20221229132505795

答:可以发现,在相同key下,使用相同iv将导致加密结果相同,使用iv等于变相增强加密密钥的复杂度。

(3)思考为什么IV必须唯一。

img

CBC的解密是从左往右看,但是IV在解密的时候,只会用于对第一个块进行解密,其他块的解密则是使用上一块的加密二进制作为IV进行解密操作。加密时,用iv和key去加密第一个块,然后用第一个块的加密数据作为下一个块的iv,依次迭代。解密时,用n-1个块的加密数据作为iv和key去解密第n个块(n>1),只有第一个块才会用加密时的iv去解密第一个块。按照这样的逻辑来看,那么如果解密时,用户的iv错误了,出错的应该只有第一个块。通过上面的分析就能知道,加密的时候,iv会影响所有数据的加密结果,而解密时,iv只会影响第一个加密块的解密结果,其他块的解密可以直接通过分隔加密数据获取正确的N-1块的IV。

6.2 已知明文攻击:假设采用OFB模式进行加密,加密时所采用的IV是相同的,请破译P2的内容。

#!/usr/bin/python3

# XOR two bytearrays
def xor(first, second):
  return bytearray(x^y for x,y in zip(first, second))

MSG   = "This is a known message!"
HEX_1 = "a469b1c502c1cab966965e50425438e1bb1b5f9037a4c159"
HEX_2 = "bf73bcd3509299d566c35b5d450337e1bb175f903fafc159"

# Convert ascii string to bytearray
D1 = bytes(MSG, 'utf-8')

# Convert hex string to bytearray
D2 = bytearray.fromhex(HEX_1)
D3 = bytearray.fromhex(HEX_2)

r1 = xor(D1, D2)
r2 = xor(D2, D3)
r3 = xor(D2, D2)
ans = xor(r1, D3)
print(r1.hex())
print(r2.hex())
print(r3.hex())
print(ans.hex())
image-20221229135115588

可以得到P2的十六进制为:4f726465723a204c61756e63682061206d697373696c6521

使用bless工具可破译出如下内容:

image-20221229135412162

6.3 选择密文攻击:请确定密文C1对应的明文内容是“Yes”还是“No”。

对于yes猜测: $$ P_2=IV \oplus IV^{’} \oplus P_x $$ IV为 The IV used IV’为next IV px为Yes的加密形式

求得p2为:

image-20221230091455214 image-20221230091317788

发现加密密文前半段与bob的密文一致,故判断为Yes

#!/usr/bin/python3

# XOR two bytearrays
def xor(first, second):
   return bytearray(x^y for x,y in zip(first, second))

MSG   = "6576e01606ffc1c3598d48305be1bf78"
HEX_1 = "653cc45306ffc1c3598d48305be1bf78"
HEX_2 = "5965730d0d0d0d0d0d0d0d0d0d0d0d0d"      # Yes加密后

D1 = bytearray.fromhex(MSG)
D2 = bytearray.fromhex(HEX_1)
D3 = bytearray.fromhex(HEX_2)

r1 = xor(D1, D2)
ans = xor(r1, D3)
print(ans.hex())

Yes:5965730D0D0D0D0D0D0D0D0D0D0D0D0D

NO: 4E6F0E0E0E0E0E0E0E0E0E0E0E0E0E0E

Task 7 Programming using the Crypto Library

7.基于Openssl的Crypto函数库编写程序破译密文所采用的加密密钥。

image-20221229144223013
#include<iostream>
#include<fstream>
#include <cstring>
#include<openssl/aes.h>
#define MSG "This is a top secret."

using namespace std;

string readFile(string filename){
    ifstream in(filename);
    string line;
    string target = "";
    if(in){
        while(getline(in, line))
            target += line;
    }else
        cout<<"NO SUCH FILE!"<<endl;
    return target;
}

//unsigned char 转 十六进制字符串
void byte_to_hexstr(const unsigned char* source, char* dest, int sourceLen){
    short i;
    unsigned char highByte, lowByte;
    for (i = 0; i < sourceLen; i++){
        highByte = source[i] >> 4;
        lowByte = source[i] & 0x0f ;
 
        highByte += 0x30;
 
        if (highByte > 0x39)
            dest[i * 2] = highByte + 0x07;
        else
            dest[i * 2] = highByte;
 
        lowByte += 0x30;
        if (lowByte > 0x39)
            dest[i * 2 + 1] = lowByte + 0x07;
        else
            dest[i * 2 + 1] = lowByte;
    }
    return ;
}

unsigned char hex_to_int(const char ch){
    if(ch >='a' && ch <='f')
        return ch - 'a' + 10;
    else if(ch >='A' && ch <='F')
        return ch - 'A' + 10;
    else
        return ch - '0';
}

void hex_to_str(char *out_string, int length, const unsigned char *in_string){
    int i, j;
    unsigned char temp='\0';

    for(i = 0, j = 0; i < length; i += 2, j++){
        temp = (hex_to_int(in_string[i]) << 4) + hex_to_int(in_string[i+1]);
        out_string[j] = temp;
    }
}

string BruteForce(string cipher, string iv, string dic){
    char current_dic[17];                       //当前字典密码
    unsigned char out[33];                      //输出结果用于和明文比较
    char target[65];                            //破译密文
    int num = 0;                                //记录读取字典行数
    strcpy(target, cipher.c_str());
    target[64] = '\0';
    AES_KEY  de_key;
    ifstream in(dic);
    string line;

    if(in){                                     //如果文件存在
        while(getline(in, line)){               //只要字典没读完
            num++;                              //读取第一行
            unsigned char plain[33] = MSG;      //初始化破解密文
            //偏移向量初始化
            int i=0;        

            //当前字典明文类型转换并填充‘#’至16字节
            strcpy(current_dic, line.c_str());
            unsigned char * dic = (unsigned char *)current_dic;
            int length = 0;
            for(; length < 16; length++){
                if(dic[length] != '\0')
                    continue;
                else{
                    dic[length] = '#';
                    dic[length+1] = '\0';             
                }
            }
            //通过字典明文生成对应的en_key
            AES_set_decrypt_key(dic, 128, &de_key);
            //解密密文
            //条件密文转ascii
            unsigned char targetcode_[65];
            hex_to_str((char*)targetcode_, 64, (unsigned char*)target);
            unsigned char vivi_[33] = {0xaa ,0xbb ,0xcc ,0xdd ,0xee ,0xff ,0x00 ,0x99 ,0x88 ,0x77 ,0x66 ,0x55 ,0x44 ,0x33 ,0x22 ,0x11};
            //解密密文
            AES_cbc_encrypt(targetcode_, out, 32, &de_key,vivi_, AES_DECRYPT);
            out[21] = '\0';
            plain[21] = '\0';
            

            if(strcmp((char*)out, (char*)plain) == 0){
                cout<<"success "<<"密钥为:"<<line<<endl;
                break;
            }  
        }
    }else
        cout<<"NO SUCH FILE!"<<endl;
    cout<<"读取行数:"<<num<<endl;
    return line;
}

int main(){
    //密文文件
    string cipherPath = "cipher.txt";
    string cipher = readFile(cipherPath);
    //向量文件
    string IVPath = "iv.txt";
    string IV = readFile(IVPath);
    
    string dic = "words.txt";
    //加密爆破  
    BruteForce(cipher, IV, dic);
    return 0;
}
Outis Yang
Outis Yang
2024 Undergraduate in Cyberspace Security

My research interests include Internet of Vehicles(IoV), Penetration Testing and Security research.