替代密码 && 置换密码

1 .替代密码

加密:

public class Caesar {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int k = 25;
//        System.out.println("输入要加密的字符串:");
        String s = in.nextLine() ;
        int len = s.length();
        System.out.println("解密后为");
        for(int i=0;i<len;i++){
            int flag = s.charAt(i) - 'a';
            if(flag>=0&&flag<=25) {
                flag = (flag+k)%26;
                char temp = (char)(flag+'a');
                
                System.out.print(temp);
            }
        }
    }
}

解密:

import java.util.Scanner;

public class Caesar {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int k = 25;
//        System.out.println("输入要加密的字符串:");
        String s = in.nextLine() ;
        int len = s.length();
        System.out.println("解密后为");
        for(int i=0;i<len;i++){
            int flag = s.charAt(i) - 'a';
            if(flag>=0&&flag<=25) {
                flag = (flag-k+26)%26;
                char temp = (char)(flag+'a');
                
                System.out.print(temp);
            }
        }
    }
}

2、置换密码

ps:

在以下代码片中注意几点
1、需要加密或解密的字符串长度必须为密钥中有效字母长度的整数倍
2、只能存在小写字母
3、若在输出矩阵中(两个for的那个),数组为arr则为加密,若为arr1则为解密

code

public class zhihuan {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in = new Scanner(System.in);
        String ming = "luozihanforestforestabca";
        String key = "huanghailong";
        HashMap<Integer,Integer>mp = new HashMap<Integer,Integer>();
        HashMap<Integer,Integer>mp2 = new HashMap<Integer,Integer>();
        int cnt = 0 ;// 统计有多少个不重复的
        for(int i=0;i<key.length();i++) {
            int t = key.charAt(i)-'a';
            if(mp.get(t) == null) {
                cnt ++;
                mp.put(t,1);
            }
        }
        mp.clear();int[] arr = new int[cnt];int[] arr1 = new int[cnt];
        cnt = 0 ;
        for(int i=0;i<key.length();i++) {
            int t = key.charAt(i)-'a';
            if(mp.get(t) == null) {
                arr[cnt] = t;
                mp2.put(cnt,t);
                mp.put(t,1);
                cnt++;
            }
        }
        mp.clear();
        Arrays.sort(arr);
        for(int i=0;i<arr.length;i++) {    
            mp.put(arr[i], i);
        }
        
        for(int i=0;i<arr.length;i++) {
            arr[i] = mp.get(mp2.get(i));
//            System.out.print(arr[i] + " ");
            arr1[arr[i]] = i;
        }
        int m = arr.length;int n = ming.length()/m;
//        System.out.println(n);
        for(int i=0;i<n;i++) {
            for(int j=0;j<m;j++) {
                int pos = i*m+arr1[j];
//                int pos = i*m+j;
                System.out.print(ming.charAt(pos));
            }
        }
    }

}

 

posted @ 2021-03-31 19:41  mcalex  阅读(560)  评论(0编辑  收藏  举报