2012-05-23 1 views
0

RSA 암호화 및 문제가 있습니다. 문자열을 암호화하고 싶습니다. 문자열을 변환하려면 이미 변환 할 rsHex 배열이 있습니다. 소스 코드를 실행하지만 "시스템이 지정한 파일을 찾을 수 없습니다"라는 오류 메시지가 나타납니다. 여기에 내 소스 코드가 있습니다. 어떻게 해결할 수 있을까요? 나 : 도와 주셔서 감사RSA 암호화 (java) 문자열 입력을 읽습니다.

import de.flexiprovider.api.keys.PrivateKey; 
import de.flexiprovider.api.keys.PublicKey; 
import java.io.BufferedInputStream; 
import java.io.BufferedOutputStream; 
import java.io.BufferedReader; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.FileReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.ObjectInputStream; 
import java.io.ObjectOutputStream; 
import java.math.BigInteger; 
import java.security.InvalidKeyException; 
import java.security.Key; 
import java.security.KeyFactory; 
import java.security.KeyPair; 
import java.security.KeyPairGenerator; 
import java.security.NoSuchAlgorithmException; 
import java.security.spec.InvalidKeySpecException; 
import java.security.spec.RSAPrivateKeySpec; 
import java.security.spec.RSAPublicKeySpec; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.crypto.BadPaddingException; 
import javax.crypto.Cipher; 
import javax.crypto.IllegalBlockSizeException; 
import javax.crypto.NoSuchPaddingException; 

public class RSA { 

private String str, s; 
private String chipertext; 
private byte[] cipherData; 


public RSA(String string) throws Exception { 

    try { 


     String input = string; 
     FileReader read = new FileReader(input); 
     BufferedReader reader = new BufferedReader(read); 
     while ((s = reader.readLine()) != null) { 
     byte[] theByteArray = s.getBytes(); 
      setUserinput(string); 
      rsHex(theByteArray); 
} 


    } catch (Exception ex) { 
     Logger.getLogger(RSA.class.getName()).log(Level.SEVERE, null, ex); 
    } 

    //Creating an RSA key pair in Java 
      KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); //instance of KeyPairGenerator 
      kpg.initialize(1024);//bit length of the modulus that required 
      KeyPair kp = kpg.genKeyPair();//returns a KeyPair object 
      Key publicKey = kp.getPublic(); //pull out the public and private keys 
      Key privateKey = kp.getPrivate(); 

      //Saving the public and private key 
      //private key will be placed on our server, and the public key distributed to clients. 
      KeyFactory fact = KeyFactory.getInstance("RSA"); 
      RSAPublicKeySpec pub = (RSAPublicKeySpec) fact.getKeySpec(publicKey, RSAPublicKeySpec.class); 
      RSAPrivateKeySpec priv = (RSAPrivateKeySpec) fact.getKeySpec(privateKey, RSAPrivateKeySpec.class); 

      // Save the file to local drive 
      saveToFile("c:\\public.key", pub.getModulus(), pub.getPublicExponent()); 
      saveToFile("c:\\private.key", priv.getModulus(),priv.getPrivateExponent()); 

    } 
private void rsHex(byte[] bytes) throws Exception { 
    StringBuilder hex = new StringBuilder(); 
    for (byte b : bytes) { 
     String hexString = Integer.toHexString(0x00FF & b); 
     hex.append(hexString.length() == 1 ? "0" + hexString : hexString); 
    } 
setChipertext(hex.toString()); 
} 

//save the moduli and exponents to file, we can just use boring old serialisation 
public void saveToFile(String fileName, BigInteger mod, BigInteger exp) throws IOException { 
    FileOutputStream f = new FileOutputStream(fileName); 
    ObjectOutputStream oos = new ObjectOutputStream(f); 
    oos.writeObject(mod); 
    oos.writeObject(exp); 
    oos.close(); 
} 

////Encryption 
//initialise the cipher with the public key that we previously saved to file. 
    PublicKey readKeyFromFile(String keyFileName) throws IOException { 
    PublicKey key = null; 

    try { 
    FileInputStream fin = new FileInputStream(keyFileName); 
    ObjectInputStream ois = new ObjectInputStream(fin); 
    BigInteger m = (BigInteger) ois.readObject(); 
    BigInteger e = (BigInteger) ois.readObject(); 
    RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e); 
    KeyFactory fact = KeyFactory.getInstance("RSA"); 
     java.security.PublicKey pubKey = fact.generatePublic(keySpec); 
    ois.close(); 
    } 
    catch (Exception e) { 
    e.printStackTrace(); 
    } 
return key; 
    } 


public void rsaEncrypt(String str)throws Exception { 

PublicKey pubKey = readKeyFromFile(str); 
    Cipher cipher = Cipher.getInstance("RSA"); 
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);//initialise the cipher 
    cipherData = cipher.doFinal(str.getBytes());//passing in the data to be encrypted 


    rsHex(cipherData); 


    } 


public String getUserinput() { 
    return str; 
    } 

    public String getChipertext() { 
    return chipertext; 
    } 

    public void setUserinput(String input) { 
    this.str = input; 
    } 

    public void setChipertext(String chipertext) throws Exception { 
    this.chipertext = chipertext; 

    } 



    } 


    ----main Program------ 
    import java.util.Scanner; 

public class TWO{ 
    public static void main(String[] args) throws Exception{ 


    Scanner scan = new Scanner(System.in); 

    System.out.println("Insert your string"); 
    String str = scan.nextLine(); 

      RSA two = new RSA(str); 


    System.out.println("Encrypted: "+ two.getChipertext()); 



} 
} 
+1

실제 RSA gubbinry에 대해서는 http://www.javamex.com/tutorials/cryptography/rsa_encryption.shtml 여기에서 제안 된 코드를 사용하고 있습니다. 어떤 실제 회선에서 오류가 발생하고 있습니까? - 상상합니다. 로컬 설치 문제일까요? –

+0

이미 해당 페이지의 코딩을 사용하고 있습니다. 지금 나는 입력 값을 읽는 문제에 직면 해있다. – chilora7

+0

예, 당신은 실제 예외를 게시 할 수 있으며 게시 된 코드에서 어떤 라인이 발생했는지 나타낼 수있다. –

답변

3

문제는 그 문자열로 FileReader와를 구성하여 파일 이름이었다 것처럼 당신이 사용자로부터 입력 문자열을 복용하고 있지만 다음 코드는이 치료된다는 것이다 .

FileReader 및 BufferedReader에 대한 모든 말도 안되는 것 대신에 string.getBytes()를 사용하지 않는 이유가 무엇입니까?

너는 또한 인생을 끔찍하게 복잡하게 만드는 것처럼 보입니다. 문자열을 가져 와서 바이트 배열로 변환 한 다음이를 다시 문자열로 변환 한 다음 다시 바이트 배열로 변환합니다. . 이것은 원래 문자열 (getBytes()에 의해 주어진 바이트) 표현을 가져 와서 RSA 암호화에 직접 전달할 수있을 때 매우 혼란 스럽다.

+0

나는 이미 값을 읽었습니다. 이제 진짜 문제가 나타납니다. InputStream의 코딩 부분은 = RSA.class.getResourceAsStream (keyFileName); System.out.println ("Hello2"); ObjectInputStream oin = 새 ObjectInputStream (새 BufferedInputStream (입)); System.out.println ("Hello3"); 안녕 3은 인쇄 할 수 없습니다. 문제를 해결할 수 있습니까? 고마워. – chilora7