简要说明
本设计为湖南大学密码学的一次课程作业设计。非作业目的可随意引用。
由于本人初次接触密码学,本设计可能存在问题以及漏洞。若发现望指出。
GitHub : https://github.com/He11oLiu/SubstitutionCipher
中文utf-8
简单偏移替换密码
初次尝试
中文utf-8的读取
utf-8
的格式
UTF-8编码规则:如果只有一个字节则其最高二进制位为0;如果是多字节,其第一个字节从最高位开始,连续的二进制位值为1的个数决定了其编码的位数,其余各字节均以10开头。
获取单个utf-8
编码的长度,注意当最高位为0
情况。
int get_utf_8_len(char s){
int i = 0x80,len = 0;
while(s&i) {i=i>>1;len++;}
return len==0?1:len;
}
从byte
数组中获取单个utf-8
字符
word_length = get_utf_8_len(word_byte[i]);
strncpy(word_utf_8,word_byte+i,word_length);
从3字节utf-8
字符中获取utf-8
编号
int get_utf_8_code(char *s){
return (*s & 0x0F)<<12 | (*(s+1)&0x3F)<<6 |(*(s+2)&0x3F);
}
获取中文字符
常用中文显示范围
U+4e00 - U+9fa5
故利用utf_8_is_cn
来判断
#define max_cn_utf_8 0x9fa5
#define min_cn_utf_8 0x4e00
#define cn_utf_8_size (max_cn_utf_8-min_cn_utf_8)
#define utf_8_is_cn(code) (code>=min_cn_utf_8 && code <max_cn_utf_8)
偏移加密测试
/**
* Caesar_cipher_encrpt
* 简单凯撒加密测试,bias为偏移量
* 常用中文大小为cn_utf_8_size
*/
void Caesar_cipher_encrpt(int_32U *plain_code,int_32U *cipher_code,int_32U bias){
*cipher_code = ((*plain_code-min_cn_utf_8)+bias)%cn_utf_8_size + min_cn_utf_8;
}
/**
* Caesar_cipher_decrpt
* 简单凯撒解密测试,bias为偏移量
* 常用中文大小为cn_utf_8_size
*/
void Caesar_cipher_decrpt(int_32U *cipher_code,int_32U *plain_code,int_32U bias){
*plain_code = ((*cipher_code+cn_utf_8_size-min_cn_utf_8)-bias)%cn_utf_8_size + min_cn_utf_8;
}
主函数中测试:
if(utf_8_is_cn(utf_8_code)){
Caesar_cipher_encrpt(&utf_8_code,&cipher_code,100);
get_utf_8_word(cipher_code, word_utf_8);
printf("Encrpted: %s ",word_utf_8);
Caesar_cipher_decrpt(&cipher_code,&utf_8_code,100);
get_utf_8_word(utf_8_code, word_utf_8);
printf("Decrpted: %s\n",word_utf_8);
}
测试结果
Encrpted: