换位密码 java_换位加密、解密算法

本文介绍了换位密码算法,一种简单的加密技术,通过二维数组移位实现加密和解密。提供了详细的Java代码示例,展示了如何基于给定的二维数组列数进行明文到密文的转换,并能正确解密回原始信息。
摘要由CSDN通过智能技术生成

换位密码算法方案,又称为置换加密方案,其根据一定的规则重新安排明文字母,使之成为密文。换位密码是最简单的密码学算法。

1. 换位加密、解密算法

换位加密解密的算法有很多种,这里介绍基于二维数组移位的换位加密、解密算法。二维数组移位的换位加密、解密算法即将明文字符串按照一个给定的顺序保存在二维数组中,然后按照另外一个顺序读出,便的到密文。执行相反的过程便可以恢复出明文。

1)换位加密算法

基于二维数组移位的加密算法的操作步骤如下:

(1)给定一个二维数组的列数,即该二维数组每行可以保存的字符个数。

(2)将明文字符串按行依次排列到该二维数组中。

(3)按列读出该二维数组中的字符,这样便得到密文。

可以根据此思路来编写相应的加密算法,代码示例如下:

/*** 加密算法

*@paramstr 明文

*@paramn 指定的二维数组的列数

*@return

*/

static char[] jiami(char[] str,intn){intlen,d,i,j,m;char[] temp,miwen;

len=str.length;if((d=len%n)!=0){

len= len + n-d;

}

temp= new char[len];

m=len/n;for(i=0;i

temp[i+m*j]=str[i*n+j];

}else{

temp[i+m*j]=' ';

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
c语言编写,欢迎扔板砖 //移位算法 #include #include #define SIZE 50 int main() { //i 用于计数输入个数,j 为临时变量, plain 存放明文, cipher 存放密文,decryption存放解密后文本,fpp 为明文文件指针,fpc 为密文文件指针 int i,j; char plain[SIZE],cipher[SIZE],decryption[SIZE],ciphertext[SIZE]; FILE * fpp,* fpc,* fpd; //加密 //建立新的明文TXT文件 printf("Caesar algorithm\n"); if((fpp=fopen("plain.txt","w+"))==NULL) { printf("creat new plain file error!\n"); exit(0); } //输入明文 printf("input plain alphabet:\n"); i=0; scanf("%c",&plain[i]); while(plain[i]!='\n'&&i<SIZE) { i++; scanf("%c",&plain[i]); } printf("success input %d characters\n",i); //将明文转存到文件中 for(j=0;j<i;j++) { if(fwrite(&plain[j],sizeof(char),1,fpp)!=1) { printf("saving plain file error!\n"); exit(0); } } printf("success saving plain text!\n"); //加密 for(j=0;j<i;j++) { cipher[j]=plain[j]+3; if(cipher[j]99) { printf("cipher %d = %c\n",j,cipher[j]); } else if(cipher[j]>122) { cipher[j]=cipher[j]%122+96; printf("cipher %d = %c\n",j,cipher[j]); } else if(cipher[j]>90) { cipher[j]=cipher[j]%90+64; printf("cipher %d = %c\n",j,cipher[j]); } else { printf("cipher %d = %c\n",j,cipher[j]); } } //建立密文文件 if((fpc=fopen("cipher.txt","w+"))==NULL) { printf("create new cipher file error!"); exit(0); } for(j=0;j<i;j++) { if(fwrite(&cipher[j],sizeof(char),1,fpc)!=1) { printf("saving cipher file error!"); exit(0); } } printf("success saving cipher file!"); printf("\n"); //解密 printf("input ciphertext alphabet:\n"); i=0; scanf("%c",&ciphertext[i]); while(ciphertext[i]!='\n'&&i<SIZE) { i++; scanf("%c",&ciphertext[i]); } for(j=0;j<i;j++) { decryption[j]=ciphertext[j]-3; if(decryption[j]90&&decryption[j]<97) { decryption[j]=123-(97-decryption[j]); printf("character %d = %c\n",j,decryption[j]); } else {
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值