2011-12-09 4 views
0

비대칭 암호화를 사용하여 클라이언트 측에서 공개 키를 사용하여 메시지를 암호화하고 서버 측에서 개인 키로 해독하려고합니다.비대칭 알고리즘 사용 문제

메시지를 암호 해독 한 후에는 plattext와 일치하지 않습니다. 이걸 좀 도와 주실 래요? 당신이 끔찍한 표현을 반환 toString() 방법을 사용하고 있기 때문에 정상

import java.io.BufferedInputStream; 
import java.io.BufferedOutputStream; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
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.PrivateKey; 
import java.security.PublicKey; 
import java.security.spec.InvalidKeySpecException; 
import java.security.spec.RSAPrivateKeySpec; 
import java.security.spec.RSAPublicKeySpec; 

import javax.crypto.BadPaddingException; 
import javax.crypto.Cipher; 
import javax.crypto.IllegalBlockSizeException; 
import javax.crypto.NoSuchPaddingException; 

public class GenerateKeys { 

    public static void saveToFile(String fileName, BigInteger mod, 
      BigInteger exp) throws IOException { 
     ObjectOutputStream oout = new ObjectOutputStream(
       new BufferedOutputStream(new FileOutputStream(fileName))); 
     try { 
      oout.writeObject(mod); 
      oout.writeObject(exp); 
     } catch (Exception e) { 
      throw new IOException("Unexpected error", e); 
     } finally { 
      oout.close(); 
     } 
    } 

    public static void rsaKeyGeneration() { 
     KeyPairGenerator kpg = null; 
     try { 
      kpg = KeyPairGenerator.getInstance("RSA"); 
     } catch (NoSuchAlgorithmException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     kpg.initialize(1024); 
     KeyPair kp = kpg.genKeyPair(); 
     Key publicKey = kp.getPublic(); 
     Key privateKey = kp.getPrivate(); 
     System.out.println("Algo is :" + publicKey.getAlgorithm()); 

     KeyFactory fact = null; 
     try { 
      fact = KeyFactory.getInstance("RSA"); 
     } catch (NoSuchAlgorithmException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     RSAPublicKeySpec pub = null; 
     try { 
      pub = fact.getKeySpec(publicKey, RSAPublicKeySpec.class); 
     } catch (InvalidKeySpecException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     RSAPrivateKeySpec priv = null; 
     try { 
      priv = fact.getKeySpec(privateKey, RSAPrivateKeySpec.class); 
     } catch (InvalidKeySpecException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     try { 
      saveToFile("C:/public1.key", pub.getModulus(), 
        pub.getPublicExponent()); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     try { 
      saveToFile("C:/private1.key", priv.getModulus(), 
        priv.getPrivateExponent()); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } 

    PublicKey readKeyFromFile(String keyFileName) throws IOException { 
     InputStream in = new FileInputStream(keyFileName); 
     ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(
       in)); 

     try { 
      BigInteger m = (BigInteger) oin.readObject(); 
      BigInteger e = (BigInteger) oin.readObject(); 
      RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e); 
      KeyFactory fact = KeyFactory.getInstance("RSA"); 
      PublicKey pubKey = fact.generatePublic(keySpec); 
      return pubKey; 
     } catch (Exception e) { 
      throw new RuntimeException("Spurious serialisation error", e); 
     } finally { 
      oin.close(); 
     } 
    } 

    public byte[] rsaEncrypt(byte[] data) { 
     PublicKey pubKey = null; 
     try { 
      pubKey = readKeyFromFile("C:/public1.key"); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     Cipher cipher = null; 
     try { 
      cipher = Cipher.getInstance("RSA"); 
     } catch (NoSuchAlgorithmException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (NoSuchPaddingException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     try { 
      cipher.init(Cipher.ENCRYPT_MODE, pubKey); 
     } catch (InvalidKeyException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     byte[] cipherData = null; 
     try { 
      cipherData = cipher.doFinal(data); 
     } catch (IllegalBlockSizeException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (BadPaddingException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     System.out 
       .println("encrypted card number is :" + cipherData.toString()); 
     return cipherData; 
    } 

    PrivateKey readPriKeyFromFile(String keyFileName) throws IOException { 
     InputStream in = new FileInputStream(keyFileName); 
     ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(
       in)); 

     try { 
      BigInteger m = (BigInteger) oin.readObject(); 
      BigInteger e = (BigInteger) oin.readObject(); 
      RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e); 
      KeyFactory fact = KeyFactory.getInstance("RSA"); 
      PrivateKey pKey = fact.generatePrivate(keySpec); 
      return pKey; 
     } catch (Exception e) { 
      throw new RuntimeException("Spurious serialisation error", e); 
     } finally { 
      oin.close(); 
     } 
    } 

    public byte[] rsaDecrypt(byte[] sampleText) { 
     PrivateKey priKey = null; 
     try { 
      priKey = readPriKeyFromFile("C:/private1.key"); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     Cipher cipher = null; 
     try { 
      cipher = Cipher.getInstance("RSA"); 
     } catch (NoSuchAlgorithmException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (NoSuchPaddingException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     try { 
      cipher.init(Cipher.DECRYPT_MODE, priKey); 
     } catch (InvalidKeyException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     byte[] cipherData = null; 
     try { 
      cipherData = cipher.doFinal(sampleText); 
      // cipherData = cipher. 
     } catch (IllegalBlockSizeException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (BadPaddingException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return cipherData; 
    } 

    public static void main(String s[]) { 
     System.out 
       .println("++++++++++++++++++++ Program to create the Keys+++++++++++++++++++++++++++++"); 
     rsaKeyGeneration(); 
     String sText = "HRB"; 
     System.out.println("Plain Text Card Number :" + sText); 
     GenerateKeys keys = new GenerateKeys(); 
     byte[] encryptedCardNo = keys.rsaEncrypt(sText.getBytes()); 
     byte[] decryptedCardNo = keys.rsaDecrypt(encryptedCardNo); 
     System.out.println("Decrypted card number is :" 
       + decryptedCardNo.toString()); 

    } 
} 
+0

당신은 아래로 여기에 몇 가지 팁을 가지고, 그것을 표시하십시오. – amrfaissal

답변

1

: 아래

는 코드입니다. 따라서 암호화 된 텍스트와 해독 된 텍스트를 모두 표시하려면 16 진수 표현을 사용해야합니다. 다음 작업을 수행하는 함수는 다음과 같습니다 바이트 [] 새로운 문자열 (바이트 [], 캐릭터 세트) : 대신 된 toString() 문자열 방법

public String byteArrayToHexString(byte[] bArray){ 
    StringBuffer buffer = new StringBuffer(); 

    for(byte b : bArray) { 
     buffer.append(Integer.toHexString(b)); 
     buffer.append(" "); 
    } 

    return buffer.toString();  
} 
1

가하는 String.getBytes (문자 집합)를 사용합니다. toString()은 바이트 배열에 대한 참조를 제공합니다. charset으로, Java 호환 플랫폼 (및 Apache Harmony, 모든 가능성 있음)에서 항상 지원되는 Charset.forName ("UTF-8")을 사용하십시오. 닫힌

private static final Charset UTF8 = Charset.forName("UTF-8"); 

...

System.out.println(new String("Hi there!".getBytes(UTF8), UTF8)); 
+1

그러나 어떤 경우에도 암호화로 인해 생성 된 바이트 배열에서 String 인스턴스를 생성해야합니다. 모든 문자 집합은 가능한 모든 코드의 하위 집합 만 지원하지만 암호 출력은 완전히 임의적 일 수 있습니다. –

+0

GregS님께 감사드립니다. 이것은 해독 된 데이터를 표시하는 것이므로 언급하지 않았습니다. –