2013-12-20 3 views
0

나는이 자바 코드를 가지고있다. 주어진 텍스트 마녀 만 암호화되어있다. 나는이 코드를 편집하여 사용자에게 물어볼 수있는 방법을 알려준다. 텍스트를 입력 한 다음 텍스트의 암호화를 수행하고 최종 결과를 표시 하시겠습니까? 나는 텍스트를 대체하려고 시도했다 ("NagaSakti"); 및 ("bismillah");(System.in); 함께하지만 작동하지 않았다! 나를자바 코드의 암호화 텍스트 입력을 묻는 방법

import java.io.UnsupportedEncodingException; 
import java.security.spec.AlgorithmParameterSpec; 
import java.security.spec.KeySpec; 
import javax.crypto.Cipher; 
import javax.crypto.IllegalBlockSizeException; 
import javax.crypto.SecretKey; 
import javax.crypto.SecretKeyFactory; 
import javax.crypto.spec.PBEKeySpec; 
import javax.crypto.spec.PBEParameterSpec; 



public class DesEncrypter { 
    Cipher ecipher; 


    // 8-byte Salt 
    byte[] salt = { 
     (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32, 
     (byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03 
    }; 

    // Iteration count 
    int iterationCount = 19; 
    public static final DesEncrypter NAGASAKTI = new DesEncrypter("NagaSakti"); 

    private DesEncrypter(String passPhrase) { 
     try { 
      // Create the key 
      KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount); 
      SecretKey key = SecretKeyFactory.getInstance(
       "PBEWithMD5AndDES").generateSecret(keySpec); 
      ecipher = Cipher.getInstance(key.getAlgorithm()); 


      // Prepare the parameter to the ciphers 
      AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount); 

      // Create the ciphers 
      ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); 

     } catch (java.security.InvalidAlgorithmParameterException e) { 
     } catch (java.security.spec.InvalidKeySpecException e) { 
     } catch (javax.crypto.NoSuchPaddingException e) { 
     } catch (java.security.NoSuchAlgorithmException e) { 
     } catch (java.security.InvalidKeyException e) { 
     } 
    } 

    public String encrypt(String str) { 
     try { 
      // Encode the string into bytes using utf-8 
      byte[] utf8 = str.getBytes("UTF8"); 

      // Encrypt 
      byte[] enc = ecipher.doFinal(utf8); 

      // Encode bytes to base64 to get a string 
      return new sun.misc.BASE64Encoder().encode(enc); 
     } catch (javax.crypto.BadPaddingException e) { 
     } catch (IllegalBlockSizeException e) { 
     } catch (UnsupportedEncodingException e) { 
     } 
     return null; 
    } 



    public static void main(String args[]){ 
     String encrypted = DesEncrypter.NAGASAKTI.encrypt("bismillah"); 
     System.out.println("Enter your text"); 


     System.out.println("encrypted text= "+ encrypted); 

    } 
} 

답변

-1

당신은 스캐너 클래스를 사용할 수 있습니다. 이 수입 추가 : main 메소드에 다음

import java.util.Scanner; 

을 이렇게 :

public static void main(String args[]){ 
    Scanner keyboard = new Scanner(System.in); 
    System.out.println("Enter your text"); 
    String textToEncrypt = keyboard.next(); 

    String encrypted = DesEncrypter.NAGASAKTI.encrypt(textToEncrypt); 

    System.out.println("encrypted text= "+ encrypted); 
} 

당신이 다음 문자열로 시작하는 줄을 변경 NagaSakti 이외의 다른 암호를 사용하려면 암호화 ...

System.out.println("Enter your pass phrase"); 
String passPhrase = keyboard.next(); 
String encrypted = new DesEncrypter(passPhrase).encrypt(textToEncrypt); 

참고 : 이렇게하려면 DesEncrypter 생성자를 public으로 변경해야합니다.

+0

고맙습니다. !!!! 마침내 그 일! – user3124061

0

이런 식으로 뭔가를 시도 도와주세요 :

// open up standard input 
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 

    String textFromUser = null; 

    // read the text from the command-line; need to use try/catch with the 
    // readLine() method 
    try { 
    textFromUser = br.readLine(); 
    } catch (IOException ioe) { 
    System.out.println("IO error trying to read your text!"); 
    } 
1

암호 읽기에는 Console을 사용하십시오. 귀하의 main 방법은 다음과 같을 수 있습니다 :

public static void main(String args[]) 
{ 
    Console console = System.console(); 
    if (console == null) 
    throw new IllegalStateException("console required"); 
    char[] password = console.readPassword("Enter your text: "); 
    DesEncrypter encrypter = new DesEncrypter(new String(password)); 
    String encrypted = encrypter.encrypt("bismillah"); 
    System.out.println("encrypted text = " + encrypted); 
} 

Console 클래스의 전문적인 API는 몇 가지 장점을 가지고 사용.

먼저 암호를 화면에 표시하지 않습니다. 이것은 숄더 서핑 도적으로부터 보호하는 데 도움이됩니다.

또한 암호는 문자 배열로 반환되므로 응용 프로그램은 암호 사용이 완료되면 배열에 0 또는 임의 문자를 채울 수 있습니다. 이렇게하면 페이징으로 인해 디스크에 기록되거나 힙 덤프 등에 포함될 가능성이 최소화됩니다.

마지막으로 정확한 고수준 API를 사용하면 코드가 무엇을하고 있는지 명확하게 알 수 있습니다. 향후 개선 될 기능 및 응용 프로그램을 단순화합니다.

사용되는 암호화에는 여러 가지 다른 문제가 있으며, 코드를 그대로 사용하는 것은 권장하지 않지만 제기 된 질문에 집중했습니다.

관련 문제