『壹』 C++ ASCII 加密
#include <stdio.h>
#include <string.h>
// 將十進制數decimal轉換為k進制數,並以字元串形式存放在字元數組s中
char *CountRule(int decimal,int k,char *s) {
int ch,i,n;
for(n = 0; decimal > 0; ++n) {
s[n] = decimal%k + '0';
decimal /= k;
}
s[n] = '\0';
for(i = 0; i < n/2; ++i) {
ch = s[i];
s[i] = s[n - i - 1];
s[n - i - 1] = ch;
}
return s;
}
// 將k進制串轉換為十進制數,並以整數返回
unsigned Transform(char s[], int k) {
int n = 1,j,len;
unsigned num = 0;
len = strlen(s);
for(j = len - 1;j >= 0; j--) {
num += n*(s[j] - '0');
n *= k;
}
return num;
}
unsigned char *Encrypt(unsigned char *plaintext,char *key,unsigned char *cryptogram) {
int i,j,klen,blen;
char ch,binarystr[9];
unsigned char *p = plaintext;
unsigned char *c = cryptogram;
klen = strlen(key);
for(i = 0; p[i]; ++i) {
c[i] = p[i] - (key[i%klen] - '0'); // 初步加密
CountRule(c[i],2,binarystr); // 將數值s[i]轉換為二進制串
blen = strlen(binarystr);
if(blen < 8) {
for(j = blen; j >= 0; --j) // 如果binarystr不夠8位,空位留前面
binarystr[j + 8 - blen] = binarystr[j];
for(j = 0; j < 8 - blen; ++j) // 然後在前面填入'0'
binarystr[j] = '0';
}
for(j = 0; j < 8; j += 2) { // 實施核心加密過程:交換相鄰奇偶位
ch = binarystr[j];
binarystr[j] = binarystr[j + 1];
binarystr[j + 1] = ch;
}
c[i] = Transform(binarystr,2); // 再把串轉回到整數
}
c[i] = '\0';
return (unsigned char *)c;
}
unsigned char *Decrypt(unsigned char *cryptogram,char *key,unsigned char *plaintext) {
int i,j,klen,blen;
char ch,binarystr[9];
unsigned char *c = cryptogram;
unsigned char *p = plaintext;
klen = strlen(key);
for(i = 0; c[i]; ++i) { // 核心解密
CountRule(c[i],2,binarystr); // 將數值s[i]轉換為二進制串
blen = strlen(binarystr);
if(blen < 8) {
for(j = blen; j >= 0; --j) // 如果binarystr不夠8位,空位留前面
binarystr[j + 8 - blen] = binarystr[j];
for(j = 0; j < 8 - blen; ++j) // 然後在前面填入'0'
binarystr[j] = '0';
}
for(j = 0; j < 8; j += 2) { // 實施核心解密過程:交換相鄰奇偶位
ch = binarystr[j];
binarystr[j] = binarystr[j + 1];
binarystr[j + 1] = ch;
}
p[i] = Transform(binarystr,2); // 再把串轉回為整數
p[i] += (key[i%klen] - '0'); // 再進行初解密
}
p[i] = '\0';
return (unsigned char *)p;
}
int main() {
unsigned char plaintext[] = "東海縣文廣體局";
unsigned char secret[80],pt[80];
char key[] = "1B01";
printf("明文 : %s\n",plaintext);
Encrypt(plaintext,key,secret);
printf("密文 : %s\n",secret);
Decrypt(secret,key,pt);
printf("明文 : %s\n",pt);
return 0;
}