简单移位加解密算法(斯巴达手杖)Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class SHIFTKeyGen {
static char[] SHIFT_Encrypt(char[] plaintext,int key){
int len,d,i,j,m;
char[] temp,ciphertext;
len=plaintext.length;
if((d=len%key)!=0){
len = len + key-d;
}
temp = new char[len];
m=len/key;
for(i=0;i<m;i++){
for(j=0;j<key;j++){
if(i*key+j<plaintext.length){
temp[i+m*j]=plaintext[i*key+j];
}else{
temp[i+m*j]=' ';
}
}
}
while(temp[len-1]==' '){
len--;
}
ciphertext = new char[len];
for(i=0;i<len;i++){
ciphertext[i]=temp[i];
}
return ciphertext;
}
static char[] SHIFT_Decrypt(char[] ciphertext,int key){
int len,d,i,j,m;
char[] temp,plaintext;
len=ciphertext.length;
if((d=len%key)!=0){
len = len + key-d;
}
temp = new char[len];
m=len/key;
for(i=0;i<key;i++){
for(j=0;j<m;j++){
if(i*m+j<ciphertext.length){
temp[i+j*key]=ciphertext[i*m+j];
}else{
temp[i+key*j]=' ';
}
}
}
while(temp[len-1]==' '){
len--;
}
plaintext = new char[len];
for(i=0;i<len;i++){
plaintext[i]=temp[i];
}
return plaintext;
}
public static void main(String[] args) throws IOException{
char[] plaintext,ciphertext,jiemi;
int key,i;
String go;
Scanner input = new Scanner(System.in);
do{
System.out.print("请输入指定的二维数组的列数:");
key= input.nextInt();
System.out.print("请输入明文:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String strtemp=br.readLine();
plaintext=strtemp.toCharArray();
System.out.print("明文为:");
for(i=0;i<plaintext.length;i++){
System.out.print(plaintext[i]);
}
System.out.println();
ciphertext=SHIFT_Encrypt(plaintext,key);
System.out.print("密文为:");
for(i=0;i<ciphertext.length;i++){
System.out.print(ciphertext[i]);
}
System.out.println();
jiemi=SHIFT_Decrypt(ciphertext,key);
System.out.print("解密为:");
for(i=0;i<jiemi.length;i++){
System.out.print(jiemi[i]);
}
System.out.println();
System.out.print("是否继续(y/n):");
go = input.next();
}
while(go.equalsIgnoreCase("y"));
System.out.println("退出程序!");
}
}