序列加密

来源:互联网 发布:无绳跳绳 知乎 编辑:程序博客网 时间:2024/05/19 12:36

现在字符序列 char buf[] = hello everyone;

按行读的话,肯定可以读出数据,如果按列来读话,则会出再乱码的现像。正是这种现

像可作为一种加密手段,称为序列加密。

#include <stdio.h>#include <string.h>#include <stdlib.h>char *encode(char *str, int column);//加密函数char **get2DMem(int row, int column);//获得二维空间char *decode(char* str, int column);//解密函数int main(void){    char *str="hello world!!";    int column=5;    char *secret=encode(str,column);    printf("encode=%s\n",secret);    str=decode(secret,column);    printf("decode=%s\n",str);    return 0;}//加密函数char *encode(char *str, int column){    int len=strlen(str);//原始长度    int secretLen=0;//由于是二维序列加密,是吧一个字符串按行存储到一个二维空间中,    if(len%column!=0)//后按列读取就是密文,如果最后一行字符串填不满,则自己拿什么字符补齐        secretLen=len+(column-len%column);//计算经过处理后的字符串长度    else        secretLen=len;    char *temp=(char *)calloc(secretLen+1, sizeof(char));    strcpy(temp,str);    int i=0;    for(i=len;i<secretLen;i++)//将原本字符串长度和新长度之间的本程序用*填充    {        temp[i]='*';     }    temp[i]='\0';    //到此处已经得到补全长度的字符串,为temp,    //接下来处理这个可以填充到二维空间的字符串,填入二维空间    //申请并返回二维空间    char *ttemp=temp;//用ttemp记录下temp的开头    int row=secretLen/column;//计算得到二维空间的行数    char **secret=get2DMem(row, column);    int j=0;    for(i=0;i<row;i++)      //将补全后的字符串按行存储到二维空间中        for(j=0;j<column;j++)        {            secret[i][j]=*(temp++);        }    //到此处已经将字符串按照行序存储到二维空间中了    //下面将二维空间中的内容按照列序读入到目标字符串中    char *result=(char *)calloc(secretLen+1, sizeof(char));    char *tresult=result;//用tresult记录结果字符串的开头    for(i=0;i<column;i++){        for(j=0;j<row;j++)        {            *result=secret[j][i];            result++;        }    }    *result=0;    //加密完成    return tresult;}//解密程序char *decode(char* str, int column){    int secretLen=strlen(str);    int row=secretLen/column;    char **secret=get2DMem(row,column);//申请同样行列数的二维空间    int i=0,j=0;    for(i=0;i<column;i++)//将字符串按列存储顺序存储到二维空间中        for(j=0;j<row;j++)        {            secret[j][i]=*str++;        }    char *tresult=(char *)calloc(secretLen+1,sizeof(char));    char *result=tresult;    for(i=0;i<row;i++)//将二维空间中的字符按行读取出来就是        for(j=0;j<column;j++)        {            //printf("%c",secret[i][j]);            *tresult++=secret[i][j];        }    *tresult=0;    while(*(--tresult)=='*')        ;    tresult++;    *tresult=0;//    printf("decode=%s\n",result);    return result;}//申请二维空间函数char **get2DMem(int row, int column){    char **p=(char **)calloc(row,sizeof(char *));    int i=0;    for(i=0;i<row;i++)    {        p[i]=(char *)calloc(column, sizeof(char));    }    return p;}


0 0
原创粉丝点击