用C语言翻译如下代码:def LISR(l): k=l[0]^l[1]^l[2]^l[3]^l[4]^l[5]^l[6]^l[7] l[0]=l[1] l[1]=l[2] l[2]=l[3] l[3]=l[4] l[4]=l[5] l[5]=l[6] l[6]=l[7] l[7]=k return l; def strEncrypt(s1,s2,key):#每次传输8个字符,分成两组按位异或,密钥4个字符 result='' for i in range(0,8): temp=ord(s1[i])^ord(s2[i])^ord(key[i]) result+=chr(temp) #print(result) #print(result) return result def encode(plainText,keylist): cipherText='' for i in range(0,len(plainText)//16): temp=plainText[i*16:(i+1)*16]#每16个字符划分成一组加密 #print(temp) L=temp[:8] #print(L) R=temp[8:] #print(R) for currentKey in keylist: temp2=R R=strEncrypt(L,R,currentKey) #print(R) L=temp2 cipherText+=R+L return cipherText if __name__ == '__main__': key=[] a=input('请输入要加密的字符串,目前算法能处理的明文字符为16的整数倍') keynum=input('请输入加密循环次数') temp=[1,0,1,1,0,1,0,1] #print(''.join('%s' %id for id in temp)) for i in range(0,int(keynum)): temp=LISR(temp) print('第'+str(i)+'组加密时使用的密钥(4个字符)',''.join('%s' %id for id in temp)) key.append("".join('%s' %id for id in temp)) print('要加密的明文为:',a) #print(key) a=encode(a,key) print('密文:',a) #####解密 key.reverse() a=encode(a,key) print('解密后的明文:',a)
时间: 2024-04-26 18:20:51 浏览: 170
C语言(加密)
#include <stdio.h>
#include <string.h>
int* LISR(int* l) {
int k = l[0] ^ l[1] ^ l[2] ^ l[3] ^ l[4] ^ l[5] ^ l[6] ^ l[7];
l[0] = l[1];
l[1] = l[2];
l[2] = l[3];
l[3] = l[4];
l[4] = l[5];
l[5] = l[6];
l[6] = l[7];
l[7] = k;
return l;
}
char* strEncrypt(char* s1, char* s2, char* key) {
char* result = "";
for (int i=0; i<8; i++) {
int temp = s1[i] ^ s2[i] ^ key[i];
result[i] = temp;
}
return result;
}
char* encode(char* plainText, char keylist[][4], int keynum) {
char* cipherText = "";
for (int i=0; i<strlen(plainText)/16; i++) {
char* temp = "";
strncpy(temp, plainText+i*16, 16);
char* L = "";
strncpy(L, temp, 8);
char* R = "";
strncpy(R, temp+8, 8);
for (int j=0; j<keynum; j++) {
char* temp2 = "";
strncpy(temp2, R, 8);
R = strEncrypt(L, R, keylist[j]);
L = temp2;
}
strncat(cipherText, R, 8);
strncat(cipherText, L, 8);
}
return cipherText;
}
int main() {
char keylist[100][4];
char a[100];
printf("请输入要加密的字符串,目前算法能处理的明文字符为16的整数倍:");
scanf("%s", a);
int keynum;
printf("请输入加密循环次数:");
scanf("%d", &keynum);
int temp[] = {1, 0, 1, 1, 0, 1, 0, 1};
for (int i=0; i<keynum; i++) {
LISR(temp);
printf("第%d组加密时使用的密钥(4个字符):%d %d %d %d\n", i, temp[0], temp[1], temp[2], temp[3]);
sprintf(keylist[i], "%d%d%d%d", temp[0], temp[1], temp[2], temp[3]);
}
printf("要加密的明文为:%s\n", a);
char* cipherText = encode(a, keylist, keynum);
printf("密文:%s\n", cipherText);
char keylist2[100][4];
memcpy(keylist2, keylist, sizeof(keylist));
for (int i=0; i<keynum; i++) {
memcpy(keylist[i], keylist2[keynum-i-1], sizeof(keylist2[keynum-i-1]));
}
char* plainText = encode(cipherText, keylist, keynum);
printf("解密后的明文:%s\n", plainText);
return 0;
}
阅读全文