2012-10-06 4 views
2

전체 알파벳을 암호화하고 사용자가 제출 한 구문을 암호화 한 다음 다시 원래 구문으로 해독하는 난수를 사용하는 기본적인 암호화 프로그램을 만들려고합니다. 그러나 매우 어렵습니다. 누구든지 내 실수를 지적하는 데 도움이 될 수 있습니다! 같은 문자에 두 글자를 코딩해서는 안됩니다. 즉, a와 b는 둘 다 c와 일치해서는 안됩니다.자바 기본 암호화 프로그램

public class MainClass { 
public static final int ALPHASIZE = 26; 
public static final char[] Lalpha = 
    { 'a','b','c','d','e','f','g','h','i','j','k','l', 
    'm','n','o','p','q','r','s','t','u','v','w','x','y','z' 
    }; 
public static final char[] Ualpha = 
    {'A','B','C','D','E','F','G','H','I','J','K','L', 
    'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', 
    }; 
protected static char[] encryptU = new char[ALPHASIZE]; 
protected static int[] decrypt = new int[ALPHASIZE]; 
protected static char[] encryptL = new char[ALPHASIZE]; 



Random rgenerator = new Random(); 

public MainClass(){ 
    int randNum = rgenerator.nextInt(ALPHASIZE); 


    for(int i=0; i<ALPHASIZE ; i++) 
    { 
     //makes sure that it won't assign a letter to itself or to one that has already been assigned 

     do { 
      randNum = rgenerator.nextInt(26); 

     } while (randNum%26==0 &&Arrays.asList(encryptU).contains(Ualpha[randNum]));  

     encryptU[i] = Ualpha[randNum]; 
     encryptL[i] = Lalpha[randNum]; 
     decrypt[i] = randNum; 

    } 
} 

public String encrypt(String secret) 
{ 
    System.out.println(Arrays.toString(encryptU)); 
     int position = 0; 
    char[] mess = secret.toCharArray(); 
    for(int i = 0 ; i<mess.length;i++) 
    { 
     if(Character.isUpperCase(mess[i])) 
     { 
    for(int j = 0; j < encryptU.length; j++) { 
     if(mess[i]==Ualpha[j]) { 
      position = j; 
    } 
    mess[i] = encryptU[position]; 

     } 

     } 

     if(Character.isLowerCase(mess[i])) 
     { 
    for(int j = 0; j < encryptU.length; j++) { 
     if(mess[i]==Lalpha[j]) { 
      position = j; 
    } 
    mess[i] = encryptL[position]; 

     } 

     } 

    } 
    return new String(mess); 
} 

public String decrypt(String secret) 
{ 
    char[] mess = secret.toCharArray(); 
    for(int i = 0 ; i<mess.length;i++) 
    { 
     if(Character.isUpperCase(mess[i])) 
       { 
       for(int j = 0; j<ALPHASIZE; j++){ 
        if(mess[i]==encryptU[j]){ 
         mess[i] = Ualpha[j]; 

         } 
        } 
       }   

     if(Character.isLowerCase(mess[i])) 
     {     
      for(int j = 0; j<ALPHASIZE; j++){ 
       if(mess[i]==encryptL[j]){ 
        mess[i] = Lalpha[j]; 

        } 
       } 
      } 
    } 

    return new String(mess); 
} 
} 
+0

많은 코드가 있습니다. 특정 문제가있는 작은 청크를 게시하면 더 나은 응답을 얻을 수 있습니다. 그것은 컴파일합니까? 같은 글자에 실제로 두 글자를 코딩하고 있습니까? –

+0

@ John 원래 질문을 다시 올릴 수 있습니까? 그것을 삭제하면 협업 포럼의 목적을 상실합니다. 오, 최선의 대답을 받아들이는 것을 잊지 마라! – arshajii

답변

2

문자/인코딩 쌍을 저장하려면 Map을 사용하는 것이 좋습니다. 아, 그리고 이러한 임의의 쌍을 만들려면 List에 문자를 추가하고 직접 휠을 다시 발명하는 대신 Collections.shuffle을 사용할 수 있습니다.


Lalpha (소문자 만 사용)을 설명하겠습니다. 당신은이 라인을 따라 뭔가 싶어 :

List<Character> l = new ArrayList<Character>(Lalpha.length); 

for (char c : Lalpha) 
    l.add(c); 

Collections.shuffle(l); 

Map<Character, Character> encoding = new HashMap<Character, Character>(Lalpha.length); 
Map<Character, Character> decoding = new HashMap<Character, Character>(Lalpha.length); 

for (int i = 0 ; i < Lalpha.length ; i++) { 
    encoding.put(Lalpha[i], l.get(i)); 
    decoding.put(l.get(i), Lalpha[i]); 
} 

이제 우리는/인코딩 문자열 helloworld을 디코딩하고 싶었 말할 수를, 우리는이 작업을 수행 할 것입니다 :

String s = "helloworld";  

// Encode: 
String enc = ""; 
for (char c : s.toCharArray()) 
    enc += encoding.get(c); 

System.out.println(enc); 

// Decode: 
String dec = ""; 
for (char c : enc.toCharArray()) 
    dec += decoding.get(c); 

System.out.println(dec); 

출력 (여러 가지 중 하나) :

vjwwmtmcwz
helloworld를

물론 같은 생각을 사용하여 대문자와 허구를 통합 할 수 있습니다.

+0

하하 ... 동의합니다 ... –

1

허용되는 문자의 순열을 생성해야하는 것처럼 들립니다.

public char[] permutation = 
{ 'a','b','c','d','e','f','g','h','i','j','k','l', 
'm','n','o','p','q','r','s','t','u','v','w','x','y','z' 
}; 


public generatePermutation() 
{ 
    Random r = new Random(); 
    char tmp; 
    int rand; 

    for(int i = 0; i < permutation.length; ++i) 
    { 
     rand = r.nextInt(permutation.length - i); 
     tmp = permutation[i]; 
     permutation[i] = permutation[rand]; 
     permutation[rand] = tmp; 
    } 
} 

마지막으로, 당신이 (당신이 이미 inputChar가 소문자인지 확인했습니다 가정) permutation[inputChar-'a']를 수행하여 암호화를 위해이 배열에 액세스 할 수 있습니다 : 이것은 내가 소문자을 위해 그것을 할 것입니다 방법이다. 그리고 암호 해독을 위해 입력 한 문자와 일치하는 문자를 찾고 색인에 'a'를 추가하십시오. 당신이 당신의 문자 세트와 "암호화"세트 사이의 임의의 매핑을 만드는 데 문제가있는 경우

0

,이 시작할 수 :

List<Character> alphabet = new LinkedList<Character>(
     new String[] {'a', 'b', ..., 'Y', 'Z'}); 

List<Character> shuffledAlphabet = new LinkedList<Character>(alphabet); 
Collections.shuffle(shuffledAlphabet); 

Map<Character, Character> encryptionMap = new HashMap<Character, Character>(); 
Map<Character, Character> decryptionMap = new HashMap<Character, Character>(); 
for (int i=0; i < alphabet.size(); i++) { 
    encryptionMap.put(alphabet.get(i), shuffledAlphabet.get(i)); 
    decryptionMap.put(shuffledAlphabet.get(i), alphabet.get(i)); 
} 

을 이제 암호화 입력 된 문자열에 대한 각 문자를 복용하여 encryptionMap을 사용하고 그 결과로 대체하십시오. 해독하려면 해독 맵에서 동일한 작업을 수행하십시오.