substitution.java
41 linesjava
DOWNLOAD
1// Aim: Program to perform Substitution cipher (Substitution Cipher).
2public class substitution{
3    private static String alfa = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
4    public static String encrypt(String text ,String key){
5        text = text.toUpperCase();
6        StringBuilder ct = new StringBuilder();
7        for(char c : text.toCharArray()){
8            int idx = alfa.indexOf(c);
9            if(idx!=-1){
10                ct.append(key.charAt(idx));
11            }
12            else{
13                    ct.append(c);
14            }
15        }
16        return ct.toString();
17    }
18    public static String decrypt(String ct ,String key){
19        ct.toUpperCase();
20        StringBuilder pt = new StringBuilder();
21        for(char c : ct.toCharArray()){
22            int idx = key.indexOf(c);
23            if(idx!=-1){
24                pt.append(alfa.charAt(idx));
25            }
26            else{
27                    pt.append(c);
28            }
29        }
30        return pt.toString();
31    }
32    public static void main(String[] args) {
33        String key = "QWERTYUIOPASDFGHJKLZXCVBNM";
34        String text = "PRIVATE";
35        String monoencrypted = encrypt(text, key);
36        String monodecrypted = decrypt(monoencrypted, key);
37        System.out.println("Encrypted: " + monoencrypted);
38        System.out.println("Decrypted: " + monodecrypted);
39
40    }
41}