基于C语言的UTF-8中英文替换密码设计

简要说明

本设计为湖南大学密码学的一次课程作业设计。非作业目的可随意引用。

由于本人初次接触密码学,本设计可能存在问题以及漏洞。若发现望指出。

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: 
  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值